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: deterministic FLUX.1, Z-Image and Qwen-Image renders on sm80, sm89 and sm120 (#12674)
Daniel Han1170b038119a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 927aa3ba291..9a9653d15f7 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -197,6 +197,7 @@ from .diffusion_attention import (_ensure_attention_backend_installed,)from . import diffusion_compile_cache as compile_cache+from .diffusion_compile_config import family_filters_reductionsfrom . import diffusion_cond_cache as cond_cachefrom . import diffusion_prompt_cache as prompt_cachefrom . import diffusion_gguf_compile as gguf_compile@@ -7079,7 +7080,7 @@ class DiffusionBackend:"vae_decode": vae_decode_compile_allowed(pipe, effective_speed),},logger = logger,- reduction_filter = bool(getattr(fam, "filter_reduction_configs", False)),+ reduction_filter = family_filters_reductions(fam),)self._raise_if_load_cancelled(_load_token)@@ -9176,7 +9177,7 @@ class DiffusionBackend:"vae_decode": vae_decode_compile_allowed(state.pipe, SPEED_DEFAULT),},logger = logger,- reduction_filter = bool(getattr(state.family, "filter_reduction_configs", False)),+ reduction_filter = family_filters_reductions(state.family),)object.__setattr__(state, "compile_cache_ctx", compile_ctx)speed_applied = apply_speed_optims(diff --git a/studio/backend/core/inference/diffusion_compile_config.py b/studio/backend/core/inference/diffusion_compile_config.pyindex 42f88ea6cba..60d7a4d7c5b 100644--- a/studio/backend/core/inference/diffusion_compile_config.py+++ b/studio/backend/core/inference/diffusion_compile_config.py@@ -34,6 +34,29 @@ def reduction_config_filter_available() -> bool:return False+def family_filters_reductions(family: Any) -> bool:+ """``filter_reduction_configs`` on every arch, or the current CUDA device listed in ``filter_reduction_configs_archs``."""+ if family is None:+ return False+ if bool(getattr(family, "filter_reduction_configs", False)):+ return True+ archs = getattr(family, "filter_reduction_configs_archs", None) or ()+ if not archs:+ return False+ cap = _device_capability()+ return cap is not None and cap in {tuple(int(v) for v in a) for a in archs}+++def _device_capability() -> Any:+ try:+ import torch+ if not torch.cuda.is_available() or getattr(torch.version, "hip", None):+ return None+ return tuple(int(v) for v in torch.cuda.get_device_capability())+ except Exception: # noqa: BLE001 - no CUDA: nothing pinned+ return None++_LOCK = threading.Lock()_KNOBS: dict[tuple[str, str], Any] = {}_generation = 0diff --git a/studio/backend/core/inference/diffusion_families.py b/studio/backend/core/inference/diffusion_families.pyindex 68f57f2ee19..1e92fbcecf1 100644--- a/studio/backend/core/inference/diffusion_families.py+++ b/studio/backend/core/inference/diffusion_families.py@@ -130,6 +130,8 @@ class DiffusionFamily:supports_torch_compile: bool = True# False keeps cudnn.benchmark off (as VideoFamily.cudnn_benchmark): its per-process conv pick changes pixels.cudnn_benchmark: bool = True+ # (major, minor) archs on which the compile pins inductor's reduction-config filter; empty = inductor's pick.+ filter_reduction_configs_archs: tuple[tuple[int, int], ...] = field(default_factory = tuple)# Optional pre-quantized transformer checkpoints as (scheme, repo_id): fetched instead of the dense bf16 (lower# load VRAM + download).prequant_repos: tuple[tuple[str, str], ...] = field(default_factory = tuple)@@ -205,11 +207,16 @@ class DiffusionFamily:return self.deploy_base_repo or trained_base+# Fresh servers rendered 2-4 variants of one seed here (FLUX.1, Z-Image, Qwen-Image; the edit siblings share their DiT):+# near-tied norm-reduction configs, benchmarked per process, sum in different orders. B200 measured deterministic.+_REDUCTION_RACE_ARCHS: tuple[tuple[int, int], ...] = ((8, 0), (8, 9), (12, 0))+# Keyed by architecture, not per variant: the base repo is read from the HF base_model tag at load time, so one entry# covers Turbo/full, schnell/dev._FAMILIES: tuple[DiffusionFamily, ...] = (DiffusionFamily(name = "flux.1",+ filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,cudnn_benchmark = False,pipeline_class = "FluxPipeline",transformer_class = "FluxTransformer2DModel",@@ -322,6 +329,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (# FLUX instruction editing: FluxKontextPipeline takes an image + instruction. Specific aliases first so# detect_family prefers this over "flux.1".name = "flux.1-kontext",+ filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,pipeline_class = "FluxKontextPipeline",transformer_class = "FluxTransformer2DModel",base_repo = "black-forest-labs/FLUX.1-Kontext-dev",@@ -332,6 +340,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (# Qwen instruction editing: the 2511 checkpoint ships as QwenImageEditPlusPipeline. Specific aliases first so# detect_family prefers this over "qwen-image".name = "qwen-image-edit",+ filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,comfy_flow_shift = 3.1, # ComfyUI ModelSamplingAuraFlow 3.1 (Qwen-Image-Edit 2511 template)# The 2509 template samples at ModelSamplingAuraFlow 3.comfy_flow_shift_variants = (("qwen-image-edit-2509", 3.0),),@@ -352,6 +361,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (),DiffusionFamily(name = "qwen-image",+ filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,comfy_flow_shift = 3.1, # ComfyUI ModelSamplingAuraFlow 3.1 (Qwen-Image templates)pipeline_class = "QwenImagePipeline",transformer_class = "QwenImageTransformer2DModel",@@ -500,6 +510,7 @@ _FAMILIES: tuple[DiffusionFamily, ...] = (),DiffusionFamily(name = "z-image",+ filter_reduction_configs_archs = _REDUCTION_RACE_ARCHS,cudnn_benchmark = False,comfy_flow_shift = 3.0, # ComfyUI shift 3 for Turbo and base (Turbo already ships 3.0)pipeline_class = "ZImagePipeline",diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex 2d880ce582a..0bc5dccc672 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -472,7 +472,7 @@ def apply_speed_optims(on_cuda = getattr(target, "device", None) == "cuda"family_allows_compile = bool(getattr(family, "supports_torch_compile", True))- filter_reductions = bool(getattr(family, "filter_reduction_configs", False))+ filter_reductions = compile_config.family_filters_reductions(family)applied["vae_single_frame"] = _vae_single_frame(pipe, logger)# Lossless: a channels-last VAE speeds up its convs with no numeric change.diff --git a/studio/backend/tests/test_diffusion_reduction_filter_arch.py b/studio/backend/tests/test_diffusion_reduction_filter_arch.pynew file mode 100644index 00000000000..ad833981fe3--- /dev/null+++ b/studio/backend/tests/test_diffusion_reduction_filter_arch.py@@ -0,0 +1,133 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""FLUX.1, Z-Image and Qwen-Image pin inductor's reduction-config filter on sm120, sm80 and sm89, so one seed renders+one image in every fresh server there.++A few of their norm reductions get several configs that sum in different orders, and a cold-cache server benchmarks+them in its own process on near-equal timings: fresh servers rendered 2-4 variants per seed on an RTX PRO 6000, A100+and L4. B200 servers were already deterministic for these families, so the opt-in is per (family, compute+capability)."""++from __future__ import annotations++import types++import pytest++torch = pytest.importorskip("torch")++from core.inference import diffusion_compile_config as cc # noqa: E402+from core.inference import diffusion_speed as ds # noqa: E402++_SM120 = (12, 0)+_MEASURED_ARCHS = ((8, 0), (8, 9), (12, 0))+_IMAGE_FAMILIES = ("flux.1", "z-image", "qwen-image", "flux.1-kontext", "qwen-image-edit")+++def _family(name):+ from core.inference import diffusion_families, video_families+ for fam in (*video_families._FAMILIES, *diffusion_families._FAMILIES):+ if fam.name == name:+ return fam+ raise AssertionError(f"no family {name}")+++def _on(monkeypatch, cap):+ monkeypatch.setattr(cc, "_device_capability", lambda: cap)+++def _filter_reaching_compile(monkeypatch, family):+ seen = {}++ def fake_compile(pipe, logger, **kwargs):+ seen.update(kwargs)+ return False++ monkeypatch.setattr(ds, "compile_eligible", lambda *a, **k: True)+ monkeypatch.setattr(ds, "_compile_repeated_blocks", fake_compile)+ target = types.SimpleNamespace(device = "cpu", dtype = torch.bfloat16, backend = "cuda")+ ds.apply_speed_optims(+ types.SimpleNamespace(), target, is_gguf = False, family = family, speed_mode = ds.SPEED_DEFAULT+ )+ return seen["filter_reductions"]++[email protected]("cap", _MEASURED_ARCHS)[email protected]("name", _IMAGE_FAMILIES)+def test_image_family_opts_in_on_the_measured_archs(monkeypatch, name, cap):+ fam = _family(name)+ assert cap in fam.filter_reduction_configs_archs+ _on(monkeypatch, cap)+ assert cc.family_filters_reductions(fam) is True+ assert _filter_reaching_compile(monkeypatch, fam) is True+++def test_the_race_families_share_one_arch_list():+ from core.inference import diffusion_families+ for name in _IMAGE_FAMILIES:+ assert (+ _family(name).filter_reduction_configs_archs == diffusion_families._REDUCTION_RACE_ARCHS+ )+ assert set(diffusion_families._REDUCTION_RACE_ARCHS) == set(_MEASURED_ARCHS)++[email protected]("cap", [(10, 0), (10, 3), (9, 0), (7, 5), (12, 1), None])[email protected]("name", _IMAGE_FAMILIES)+def test_image_family_keeps_inductor_pick_elsewhere(monkeypatch, name, cap):+ # B200 (measured deterministic), B300, H100, T4, other Blackwell parts (unmeasured), no CUDA / ROCm.+ _on(monkeypatch, cap)+ fam = _family(name)+ assert cc.family_filters_reductions(fam) is False+ assert _filter_reaching_compile(monkeypatch, fam) is False++[email protected]("name", ["sdxl", "hunyuanvideo-1.5", "wan2.2-ti2v-5b"])+def test_unmeasured_families_stay_off_on_sm120(monkeypatch, name):+ _on(monkeypatch, _SM120)+ assert cc.family_filters_reductions(_family(name)) is False+++def test_all_arch_opt_in_still_applies_everywhere(monkeypatch):+ for cap in (_SM120, (10, 0), None):+ _on(monkeypatch, cap)+ assert cc.family_filters_reductions(_family("ltx-2")) is True+++def test_no_family_or_plain_object(monkeypatch):+ _on(monkeypatch, _SM120)+ assert cc.family_filters_reductions(None) is False+ assert cc.family_filters_reductions(types.SimpleNamespace()) is False+ assert (+ cc.family_filters_reductions(+ types.SimpleNamespace(filter_reduction_configs_archs = [[12, 0]])+ )+ is True+ )+++def test_capability_query_never_raises(monkeypatch):+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)+ monkeypatch.setattr(torch.version, "hip", None, raising = False)++ def boom(*a, **k):+ raise RuntimeError("no device")++ monkeypatch.setattr(torch.cuda, "get_device_capability", boom)+ assert cc._device_capability() is None+ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda *a, **k: (12, 0))+ assert cc._device_capability() == _SM120+ monkeypatch.setattr(torch.version, "hip", "6.4", raising = False)+ assert cc._device_capability() is None+++def test_load_paths_key_the_bundle_on_the_same_decision():+ # The bundle key follows the arch-scoped decision, else a load reuses a bundle compiled the other way.+ import inspect++ from core.inference import diffusion++ src = inspect.getsource(diffusion)+ assert src.count("reduction_filter = family_filters_reductions(") == 2+ assert 'getattr(fam, "filter_reduction_configs"' not in src+ assert 'getattr(state.family, "filter_reduction_configs"' not in srcdiff --git a/studio/backend/tests/test_diffusion_reduction_rblock.py b/studio/backend/tests/test_diffusion_reduction_rblock.pyindex 0106ff3e3da..1fab5d812a2 100644--- a/studio/backend/tests/test_diffusion_reduction_rblock.py+++ b/studio/backend/tests/test_diffusion_reduction_rblock.py@@ -250,6 +250,8 @@ def _filter_reaching_compile(monkeypatch, family):def test_only_ltx_opts_into_the_reduction_filter(monkeypatch):+ # Off sm120, where the image families' arch-scoped opt-in (test_diffusion_reduction_filter_arch.py) is inert.+ monkeypatch.setattr(cc, "_device_capability", lambda: (10, 0))assert _filter_reaching_compile(monkeypatch, _family("ltx-2")) is Truefor name in ("hunyuanvideo-1.5", "wan2.2-ti2v-5b", "flux.1"):assert _filter_reaching_compile(monkeypatch, _family(name)) is False, name@@ -376,6 +378,28 @@ def _ltx_like_block_norm():return head, (x, temb)+def _qwen_like_text_norm():+ """Qwen-Image block, text stream: LayerNorm (no affine, eps 1e-6, fp32 statistics) over the 3072 hidden of 64 bf16+ text tokens, then the AdaLN modulation (shift / scale chunks of the timestep embedding, addcmul). With the int8+ GEMM's bf16 producer on sm120 this reduction gets R0_BLOCK 4096 (one Welford pass) and 2048 (two, then combined).+ The modulated output stays fp32 here so the two statistics orders show on every GPU."""++ class Head(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.norm = torch.nn.LayerNorm(3072, elementwise_affine = False, eps = 1e-6)++ def forward(self, x, mod):+ shift, scale = mod.float().chunk(2, dim = -1)+ return torch.addcmul(shift.unsqueeze(1), self.norm(x.float()), 1 + scale.unsqueeze(1))++ torch.manual_seed(0)+ head = Head().cuda()+ x = (torch.randn(1, 64, 3072, device = "cuda") * 3 + 0.2).to(torch.bfloat16)+ mod = (torch.randn(1, 6144, device = "cuda") * 0.5).to(torch.bfloat16)+ return head, (x, mod)++def _run_norm(monkeypatch,tmp_path,@@ -422,7 +446,9 @@ def _run_norm(@pytest.mark.gpu@_needs_filter@pytest.mark.parametrize(- "build", [_wan_like_block_head, _ltx_like_block_norm], ids = ["wan_layernorm", "ltx23_rmsnorm"]+ "build",+ [_wan_like_block_head, _ltx_like_block_norm, _qwen_like_text_norm],+ ids = ["wan_layernorm", "ltx23_rmsnorm", "qwen_image_text_layernorm"],)def test_filter_option_gives_the_norm_one_config(monkeypatch, tmp_path, build):if not torch.cuda.is_available() or torch.cuda.get_device_capability()[0] < 8: