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: build the CFG-parallel replica outside inference mode and catch in-place edits of inference weights (#14626)
Daniel Hand5f0d8b8f456
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 6a3b7e8c0ee..5f4910990a4 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -12011,6 +12011,7 @@ class DiffusionBackend:passpipe._unsloth_loras = ()cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)returnif _small_host_int8(pipe):@@ -12074,10 +12075,12 @@ class DiffusionBackend:# The adapters the graphs were captured with are gone and the marker says none are applied,# so no later call reaches the resets above; without this a base-model render replays them.cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)raise ValueError(f"Failed to apply LoRA: {exc}") from excpipe._unsloth_loras = desired# load_lora_weights can re-materialise parameters the graphs baked pointers to.cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)def _adjust_baked_loras(self,@@ -12115,6 +12118,7 @@ class DiffusionBackend:pipe._unsloth_loras = disabled# Adapter scales are Python values read inside the LoRA forward, so a graph bakes them in.cuda_graph.reset_all(getattr(state, "cuda_graphs", ()))+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)returndesired = self._resolve_lora_set(specs,@@ -12148,6 +12152,7 @@ class DiffusionBackend:)pipe._unsloth_loras = updatedcuda_graph.reset_all(getattr(state, "cuda_graphs", ()))+ invalidate_cfg_replica(pipe, "the LoRA adapters changed", logger)@staticmethoddef _reset_step_cache(pipe: Any) -> None:diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex f4b38589698..284ebc2f1fc 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -1266,9 +1266,28 @@ def _rebind_root_forward(original: Any, source: Any, replica: Any) -> None:def build_replica(module: Any, device: Any) -> Any:"""A copy of ``module`` whose parameters and buffers are created directly on ``device`` (never staged on the- source card), with every recorded ``Module.compile`` re-applied to the copy. Raises when it cannot be built."""+ source card), with every recorded ``Module.compile`` re-applied to the copy. Raises when it cannot be built.++ Built outside inference mode: inside it, torchao weights made outside raise "Cannot set version_counter for+ inference tensor" and ones made inside silently stay on the source card."""torch = _torch()device = torch.device(device)+ with torch.inference_mode(False), torch.no_grad():+ replica = _copy_module(module, device)+ stray = sorted(+ {+ str(t.device)+ for t in (*replica.parameters(), *replica.buffers())+ if t.device.type == "cuda" and t.device != device+ }+ )+ if stray:+ raise RuntimeError(f"replica weights stayed on {', '.join(stray)}, not {device}")+ return replica+++def _copy_module(module: Any, device: Any) -> Any:+ torch = _torch()memo: dict[int, Any] = {}keep: list[Any] = []for _name, param in module.named_parameters(remove_duplicate = True):@@ -1291,8 +1310,13 @@ def build_replica(module: Any, device: Any) -> Any:for sub in module.modules():offload_keys = set(_offload_attr_keys(sub))for key, value in sub.__dict__.items():- if isinstance(value, CfgParallelRouter) or key in offload_keys:- # never traversed: offload state holds pinned host copies a deepcopy would duplicate+ if (+ isinstance(value, CfgParallelRouter)+ or key in offload_keys+ or key in _SOURCE_ONLY_ATTRS+ ):+ # never traversed: offload state holds pinned host copies a deepcopy would duplicate, and a+ # source-only cache holds source-card tensorsmemo[id(value)] = _DROPfor attr in ("_forward_hooks", "_forward_pre_hooks"):for hook in (getattr(sub, attr, None) or {}).values():@@ -1362,6 +1386,9 @@ def build_replica(module: Any, device: Any) -> Any:_SHARED_STATE_TYPES = frozenset({"NVFP4StepController"})+# Caches only the source's own hooks fill and clear: the FLUX.3 conditioning blocks reach the copy through the+# forwarded call (diffusion_cond_blocks), so a copied cache would only pin source-card tensors that no render clears.+_SOURCE_ONLY_ATTRS = frozenset({"_unsloth_cond_cache"})def _rewrap_compiled(source: Any, replica: Any) -> None:@@ -1419,6 +1446,58 @@ def weights_fingerprint(module: Any) -> int:return hash(tuple(parts))+_PROBE_SAMPLES = 64+++def _dense_leaves(t: Any, depth: int = 0) -> Iterator[Any]:+ """The plain tensors holding ``t``'s values: ``t`` itself, or a torchao subclass's inner tensors (qdata, scales)."""+ flatten = getattr(type(t), "__tensor_flatten__", None)+ if flatten is None or depth > 4:+ yield t+ return+ try:+ names, _ctx = t.__tensor_flatten__()+ except Exception: # noqa: BLE001 - an opaque subclass: probe the outer tensor+ yield t+ return+ for name in names:+ inner = getattr(t, name, None)+ if inner is not None:+ yield from _dense_leaves(inner, depth + 1)+++def weights_probe(module: Any, index_cache: Optional[dict] = None) -> Optional[bytes]:+ """Sampled bytes of every inference tensor (no version counter, so invisible to :func:`weights_fingerprint`),+ read back in one host sync; None when there are none. Edits missing every sampled byte go unseen."""+ torch = _torch()+ cache = {} if index_cache is None else index_cache+ by_device: dict = {}+ with torch.no_grad():+ for _name, t in (*module.named_parameters(), *module.named_buffers()):+ if not t.is_inference():+ continue+ for leaf in _dense_leaves(t):+ if not isinstance(leaf, torch.Tensor) or leaf.numel() == 0 or leaf.is_meta:+ continue+ # bytes, not elements: a gather is not implemented for every weight dtype (fp8, packed fp4)+ flat = _as_bytes(leaf)+ n = flat.numel()+ key = (n, flat.device)+ idx = cache.get(key)+ if idx is None:+ idx = torch.linspace(+ 0, n - 1, steps = min(n, _PROBE_SAMPLES), device = flat.device+ ).long()+ cache[key] = idx+ by_device.setdefault(flat.device, []).append(flat.index_select(0, idx))+ if not by_device:+ return None+ return b"".join(+ torch.cat(chunks).cpu().numpy().tobytes()+ for _dev, chunks in sorted(by_device.items(), key = lambda kv: str(kv[0]))+ )++_LATENT_KEYS = ("hidden_states", "sample", "x", "latents", "img", "latent")@@ -1861,6 +1940,9 @@ class CfgParallelRouter:self.pending: Optional[dict] = Noneself.b0_leaves: dict = {}self.fingerprint: Optional[int] = None+ self.probe: Optional[bytes] = None+ self.probe_index: dict = {}+ self.probed_this_render = Falseself.pairs: list = []# A call new to either side may compile (FX tracing is process-wide up to torch 2.13): it never overlaps the other side.self.warm_primary: set = set()@@ -1913,6 +1995,7 @@ class CfgParallelRouter:# the next render shows its own guidance shape: no speculative branch before its first odd callself.cfg_seen = Falseself.singles = 0+ self.probed_this_render = Falsedef _note_refusal(self, exc: BaseException) -> None:from .diffusion_cuda_graph import OutsideWorkRefused@@ -2202,6 +2285,20 @@ class CfgParallelRouter:except Exception as exc: # noqa: BLE001 - unverifiable weights: never risk a stale replicaself.disable(f"cannot fingerprint the denoiser: {exc}")return+ if current == self.fingerprint and not self.probed_this_render:+ from .diffusion_cuda_graph import OutsideWorkRefused, outside_capture+ try:+ with outside_capture():+ probe = weights_probe(module, self.probe_index)+ except OutsideWorkRefused:+ probe = self.probe # another pipeline is recording: re-read on the next step+ except Exception as exc: # noqa: BLE001 - unverifiable weights: never risk a stale replica+ self.disable(f"cannot probe the denoiser weights: {exc}")+ return+ else:+ self.probed_this_render = True+ if probe != self.probe:+ current = Noneif current != self.fingerprint:if self.logger is not None:self.logger.info(@@ -2245,7 +2342,9 @@ class CfgParallelRouter:self.fingerprint = weights_fingerprint(module)# Copying the weights to the replica card is CUDA work another pipeline's capture prohibits.with outside_capture(), _device_context(self.secondary):+ self.probe = weights_probe(module, self.probe_index)self.replica = self.replica_factory()+ self.probed_this_render = Trueself.pairs = list(zip(module.modules(), self.replica.modules()))self.worker = _ReplicaWorker(self.secondary)weakref.finalize(self, self.worker.close)diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex 420f8fc338f..51d84e386fa 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -14321,3 +14321,31 @@ def test_untrusted_hub_single_file_header_is_checked_before_the_flux2_gguf_probemonkeypatch, tmp_path, lambda p: p.write_bytes(b"GGUF" + b"\x00" * 64), card_tag = None)assert probed == []+++def test_a_lora_change_drops_the_cfg_parallel_replica(monkeypatch):+ # set_adapters / load / unload change the denoiser's weights: a CFG-parallel replica built before must be rebuilt.+ from core.inference import diffusion as dmod++ backend = DiffusionBackend()+ monkeypatch.setattr(+ DiffusionBackend,+ "_resolve_lora_set",+ staticmethod(+ lambda specs, **k: tuple((i, f"/adapters/{i}.safetensors", w) for (i, w) in specs)+ ),+ )+ dropped: list = []+ monkeypatch.setattr(+ dmod, "invalidate_cfg_replica", lambda pipe, reason, logger = None: dropped.append(pipe)+ )+ ev = threading.Event()+ pipe = _BakePipe()+ pipe._unsloth_loras = (("sloth", "/adapters/sloth.safetensors", 0.8),)+ pipe._unsloth_loras_baked = True+ backend._apply_loras(_quant_lora_state(pipe), [("sloth", 0.8)], ev)+ assert dropped == [] # same set: the weights did not change+ backend._apply_loras(_quant_lora_state(pipe), [("sloth", 1.4)], ev)+ assert dropped == [pipe]+ backend._apply_loras(_quant_lora_state(pipe), [], ev)+ assert dropped == [pipe, pipe]diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.pyindex 4a322f961b2..5e65112e3ae 100644--- a/studio/backend/tests/test_diffusion_multigpu.py+++ b/studio/backend/tests/test_diffusion_multigpu.py@@ -956,6 +956,30 @@ def test_offload_torch_hooks_are_stripped_from_the_replica():assert calls == []+def test_the_conditioning_block_cache_stays_with_the_source():+ """FLUX.3's conditioning-block cache lives in the source's __dict__ and holds source-card tensors; the replica gets+ the states through the forwarded call, so a copy would stay on the source card and never be cleared."""+ dit = _Dit()+ states = {"temb": torch.ones(2, 4)}+ dit.__dict__["_unsloth_cond_cache"] = {("key",): states}+ replica = mg.build_replica(dit, torch.device("cpu"))+ assert "_unsloth_cond_cache" not in replica.__dict__+ assert dit.__dict__["_unsloth_cond_cache"] == {("key",): states}+ out = replica(+ hidden_states = torch.ones(1, 4),+ timestep = torch.tensor(1.0),+ encoder_hidden_states = torch.ones(1, 4),+ )[0]+ assert torch.equal(+ out,+ dit(+ hidden_states = torch.ones(1, 4),+ timestep = torch.tensor(1.0),+ encoder_hidden_states = torch.ones(1, 4),+ )[0],+ )++def test_predicted_branch_hits_and_stays_exact():torch.manual_seed(0)dit = _Dit()@@ -2368,6 +2392,91 @@ def test_replica_blocks_get_their_own_compile_guard():assert replica.__dict__.get("_unsloth_compile_guard") is guard+def test_replica_builds_inside_inference_mode_from_torchao_int8_weights():+ # Regression: building inside inference_mode raised "Cannot set version_counter" on torchao int8 weights.+ pytest.importorskip("torchao")+ from torchao.quantization import quantize_++ from core.inference.diffusion_transformer_quant import TQ_INT8, _make_quant_config++ torch.manual_seed(0)+ dit = torch.nn.Sequential(torch.nn.Linear(64, 64), torch.nn.GELU(), torch.nn.Linear(64, 64))+ with torch.no_grad():+ quantize_(dit, _make_quant_config(TQ_INT8))+ assert type(dit[0].weight).__module__.startswith("torchao")+ x = torch.randn(8, 64)+ with torch.inference_mode():+ replica = mg.build_replica(dit, torch.device("cpu"))+ assert torch.equal(replica(x), dit(x))+ assert replica[0].weight is not dit[0].weight+++class _ScaleDit(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.register_buffer("scale", torch.ones(4))++ def forward(+ self,+ hidden_states,+ timestep,+ encoder_hidden_states,+ return_dict = False,+ ):+ return (hidden_states * self.scale * timestep + encoder_hidden_states.sum(),)+++def test_probe_sees_an_in_place_edit_of_an_inference_tensor():+ with torch.inference_mode():+ dit = _ScaleDit()+ assert dit.scale.is_inference()+ fp, probe = mg.weights_fingerprint(dit), mg.weights_probe(dit)+ with torch.inference_mode():+ dit.scale.mul_(3.0)+ # no version counter on an inference tensor: the fingerprint cannot see the edit, the probe does+ assert mg.weights_fingerprint(dit) == fp+ assert probe is not None and mg.weights_probe(dit) != probe+ assert mg.weights_probe(_Dit()) is None+++def test_an_in_place_edit_of_inference_weights_rebuilds_the_replica_on_the_next_render():+ with torch.inference_mode():+ dit = _ScaleDit()+ router, replicas = _router(dit)+ latents = torch.randn(2, 4)+ _cfg_loop(dit, latents.clone(), steps = 3)+ router.end_render()+ assert len(replicas) == 1 and router.stats["replica_rebuilds"] == 0+ _cfg_loop(dit, latents.clone(), steps = 3)+ router.end_render()+ assert len(replicas) == 1 # unchanged weights: the probe matches, no rebuild+ dit.scale.mul_(3.0)+ _cfg_loop(dit, latents.clone(), steps = 3)+ assert router.stats["replica_rebuilds"] == 1 and len(replicas) == 2+ assert router.disabled_reason is None+++def test_invalidate_cfg_replica_drops_a_built_replica():+ class Pipe:+ pass++ pipe = Pipe()+ dit = _Dit()+ router, replicas = _router(dit)+ mg._CFG_ROUTERS[pipe] = router+ try:+ with torch.no_grad():+ _cfg_loop(dit, torch.randn(2, 4), steps = 2)+ assert router.replica is not None+ assert mg.invalidate_cfg_replica(pipe, "test") is True+ assert router.replica is None and router.stats["replica_rebuilds"] == 1+ with torch.no_grad():+ _cfg_loop(dit, torch.randn(2, 4), steps = 2)+ assert len(replicas) == 2+ finally:+ mg._CFG_ROUTERS.pop(pipe, None)++@pytest.mark.parametrize("dynamic", [None, False])def test_a_warm_signature_never_compiles_on_a_changed_number(dynamic):# A warm call runs beside the other side, so it must never compile (FX tracing is process-wide up to 2.13).diff --git a/studio/backend/tests/test_diffusion_multigpu_cuda.py b/studio/backend/tests/test_diffusion_multigpu_cuda.pyindex f8b702c1809..02b839acf27 100644--- a/studio/backend/tests/test_diffusion_multigpu_cuda.py+++ b/studio/backend/tests/test_diffusion_multigpu_cuda.py@@ -204,3 +204,70 @@ def test_zimage_pair_runs_on_two_cards_and_stays_exact():zs.uninstall_zimage_cfg_split(pipe)assert torch.equal(out, reference)assert router.stats["pairs_parallel"] == 4 and router.disabled_reason is None+++def _int8_dit(load_under_inference_mode):+ pytest.importorskip("torchao")+ from torchao.quantization import quantize_++ from core.inference.diffusion_transformer_quant import TQ_INT8, _make_quant_config++ torch.manual_seed(0)++ class Dit(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.a = torch.nn.Linear(128, 128)+ self.b = torch.nn.Linear(128, 128)++ def forward(+ self,+ hidden_states,+ timestep,+ encoder_hidden_states,+ return_dict = False,+ ):+ h = self.b(torch.nn.functional.gelu(self.a(hidden_states)))+ return (h * timestep + encoder_hidden_states.sum(),)++ ctx = torch.inference_mode() if load_under_inference_mode else torch.no_grad()+ with ctx:+ dit = Dit().to("cuda:0", torch.bfloat16).eval()+ quantize_(dit, _make_quant_config(TQ_INT8))+ return dit++[email protected]("load_under_inference_mode", [False, True])+def test_int8_replica_builds_inside_inference_mode_on_the_second_card(load_under_inference_mode):+ # Inside inference_mode: outside-made weights raised "Cannot set version_counter"; inside-made stayed on cuda:0.+ dit = _int8_dit(load_under_inference_mode)+ latents = torch.randn(4, 128, device = "cuda:0", dtype = torch.bfloat16)+ cond = torch.randn(3, 128, device = "cuda:0", dtype = torch.bfloat16)+ neg = torch.randn(3, 128, device = "cuda:0", dtype = torch.bfloat16)+ with torch.inference_mode():+ reference = _render(dit, latents, cond, neg, 4)+ router = _arm(dit)+ out = _render(dit, latents, cond, neg, 4)+ torch.cuda.synchronize()+ assert router.disabled_reason is None, router.disabled_reason+ assert router.stats["steps_parallel"] > 0+ assert {str(t.device) for t in router.replica.parameters()} == {"cuda:1"}+ assert torch.equal(out, reference)+++def test_an_in_place_edit_of_inference_weights_rebuilds_the_replica():+ # Inference tensors carry no version counter: the fingerprint alone kept a replica holding the old values.+ with torch.inference_mode():+ dit, latents, cond, neg = _setup()+ router = _arm(dit)+ _render(dit, latents, cond, neg, 3)+ router.end_render()+ assert router.replica is not None+ dit.scale.mul_(3.0)+ dit.forward = dit.__class__.forward.__get__(dit)+ reference = _render(dit, latents, cond, neg, 4)+ dit.forward = router+ out = _render(dit, latents, cond, neg, 4)+ torch.cuda.synchronize()+ assert router.stats["replica_rebuilds"] == 1+ assert torch.equal(out, reference)diff --git a/tests/test_nvfp4_autocast_callers.py b/tests/test_nvfp4_autocast_callers.pyindex 92c7f548ab8..8923501fcab 100644--- a/tests/test_nvfp4_autocast_callers.py+++ b/tests/test_nvfp4_autocast_callers.py@@ -61,7 +61,6 @@ def _nvfp4_linear_module(in_features, out_features, seed, dtype):def _dense_weight(layer, dtype):from unsloth.kernels import nvfp4-qs = layer.weight.quant_statereturn nvfp4.nvfp4_dequantize(layer.weight, qs.scale, qs.global_scale, dtype)@@ -178,9 +177,7 @@ def test_llama_attention_decode_under_mixed_autocast(mods, bsz, dtype, amp):assert out.dtype == (dtype if bsz == 1 else amp)assert K.dtype == dtype and V.dtype == dtypeassert K.shape == (bsz, N_KV, cached + step + 1, HEAD_DIM)- torch.testing.assert_close(- out.double(), _reference(attn, X, K, V), atol = 5e-2, rtol = 5e-2- )+ torch.testing.assert_close(out.double(), _reference(attn, X, K, V), atol = 5e-2, rtol = 5e-2)@pytest.mark.parametrize("bias_dtype", [torch.float16, torch.float32])