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: fp8 / mxfp8 image LoRA training on every aspect bucket, mxfp8 for biased linears, fp8 sm89 floor (#13317)

Daniel Han3deec0e8fb70
diff --git a/studio/backend/core/training/diffusion_dit_trainer.py b/studio/backend/core/training/diffusion_dit_trainer.py
index 9cc9d418628..927395219e4 100644
--- a/studio/backend/core/training/diffusion_dit_trainer.py
+++ b/studio/backend/core/training/diffusion_dit_trainer.py
@@ -330,9 +330,9 @@ def _load_pipe_without_transformer(pipe_cls, cfg, device):
def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
"""Load the transformer alone in the resolved ``base_precision``. nf4: a prequant (bnb-4bit)
repo carries its quantization config and loads 4-bit as-is, while a dense base is quantized
- to nf4 on the fly; the memory floor. bf16 / fp8 / mxfp8: the dense transformer (fp8/mxfp8
- convert its frozen linears to float8 training compute AFTER the LoRA attaches; storage stays
- bf16). int8: the dense transformer quantized in place to torchao weight-only int8 (the
+ to nf4 on the fly; the memory floor. bf16 / fp8 / mxfp8: the dense transformer, converted AFTER the LoRA
+ attaches (fp8 stores its frozen linears in e4m3, about half the bf16 weight memory; mxfp8 keeps bf16 storage).
+ int8: the dense transformer quantized in place to torchao weight-only int8 (the
PEFT-attachable scheme), roughly halving the bf16 weight footprint."""
import torch
@@ -350,8 +350,13 @@ def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
transformer = transformer.to(device)
return transformer
+ if base_precision == "fp8":
+ transformer = _load_fp8_prequant_transformer(transformer_cls, cfg, device)
+ if transformer is not None:
+ return transformer
+
# int8 quantizes AFTER the LoRA attaches: quantizing first makes peft dispatch TorchaoLoraLinear, whose peft-0.18
- # constructor rejects the torchao-0.16 config API.
+ # constructor rejects the torchao-0.16 config API (peft 0.19+ accepts it; the order works for both).
return transformer_cls.from_pretrained(
cfg.base_model,
subfolder = "transformer",
@@ -360,6 +365,32 @@ def _load_dit_transformer(transformer_cls, cfg, device, base_precision):
).to(device)
+def _load_fp8_prequant_transformer(transformer_cls, cfg, device):
+ """The family's hosted fp8 denoiser (the file Studio inference uses) as the fp8 base, skipping the bf16 transformer
+ download; None (load bf16 and quantize, as before) when none is mapped for this exact base or it fails to load."""
+ import logging
+
+ from core.training.diffusion_fp8_prequant import load_fp8_transformer, resolve_fp8_checkpoint
+
+ log = logging.getLogger(__name__)
+ path = resolve_fp8_checkpoint(
+ getattr(cfg, "resolved_family", None), cfg.base_model, cfg.hf_token, logger = log
+ )
+ if path is None:
+ return None
+ try:
+ transformer = load_fp8_transformer(
+ transformer_cls, cfg.base_model, path, device, hf_token = cfg.hf_token
+ )
+ except Exception as exc: # noqa: BLE001 -- the dense path still works
+ log.warning("fp8 prequant: %s did not load (%s); loading bf16", path, exc)
+ gc.collect()
+ return None
+ transformer._studio_fp8_prequant_path = path
+ log.info("fp8 base loaded from the pre-quantized checkpoint %s", path)
+ return transformer
+
+
def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
"""torchao weight-only int8 on the big frozen linears, applied after add_adapter so the base_layer
inside each LoRA wrapper quantizes while the adapters stay high precision. ``make_filter_fn``
@@ -399,11 +430,22 @@ def _int8_quantize_base(transformer, family: Optional[str] = None) -> None:
apply_small_m_padding(transformer, "int8", family)
-def _fp8_module_filter(mod, fqn: str) -> bool:
- """Which frozen linears get float8 training compute: skip anything LoRA-owned (the adapters must
- stay high precision, since PEFT has no float8 base support), the output projection, and
- shapes float8 kernels reject (dims not divisible by 16), matching the diffusers FLUX2
- reference filter."""
+# Small-M linears (conditioning vectors, LTX-2 one-token audio) stay bf16: the float8 / MX casts cost more than the GEMM.
+# final_layer is Krea 2's output projection.
+_LOWP_EXTRA_EXCLUDE_TOKENS = ("final_layer",)
+
+
+def _lowp_exclude_tokens(family: Optional[str] = None) -> tuple[str, ...]:
+ from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme
+ return tuple(exclude_tokens_for_scheme("int8", family)) + _LOWP_EXTRA_EXCLUDE_TOKENS
+
+
+def _lowp_module_filter(
+ mod,
+ fqn: str,
+ align: int,
+ exclude_tokens: tuple[str, ...] = (),
+) -> bool:
import torch.nn as nn
if not isinstance(mod, nn.Linear):
@@ -412,93 +454,245 @@ def _fp8_module_filter(mod, fqn: str) -> bool:
return False
if fqn.endswith("proj_out") or ".proj_out." in fqn:
return False
- return mod.in_features % 16 == 0 and mod.out_features % 16 == 0
-
-
-def _fp8_training_config():
- """The float8 training config: per-ROW (rowwise) scaling when this torchao build ships the
- recipe, else the tensorwise default. The DiT families carry extreme activation outliers
- (Z-Image MLP activations peak near 6.6e4, the same range that forced per-row scaling in the
- inference quant layer): one tensor-wide dynamic scale pushes normal values (~1-30) below fp8
- resolution, so the frozen base's forward -- the signal the LoRA regresses against --
- degrades. Per-row scaling confines each outlier to its own token/channel. The tensorwise
- fallback keeps pad_inner_dim so a non-16-aligned inner dim never aborts the scaled_mm (the
- rowwise recipe manages its own padding rules and rejects the knob, hence the split)."""
- from torchao.float8 import Float8LinearConfig
+ name = fqn.lower()
+ if any(tok in name for tok in exclude_tokens):
+ return False
+ return mod.in_features % align == 0 and mod.out_features % align == 0
+
+
+def _fp8_module_filter(
+ mod,
+ fqn: str,
+ exclude_tokens: tuple[str, ...] = (),
+) -> bool:
+ """Dims divisible by 16 (the diffusers FLUX2 reference filter)."""
+ return _lowp_module_filter(mod, fqn, 16, exclude_tokens)
+
+
+def _in_repeated_blocks(transformer, module_filter):
+ """Restrict the filter to the regionally compiled ``_repeated_blocks`` (if any)."""
+ names = set(getattr(transformer, "_repeated_blocks", None) or ())
+ prefixes = tuple(
+ f"{fqn}." for fqn, mod in transformer.named_modules() if mod.__class__.__name__ in names
+ )
+ if not prefixes:
+ return module_filter
+ return lambda mod, fqn: fqn.startswith(prefixes) and module_filter(mod, fqn)
+
+
+def _lowp_targets(transformer, base_filter, family: Optional[str]) -> list:
+ tokens = _lowp_exclude_tokens(family)
+ keep = _in_repeated_blocks(transformer, lambda mod, fqn: base_filter(mod, fqn, tokens))
+ return [
+ (fqn, mod)
+ for fqn, mod in transformer.named_modules()
+ if not getattr(mod, "_studio_lowp", None) and keep(mod, fqn)
+ ]
+
+
+def _require_lowp_modules(transformer, mode: str) -> bool:
+ """Raises when nothing converted (FLUX.1 / LTX-2 on torchao 0.17, all biased), so bf16 is recorded."""
+ if not any(getattr(mod, "_studio_lowp", None) == mode for mod in transformer.modules()):
+ raise RuntimeError("no eligible linear layers")
+ return True
+
+
+def _convert_fp8(transformer, family: Optional[str] = None) -> bool:
+ """Frozen base linears to weight-cached fp8 (``diffusion_frozen_fp8``): rowwise float scales, as DiT activation
+ outliers (Z-Image ~2.7e6) crush a tensorwise one."""
+ from core.training.diffusion_frozen_fp8 import convert_frozen_fp8
+
+ _, failed = convert_frozen_fp8(
+ transformer, {fqn for fqn, _ in _lowp_targets(transformer, _fp8_module_filter, family)}
+ )
+ transformer._studio_fp8_failed = failed
+ return _require_lowp_modules(transformer, "fp8")
+
+
+def _probe_lowp(convert, transformer) -> None:
+ """Tiny converted Linear fwd + bwd so an unverified arch falls back to bf16 at load, not mid-run.
+ 48 rows: not a multiple of 16 / 32."""
+ import torch
+ import torch.nn as nn
+
try:
- return Float8LinearConfig.from_recipe_name("rowwise")
- except Exception: # noqa: BLE001 -- older torchao without the rowwise recipe
- return Float8LinearConfig(pad_inner_dim = True)
+ device = next(transformer.parameters()).device
+ except StopIteration:
+ return
+ if device.type != "cuda":
+ return
+
+ class _Probe(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ff = nn.Linear(64, 64, bias = False)
+
+ def forward(self, x):
+ return self.ff(x)
+ # Forked RNG: the probe's init + randn run after the seed and would shift the noise / timestep draws vs bf16.
+ with torch.random.fork_rng(devices = [device]):
+ probe = _Probe().to(device = device, dtype = torch.bfloat16).requires_grad_(False)
+ convert(probe)
+ x = torch.randn(1, 48, 64, device = device, requires_grad = True)
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ y = probe(x)
+ y.float().sum().backward()
+ torch.cuda.synchronize(device)
+ if not (torch.isfinite(y).all() and torch.isfinite(x.grad).all()):
+ raise RuntimeError("probe GEMM returned non-finite values")
-def _apply_fp8_training(transformer, on_event) -> bool:
- """Convert the frozen base linears to torchao float8 training compute (dynamic scaling; weights
- stay bf16 in memory). Applied AFTER add_adapter so the filter can exclude the LoRA modules.
- Never fatal: on any failure the run continues in bf16 with a warning."""
+
+def _apply_fp8_training(
+ transformer,
+ on_event,
+ family: Optional[str] = None,
+) -> bool:
+ """fp8 compute + storage for the frozen base, after add_adapter. Never fatal: falls back to bf16."""
+ from core.training.diffusion_fp8_prequant import dequantize_placeholders
try:
- from torchao.float8 import convert_to_float8_training
- convert_to_float8_training(
- transformer,
- module_filter_fn = _fp8_module_filter,
- config = _fp8_training_config(),
- )
- return True
+ _probe_lowp(_convert_fp8, transformer)
+ converted = _convert_fp8(transformer, family)
+ # A prequant base's fp8 layers the conversion did not take stay bf16, as on the dense path.
+ dequantize_placeholders(transformer)
+ failed = getattr(transformer, "_studio_fp8_failed", 0)
+ if failed:
+ _emit(
+ on_event,
+ "warning",
+ message = f"fp8: {failed} layer(s) could not be converted and stay bf16.",
+ )
+ import torch
+
+ device = next(transformer.parameters()).device.type
+ if device == "cuda":
+ torch.cuda.empty_cache()
+ elif device == "xpu":
+ torch.xpu.empty_cache()
+ return converted
except Exception as exc: # noqa: BLE001 -- fp8 is an optimisation, never fatal
+ dequantize_placeholders(transformer)
_emit(on_event, "warning", message = f"fp8 training unavailable, using bf16 compute: {exc}")
return False
-def _mx_module_filter(mod, fqn: str) -> bool:
- """Which frozen linears get mxfp8 training compute: skip anything LoRA-owned (the adapters must
- stay high precision), the output projection (same guard as fp8), and shapes the 32-wide MX
- block scaling cannot tile (dims not divisible by 32)."""
- import torch.nn as nn
-
- if not isinstance(mod, nn.Linear):
- return False
- if "lora_" in fqn:
- return False
- if fqn.endswith("proj_out") or ".proj_out." in fqn:
- return False
- # Skip biased linears: the torchao 0.17 MX path swaps the weight for a wrapper that drops the bias, changing the
- # output the LoRA regresses against.
- if getattr(mod, "bias", None) is not None:
- return False
- return mod.in_features % 32 == 0 and mod.out_features % 32 == 0
+def _mx_module_filter(
+ mod,
+ fqn: str,
+ exclude_tokens: tuple[str, ...] = (),
+) -> bool:
+ """32-wide MX blocks and a bf16 weight (the MX casts assert it)."""
+ import torch
+ return _lowp_module_filter(mod, fqn, 32, exclude_tokens) and mod.weight.dtype == torch.bfloat16
def _mxfp8_training_config():
- """The torchao MX training config across the prototype API's revisions: torchao 0.16 ships
- ``MXLinearConfig`` in ``prototype.mx_formats``; 0.17 removed it in favour of the
- ``MXFP8TrainingOpConfig`` recipe API shared with MoE training. Both feed ``quantize_``.
- Raises ImportError when neither API exists (mxfp8 then falls back to bf16)."""
+ """RCEIL MX config: torchao 0.14-0.16 ``MXLinearConfig``, else 0.17+ with hp wgrad: torchao computes grad_weight
+ even for a frozen weight, and its dim1 cast asserts tokens % 32 == 0 (the gradient is discarded anyway)."""
try:
from torchao.prototype.mx_formats import MXLinearConfig
- return MXLinearConfig.from_recipe_name("mxfp8_cublas")
+ return MXLinearConfig.from_recipe_name("mxfp8_cublas_rceil")
except ImportError:
from torchao.prototype.moe_training.config import (
MXFP8TrainingOpConfig,
MXFP8TrainingRecipe,
)
- return MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe.MXFP8_RCEIL)
+ return MXFP8TrainingOpConfig.from_recipe(MXFP8TrainingRecipe.MXFP8_RCEIL_WGRAD_WITH_HP)
-def _apply_mxfp8_training(transformer, on_event) -> bool:
- """Swap the frozen base linears to torchao MX float8 training compute (mxfp8, the
- Blackwell-native block-scaled format; the swap is in place and the weights stay bf16 in
- memory, so like fp8 this is a speed mode, not a memory mode). Applied AFTER add_adapter so
- the filter can exclude the LoRA modules. Only competitive under torch.compile and only ahead
- of compiled bf16 at large token counts (high resolution or batch), which is why it stays an
- explicit opt-in rather than an "auto" pick. Never fatal: on any failure the run continues in
- bf16 with a warning."""
+def _mx_linear_class():
try:
- from torchao.quantization import quantize_
- quantize_(
- transformer,
- _mxfp8_training_config(),
- filter_fn = _mx_module_filter,
+ from torchao.prototype.moe_training.mxfp8_linear import MXFP8Linear
+ return MXFP8Linear
+ except ImportError:
+ return None
+
+
+_ROW_PADDED_MX: dict = {}
+
+
+def _row_padded_mx_linear(base_cls):
+ """torchao <= 0.16 MXLinear has no hp wgrad and asserts tokens % 32 == 0: pad zero rows, slice off
+ (MX scales are per block along the feature dim, so real rows are unchanged)."""
+ cls = _ROW_PADDED_MX.get(base_cls)
+ if cls is None:
+ import torch.nn.functional as F
+ def forward(self, x):
+ shape = x.shape
+ rows = x.reshape(-1, shape[-1])
+ m = rows.shape[0]
+ y = base_cls.forward(self, F.pad(rows, (0, 0, 0, (-m) % 32)))[:m]
+ return y.reshape(*shape[:-1], y.shape[-1])
+
+ cls = _ROW_PADDED_MX[base_cls] = type(
+ f"RowPadded{base_cls.__name__}", (base_cls,), {"forward": forward}
)
- return True
+ return cls
+
+
+def _autocast_mx_input(module, args):
+ import torch
+
+ x = args[0] if args else None
+ if (
+ isinstance(x, torch.Tensor)
+ and x.dtype == torch.float32
+ and x.is_cuda
+ and torch.is_autocast_enabled("cuda")
+ ):
+ return (x.to(torch.get_autocast_dtype("cuda")), *args[1:])
+ return None
+
+
+def _convert_mxfp8(transformer, family: Optional[str] = None) -> bool:
+ import torch.nn as nn
+
+ config = _mxfp8_training_config()
+ targets = [
+ (fqn, mod)
+ for fqn, mod in _lowp_targets(transformer, _mx_module_filter, family)
+ if type(mod) is nn.Linear
+ ]
+ if not hasattr(config, "wgrad_with_hp"):
+ from torchao.quantization import quantize_
+
+ names = {fqn for fqn, _ in targets}
+ quantize_(transformer, config, filter_fn = lambda mod, fqn: fqn in names)
+ for _, mod in targets:
+ mod.__class__ = _row_padded_mx_linear(mod.__class__)
+ else:
+ linear_cls = _mx_linear_class()
+ if linear_cls is not None:
+ for _, mod in targets:
+ mod.__class__ = linear_cls
+ mod.kernel_preference = config.kernel_preference
+ mod.scale_calculation_mode = config.scale_calculation_mode
+ mod.wgrad_with_hp = config.wgrad_with_hp
+ else:
+ from torchao.quantization import quantize_
+
+ targets = [(fqn, mod) for fqn, mod in targets if mod.bias is None]
+ names = {fqn for fqn, _ in targets}
+ quantize_(transformer, config, filter_fn = lambda mod, fqn: fqn in names)
+ # The MX linear asserts bf16 input above autocast (fp32 LayerNorm output into FLUX.2 ff.linear_in raised).
+ for _, mod in targets:
+ mod.register_forward_pre_hook(_autocast_mx_input)
+ for _, mod in targets:
+ mod._studio_lowp = "mxfp8"
+ return _require_lowp_modules(transformer, "mxfp8")
+
+
+def _apply_mxfp8_training(
+ transformer,
+ on_event,
+ family: Optional[str] = None,
+) -> bool:
+ """torchao mxfp8 compute for the frozen base (speed only), after add_adapter; never fatal.
+ 0.18+ swaps the class to MXFP8Linear, not ``quantize_``: its wrapper drops the bias (pytorch/ao#4846),
+ so on torchao 0.17 biased linears stay bf16."""
+ try:
+ _probe_lowp(_convert_mxfp8, transformer)
+ return _convert_mxfp8(transformer, family)
except Exception as exc: # noqa: BLE001 -- mxfp8 is an optimisation, never fatal
_emit(on_event, "warning", message = f"mxfp8 training unavailable, using bf16 compute: {exc}")
return False
@@ -516,8 +710,8 @@ def _pick_auto_precision(
"""Pure policy for base_precision="auto": nf4 for a prequant base or no CUDA; else the fastest
dense mode whose weights + headroom (activations, optimizer, cache) fit the free VRAM at
decision time. bf16 + regional compile is the measured speed winner (2.3-2.6x over nf4 on
- B200); fp8 stays an explicit opt-in because torchao float8's dynamic-scaling overhead made it
- SLOWER than compiled bf16 at LoRA-training shapes on the same hardware. int8 must still
+ B200); fp8 stays an explicit opt-in: it trades e4m3 rounding (~0.5% loss vs bf16) for ~half the base weight
+ memory and only ~7% speed at LoRA-training shapes. int8 must still
materialise the full bf16 transformer before ``quantize_`` shrinks it module-by-module, so
its band requires the dense-load transient (1.15x dense) to fit -- what int8 buys in that
band is steady-state headroom for activations and the latent cache, not load-time memory.
@@ -600,6 +794,18 @@ def _resolve_base_precision(cfg, spec, device) -> str:
)
# mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, after a full dense load.
# Re-check here to fail fast for a stale client.
+ # fp8 needs sm89+ (Ada / Hopper / Blackwell): below it the first float8 _scaled_mm raises inside the loop.
+ if mode == "fp8" and device == "cuda":
+ try:
+ import torch
+ fp8_ok = torch.cuda.get_device_capability() >= (8, 9)
+ except Exception: # noqa: BLE001 -- probe failure -> treat as unsupported, fail fast
+ fp8_ok = False
+ if not fp8_ok:
+ raise ValueError(
+ "base_precision='fp8' needs an Ada, Hopper or Blackwell (sm89+) GPU; this GPU is "
+ "older. Use base_precision='bf16', 'int8', 'nf4', or 'auto'."
+ )
if mode == "mxfp8" and device == "cuda":
try:
import torch
@@ -1971,6 +2177,12 @@ def _maybe_compile_transformer(
dynamo_cfg.suppress_errors = True
# dynamic=True matches the inference speed layer: on torch 2.10 / B200 the dynamic=False specialisation failed
# with CUBLAS_STATUS_EXECUTION_FAILED.
+ try:
+ # torch 2.12 / 2.13 inductor CantSplit in the dynamic joint-stream cat backward (FLUX.1 fp8); probe-gated.
+ from core.inference.diffusion_inductor_backports import install as _install_backports
+ _install_backports()
+ except Exception: # noqa: BLE001 -- the backport is best-effort
+ pass
fn(fullgraph = not base_is_bnb, dynamic = True)
return True
except Exception as exc: # noqa: BLE001 -- optimisation only, never fatal
@@ -1978,6 +2190,35 @@ def _maybe_compile_transformer(
return False
+def _dynamo_compile_counters() -> Optional[tuple[int, int, int]]:
+ """(graph breaks, failed frames, unique graphs), or None."""
+ try:
+ from torch._dynamo.utils import counters
+ frames = counters["frames"]
+ return (
+ sum(counters["graph_break"].values()),
+ frames["total"] - frames["ok"],
+ counters["stats"]["unique_graphs"],
+ )
+ except Exception: # noqa: BLE001 -- diagnostics only
+ return None
+
+
+def _compile_engagement_warning(before, after) -> Optional[str]:
+ """Why compiled blocks run eager since ``before`` (suppress_errors hides failures), else None."""
+ if before is None or after is None:
+ return None
+ breaks, failed, graphs = (a - b for a, b in zip(after, before))
+ if breaks > 0 or failed > 0:
+ return (
+ f"torch.compile did not fully engage ({breaks} graph break(s), {failed} frame(s) "
+ f"fell back to eager): training continues, slower than compiled."
+ )
+ if graphs <= 0:
+ return "torch.compile produced no graphs: the transformer blocks are running eager."
+ return None
+
+
def run_dit_lora_training(
config: DiffusionLoraConfig,
*,
@@ -2280,9 +2521,13 @@ def _train_dit(
# and stay high precision.
if base_precision == "int8":
_int8_quantize_base(transformer, cfg.resolved_family)
- if base_precision == "fp8" and not _apply_fp8_training(transformer, on_event):
+ if base_precision == "fp8" and not _apply_fp8_training(
+ transformer, on_event, cfg.resolved_family
+ ):
base_precision = "bf16"
- if base_precision == "mxfp8" and not _apply_mxfp8_training(transformer, on_event):
+ if base_precision == "mxfp8" and not _apply_mxfp8_training(
+ transformer, on_event, cfg.resolved_family
+ ):
base_precision = "bf16"
# LoRA EMA (opt-in via cfg.ema_decay): shadows ONLY the trainable adapter params, initialised after the precision
@@ -2508,6 +2753,7 @@ def _train_dit(
_sample(resumed)
train_peak = TrainingPeakMemory(device)
+ compile_watch = _dynamo_compile_counters() if compiled else None
for opt_step in range(resumed, cfg.train_steps):
if stop_latched:
stopped = True
@@ -2595,6 +2841,11 @@ def _train_dit(
if ran_here == 1:
# Step 1 pays the one-time costs (cudnn autotune, compile warmup), so the reported rate starts after it.
t_steady = now
+ if compile_watch is not None:
+ reason = _compile_engagement_warning(compile_watch, _dynamo_compile_counters())
+ if reason:
+ _emit(on_event, "warning", message = reason)
+ compile_watch = None
if done % cfg.log_every == 0 or done == cfg.train_steps:
peak_gb = train_peak.gb()
per_step = batch_size * cfg.gradient_accumulation_steps
diff --git a/studio/backend/core/training/diffusion_fp8_prequant.py b/studio/backend/core/training/diffusion_fp8_prequant.py
new file mode 100644
index 00000000000..329c5f7cf9a
--- /dev/null
+++ b/studio/backend/core/training/diffusion_fp8_prequant.py
@@ -0,0 +1,261 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""base_precision="fp8" training straight from a hosted ``unsloth/*-FP8`` denoiser checkpoint.
+
+Same file Studio fp8 inference resolves (one download, dense bf16 never fetched). Layout ``<fqn>._weight_qdata`` e4m3
+[out, in] + ``<fqn>._weight_scale`` fp32 [out, 1] is FrozenFp8Linear's per-row format. Anything unexpected returns None
+and the caller loads bf16.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import struct
+from typing import Any, Optional
+
+_FORMAT = "unsloth_prequant_transformer_state_dict_v1"
+_QDATA = "._weight_qdata"
+_SCALE = "._weight_scale"
+# Root-level plain tensors (z-image's pad tokens) are stored under this prefix (prequant_safetensors).
+_ROOT = "unsloth_root::"
+_DISABLE_ENV = "UNSLOTH_DIFFUSION_TRAIN_FP8_PREQUANT"
+_MAX_HEADER = 64 << 20
+# Attribute a placeholder nn.Linear carries until _apply_fp8_training converts or dequantizes it.
+PREQUANT_ATTR = "_studio_fp8_prequant"
+
+
+def _disabled() -> bool:
+ return os.environ.get(_DISABLE_ENV, "").strip().lower() in ("0", "false", "no", "off")
+
+
+def _parse_header(raw: bytes) -> dict:
+ header = json.loads(raw)
+ if not isinstance(header, dict):
+ raise ValueError("safetensors header is not an object")
+ return header
+
+
+def _local_header(path: str) -> dict:
+ with open(path, "rb") as fh:
+ (n,) = struct.unpack("<Q", fh.read(8))
+ if n > _MAX_HEADER:
+ raise ValueError("safetensors header too large")
+ return _parse_header(fh.read(n))
+
+
+def _remote_header(repo_id: str, filename: str, token: Optional[str]) -> dict:
+ """Range reads (~40 KB), so a checkpoint baked from another base is refused before its multi-GB download."""
+ from huggingface_hub import HfFileSystem
+ with HfFileSystem(token = token).open(f"{repo_id}/{filename}", "rb", block_size = 1 << 16) as fh:
+ (n,) = struct.unpack("<Q", fh.read(8))
+ if n > _MAX_HEADER:
+ raise ValueError("safetensors header too large")
+ return _parse_header(fh.read(n))
+
+
+def checkpoint_problem(header: dict, base_model: str) -> Optional[str]:
+ """Why this safetensors header cannot seed fp8 training of ``base_model``, or None when it can."""
+ meta = header.get("__metadata__") or {}
+ if meta.get("unsloth_format") != _FORMAT:
+ return f"format {meta.get('unsloth_format')!r} is not {_FORMAT}"
+ try:
+ info = json.loads(meta.get("unsloth_metadata") or "{}")
+ except ValueError:
+ return "unreadable unsloth_metadata"
+ if info.get("scheme") != "fp8":
+ return f"scheme {info.get('scheme')!r} is not fp8"
+ if info.get("fp8_granularity") not in (None, "per_row"):
+ return f"fp8 granularity {info.get('fp8_granularity')!r} is not per_row"
+ ckpt_base = info.get("base_model_id")
+ if not ckpt_base:
+ return "no base_model_id"
+ from core.inference.diffusion_prequant import _same_base_model
+
+ if not _same_base_model(str(ckpt_base), str(base_model)):
+ return f"baked from {ckpt_base!r}, not {base_model!r}"
+ n_quant = 0
+ for name, entry in header.items():
+ if not name.endswith(_QDATA):
+ continue
+ stem = name[: -len(_QDATA)]
+ scale = header.get(stem + _SCALE)
+ shape = entry.get("shape") or []
+ if (
+ entry.get("dtype") != "F8_E4M3"
+ or len(shape) != 2
+ or scale is None
+ or scale.get("dtype") != "F32"
+ or scale.get("shape") != [shape[0], 1]
+ ):
+ return f"{stem}: not an e4m3 [out, in] weight with an fp32 [out, 1] scale"
+ n_quant += 1
+ if not n_quant:
+ return "no fp8 weights"
+ return None
+
+
+def _hub_cache() -> Optional[str]:
+ try:
+ from utils.hf_cache_settings import active_hf_hub_cache
+ return active_hf_hub_cache()
+ except Exception: # noqa: BLE001 -- unset: huggingface_hub's own default
+ return None
+
+
+def resolve_fp8_checkpoint(
+ family: Optional[str],
+ base_model: str,
+ hf_token: Optional[str] = None,
+ logger: Any = None,
+) -> Optional[str]:
+ """Local path of a validated fp8 denoiser checkpoint for ``base_model`` (downloaded into the inference cache root
+ when absent), or None. Never raises."""
+ if _disabled() or not family or not base_model:
+ return None
+ try:
+ from core.inference.diffusion_families import detect_family
+ from core.inference.diffusion_prequant import (
+ _download_checkpoint_name,
+ _same_base_model, # noqa: F401 -- imported here so a missing helper falls back early
+ cached_checkpoint_path,
+ candidate_filenames_of,
+ is_comfy_prequant_filename,
+ resolve_prequant_source,
+ )
+
+ fam = detect_family("", override = str(family).strip().lower())
+ if fam is None or not fam.prequant_repos:
+ return None
+ src = resolve_prequant_source(fam, "fp8", base_repo = base_model)
+ if src is None or src.kind != "repo":
+ return None
+ # Studio's own safetensors only: comfy twins, ConvRot rotations and pickles are other layouts.
+ names = [
+ n
+ for n in candidate_filenames_of(src)
+ if n.endswith(".safetensors")
+ and not is_comfy_prequant_filename(n)
+ and "convrot" not in n.lower()
+ ]
+ cache_dir = _hub_cache()
+ for name in names:
+ path = cached_checkpoint_path(src, cache_dir = cache_dir, names = [name], online = False)
+ try:
+ header = (
+ _local_header(path) if path else _remote_header(src.location, name, hf_token)
+ )
+ except Exception as exc: # noqa: BLE001 -- 404 / offline: next name
+ if logger is not None:
+ logger.info("fp8 prequant: %s/%s unreadable: %s", src.location, name, exc)
+ continue
+ problem = checkpoint_problem(header, base_model)
+ if problem:
+ if logger is not None:
+ logger.info("fp8 prequant: %s/%s refused: %s", src.location, name, problem)
+ return None
+ if path is None:
+ path = _download_checkpoint_name(
+ src, name, hf_token, cache_dir, propagate_missing = False
+ )
+ # The downloaded header is the one we load, so recheck it (a republish between the reads).
+ problem = checkpoint_problem(_local_header(path), base_model)
+ if problem:
+ if logger is not None:
+ logger.info("fp8 prequant: %s refused: %s", path, problem)
+ return None
+ return path
+ except Exception as exc: # noqa: BLE001 -- the dense path is always there
+ if logger is not None:
+ logger.warning("fp8 prequant: resolution failed, loading bf16: %s", exc)
+ return None
+
+
+def _placeholder_weight(out_f: int, in_f: int, device):
+ import torch
+
+ # Zero-stride, one element: PEFT reads only its device / dtype when it attaches LoRA.
+ return torch.nn.Parameter(
+ torch.zeros((), dtype = torch.bfloat16, device = device).expand(out_f, in_f),
+ requires_grad = False,
+ )
+
+
+def load_fp8_transformer(
+ transformer_cls,
+ config_repo: str,
+ path: str,
+ device,
+ hf_token = None,
+):
+ """Build ``transformer_cls`` from ``config_repo``'s transformer config and the fp8 checkpoint at ``path``. Raises on any key / shape mismatch."""
+ import torch
+ import torch.nn as nn
+ from accelerate import init_empty_weights
+ from safetensors import safe_open
+
+ config = transformer_cls.load_config(config_repo, subfolder = "transformer", token = hf_token)
+ with init_empty_weights():
+ model = transformer_cls.from_config(config)
+ expected = set(model.state_dict().keys())
+ keep_fp32 = tuple(getattr(model, "_keep_in_fp32_modules", None) or ())
+ dense: dict = {}
+ quant: dict = {}
+ dev = str(device)
+ with safe_open(path, framework = "pt", device = dev) as f:
+ keys = list(f.keys())
+ for key in keys:
+ if key.endswith(_SCALE):
+ continue
+ if key.endswith(_QDATA):
+ stem = key[: -len(_QDATA)]
+ quant[stem] = (f.get_tensor(key), f.get_tensor(stem + _SCALE).float())
+ continue
+ t = f.get_tensor(key)
+ name = key[len(_ROOT) :] if key.startswith(_ROOT) else key
+ fp32 = any(tok in name.split(".") for tok in keep_fp32)
+ dense[name] = t.to(torch.float32 if fp32 else torch.bfloat16)
+ got = set(dense) | {f"{s}.weight" for s in quant}
+ if got != expected:
+ missing = sorted(expected - got)[:5]
+ extra = sorted(got - expected)[:5]
+ raise ValueError(
+ f"checkpoint keys differ from the model: missing {missing}, unexpected {extra}"
+ )
+ for stem, (q, s) in quant.items():
+ mod = model.get_submodule(stem)
+ if type(mod) is not nn.Linear or tuple(mod.weight.shape) != tuple(q.shape):
+ raise ValueError(f"{stem}: checkpoint fp8 weight {tuple(q.shape)} does not fit {mod!r}")
+ mod.weight = _placeholder_weight(q.shape[0], q.shape[1], device)
+ setattr(mod, PREQUANT_ATTR, (q, s))
+ model.load_state_dict(dense, strict = False, assign = True)
+ leftover = [n for n, p in model.named_parameters() if p.device.type == "meta"]
+ if leftover:
+ raise ValueError(f"parameters left unloaded: {leftover[:5]}")
+ # from_pretrained hands back an eval-mode module; match it (the trainer calls train() itself).
+ return model.to(device).eval()
+
+
+def dequantize_placeholders(model) -> int:
+ """Give every still-pending fp8 Linear a real bf16 weight (q * scale): the layers fp8 training leaves bf16
+ (outside the compiled blocks, excluded tokens, a failed conversion, a bf16 fallback). Returns how many."""
+ import torch
+ import torch.nn as nn
+
+ n = 0
+ for mod in model.modules():
+ pending = getattr(mod, PREQUANT_ATTR, None)
+ if pending is None:
+ continue
+ q, s = pending
+ w = torch.empty(q.shape, dtype = torch.bfloat16, device = q.device)
+ with torch.no_grad():
+ for i in range(0, q.shape[0], 2048):
+ w[i : i + 2048] = (q[i : i + 2048].float() * s[i : i + 2048].reshape(-1, 1)).to(
+ torch.bfloat16
+ )
+ mod.weight = nn.Parameter(w, requires_grad = False)
+ delattr(mod, PREQUANT_ATTR)
+ n += 1
+ return n
diff --git a/studio/backend/core/training/diffusion_frozen_fp8.py b/studio/backend/core/training/diffusion_frozen_fp8.py
new file mode 100644
index 00000000000..4666d04828a
--- /dev/null
+++ b/studio/backend/core/training/diffusion_frozen_fp8.py
@@ -0,0 +1,113 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""fp8 compute for the frozen base linears of a LoRA run.
+
+Each weight is quantized once to e4m3 (float scale per output row) and its bf16 copy freed; backward returns only
+grad_x, so nothing from x is saved (torchao's Float8Linear re-quantizes the bf16 weight ~4x per layer per step).
+GEMMs use unit scales with row scales applied after: rowwise ``_scaled_mm`` on sm100 routes to an untuned CUTLASS
+kernel, tensorwise to cuBLAS (aten ScaledBlas.cpp).
+"""
+
+import torch
+import torch.nn as nn
+
+_E4M3 = torch.float8_e4m3fn
+_E4M3_MAX = float(torch.finfo(_E4M3).max)
+_EPS = 1e-12
+
+
+def _rowwise_quant(x2d):
+ xf = x2d.float()
+ amax = xf.abs().amax(dim = -1, keepdim = True).clamp_min(_EPS)
+ q = (xf * (_E4M3_MAX / amax)).clamp(-_E4M3_MAX, _E4M3_MAX).to(_E4M3)
+ return q, amax / _E4M3_MAX
+
+
+def _quantize_weight(w, rows = 2048):
+ q = torch.empty(w.shape, dtype = _E4M3, device = w.device)
+ s = torch.empty((w.shape[0], 1), dtype = torch.float32, device = w.device)
+ for i in range(0, w.shape[0], rows):
+ q[i : i + rows], s[i : i + rows] = _rowwise_quant(w[i : i + rows])
+ return q, s
+
+
+def _unit_scaled_mm(a, b):
+ one = torch.ones(
+ (), device = a.device, dtype = torch.float32
+ ) # a fresh scalar: a buffer view fails to lower
+ out = torch._scaled_mm(a, b, scale_a = one, scale_b = one, out_dtype = torch.bfloat16)
+ return out[0] if isinstance(out, tuple) else out # torch < 2.5 also returned amax
+
+
+@torch._dynamo.allow_in_graph # as torchao's float8 matmul: inlining the Function trips a dynamo freevar assert
+class _FrozenFp8MM(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x2d, q, s_row, out_dtype):
+ xq, sx = _rowwise_quant(x2d)
+ y = (_unit_scaled_mm(xq, q.t()).float() * (sx * s_row)).to(out_dtype)
+ ctx.save_for_backward(q, s_row)
+ ctx.x_dtype = x2d.dtype
+ return y
+
+ @staticmethod
+ def backward(ctx, gy):
+ if not ctx.needs_input_grad[0]:
+ return None, None, None, None
+ q, s_row = ctx.saved_tensors
+ # The weight scale sits on the reduction dim of grad_y @ W, so it folds into grad_y; mat2 must be column-major.
+ gq, sg = _rowwise_quant(gy.float() * s_row)
+ gx = _unit_scaled_mm(gq, q.t().contiguous().t()).float() * sg
+ return gx.to(ctx.x_dtype), None, None, None
+
+
+class FrozenFp8Linear(nn.Module):
+ """A frozen nn.Linear (a PEFT LoRA base_layer) with an fp8 weight; in / out features must be 16-aligned."""
+
+ def __init__(self, linear: nn.Linear):
+ super().__init__()
+ out_f, in_f = linear.weight.shape
+ if in_f % 16 or out_f % 16:
+ raise ValueError(f"fp8 needs 16-aligned dims, got {out_f}x{in_f}")
+ self.in_features, self.out_features = in_f, out_f
+ # A Linear loaded from a hosted fp8 checkpoint carries its per-row codes already (diffusion_fp8_prequant).
+ pre = getattr(linear, "_studio_fp8_prequant", None)
+ q, s = pre if pre is not None else _quantize_weight(linear.weight.detach())
+ self.register_buffer("weight", q)
+ self.register_buffer("weight_scale", s.reshape(1, out_f).contiguous())
+ self.bias = (
+ None if linear.bias is None else nn.Parameter(linear.bias.detach(), requires_grad = False)
+ )
+
+ def forward(self, x):
+ if torch.is_autocast_enabled(x.device.type):
+ x = x.to(torch.get_autocast_dtype(x.device.type))
+ shape = x.shape
+ y = _FrozenFp8MM.apply(x.reshape(-1, shape[-1]), self.weight, self.weight_scale, x.dtype)
+ y = y.reshape(*shape[:-1], self.out_features)
+ return y if self.bias is None else y + self.bias.to(y.dtype)
+
+ def extra_repr(self):
+ return f"in_features={self.in_features}, out_features={self.out_features}, fp8"
+
+
+def convert_frozen_fp8(model: nn.Module, names) -> tuple[int, int]:
+ """Swap each frozen nn.Linear in ``names`` for FrozenFp8Linear one at a time (bounds peak memory); a layer that
+ fails stays bf16 rather than raising mid-conversion. Returns (converted, failed)."""
+ done = failed = 0
+ for fqn in sorted(names):
+ parent_name, _, child = fqn.rpartition(".")
+ parent = model.get_submodule(parent_name) if parent_name else model
+ old = getattr(parent, child)
+ if type(old) is not nn.Linear or old.weight.requires_grad:
+ continue
+ try:
+ new = FrozenFp8Linear(old)
+ except (RuntimeError, ValueError):
+ failed += 1
+ continue
+ new._studio_lowp = "fp8"
+ setattr(parent, child, new)
+ done += 1
+ return done, failed
diff --git a/studio/backend/core/training/diffusion_h3_trainer.py b/studio/backend/core/training/diffusion_h3_trainer.py
index d233428fe62..aea1bdd2c06 100644
--- a/studio/backend/core/training/diffusion_h3_trainer.py
+++ b/studio/backend/core/training/diffusion_h3_trainer.py
@@ -535,6 +535,8 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
from peft.utils import get_peft_model_state_dict
from core.training.diffusion_dit_trainer import (
+ _compile_engagement_warning,
+ _dynamo_compile_counters,
_int8_quantize_base,
_make_optimizer,
_maybe_compile_transformer,
@@ -700,6 +702,7 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
t_steady = None
done = 0
reset_training_peak_memory(device)
+ compile_watch = _dynamo_compile_counters() if compiled else None
for opt_step in range(cfg.train_steps):
optimizer.zero_grad(set_to_none = True)
step_loss = 0.0
@@ -777,6 +780,11 @@ def _train_h3(cfg, pairs, rng, device, weight_dtype, on_event, _check_stop, _sav
now = time.time()
if done == 1:
t_steady = now
+ if compile_watch is not None:
+ reason = _compile_engagement_warning(compile_watch, _dynamo_compile_counters())
+ if reason:
+ _emit(on_event, "warning", message = reason)
+ compile_watch = None
if done % cfg.log_every == 0 or done == cfg.train_steps:
peak_gb = training_peak_memory_gb(device)
per_step = cfg.gradient_accumulation_steps
diff --git a/studio/backend/core/training/diffusion_lora_trainer.py b/studio/backend/core/training/diffusion_lora_trainer.py
index 3ba83459fdb..1217088a88f 100644
--- a/studio/backend/core/training/diffusion_lora_trainer.py
+++ b/studio/backend/core/training/diffusion_lora_trainer.py
@@ -464,7 +464,11 @@ def run_diffusion_lora_training(
# Regionally torch.compile the U-Net repeated blocks via the DiT trainer's never-fatal wrapper (failure
# falls back to eager).
- from core.training.diffusion_dit_trainer import _maybe_compile_transformer
+ from core.training.diffusion_dit_trainer import (
+ _compile_engagement_warning,
+ _dynamo_compile_counters,
+ _maybe_compile_transformer,
+ )
compiled = _maybe_compile_transformer(
unet, cfg, False, device, on_event, base_precision = "bf16"
@@ -741,6 +745,7 @@ def run_diffusion_lora_training(
_sample(resumed)
train_peak = TrainingPeakMemory(device)
+ compile_watch = _dynamo_compile_counters() if compiled else None
for opt_step in range(resumed, cfg.train_steps):
if stop_latched:
stopped = True
@@ -845,6 +850,11 @@ def run_diffusion_lora_training(
if ran_here == 1:
# Step 1 pays the one-time costs (cudnn autotune, compile warmup), so the rate starts after it.
t_steady = now
+ if compile_watch is not None:
+ reason = _compile_engagement_warning(compile_watch, _dynamo_compile_counters())
+ if reason:
+ _emit(on_event, "warning", message = reason)
+ compile_watch = None
if done % cfg.log_every == 0 or done == cfg.train_steps:
# ``learning_rate`` (not ``lr``) is the field the Unsloth training pump reads.
peak_gb = train_peak.gb()
diff --git a/studio/backend/core/training/diffusion_train_common.py b/studio/backend/core/training/diffusion_train_common.py
index fe9bc913afa..5c2cd346817 100644
--- a/studio/backend/core/training/diffusion_train_common.py
+++ b/studio/backend/core/training/diffusion_train_common.py
@@ -428,9 +428,9 @@ def has_functional_torchao() -> bool:
def train_precision_modes() -> tuple[list[str], str]:
"""(supported base_precision modes, recommended pick) for the current machine: nf4 always works;
- bf16/auto need a bf16-capable CUDA GPU (Ampere+); int8/fp8/mxfp8 additionally need a
+ bf16/auto need a bf16-capable CUDA GPU (Ampere+); int8/mxfp8 additionally need a
FUNCTIONAL torchao (their explicit paths import it with no fallback, and the Windows-ROCm
- stub only looks installed). fp8 also needs sm89+; mxfp8 needs the Blackwell tensor cores
+ stub only looks installed). fp8 needs sm89+ (torch's own _scaled_mm); mxfp8 needs the Blackwell tensor cores
(sm100+) its cuBLAS kernels target. The dense modes all train in bf16 compute, which the DiT
trainer requires, so a non-bf16 CUDA GPU (T4/V100/RTX 20xx) is offered only nf4 -- otherwise
/info would advertise a start that evicts resident models and then fails the trainer's bf16
@@ -442,11 +442,12 @@ def train_precision_modes() -> tuple[list[str], str]:
if flow_bf16_trainable():
modes.append("bf16")
# ROCm capability values are gfx versions, not the NVIDIA SM levels checked below.
- torchao_ok = has_functional_torchao() and not torch_is_rocm()
+ rocm = torch_is_rocm()
+ torchao_ok = has_functional_torchao() and not rocm
if torchao_ok:
modes.append("int8")
major, minor = torch.cuda.get_device_capability()
- if torchao_ok and (major, minor) >= (8, 9) and hasattr(torch, "float8_e4m3fn"):
+ if not rocm and (major, minor) >= (8, 9) and hasattr(torch, "float8_e4m3fn"):
modes.append("fp8")
if torchao_ok and (major, minor) >= (10, 0):
modes.append("mxfp8")
@@ -974,8 +975,8 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
rejected before teardown: the bf16-GPU requirement; no accelerator at all (which covers nf4
too); the dense precisions needing CUDA; the torchao precisions against a ROCm build, which
clears the stub test and hands the sm100 floor an AMD gfx version; explicit int8 needing a
- FUNCTIONAL torchao; explicit fp8/mxfp8 against the Windows-ROCm stub; explicit mxfp8 needing
- Blackwell. Add a gate there, add it here. Never raises."""
+ FUNCTIONAL torchao; explicit fp8/mxfp8 against the Windows-ROCm stub; explicit fp8 needing
+ sm89+ and mxfp8 Blackwell. Add a gate there, add it here. Never raises."""
reason = bf16_unsupported_reason(resolved_family)
if reason:
return reason
@@ -1018,6 +1019,18 @@ def training_precision_preflight_error(resolved_family: str, base_precision: str
)
# mxfp8 needs Blackwell (sm100+): its MX GEMM raises at the first training step, AFTER a full dense load.
# Re-check here so a stale client fails fast before eviction.
+ # fp8 needs sm89+: below it the first float8 _scaled_mm raises inside the loop, after eviction.
+ if mode == "fp8":
+ try:
+ import torch
+ fp8_ok = torch.cuda.get_device_capability() >= (8, 9)
+ except Exception: # noqa: BLE001 -- probe failure -> treat as unsupported, fail fast
+ fp8_ok = False
+ if not fp8_ok:
+ return (
+ "base_precision='fp8' needs an Ada, Hopper or Blackwell (sm89+) GPU; this GPU is "
+ "older. Use base_precision='bf16', 'int8', 'nf4', or 'auto'."
+ )
if mode == "mxfp8":
try:
import torch
diff --git a/studio/backend/tests/test_diffusion_base_precision.py b/studio/backend/tests/test_diffusion_base_precision.py
index 0f86f06a1f9..fd3d5f6f78a 100644
--- a/studio/backend/tests/test_diffusion_base_precision.py
+++ b/studio/backend/tests/test_diffusion_base_precision.py
@@ -148,7 +148,10 @@ def test_resolve_base_precision_explicit_int8_gates_on_torchao(monkeypatch):
monkeypatch.setattr(dit, "has_functional_torchao", lambda: True)
assert dit._resolve_base_precision(cfg, spec, "cuda") == "int8"
- # The gate is int8-specific: explicit bf16/fp8 pass through regardless of torchao.
+ # The gate is int8-specific: explicit bf16/fp8 pass through regardless of torchao (fp8 on an sm89 GPU).
+ import torch
+
+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a, **k: (8, 9))
monkeypatch.setattr(dit, "has_functional_torchao", lambda: False)
assert dit._resolve_base_precision(_cfg(base_precision = "bf16"), spec, "cuda") == "bf16"
assert dit._resolve_base_precision(_cfg(base_precision = "fp8"), spec, "cuda") == "fp8"
@@ -630,6 +633,328 @@ def test_fp8_module_filter():
assert dit._fp8_module_filter(nn.LayerNorm(64), "transformer_blocks.0.norm") is False
+def _real_cuda():
+ import torch
+
+ # Other suites in a worker can leave torch.cuda.is_available() spoofed True; the C call asks the driver.
+ return torch.cuda.is_available() and getattr(torch._C, "_cuda_getDeviceCount", lambda: 0)() > 0
+
+
+def _block_model(bias = False):
+ import torch
+
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ff = nn.Linear(64, 64, bias = bias)
+ self.norm1 = nn.Module()
+ self.norm1.linear = nn.Linear(64, 64 * 6, bias = True) # AdaLN: M = batch rows
+
+ class Model(nn.Module):
+ _repeated_blocks = ["Block"]
+
+ def __init__(self):
+ super().__init__()
+ self.time_mod_proj = nn.Linear(64, 64 * 6, bias = False)
+ self.blocks = nn.ModuleList([Block(), Block()])
+ self.final_layer = nn.Module()
+ self.final_layer.linear = nn.Linear(64, 64)
+
+ return Model().to(torch.bfloat16)
+
+
+def test_float8_filters_stay_inside_the_repeated_blocks():
+ m = _block_model()
+ for base in (dit._fp8_module_filter, dit._mx_module_filter):
+ f = dit._in_repeated_blocks(m, base)
+ assert f(m.blocks[1].ff, "blocks.1.ff") is True
+ assert f(m.time_mod_proj, "time_mod_proj") is False
+ assert f(m.blocks[0].ff, "blocks.0.ff.lora_A.default") is False
+ assert (
+ dit._in_repeated_blocks(nn.Linear(64, 64), dit._fp8_module_filter) is dit._fp8_module_filter
+ )
+
+
+ "family, fqn, kept",
+ [
+ ("flux.1", "transformer_blocks.0.attn.to_q", True),
+ ("flux.1", "transformer_blocks.0.ff.net.0.proj", True),
+ ("flux.1", "transformer_blocks.0.norm1.linear", False),
+ ("flux.1", "transformer_blocks.0.norm1_context.linear", False),
+ ("flux.1", "single_transformer_blocks.0.norm.linear", False),
+ ("flux.1", "single_transformer_blocks.0.proj_mlp", True),
+ ("flux.2-klein", "single_transformer_blocks.0.attn.to_qkv_mlp_proj", True),
+ ("flux.2-klein", "double_stream_modulation_img.linear", False),
+ ("z-image", "layers.0.feed_forward.w1", True),
+ ("z-image", "layers.0.adaLN_modulation.0", False),
+ ("z-image", "noise_refiner.0.adaLN_modulation.0", False),
+ ("krea-2", "transformer_blocks.0.ff.gate", True),
+ ("krea-2", "time_mod_proj", False),
+ ("krea-2", "final_layer.linear", False),
+ ("ltx-2", "transformer_blocks.0.attn1.to_q", True),
+ ("ltx-2", "transformer_blocks.0.audio_attn1.to_q", False),
+ ("ltx-2", "transformer_blocks.0.audio_ff.net.0.proj", False),
+ ("ltx-2", "transformer_blocks.0.video_to_audio_attn.to_k", False),
+ ],
+)
+def test_lowp_filters_skip_small_m_linears(family, fqn, kept):
+ import torch
+
+ lin = nn.Linear(3072, 3072, bias = True).to(torch.bfloat16)
+ tokens = dit._lowp_exclude_tokens(family)
+ assert dit._fp8_module_filter(lin, fqn, tokens) is kept
+ assert dit._mx_module_filter(lin, fqn, tokens) is kept
+
+
+def test_lowp_exclusions_extend_the_int8_small_m_list():
+ from core.inference.diffusion_transformer_quant import exclude_tokens_for_scheme
+
+ for family in (None, "flux.1", "ltx-2", "krea-2"):
+ tokens = dit._lowp_exclude_tokens(family)
+ assert set(exclude_tokens_for_scheme("int8", family)) <= set(tokens)
+ assert "final_layer" in tokens
+ assert "audio" in dit._lowp_exclude_tokens("ltx-2")
+ assert "audio" not in dit._lowp_exclude_tokens("flux.1")
+
+
+def test_mx_input_hook_mirrors_autocast():
+ import torch
+
+ x = torch.ones(2, 4)
+ assert dit._autocast_mx_input(None, (x,)) is None # CPU / no autocast: untouched
+ if not _real_cuda():
+ pytest.skip("needs CUDA autocast")
+ xc = x.cuda()
+ assert dit._autocast_mx_input(None, (xc,)) is None
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ (out,) = dit._autocast_mx_input(None, (xc,))
+ assert out.dtype == torch.bfloat16
+ assert dit._autocast_mx_input(None, (xc.bfloat16(),)) is None
+
+
[email protected]("mode", ["mxfp8"])
+def test_lowp_apply_without_torchao_is_a_noop_with_warning(monkeypatch, mode):
+ import sys
+
+ for name in (
+ "torchao",
+ "torchao.float8",
+ "torchao.quantization",
+ "torchao.prototype.mx_formats",
+ "torchao.prototype.moe_training.config",
+ ):
+ monkeypatch.setitem(sys.modules, name, None)
+ m = _block_model()
+ before = [type(x) for x in m.modules()]
+ events = []
+ apply = dit._apply_fp8_training if mode == "fp8" else dit._apply_mxfp8_training
+ assert apply(m, events.append, "flux.1") is False
+ assert [type(x) for x in m.modules()] == before
+ assert [e["type"] for e in events] == ["warning"] and mode in events[0]["message"]
+
+
+def _fake_mx_backend(monkeypatch, *, with_linear_cls = True):
+ """A torchao 0.18-shaped MX API without the GPU: records the swaps."""
+ import sys
+ from types import SimpleNamespace
+
+ class _Op:
+ wgrad_with_hp = True
+ kernel_preference = "auto"
+ scale_calculation_mode = "rceil"
+
+ class _Recipe:
+ MXFP8_RCEIL_WGRAD_WITH_HP = "hp"
+
+ class MXFP8Linear(nn.Linear):
+ pass
+
+ quantized = []
+ monkeypatch.setitem(sys.modules, "torchao.prototype.mx_formats", None)
+ cfg_mod = SimpleNamespace(
+ MXFP8TrainingOpConfig = SimpleNamespace(from_recipe = lambda r: _Op()),
+ MXFP8TrainingRecipe = _Recipe,
+ )
+ monkeypatch.setitem(sys.modules, "torchao.prototype.moe_training.config", cfg_mod)
+ monkeypatch.setitem(
+ sys.modules,
+ "torchao.prototype.moe_training.mxfp8_linear",
+ SimpleNamespace(MXFP8Linear = MXFP8Linear) if with_linear_cls else None,
+ )
+
+ def quantize_(model, config, filter_fn):
+ for fqn, mod in model.named_modules():
+ if filter_fn(mod, fqn):
+ quantized.append(fqn)
+
+ monkeypatch.setitem(sys.modules, "torchao.quantization", SimpleNamespace(quantize_ = quantize_))
+ return MXFP8Linear, quantized
+
+
+def test_mxfp8_swaps_biased_and_unbiased_block_linears_once(monkeypatch):
+ linear_cls, quantized = _fake_mx_backend(monkeypatch)
+ m = _block_model(bias = True)
+ params = [id(p) for p in m.parameters()]
+ assert dit._apply_mxfp8_training(m, None, "flux.1") is True
+ swapped = sorted(n for n, x in m.named_modules() if type(x) is linear_cls)
+ # Biased block linears included; AdaLN (norm1.linear), top-level and final_layer stay bf16.
+ assert swapped == ["blocks.0.ff", "blocks.1.ff"]
+ assert m.blocks[0].ff.wgrad_with_hp is True and quantized == []
+ assert [id(p) for p in m.parameters()] == params # the Parameters stay
+ hooks = len(m.blocks[0].ff._forward_pre_hooks)
+ assert dit._apply_mxfp8_training(m, None, "flux.1") is True
+ assert len(m.blocks[0].ff._forward_pre_hooks) == hooks == 1
+
+
+def test_mxfp8_torchao_0_17_keeps_biased_linears_dense(monkeypatch):
+ # Without MXFP8Linear the quantize_ weight wrapper is the only path, and it drops F.linear's bias (pytorch/ao#4846).
+ _, quantized = _fake_mx_backend(monkeypatch, with_linear_cls = False)
+ m = _block_model(bias = True)
+ events = []
+ assert dit._apply_mxfp8_training(m, events.append, "flux.1") is False
+ assert quantized == [] and "no eligible linear layers" in events[0]["message"]
+ m2 = _block_model(bias = False)
+ assert dit._apply_mxfp8_training(m2, None, "flux.1") is True
+ assert quantized == ["blocks.0.ff", "blocks.1.ff"]
+
+
+def test_fp8_quantizes_each_frozen_base_weight_once():
+ import torch
+
+ from core.training.diffusion_frozen_fp8 import FrozenFp8Linear
+
+ m = _block_model(bias = True).requires_grad_(False)
+ ref = {
+ fqn: mod.weight.float().clone()
+ for fqn, mod in m.named_modules()
+ if isinstance(mod, nn.Linear)
+ }
+ assert dit._convert_fp8(m, "flux.1") is True
+ swapped = {fqn: mod for fqn, mod in m.named_modules() if isinstance(mod, FrozenFp8Linear)}
+ # Only the repeated blocks' big linears; the AdaLN rows stay bf16 like the int8 / MX paths.
+ assert sorted(swapped) == ["blocks.0.ff", "blocks.1.ff"]
+ for fqn, mod in swapped.items():
+ assert mod.weight.dtype == torch.float8_e4m3fn and not isinstance(mod.weight, nn.Parameter)
+ assert mod._studio_lowp == "fp8" and mod.bias is not None and not mod.bias.requires_grad
+ deq = mod.weight.float() * mod.weight_scale.t()
+ assert ((deq - ref[fqn]).norm() / ref[fqn].norm()).item() < 0.04
+ # The bf16 weight is gone: no frozen base Parameter left on a converted path, so its memory is freed.
+ assert not any(n.endswith("ff.weight") for n, _ in m.named_parameters())
+
+
+def test_fp8_layer_that_fails_stays_bf16_and_the_rest_convert(monkeypatch):
+ import core.training.diffusion_frozen_fp8 as ff
+
+ real = ff._quantize_weight
+ calls = []
+
+ def flaky(w, rows = 2048):
+ calls.append(1)
+ if len(calls) == 1:
+ raise RuntimeError("CUDA out of memory")
+ return real(w, rows)
+
+ monkeypatch.setattr(ff, "_quantize_weight", flaky)
+ m = _block_model().requires_grad_(False)
+ events = []
+ assert dit._apply_fp8_training(m, events.append, "flux.1") is True
+ kinds = sorted(type(b.ff).__name__ for b in m.blocks)
+ assert kinds == ["FrozenFp8Linear", "Linear"]
+ assert any("1 layer(s)" in e.get("message", "") for e in events)
+
+
+def test_fp8_chunked_quantization_matches_one_shot():
+ import torch
+
+ from core.training.diffusion_frozen_fp8 import _quantize_weight, _rowwise_quant
+
+ w = (
+ torch.randn(300, 64, dtype = torch.bfloat16)
+ * torch.logspace(-3, 3, 300).unsqueeze(1).bfloat16()
+ )
+ q1, s1 = _rowwise_quant(w)
+ q2, s2 = _quantize_weight(w, rows = 64)
+ assert torch.equal(q1.view(torch.uint8), q2.view(torch.uint8)) and torch.equal(s1, s2)
+
+
+def test_fp8_conversion_needs_no_torchao(monkeypatch):
+ import sys
+
+ for name in ("torchao", "torchao.float8", "torchao.quantization"):
+ monkeypatch.setitem(sys.modules, name, None)
+ m = _block_model().requires_grad_(False)
+ assert dit._apply_fp8_training(m, lambda e: None, "flux.1") is True
+
+
+def _lowp_gpu_ready(mode):
+ import torch
+
+ if not _real_cuda():
+ return False
+ need = (8, 9) if mode == "fp8" else (10, 0)
+ return torch.cuda.get_device_capability() >= need
+
+
[email protected]("mode", ["fp8", "mxfp8"])
[email protected]("compiled", [False, True])
+def test_lowp_backward_on_odd_token_counts(mode, compiled):
+ """Token counts not divisible by 16 / 32 (LTX-2 192x320 = 60) raised in the frozen grad_weight GEMM."""
+ import torch
+
+ if not _lowp_gpu_ready(mode):
+ pytest.skip(f"{mode} needs a capable CUDA GPU")
+ pytest.importorskip("torchao")
+
+ class Block(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.ff = nn.Linear(256, 512, bias = True)
+
+ def forward(self, x):
+ return self.ff(x)
+
+ class Model(nn.Module):
+ _repeated_blocks = ["Block"]
+
+ def __init__(self):
+ super().__init__()
+ self.blocks = nn.ModuleList([Block()])
+
+ def forward(self, x):
+ return self.blocks[0](x)
+
+ torch.manual_seed(0)
+ ref = Model().to("cuda", torch.bfloat16).requires_grad_(False)
+ m = Model().to("cuda", torch.bfloat16).requires_grad_(False)
+ m.load_state_dict(ref.state_dict())
+ apply = dit._apply_fp8_training if mode == "fp8" else dit._apply_mxfp8_training
+ events = []
+ applied = apply(m, events.append, "flux.1")
+ # torchao 0.17 on torch 2.11 (the installer's pairing) refuses MX training on any GPU; the fallback is the test.
+ if not applied and mode == "mxfp8" and any("unavailable" in str(e) for e in events):
+ pytest.skip(f"this torch / torchao cannot run mxfp8 training: {events}")
+ assert applied is True, events
+ assert type(m.blocks[0].ff) is not nn.Linear
+ run = torch.compile(m, fullgraph = True, dynamic = True) if compiled else m
+ for tokens in (60, 240, 1008, 1024):
+ x = torch.randn(1, tokens, 256, device = "cuda", requires_grad = True)
+ xr = x.detach().clone().requires_grad_(True)
+ with torch.autocast("cuda", dtype = torch.bfloat16):
+ y = run(x)
+ yr = ref(xr)
+ g = torch.randn_like(yr)
+ y.backward(g)
+ yr.backward(g)
+ rel = lambda a, b: float((a.float() - b.float()).norm() / b.float().norm()) # noqa: E731
+ assert rel(y, yr) < 0.1 and rel(x.grad, xr.grad) < 0.1, (
+ tokens,
+ rel(y, yr),
+ rel(x.grad, xr.grad),
+ )
+ assert m.blocks[0].ff.weight.grad is None
+
+
# ── _should_compile fp8 branch ────────────────────────────────────────────────
def test_should_compile_fp8_branch():
# fp8 is only competitive compiled, so auto arms compile for it on a dense (non-bnb) cuda base.
@@ -650,24 +975,22 @@ def test_train_precision_modes_no_cuda(monkeypatch):
def test_train_precision_modes_gates_int8_fp8_on_torchao(monkeypatch):
- # int8/fp8 are only advertised when torchao is FUNCTIONAL: their explicit paths import it with no fallback.
+ # int8/mxfp8 are only advertised when torchao is FUNCTIONAL: their explicit paths import it with no fallback.
+ # fp8 runs on torch's own _scaled_mm, so only the GPU decides.
import torch
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
monkeypatch.setattr(torch.cuda, "is_bf16_supported", lambda: True)
monkeypatch.setattr(torch.cuda, "get_device_capability", lambda: (10, 0))
- # No functional torchao (absent or stub): bf16 + auto only, int8/fp8 dropped.
monkeypatch.setattr(common, "has_functional_torchao", lambda: False)
modes, recommended = train_precision_modes()
- assert modes == ["nf4", "bf16", "auto"]
- assert "int8" not in modes and "fp8" not in modes
+ assert modes == ["nf4", "bf16", "fp8", "auto"]
assert recommended == "auto"
- # With a functional torchao on an fp8-capable GPU, int8 + fp8 are advertised again.
monkeypatch.setattr(common, "has_functional_torchao", lambda: True)
modes2, _ = train_precision_modes()
- assert "int8" in modes2 and "fp8" in modes2
+ assert modes2 == ["nf4", "bf16", "int8", "fp8", "mxfp8", "auto"]
def test_train_precision_modes_gates_dense_on_bf16_support(monkeypatch):
@@ -813,3 +1136,42 @@ def test_dit_accelerator_gate_survives_a_torch_without_every_probe(monkeypatch):
# A working probe still clears the gate even when its neighbours are broken.
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
assert dit_accelerator_missing_reason("flux.1") is None
+
+
[email protected]("mode", ["fp8", "mxfp8"])
+def test_lowp_probe_failure_falls_back_before_touching_the_model(monkeypatch, mode):
+ # An arch whose float8 / MX GEMM fails (unverified sm89 / sm120 paths) must fall back to bf16 at load, not mid-run.
+ def broken_probe(convert, transformer):
+ raise RuntimeError("CUBLAS_STATUS_NOT_SUPPORTED")
+
+ monkeypatch.setattr(dit, "_probe_lowp", broken_probe)
+ m = _block_model()
+ before = [type(x) for x in m.modules()]
+ events = []
+ apply = dit._apply_fp8_training if mode == "fp8" else dit._apply_mxfp8_training
+ assert apply(m, events.append, "flux.1") is False
+ assert [type(x) for x in m.modules()] == before
+ assert not any(getattr(x, "_studio_lowp", None) for x in m.modules())
+ assert "CUBLAS_STATUS_NOT_SUPPORTED" in events[0]["message"] and mode in events[0]["message"]
+
+
+def test_lowp_probe_skips_off_cuda_and_raises_on_a_failing_gemm():
+ import torch
+
+ calls = []
+ dit._probe_lowp(lambda probe: calls.append(probe), _block_model()) # CPU model: no probe
+ assert calls == []
+ if not _real_cuda():
+ pytest.skip("needs CUDA")
+
+ def failing_convert(probe):
+ probe.ff.forward = lambda x: (_ for _ in ()).throw(RuntimeError("scaled_mm unsupported"))
+
+ with pytest.raises(RuntimeError, match = "scaled_mm unsupported"):
+ dit._probe_lowp(failing_convert, _block_model().cuda())
+ model = _block_model().cuda()
+ cpu_state, cuda_state = torch.get_rng_state(), torch.cuda.get_rng_state()
+ dit._probe_lowp(lambda probe: None, model) # a working GEMM passes
+ # The seed is set before conversion: the probe must not move the training draws.
+ assert torch.equal(torch.get_rng_state(), cpu_state)
+ assert torch.equal(torch.cuda.get_rng_state(), cuda_state)
diff --git a/studio/backend/tests/test_diffusion_dit_trainer.py b/studio/backend/tests/test_diffusion_dit_trainer.py
index c66fd27ccbb..ef71751a493 100644
--- a/studio/backend/tests/test_diffusion_dit_trainer.py
+++ b/studio/backend/tests/test_diffusion_dit_trainer.py
@@ -355,13 +355,18 @@ def _linear(
def test_mx_module_filter_accepts_dense_block_linear():
- # A bias-free 3072x3072 attention/FFN linear at a normal block fqn is a valid mxfp8 target.
- assert _mx_module_filter(_linear(3072, 3072), "blocks.0.ff.up") is True
+ # A bf16 3072x3072 attention/FFN linear at a normal block fqn is a valid mxfp8 target.
+ assert _mx_module_filter(_linear(3072, 3072).bfloat16(), "blocks.0.ff.up") is True
-def test_mx_module_filter_skips_biased_linear():
- # The torchao 0.17 MX training path drops the bias, so an mxfp8'd biased FROZEN linear would corrupt the base output the LoRA regresses against.
- assert _mx_module_filter(_linear(3072, 3072, bias = True), "blocks.0.ff.up") is False
+def test_mx_module_filter_keeps_biased_linear():
+ # MXFP8Linear adds the bias; only torchao 0.17's quantize_ wrapper drops it (biased skipped there alone).
+ assert _mx_module_filter(_linear(3072, 3072, bias = True).bfloat16(), "blocks.0.ff.up") is True
+
+
+def test_mx_module_filter_rejects_non_bf16_weight():
+ # The MX casts assert a bf16 weight.
+ assert _mx_module_filter(_linear(3072, 3072), "blocks.0.ff.up") is False
def test_resolve_base_precision_explicit_mxfp8_requires_blackwell(monkeypatch):
@@ -435,6 +440,7 @@ def test_mxfp8_training_config_falls_back_to_the_torchao_0_17_api(monkeypatch):
class _Recipe:
MXFP8_RCEIL = "mxfp8_rceil"
+ MXFP8_RCEIL_WGRAD_WITH_HP = "mxfp8_rceil_wgrad_with_hp"
class _OpConfig:
@staticmethod
@@ -449,7 +455,25 @@ def test_mxfp8_training_config_falls_back_to_the_torchao_0_17_api(monkeypatch):
)
monkeypatch.setitem(sys.modules, "torchao.prototype.moe_training.config", fake_config)
assert _mxfp8_training_config() == "cfg-0.17"
- assert calls["recipe"] == _Recipe.MXFP8_RCEIL
+ # High-precision wgrad: the MX dim1 cast of the frozen weight's discarded gradient asserts tokens % 32 == 0.
+ assert calls["recipe"] == _Recipe.MXFP8_RCEIL_WGRAD_WITH_HP
+
+
+def test_mxfp8_training_config_legacy_api_uses_rceil(monkeypatch):
+ # torchao 0.14-0.16: "mxfp8_cublas" is FLOOR scaling; RCEIL matches the 0.17+ recipe's numerics.
+ from types import SimpleNamespace
+
+ from core.training.diffusion_dit_trainer import _mxfp8_training_config
+
+ class _Cfg:
+ @staticmethod
+ def from_recipe_name(name):
+ return name
+
+ monkeypatch.setitem(
+ sys.modules, "torchao.prototype.mx_formats", SimpleNamespace(MXLinearConfig = _Cfg)
+ )
+ assert _mxfp8_training_config() == "mxfp8_cublas_rceil"
def _patch_capability(monkeypatch, capability):
@@ -503,3 +527,102 @@ def test_train_precision_modes_pre_ampere_is_nf4_only(monkeypatch):
modes, recommended = train_precision_modes()
assert modes == ["nf4"]
assert recommended == "nf4"
+
+
+ "capability, lowp",
+ [
+ ((7, 5), set()),
+ ((8, 0), set()),
+ ((8, 6), set()),
+ ((8, 9), {"fp8"}),
+ ((9, 0), {"fp8"}),
+ ((10, 0), {"fp8", "mxfp8"}),
+ ((12, 0), {"fp8", "mxfp8"}),
+ ],
+)
+def test_lowp_routing_per_nvidia_arch(monkeypatch, capability, lowp):
+ # fp8 only on sm89+, mxfp8 only on sm100+, refused by the child and the pre-eviction preflight alike.
+ import core.training.diffusion_train_common as dtc
+ from core.training.diffusion_train_common import training_precision_preflight_error
+
+ _patch_capability(monkeypatch, capability)
+ monkeypatch.setattr(dtc, "bf16_unsupported_reason", lambda _f: None)
+ monkeypatch.setattr(dtc, "dit_accelerator_missing_reason", lambda _f: None)
+ modes, _ = train_precision_modes()
+ assert {m for m in modes if m in ("fp8", "mxfp8")} == (lowp if capability >= (8, 0) else set())
+ for mode, floor in (("fp8", "sm89"), ("mxfp8", "Blackwell")):
+ cfg = types.SimpleNamespace(base_precision = mode, mixed_precision = "bf16", base_model = "x")
+ reason = training_precision_preflight_error("flux.1", mode)
+ if mode in lowp:
+ assert _resolve_base_precision(cfg, None, "cuda") == mode
+ assert reason is None
+ else:
+ with pytest.raises(ValueError, match = floor):
+ _resolve_base_precision(cfg, None, "cuda")
+ assert reason and floor in reason
+
+
[email protected]("device", ["cpu", "mps", "xpu"])
[email protected]("mode", ["fp8", "mxfp8"])
+def test_lowp_refused_off_cuda(device, mode):
+ # The float8 / MX conversions are reachable only from a CUDA run: every other device is refused up front.
+ cfg = types.SimpleNamespace(base_precision = mode, mixed_precision = "bf16", base_model = "x")
+ with pytest.raises(ValueError, match = "CUDA"):
+ _resolve_base_precision(cfg, None, device)
+
+
[email protected]("mode", ["fp8", "mxfp8"])
+def test_lowp_refused_on_rocm(monkeypatch, mode):
+ import core.training.diffusion_dit_trainer as dit
+ import core.training.diffusion_train_common as dtc
+
+ _patch_capability(monkeypatch, (10, 0))
+ monkeypatch.setattr(dit, "torch_is_rocm", lambda: True)
+ monkeypatch.setattr(dtc, "torch_is_rocm", lambda: True)
+ assert not {"fp8", "mxfp8"} & set(train_precision_modes()[0])
+ cfg = types.SimpleNamespace(base_precision = mode, mixed_precision = "bf16", base_model = "x")
+ with pytest.raises(ValueError, match = "ROCm"):
+ _resolve_base_precision(cfg, None, "cuda")
+
+
+def test_compile_engagement_warning():
+ from core.training.diffusion_dit_trainer import _compile_engagement_warning
+
+ assert _compile_engagement_warning(None, (0, 0, 3)) is None
+ assert _compile_engagement_warning((0, 0, 0), (0, 0, 3)) is None
+ assert "no graphs" in _compile_engagement_warning((0, 0, 0), (0, 0, 0))
+ assert "1 graph break" in _compile_engagement_warning((0, 0, 0), (1, 0, 3))
+ assert "2 frame(s)" in _compile_engagement_warning((4, 1, 5), (4, 3, 9))
+
+
+def test_compile_engagement_reads_real_dynamo_counters():
+ # suppress_errors hides failed compiles and nf4 splits on graph breaks; both must surface.
+ import torch
+
+ from core.training.diffusion_dit_trainer import (
+ _compile_engagement_warning,
+ _dynamo_compile_counters,
+ )
+
+ def body(x):
+ x = x + 1
+ torch._dynamo.graph_break()
+ return x * 2
+
+ def broken_backend(gm, example_inputs):
+ raise RuntimeError("backend failed")
+
+ torch._dynamo.reset()
+ before = _dynamo_compile_counters()
+ torch.compile(lambda x: x * 3, backend = "eager", fullgraph = True)(torch.ones(2))
+ assert _compile_engagement_warning(before, _dynamo_compile_counters()) is None
+ before = _dynamo_compile_counters()
+ assert torch.compile(body, backend = "eager")(torch.ones(2)).tolist() == [4.0, 4.0]
+ assert "graph break" in _compile_engagement_warning(before, _dynamo_compile_counters())
+ before = _dynamo_compile_counters()
+ with torch._dynamo.config.patch(suppress_errors = True):
+ out = torch.compile(lambda x: x * 5, backend = broken_backend)(torch.ones(2))
+ assert out.tolist() == [5.0, 5.0]
+ assert "fell back to eager" in _compile_engagement_warning(before, _dynamo_compile_counters())
+ torch._dynamo.reset()
diff --git a/studio/backend/tests/test_diffusion_fp8_prequant.py b/studio/backend/tests/test_diffusion_fp8_prequant.py
new file mode 100644
index 00000000000..0dc530f30fd
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_fp8_prequant.py
@@ -0,0 +1,281 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""fp8 LoRA training seeded from a hosted unsloth/*-FP8 denoiser checkpoint (CPU only)."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+import torch
+import torch.nn as nn
+
+from core.training import diffusion_dit_trainer as dit
+from core.training import diffusion_fp8_prequant as pq
+from core.training.diffusion_frozen_fp8 import FrozenFp8Linear, _quantize_weight
+
+_BASE = "Tongyi-MAI/Z-Image-Turbo"
+
+
+def _meta(
+ base = _BASE,
+ scheme = "fp8",
+ granularity = "per_row",
+ fmt = pq._FORMAT,
+):
+ info = {"scheme": scheme, "base_model_id": base, "fp8_granularity": granularity}
+ return {"unsloth_format": fmt, "unsloth_metadata": json.dumps(info)}
+
+
+def _header(**kw):
+ return {
+ "__metadata__": _meta(**kw),
+ "blk.lin._weight_qdata": {"dtype": "F8_E4M3", "shape": [32, 64]},
+ "blk.lin._weight_scale": {"dtype": "F32", "shape": [32, 1]},
+ "blk.norm.weight": {"dtype": "BF16", "shape": [64]},
+ }
+
+
+def test_checkpoint_problem_accepts_the_hosted_per_row_layout():
+ assert pq.checkpoint_problem(_header(), _BASE) is None
+ assert pq.checkpoint_problem(_header(), "/models/Z-Image-Turbo") is None
+
+
+ "kw, base, why",
+ [
+ ({}, "Tongyi-MAI/Z-Image", "baked from"),
+ (
+ {"base": "black-forest-labs/FLUX.2-klein-4B"},
+ "black-forest-labs/FLUX.2-klein-base-4B",
+ "baked from",
+ ),
+ ({"scheme": "int8"}, _BASE, "scheme"),
+ ({"granularity": "per_tensor"}, _BASE, "granularity"),
+ ({"fmt": "comfy"}, _BASE, "format"),
+ ],
+)
+def test_checkpoint_problem_refuses_other_bases_and_layouts(kw, base, why):
+ assert why in pq.checkpoint_problem(_header(**kw), base)
+
+
+ "scale",
+ [
+ {"dtype": "F32", "shape": [1]},
+ {"dtype": "F32", "shape": [32, 2]},
+ {"dtype": "BF16", "shape": [32, 1]},
+ ],
+)
+def test_checkpoint_problem_refuses_non_row_scales(scale):
+ h = _header()
+ h["blk.lin._weight_scale"] = scale
+ assert "scale" in pq.checkpoint_problem(h, _BASE)
+
+
+class _Blk(nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.lin = nn.Linear(64, 32, bias = True)
+ self.norm = nn.LayerNorm(64)
+
+
+class _Tiny(nn.Module):
+ _keep_in_fp32_modules = ["norm"]
+
+ def __init__(self):
+ super().__init__()
+ self.blk = _Blk()
+ self.out = nn.Linear(32, 16, bias = False)
+ self.pad = nn.Parameter(
+ torch.randn(1, 64)
+ ) # a root tensor, stored under unsloth_root:: (z-image)
+
+ @classmethod
+ def load_config(
+ cls,
+ repo,
+ subfolder = None,
+ token = None,
+ ):
+ return {}
+
+ @classmethod
+ def from_config(cls, config):
+ return cls()
+
+
+def _write_ckpt(path, ref):
+ from safetensors.torch import save_file
+
+ q, s = _quantize_weight(ref.blk.lin.weight.detach())
+ tensors = {
+ "blk.lin._weight_qdata": q,
+ "blk.lin._weight_scale": s,
+ "blk.lin.bias": ref.blk.lin.bias.detach().bfloat16(),
+ "blk.norm.weight": ref.blk.norm.weight.detach().bfloat16(),
+ "blk.norm.bias": ref.blk.norm.bias.detach().bfloat16(),
+ "out.weight": ref.out.weight.detach().bfloat16(),
+ "unsloth_root::pad": ref.pad.detach().bfloat16(),
+ }
+ save_file(tensors, str(path), metadata = _meta())
+ return q, s
+
+
+def test_load_keeps_the_stored_codes_and_dequantizes_the_rest(tmp_path):
+ torch.manual_seed(0)
+ ref = _Tiny()
+ path = tmp_path / "ck.safetensors"
+ q, s = _write_ckpt(path, ref)
+ assert pq.checkpoint_problem(pq._local_header(str(path)), _BASE) is None
+
+ m = pq.load_fp8_transformer(_Tiny, _BASE, str(path), "cpu")
+ lin = m.blk.lin
+ # zero-stride placeholder: no bf16 copy of the fp8 weight is ever materialised
+ assert lin.weight.shape == (32, 64) and lin.weight.stride() == (0, 0)
+ assert lin.weight.dtype == torch.bfloat16 and not lin.weight.requires_grad
+ assert m.blk.norm.weight.dtype == torch.float32 # _keep_in_fp32_modules, as diffusers loads it
+ assert m.out.weight.dtype == torch.bfloat16
+ assert torch.equal(m.pad, ref.pad.detach().bfloat16())
+
+ fp8 = FrozenFp8Linear(lin)
+ assert torch.equal(fp8.weight.view(torch.uint8), q.view(torch.uint8))
+ assert torch.equal(fp8.weight_scale, s.reshape(1, -1))
+ assert torch.equal(fp8.bias, ref.blk.lin.bias.detach().bfloat16())
+
+ assert pq.dequantize_placeholders(m) == 1
+ assert lin.weight.stride() == (64, 1)
+ assert torch.equal(lin.weight, (q.float() * s).bfloat16())
+ assert pq.dequantize_placeholders(m) == 0 # idempotent
+
+
+def test_dense_requantize_of_the_stored_weight_is_the_stored_codes(tmp_path):
+ """The prequant layer and today's quantize-at-load agree: re-quantizing q * scale returns q and scale."""
+ torch.manual_seed(1)
+ w = torch.randn(48, 64) * torch.logspace(-3, 1, 48).unsqueeze(1)
+ q, s = _quantize_weight(w)
+ q2, s2 = _quantize_weight(q.float() * s)
+ assert torch.equal(q2.view(torch.uint8), q.view(torch.uint8))
+ assert torch.allclose(s2, s, rtol = 1e-6, atol = 0)
+
+
+def test_load_refuses_a_checkpoint_for_another_architecture(tmp_path):
+ from safetensors.torch import save_file
+ save_file(
+ {"other.weight": torch.zeros(2, 2)}, str(tmp_path / "x.safetensors"), metadata = _meta()
+ )
+ with pytest.raises(ValueError, match = "keys differ"):
+ pq.load_fp8_transformer(_Tiny, _BASE, str(tmp_path / "x.safetensors"), "cpu")
+
+
+def test_resolve_needs_a_mapping_and_honours_the_opt_out(monkeypatch):
+ assert (
+ pq.resolve_fp8_checkpoint("z-image", "Tongyi-MAI/Z-Image") is None
+ ) # no hosted fp8 for the base
+ assert pq.resolve_fp8_checkpoint("ltx-2", "Lightricks/LTX-2") is None # not an image family
+ assert pq.resolve_fp8_checkpoint(None, _BASE) is None
+ monkeypatch.setenv(pq._DISABLE_ENV, "0")
+ assert pq.resolve_fp8_checkpoint("z-image", _BASE) is None
+
+
+def test_resolve_refuses_another_bases_checkpoint_before_downloading(monkeypatch):
+ import core.inference.diffusion_prequant as dp
+
+ seen = []
+ monkeypatch.setattr(dp, "cached_checkpoint_path", lambda *a, **k: None)
+ monkeypatch.setattr(
+ pq,
+ "_remote_header",
+ lambda repo, name, token: seen.append(name) or _header(base = "x/FLUX.2-klein-4B"),
+ )
+ monkeypatch.setattr(dp, "_download_checkpoint_name", lambda *a, **k: pytest.fail("downloaded"))
+ assert (
+ pq.resolve_fp8_checkpoint("flux.2-klein", "black-forest-labs/FLUX.2-klein-base-4B") is None
+ )
+ assert seen == [
+ "FLUX.2-klein-4B-FP8.safetensors"
+ ] # Studio's own safetensors only, no comfy / pickle
+
+
+def test_resolve_downloads_the_inference_file_into_the_live_cache(monkeypatch, tmp_path):
+ import core.inference.diffusion_prequant as dp
+
+ path = tmp_path / "Z-Image-Turbo-FP8.safetensors"
+ _write_ckpt(path, _Tiny())
+ calls = []
+ monkeypatch.setattr(dp, "cached_checkpoint_path", lambda *a, **k: None)
+ monkeypatch.setattr(pq, "_remote_header", lambda repo, name, token: _header())
+ monkeypatch.setattr(pq, "_hub_cache", lambda: "/live/cache")
+
+ def _dl(src, name, token, cache_dir, **k):
+ calls.append((src.location, name, cache_dir))
+ return str(path)
+
+ monkeypatch.setattr(dp, "_download_checkpoint_name", _dl)
+ assert pq.resolve_fp8_checkpoint("z-image", _BASE) == str(path)
+ assert calls == [("unsloth/Z-Image-Turbo-FP8", "Z-Image-Turbo-FP8.safetensors", "/live/cache")]
+
+
+def test_resolve_never_raises(monkeypatch):
+ import core.inference.diffusion_prequant as dp
+ monkeypatch.setattr(dp, "resolve_prequant_source", lambda *a, **k: 1 / 0)
+ assert pq.resolve_fp8_checkpoint("z-image", _BASE) is None
+
+
+class _Cls:
+ calls = []
+
+ @classmethod
+ def from_pretrained(cls, *a, **k):
+ cls.calls.append(k.get("subfolder"))
+ return nn.Linear(2, 2)
+
+
+def _cfg():
+ return SimpleNamespace(base_model = _BASE, hf_token = None, resolved_family = "z-image")
+
+
+def test_fp8_load_falls_back_to_bf16_without_a_checkpoint(monkeypatch):
+ _Cls.calls = []
+ monkeypatch.setattr(pq, "resolve_fp8_checkpoint", lambda *a, **k: None)
+ dit._load_dit_transformer(_Cls, _cfg(), "cpu", "fp8")
+ assert _Cls.calls == ["transformer"]
+
+
+def test_fp8_load_falls_back_to_bf16_when_the_checkpoint_fails(monkeypatch):
+ _Cls.calls = []
+ monkeypatch.setattr(pq, "resolve_fp8_checkpoint", lambda *a, **k: "/x.safetensors")
+ monkeypatch.setattr(pq, "load_fp8_transformer", lambda *a, **k: 1 / 0)
+ dit._load_dit_transformer(_Cls, _cfg(), "cpu", "fp8")
+ assert _Cls.calls == ["transformer"]
+
+
[email protected]("mode", ["bf16", "int8", "mxfp8"])
+def test_other_modes_never_look_for_the_fp8_checkpoint(monkeypatch, mode):
+ _Cls.calls = []
+ monkeypatch.setattr(pq, "resolve_fp8_checkpoint", lambda *a, **k: pytest.fail("looked"))
+ dit._load_dit_transformer(_Cls, _cfg(), "cpu", mode)
+ assert _Cls.calls == ["transformer"]
+
+
+def test_fp8_load_uses_the_checkpoint(monkeypatch):
+ _Cls.calls = []
+ sentinel = nn.Linear(2, 2)
+ monkeypatch.setattr(pq, "resolve_fp8_checkpoint", lambda *a, **k: "/x.safetensors")
+ monkeypatch.setattr(pq, "load_fp8_transformer", lambda *a, **k: sentinel)
+ assert dit._load_dit_transformer(_Cls, _cfg(), "cpu", "fp8") is sentinel
+ assert _Cls.calls == []
+
+
+def test_failed_fp8_conversion_dequantizes_the_prequant_base(monkeypatch, tmp_path):
+ path = tmp_path / "ck.safetensors"
+ q, s = _write_ckpt(path, _Tiny())
+ m = pq.load_fp8_transformer(_Tiny, _BASE, str(path), "cpu")
+ monkeypatch.setattr(dit, "_convert_fp8", lambda *a, **k: 1 / 0)
+ events = []
+ assert dit._apply_fp8_training(m, events.append) is False
+ assert [e["type"] for e in events] == ["warning"]
+ assert torch.equal(m.blk.lin.weight, (q.float() * s).bfloat16())
+ assert not hasattr(m.blk.lin, pq.PREQUANT_ATTR)