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 single-file fp8 on torchao under group offload, and keep Qwen-Image-2.1's timestep table in fp32 (#17127)
Daniel Han83e55c4801bc
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex bafa6cf6884..81732b52608 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -3803,10 +3803,15 @@ def _torchao_render_needs_no_grad(state: Any) -> bool:Stored fp8 codes too: moved under inference_mode they become unversionable, re-copied to host every offload."""if getattr(state, "offload_policy", OFFLOAD_NONE) == OFFLOAD_NONE:return False+ pipe = getattr(state, "pipe", None)return bool(getattr(state, "transformer_quant", None)or getattr(state, "text_encoder_quant", None)- or pipe_fp8_stored_layers(getattr(state, "pipe", None))+ or pipe_fp8_stored_layers(pipe)+ or any(+ comfy_torchao_quantized(getattr(pipe, attr, None))+ for attr in ("transformer", "transformer_2")+ ))@@ -9936,6 +9941,9 @@ class DiffusionBackend:elif comfy_scan is not None:# int8 / fp8 codes go to Studio's runtime unchanged where it runs; the rest dequantize._comfy_offload = self._comfy_offload_for(plan, single_file_path)+ _comfy_fp8_plan = (+ self._comfy_fp8_stream_plan(plan) if _comfy_offload else None+ )transformer = load_comfy_quant_transformer(transformer_cls,single_file_path,@@ -9952,6 +9960,7 @@ class DiffusionBackend:fam.name,base,offload = _comfy_offload,+ torchao_offload = _comfy_fp8_plan is not None,),**comfy_block_backends(comfy_scan,@@ -9973,6 +9982,8 @@ class DiffusionBackend:),)comfy_compile = comfy_torchao_quantized(transformer)+ if _comfy_fp8_plan is not None and comfy_compile:+ plan = _comfy_fp8_planelse:if kind != "gguf" and (not hasattr(transformer_cls, "from_single_file")@@ -11548,6 +11559,24 @@ class DiffusionBackend:priced = getattr(self, "_comfy_priced_offload", None) or {}return not plan_keeps_transformer_resident(plan) or bool(priced.get(str(single_file_path)))+ @staticmethod+ def _comfy_fp8_stream_plan(plan: Any) -> Any:+ """The streaming placement torchao fp8 takes under an offloaded ``plan`` (``torchao_offload_plan``), else None."""+ if plan_keeps_transformer_resident(plan):+ return None+ try:+ placed = torchao_offload_plan(plan, "fp8")+ except Exception: # noqa: BLE001 - an unanswerable probe keeps today's fp8 storage+ return None+ if placed is None or getattr(placed, "offload_policy", None) not in (+ OFFLOAD_GROUP,+ OFFLOAD_STREAMING,+ ):+ return None+ if plan_keeps_transformer_resident(placed):+ return None+ return placed+def _fp8_widen_for(self, single_file_path: Any, target: Any, loras: Any) -> bool:"""The planner's ``fp8_widen_chosen`` pick for this file, re-checked against device / LoRA / env: only thendoes the host RAM refusal reserve what that rule keeps free."""@@ -13350,8 +13379,7 @@ class DiffusionBackend:and transformer_resident is not Noneand not plan_keeps_transformer_resident(plan)):- # Offloaded: the loader probes the backends with offload=True (torchao fp8 does not survive the hooks), so- # price what that load builds, widened and fp8-stored, before choosing storage.+ # Offloaded: price what the offload=True loader builds, widened and fp8-stored, before choosing storage.offloaded = single_file_resident_at(False, True)if offloaded is not None and offloaded != transformer_resident:# Smaller (the int8 / fp8 twin only offload runs): the load keeps those backends even if the new plandiff --git a/studio/backend/core/inference/diffusion_comfy_quant.py b/studio/backend/core/inference/diffusion_comfy_quant.pyindex 9f557c2293d..339c89fa3aa 100644--- a/studio/backend/core/inference/diffusion_comfy_quant.py+++ b/studio/backend/core/inference/diffusion_comfy_quant.py@@ -54,6 +54,8 @@ _CONSUMED = {MXFP8: (".weight_scale", ".input_scale"),}_LEGACY_RENAME = {".scale_weight": ".weight_scale", ".scale_input": ".input_scale"}+# __init__ buffers kept as built: Qwen-Image-2.1's fp32 timestep table in bf16 moved renders (LPIPS 0.106 -> 0.174).+FP32_INIT_BUFFER_MODULES = frozenset({"QwenImage21TemporalTimesteps"})# Container prefixes a declaration may omit while its weight carries one._DECLARATION_PREFIXES = ("model.diffusion_model.", "diffusion_model.")@@ -996,6 +998,7 @@ def comfy_fp8_backend(base_repo: Optional[str] = None,*,offload: bool = False,+ torchao_offload: bool = False,) -> Optional[str]:"""Which of Studio's fp8 runtimes takes the ``float8_e4m3fn`` layers, by the rule its own fp8 quantfollows: ``"torchao"`` (the per-row ``Float8Tensor`` and ``_scaled_mm``) on a resident plan whose GPU@@ -1003,6 +1006,7 @@ def comfy_fp8_backend(quant runs natively (ROCm, the stubbed torchao), None (dequantize to bf16) where neither runs: anolder GPU, CPU, MPS, or an offloaded plan on the torchao path (the model offload hooks cannot move a``Float8Tensor``: "Attempted to set the storage of a tensor on device cuda:0 to a storage on ... cpu").+ ``torchao_offload``: the plan streams the denoiser (``torchao_offload_plan``), which torchao survives.``UNSLOTH_DIFFUSION_COMFY_FP8=0`` never takes an fp8 GEMM."""if (os.environ.get(COMFY_FP8_ENV) or "").strip().lower() in ("0", "off", "false", "no"):return None@@ -1018,7 +1022,7 @@ def comfy_fp8_backend(if native_quant_scheme(target, TQ_FP8, family = family, offload = offload) == TQ_FP8:return "native"if (- not offload+ (not offload or torchao_offload)and getattr(target, "dtype", None) is torch.bfloat16and select_transformer_quant_scheme(target, TQ_FP8, family = family, base_repo = base_repo)== TQ_FP8@@ -1782,6 +1786,8 @@ def load_comfy_quant_transformer(for module_name, module in model.named_modules():if module_name in block_native or module_name in block_packed:continue # fp32 scales / alpha the block kernels need; codes are not floating+ if type(module).__name__ in FP32_INIT_BUFFER_MODULES:+ continuefor buffer_name, buffer in list(module._buffers.items()):if (f"{module_name}.{buffer_name}" if module_name else buffer_name) in loaded:continuediff --git a/studio/backend/tests/test_diffusion_comfy_quant.py b/studio/backend/tests/test_diffusion_comfy_quant.pyindex abd20ad0cfc..e2eda1103ac 100644--- a/studio/backend/tests/test_diffusion_comfy_quant.py+++ b/studio/backend/tests/test_diffusion_comfy_quant.py@@ -739,18 +739,30 @@ def test_fp8_storage_keeps_fp32_modules_and_the_torchao_layers_apart(tmp_path, m@pytest.mark.parametrize(- "native, supported, offload, dtype, env, want",+ "native, supported, offload, streams, dtype, env, want",[- (None, "fp8", False, "bfloat16", None, "torchao"),- (None, "fp8", True, "bfloat16", None, None), # offloaded torchao fp8: dequantize, as before- (None, None, False, "bfloat16", None, None), # no fp8 GEMM (older GPU, CPU, MPS)- ("fp8", None, False, "bfloat16", None, "native"), # ROCm / stubbed torchao- (None, "fp8", False, "float16", None, None),- (None, "fp8", False, "bfloat16", "0", None), # kill switch+ (None, "fp8", False, False, "bfloat16", None, "torchao"),+ (+ None,+ "fp8",+ True,+ False,+ "bfloat16",+ None,+ None,+ ), # offloaded torchao fp8: dequantize, as before+ (None, "fp8", True, True, "bfloat16", None, "torchao"), # streamed through group offload+ (None, None, True, True, "bfloat16", None, None), # streamed, but no fp8 GEMM (A100)+ (None, "fp8", True, True, "float16", None, None),+ (None, "fp8", True, True, "bfloat16", "0", None),+ (None, None, False, False, "bfloat16", None, None), # no fp8 GEMM (older GPU, CPU, MPS)+ ("fp8", None, False, False, "bfloat16", None, "native"), # ROCm / stubbed torchao+ (None, "fp8", False, False, "float16", None, None),+ (None, "fp8", False, False, "bfloat16", "0", None), # kill switch],)def test_fp8_backend_follows_studios_own_fp8_rule(- monkeypatch, native, supported, offload, dtype, env, want+ monkeypatch, native, supported, offload, streams, dtype, env, want):import core.inference.diffusion_transformer_quant as tq@@ -761,7 +773,45 @@ def test_fp8_backend_follows_studios_own_fp8_rule(else:monkeypatch.setenv(cq.COMFY_FP8_ENV, env)target = types.SimpleNamespace(device = "cuda", dtype = getattr(torch, dtype))- assert cq.comfy_fp8_backend(target, "z-image", offload = offload) == want+ assert cq.comfy_fp8_backend(target, "z-image", offload = offload, torchao_offload = streams) == want+++ "policy, stream, placed, want",+ [+ ("group", True, "same", "same"),+ ("streaming", True, "same", "same"),+ # whole-module offload whose quantised parts do not fit: streamed, as Studio's own fp8 is+ ("model", True, "streaming", "streaming"),+ ("model", True, "same", None), # fits whole: whole-module offload keeps fp8 storage+ (+ "group",+ True,+ None,+ None,+ ), # torchao or diffusers too old, or the pin does not fit host RAM+ ("sequential", True, None, None),+ ("group", False, "same", None), # resident denoiser: the resident rule already applies+ ("none", True, "same", None),+ ],+)+def test_single_file_fp8_takes_torchao_only_when_offload_streams_it(+ monkeypatch, policy, stream, placed, want+):+ import core.inference.diffusion as d++ plan = types.SimpleNamespace(offload_policy = policy, stream_transformer = stream)+ streamed = types.SimpleNamespace(offload_policy = "streaming", stream_transformer = True)+ seen = []++ def offload_plan(p, scheme):+ seen.append(scheme)+ return {"same": p, "streaming": streamed, None: None}[placed]++ monkeypatch.setattr(d, "torchao_offload_plan", offload_plan)+ got = d.DiffusionBackend._comfy_fp8_stream_plan(plan)+ assert got is {"same": plan, "streaming": streamed, None: None}[want]+ assert seen in ([], ["fp8"])# ------------------------------------------------------------------------------------- hosted prequant route@@ -975,6 +1025,37 @@ def test_buffers_built_in_init_follow_the_compute_dtype(comfy_file):assert model.blocks[0].to_q.weight_q.dtype == torch.int8+def test_a_timestep_table_built_in_fp32_stays_fp32(comfy_file):+ """Qwen-Image-2.1's sinusoidal timestep table is computed in fp32; bf16 frequencies shift every timestep."""+ path, _, _ = comfy_file++ class QwenImage21TemporalTimesteps(nn.Module):+ def __init__(self) -> None:+ super().__init__()+ freqs = torch.exp(-torch.arange(0, 128, dtype = torch.float32) / 128 * 9.21)+ self.register_buffer("freqs", freqs, persistent = False)++ class _Timed(_Tiny):+ def __init__(self, **kwargs) -> None:+ super().__init__(**kwargs)+ self.time_proj = QwenImage21TemporalTimesteps()+ self.register_buffer("rope", torch.ones(4, dtype = torch.float32), persistent = False)++ model = cq.load_comfy_quant_transformer(+ _Timed,+ path,+ cq.refuse_comfy_quant(path),+ {"torch_dtype": torch.bfloat16, "config": "base/repo", "subfolder": "transformer"},+ int8_backend = "native",+ family = "qwen-image-2.1",+ )+ assert model.time_proj.freqs.dtype == torch.float32+ assert torch.equal(model.time_proj.freqs, QwenImage21TemporalTimesteps().freqs)+ assert (+ model.rope.dtype == torch.bfloat16+ ) # every other __init__ buffer still follows the compute dtype++def test_a_lora_on_stored_fp8_layers_is_refused_with_the_way_out(tmp_path, monkeypatch):"""Stored fp8 Linears are not nn.Linear: a generation-time LoRA is refused by name."""import threadingdiff --git a/studio/backend/tests/test_diffusion_offload_precision.py b/studio/backend/tests/test_diffusion_offload_precision.pyindex d67e860c1a1..1238f33bb96 100644--- a/studio/backend/tests/test_diffusion_offload_precision.py+++ b/studio/backend/tests/test_diffusion_offload_precision.py@@ -329,6 +329,27 @@ def test_offloaded_stored_fp8_renders_under_no_grad(policy, no_grad):assert vid._render_under_no_grad(state) is no_grad+ "policy, info, no_grad",+ [+ (OFFLOAD_STREAMING, {"fp8_backend": "torchao", "fp8": 229}, True),+ (OFFLOAD_GROUP, {"backend": "torchao", "int8": 8}, True),+ (OFFLOAD_NONE, {"fp8_backend": "torchao", "fp8": 229}, False),+ (OFFLOAD_STREAMING, {"fp8_backend": None, "fp8": 0}, False),+ ],+)+def test_streamed_single_file_torchao_renders_under_no_grad(policy, info, no_grad):+ """A single file's torchao layers carry no transformer_quant; a bf16 text encoder must not drop no_grad."""+ transformer = types.SimpleNamespace(_unsloth_comfy_quant = info)+ state = types.SimpleNamespace(+ offload_policy = policy,+ transformer_quant = None,+ text_encoder_quant = None,+ pipe = types.SimpleNamespace(transformer = transformer),+ )+ assert dmod._torchao_render_needs_no_grad(state) is no_grad++def test_render_uses_the_widened_switch():import inspect