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: pin inductor's reduction configs for LTX-2 compiles so renders match across servers (#12651)
Daniel Han05841349bb01
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 308e62b56c4..5f0ca4759ba 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -7014,6 +7014,7 @@ class DiffusionBackend:"vae_decode": vae_decode_compile_allowed(pipe, effective_speed),},logger = logger,+ reduction_filter = bool(getattr(fam, "filter_reduction_configs", False)),)self._raise_if_load_cancelled(_load_token)@@ -9044,6 +9045,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)),)object.__setattr__(state, "compile_cache_ctx", compile_ctx)speed_applied = apply_speed_optims(diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.pyindex 52a40c80188..d86d33e22b9 100644--- a/studio/backend/core/inference/diffusion_cache.py+++ b/studio/backend/core/inference/diffusion_cache.py@@ -40,6 +40,9 @@ FBCACHE_MIN_STEPS = 20# == diffusion_speed.SPEED_MAX, spelled out to keep this module import-free.AUTO_STEP_CACHE_TIER = "max"+# == diffusion_speed.REDUCTION_FILTER_OPTION, spelled out to keep this module import-free.+_REDUCTION_FILTER_OPTION = "test_configs.force_filter_reduction_configs"+def auto_step_cache_allowed(speed_mode: Optional[str]) -> bool:"""Takes the EFFECTIVE speed tier."""@@ -201,7 +204,11 @@ def _compile_hooked_block_inners(transformer: Any, logger: Any = None) -> int:# default tier. Dynamo caches per code object, so re-arming after a toggle is ~free.# Automatic dynamic when the speed layer chose it (max tier or torchao weights), as the blocks do.dynamic = None if getattr(transformer, "_unsloth_auto_dynamic", False) else True- compiled = torch.compile(orig, fullgraph = False, dynamic = dynamic)+ # Same reduction-config filter as the blocks (diffusion_speed.pin_reduction_configs).+ block_kwargs = getattr(transformer, "_unsloth_regional_compile_kwargs", None) or {}+ pinned = (block_kwargs.get("options") or {}).get(_REDUCTION_FILTER_OPTION)+ extra = {"options": {_REDUCTION_FILTER_OPTION: True}} if pinned else {}+ compiled = torch.compile(orig, fullgraph = False, dynamic = dynamic, **extra)# Same runtime fallback as the block's own compile: a lowering failure on the first computed step# restores the eager inner instead of failing the render.guard = getattr(transformer, "_unsloth_compile_guard", None)diff --git a/studio/backend/core/inference/diffusion_compile_cache.py b/studio/backend/core/inference/diffusion_compile_cache.pyindex b6552bca3f3..3be9c6dfb91 100644--- a/studio/backend/core/inference/diffusion_compile_cache.py+++ b/studio/backend/core/inference/diffusion_compile_cache.py@@ -291,6 +291,7 @@ def model_fingerprint(attention_backend: Any,compile_kwargs: dict[str, Any],shape_bucket: Any = None,+ reduction_filter: bool = False,) -> dict[str, Any]:"""MODEL-graph dimensions that change the compiled artifact.@@ -329,10 +330,13 @@ def model_fingerprint(if dynamic_text:fp["dynamic_text"] = dynamic_text# Inductor keys graphs on dynamic_scale_rblock: an old bundle would hit, miss every graph, and never be rewritten.- from .diffusion_compile_config import reduction_blocks_pinned+ from .diffusion_compile_config import reduction_blocks_pinned, reduction_config_filter_availableif reduction_blocks_pinned():fp["inductor"] = {"dynamic_scale_rblock": False}+ # Only for a family whose compile pins the reduction-config filter, so every other bundle keeps its key.+ if reduction_filter and reduction_config_filter_available():+ fp["inductor"]["force_filter_reduction_configs"] = Truereturn fp@@ -384,6 +388,7 @@ def begin(compile_kwargs: dict[str, Any],shape_bucket: Any = None,logger: Any = None,+ reduction_filter: bool = False,) -> Optional[CacheContext]:"""Point inductor at a per-key dir and load a matching bundle, BEFORE compile.@@ -414,6 +419,7 @@ def begin(attention_backend = attention_backend,compile_kwargs = compile_kwargs,shape_bucket = shape_bucket,+ reduction_filter = reduction_filter,)key = cache_key(env_fp, model_fp)cdir = cache_root() / keydiff --git a/studio/backend/core/inference/diffusion_compile_config.py b/studio/backend/core/inference/diffusion_compile_config.pyindex 1f7d1147849..42f88ea6cba 100644--- a/studio/backend/core/inference/diffusion_compile_config.py+++ b/studio/backend/core/inference/diffusion_compile_config.py@@ -12,7 +12,8 @@ from contextvars import ContextVarfrom typing import Any# dynamic_scale_rblock benchmarks R0_BLOCK vs R0_BLOCK/2 per process (never cached); the two sum in different orders,-# so renders differed across servers on one seed (FLUX.1-schnell int8, B200). =1 restores inductor's default.+# so renders differed across servers on one seed (FLUX.1-schnell int8, B200). =1 restores inductor's default, and also+# drops the per-family reduction-config filter (diffusion_speed.pin_reduction_configs).DYNAMIC_SCALE_RBLOCK_ENV = "UNSLOTH_DIFFUSION_DYNAMIC_SCALE_RBLOCK"@@ -22,6 +23,17 @@ def reduction_blocks_pinned() -> bool:return raw not in ("1", "on", "true", "yes")+def reduction_config_filter_available() -> bool:+ """torch has the reduction-config filter (2.10+) and the kill switch is unset."""+ if not reduction_blocks_pinned():+ return False+ try:+ import torch+ return hasattr(torch._inductor.config.test_configs, "force_filter_reduction_configs")+ except Exception: # noqa: BLE001 - no torch / inductor: nothing pinned+ return False++_LOCK = threading.Lock()_KNOBS: dict[tuple[str, str], Any] = {}_generation = 0diff --git a/studio/backend/core/inference/diffusion_speed.py b/studio/backend/core/inference/diffusion_speed.pyindex fe857916a1f..32f7490124f 100644--- a/studio/backend/core/inference/diffusion_speed.py+++ b/studio/backend/core/inference/diffusion_speed.py@@ -65,6 +65,7 @@ _INDUCTOR_FLAGS = ()_INDUCTOR_TRITON_FLAGS = (("unique_kernel_names", "inductor_triton_unique_kernel_names"),)_DYNAMO_MODULE = "torch._dynamo.config"+REDUCTION_FILTER_OPTION = "test_configs.force_filter_reduction_configs"_INDUCTOR_MODULE = "torch._inductor.config"_INDUCTOR_TRITON_MODULE = "torch._inductor.config.triton"@@ -471,6 +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))applied["vae_single_frame"] = _vae_single_frame(pipe, logger)# Lossless: a channels-last VAE speeds up its convs with no numeric change.@@ -515,6 +517,7 @@ def apply_speed_optims(cache_active = cache_active,offload_active = offload_active,denoiser_offloaded = denoiser_offloaded,+ filter_reductions = filter_reductions,)elif (mode == SPEED_MAX@@ -528,6 +531,7 @@ def apply_speed_optims(cache_active = cache_active,offload_active = offload_active,denoiser_offloaded = denoiser_offloaded,+ filter_reductions = filter_reductions,)if applied["compiled"]:@@ -869,6 +873,7 @@ def _compile_repeated_blocks(cache_active: bool = False,offload_active: bool = False,denoiser_offloaded: Optional[bool] = None,+ filter_reductions: bool = False,) -> bool:dits = [t for t in _denoiser_dits(pipe) if callable(getattr(t, "compile_repeated_blocks", None))@@ -902,6 +907,8 @@ def _compile_repeated_blocks(}if max_autotune:kwargs["mode"] = "max-autotune-no-cudagraphs"+ if filter_reductions:+ pin_reduction_configs(kwargs, logger)try:import torch@@ -945,6 +952,8 @@ def _compile_repeated_blocks(unet_kwargs: dict[str, Any] = {"fullgraph": kwargs["fullgraph"], "dynamic": False}if max_autotune:unet_kwargs["mode"] = "max-autotune-no-cudagraphs"+ if filter_reductions:+ pin_reduction_configs(unet_kwargs, logger)try:unet.compile(**unet_kwargs)return True@@ -1042,6 +1051,28 @@ def _compile_repeated_blocks(return engaged+def pin_reduction_configs(kwargs: dict[str, Any], logger: Any = None) -> bool:+ """Keep one config per multi-config reduction instead of a per-process benchmark whose pick changes the sum order+ (LTX-2 block RMSNorm: R0_BLOCK 4096 vs 2048 tie on B200, half the servers rendered another clip). Per-compile+ ``options`` (``mode`` folded in), never the global knob: HunyuanVideo-1.5 is ~2% slower per step with it.+ config.deterministic is unusable: dynamo resets it after the first frame. Returns True when engaged."""+ if not compile_config.reduction_config_filter_available():+ return False+ try:+ options = dict(kwargs.get("options") or {})+ mode = kwargs.get("mode")+ if mode is not None:+ from torch._inductor import list_mode_options+ options = {**list_mode_options(mode, kwargs.get("dynamic")), **options}+ options[REDUCTION_FILTER_OPTION] = True+ except Exception as exc: # noqa: BLE001 - optimisation only+ _warn(logger, "reduction config filter", exc)+ return False+ kwargs.pop("mode", None)+ kwargs["options"] = options+ return True++def _install_inductor_backports(logger: Any) -> bool:"""Probe-gated backport of torch 2.14's CantSplit divisibility proof for 2.12 / 2.13. Never fails a load."""try:diff --git a/studio/backend/core/inference/video_families.py b/studio/backend/core/inference/video_families.pyindex 483efd29d7c..02d5a3f69e5 100644--- a/studio/backend/core/inference/video_families.py+++ b/studio/backend/core/inference/video_families.py@@ -92,6 +92,9 @@ class VideoFamily:vae_force_fp32: bool = False# False holds cudnn.benchmark off: its per-process conv pick makes servers decode the same latents differently.cudnn_benchmark: bool = True+ # One config per reduction instead of a per-process benchmark that can change the render (diffusion_speed.+ # pin_reduction_configs). Off by default: it can keep a slower config (HunyuanVideo-1.5 ~2% per step).+ filter_reduction_configs: bool = False# Curated GGUF repo for the picker (the DiT as single-file GGUF quants).gguf_repo: Optional[str] = None# Hosted PRE-CAST text-encoder checkpoints as (scheme, component, repo_id); same semantics as@@ -267,6 +270,8 @@ _FAMILIES: tuple[VideoFamily, ...] = (prequant_variant_repos = (("lightricks/ltx-2.3", "fp8", "unsloth/LTX-2.3-FP8"),),# no steady gain on LTX's VAE / vocoder convs, but a per-shape re-tune (first render 26 s vs 10 s)cudnn_benchmark = False,+ # Block RMSNorm (hidden 4096) R0_BLOCK 4096 vs 2048 tie on B200: 3 of 6 cold servers rendered another clip.+ filter_reduction_configs = True,),# Wan2.2-TI2V-5B (diffusers >= 0.35, verified on 0.39): ~5B single-stream DiT (UMT5 encoder), no audio. Its VAE's# temporal compression 4 gives valid frame counts 4k+1. Defaults 20 steps / CFG 5 (ComfyUI's template).diff --git a/studio/backend/tests/test_diffusion_reduction_rblock.py b/studio/backend/tests/test_diffusion_reduction_rblock.pyindex 1725df98577..0106ff3e3da 100644--- a/studio/backend/tests/test_diffusion_reduction_rblock.py+++ b/studio/backend/tests/test_diffusion_reduction_rblock.py@@ -29,11 +29,15 @@ _KILL_SWITCH = "UNSLOTH_DIFFUSION_DYNAMIC_SCALE_RBLOCK"@pytest.fixture(autouse = True)def _clean(monkeypatch):before = (_INDUCTOR.dynamic_scale_rblock, _INDUCTOR.emulate_precision_casts)+ test_cfg = _INDUCTOR.test_configs+ before_filter = getattr(test_cfg, "force_filter_reduction_configs", None)monkeypatch.delenv(_KILL_SWITCH, raising = False)cc._reset_for_tests()yieldcc._reset_for_tests()_INDUCTOR.dynamic_scale_rblock, _INDUCTOR.emulate_precision_casts = before+ if before_filter is not None:+ test_cfg.force_filter_reduction_configs = before_filterclass _Transformer:@@ -209,3 +213,240 @@ def test_pinned_reduction_has_one_block_size_and_the_default_has_two(monkeypatchpinned_seen, sha_pinned = _run_counting_reduction_autotunes(monkeypatch, tmp_path / "pinned")assert pinned_seen == []assert sha_pinned in (sha_small, sha_large)+++# Per-family reduction-config filter (diffusion_speed.pin_reduction_configs): per compile only, never the global knob.++_FILTER = "test_configs.force_filter_reduction_configs"+_HAS_FILTER = hasattr(_INDUCTOR.test_configs, "force_filter_reduction_configs")+_needs_filter = pytest.mark.skipif(+ not _HAS_FILTER, reason = "torch has no inductor reduction-config filter"+)+++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 _filter_reaching_compile(monkeypatch, family):+ """What apply_speed_optims hands the regional compile for ``family`` on a bf16 CUDA target, default tier."""+ 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"]+++def test_only_ltx_opts_into_the_reduction_filter(monkeypatch):+ assert _filter_reaching_compile(monkeypatch, _family("ltx-2")) is True+ for name in ("hunyuanvideo-1.5", "wan2.2-ti2v-5b", "flux.1"):+ assert _filter_reaching_compile(monkeypatch, _family(name)) is False, name+++def _compiled_kwargs(max_autotune = False, filter_reductions = False):+ pipe = types.SimpleNamespace(transformer = _Transformer())+ assert (+ ds._compile_repeated_blocks(+ pipe, None, max_autotune = max_autotune, filter_reductions = filter_reductions+ )+ is True+ )+ return pipe.transformer.kwargs+++@_needs_filter[email protected]("max_autotune", [False, True])+def test_opted_in_compile_carries_the_filter_and_leaves_the_process_knob(max_autotune):+ _INDUCTOR.test_configs.force_filter_reduction_configs = False+ kwargs = _compiled_kwargs(max_autotune, filter_reductions = True)+ assert kwargs["options"][_FILTER] is True+ # torch.compile takes mode or options: max's mode is folded into the options.+ assert "mode" not in kwargs+ if max_autotune:+ assert kwargs["options"]["max_autotune"] is True+ assert _INDUCTOR.test_configs.force_filter_reduction_configs is False+ assert not cc.is_recorded(+ "torch._inductor.config.test_configs", "force_filter_reduction_configs"+ )++[email protected]("max_autotune", [False, True])+def test_other_families_compile_with_inductor_default(max_autotune):+ kwargs = _compiled_kwargs(max_autotune, filter_reductions = False)+ assert "options" not in kwargs+ assert ("mode" in kwargs) is max_autotune+++@_needs_filter+def test_kill_switch_drops_the_filter(monkeypatch):+ monkeypatch.setenv(_KILL_SWITCH, "1")+ kwargs = _compiled_kwargs(filter_reductions = True)+ assert "options" not in kwargs+++@_needs_filter+def test_bundle_key_carries_the_filter_only_when_set(monkeypatch):+ plain = _fingerprint()+ assert plain["inductor"] == {"dynamic_scale_rblock": False}+ filtered = cache.model_fingerprint(+ family = "ltx-2",+ transformer = None,+ dtype = "torch.bfloat16",+ quant = "int8",+ attention_backend = "_native_cudnn",+ compile_kwargs = {"fullgraph": True, "dynamic": None, "mode": "default"},+ reduction_filter = True,+ )+ assert filtered["inductor"] == {+ "dynamic_scale_rblock": False,+ "force_filter_reduction_configs": True,+ }+ monkeypatch.setenv(_KILL_SWITCH, "1")+ assert "inductor" not in cache.model_fingerprint(+ family = "ltx-2",+ transformer = None,+ dtype = "torch.bfloat16",+ quant = "int8",+ attention_backend = "_native_cudnn",+ compile_kwargs = {"fullgraph": True, "dynamic": None, "mode": "default"},+ reduction_filter = True,+ )+++def _wan_like_block_head():+ """Wan TI2V-5B block head: fp32 LayerNorm of the bf16 stream, per-token AdaLN modulation, then a Linear."""++ class Head(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.norm = torch.nn.LayerNorm(3072, elementwise_affine = False, eps = 1e-6)+ self.table = torch.nn.Parameter(torch.randn(1, 6, 3072) / 3072**0.5)+ self.proj = torch.nn.Linear(3072, 3072)++ def forward(self, x, temb):+ shift, scale, *_ = (self.table.unsqueeze(0) + temb.float()).chunk(6, dim = 2)+ h = (self.norm(x.float()) * (1 + scale.squeeze(2)) + shift.squeeze(2)).type_as(x)+ return self.proj(h)++ torch.manual_seed(0)+ head = Head().cuda()+ head.proj.to(torch.bfloat16)+ x = (torch.randn(1, 6160, 3072, device = "cuda") * 4 + 0.3).to(torch.bfloat16)+ temb = (torch.randn(1, 6160, 6, 3072, device = "cuda") * 0.5).to(torch.bfloat16)+ return head, (x, temb)+++def _ltx_like_block_norm():+ """LTX-2.3 block head at 768x512x121: fp32-stat RMSNorm over hidden 4096, per-token AdaLN modulation, a Linear.+ The norm weight keeps both summation orders visible in the output on every torch."""++ class Head(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.table = torch.nn.Parameter(torch.randn(6, 4096) / 64)+ self.weight = torch.nn.Parameter(1 + 0.1 * torch.randn(4096))+ self.proj = torch.nn.Linear(4096, 4096)++ def forward(self, x, temb):+ shift, scale, *_ = (+ self.table[None, None] + temb.reshape(1, temb.shape[1], 6, -1)+ ).unbind(dim = 2)+ h = x.float()+ normed = (+ h * torch.rsqrt(h.pow(2).mean(-1, keepdim = True) + 1e-6) * self.weight.float()+ ).to(x.dtype)+ return self.proj(normed * (1 + scale) + shift)++ torch.manual_seed(0)+ head = Head().cuda().to(torch.bfloat16)+ x = (torch.randn(1, 6144, 4096, device = "cuda") * 3 + 0.2).to(torch.bfloat16)+ temb = (torch.randn(1, 6144, 6 * 4096, device = "cuda") * 0.5).to(torch.bfloat16)+ return head, (x, temb)+++def _run_norm(+ monkeypatch,+ tmp_path,+ *,+ force_r0_block = None,+ build = None,+ compile_kwargs = None,+):+ from torch._inductor.runtime import triton_heuristics++ monkeypatch.setenv("TORCHINDUCTOR_CACHE_DIR", str(tmp_path / "inductor"))+ monkeypatch.setenv("TRITON_CACHE_DIR", str(tmp_path / "triton"))+ from torch._inductor.codecache import PyCodeCache++ torch._dynamo.reset()+ PyCodeCache.cache_clear()+ seen = []+ real = triton_heuristics.CachingAutotuner.autotune_to_one_config++ def autotune(self, *args, **kwargs):+ blocks = sorted(+ {launcher.config.kwargs.get("R0_BLOCK") for launcher in self.launchers} - {None}+ )+ if len(blocks) > 1:+ seen.append(blocks)+ if force_r0_block in blocks:+ self.launchers = [+ l for l in self.launchers if l.config.kwargs.get("R0_BLOCK") == force_r0_block+ ]+ return None+ return real(self, *args, **kwargs)++ monkeypatch.setattr(triton_heuristics.CachingAutotuner, "autotune_to_one_config", autotune)+ head, inputs = (build or _wan_like_block_head)()+ with torch.no_grad():+ out = torch.compile(head, **(compile_kwargs or {"fullgraph": True, "dynamic": False}))(+ *inputs+ )+ torch.cuda.synchronize()+ torch._dynamo.reset()+ return seen, hashlib.sha256(out.float().cpu().numpy().tobytes()).hexdigest()+++@_needs_filter+ "build", [_wan_like_block_head, _ltx_like_block_norm], ids = ["wan_layernorm", "ltx23_rmsnorm"]+)+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:+ pytest.skip("needs an sm80+ CUDA GPU")+ pytest.importorskip("triton")+ _INDUCTOR.emulate_precision_casts = True+ _INDUCTOR.dynamic_scale_rblock = False+ _INDUCTOR.test_configs.force_filter_reduction_configs = False+ default_seen, _ = _run_norm(monkeypatch, tmp_path / "default", build = build)+ if not default_seen:+ pytest.skip("the reduction heuristic gives this GPU's norm a single config")+ small, large = min(default_seen[0]), max(default_seen[0])+ _, sha_small = _run_norm(monkeypatch, tmp_path / "small", force_r0_block = small, build = build)+ _, sha_large = _run_norm(monkeypatch, tmp_path / "large", force_r0_block = large, build = build)+ # The per-process benchmark decides the summation order: that is the cross-server drift.+ assert sha_small != sha_large+ kwargs = {"fullgraph": True, "dynamic": False}+ assert ds.pin_reduction_configs(kwargs) is True+ pinned_seen, sha_pinned = _run_norm(+ monkeypatch, tmp_path / "pinned", build = build, compile_kwargs = kwargs+ )+ assert pinned_seen == []+ assert sha_pinned in (sha_small, sha_large)+ # Per compile only: the same process compiling without the option still sees inductor's configs.+ assert _INDUCTOR.test_configs.force_filter_reduction_configs is False+ after_seen, _ = _run_norm(monkeypatch, tmp_path / "after", build = build)+ assert after_seen == default_seen