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 diffusion: CUDA graph re-check fixes (eager OOM retry on originals, planned negative length records on the first render) (#14682)
Daniel Hanc5196093f4f5
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.pyindex d3bd71a271e..351b1673ea0 100644--- a/studio/backend/core/inference/diffusion_cuda_graph.py+++ b/studio/backend/core/inference/diffusion_cuda_graph.py@@ -1191,6 +1191,9 @@ class GraphedForward:self._sealed_scopes: set = set()self._scope_captures: dict = {}self._render_scopes: set = set()+ # Keys warmed since the last render end/reset may still record after a seal (true CFG's other-length+ # negative). Not ``_warmed``: it outlives resets, so would reopen sealed scopes.+ self._open_warmups: set = set()_LIVE_WRAPPERS.add(self)@property@@ -1271,6 +1274,7 @@ class GraphedForward:self._sealed_scopes.clear()self._scope_captures.clear()self._render_scopes.clear()+ self._open_warmups.clear()if getattr(self, "fallback_handle", None) is not None:try:self.fallback_handle.reset()@@ -1659,8 +1663,10 @@ class GraphedForward:return self._eager(eager_args, eager_kwargs)if scope is not None:self._render_scopes.add(scope)- if scope in getattr(self, "_sealed_scopes", ()) and (- self.placement is None or key not in self._recorded+ if (+ scope in getattr(self, "_sealed_scopes", ())+ and (self.placement is None or key not in self._recorded)+ and not (self.plan is not None and key in self._open_warmups)):# A prompt length first seen after the first render: no warm-up, no capture, no eviction on this# render. (An offloaded key it recorded before re-records after its weights moved, as before.)@@ -1680,6 +1686,7 @@ class GraphedForward:self._warmed[key] = Nonewhile len(self._warmed) > 4 * self.max_graphs:self._warmed.pop(next(iter(self._warmed)))+ self._open_warmups.add(key)self.stats["shape_warmups"] += 1# Copies laid out like the capture statics: compiled code guards on strides/offsets, else the# capture compiles a new variant inside itself and fails.@@ -2726,6 +2733,7 @@ def seal_lengths(handles: Any) -> None:if handle._scope_captures.get(scope, 0) > 0:handle._sealed_scopes.add(scope)handle._render_scopes.clear()+ handle._open_warmups.clear()except Exception: # noqa: BLE001 - optimisation onlypassdiff --git a/studio/backend/tests/test_diffusion_cuda_graph.py b/studio/backend/tests/test_diffusion_cuda_graph.pyindex 43290bac6c4..d3f07fb8577 100644--- a/studio/backend/tests/test_diffusion_cuda_graph.py+++ b/studio/backend/tests/test_diffusion_cuda_graph.py@@ -1274,6 +1274,62 @@ def test_a_new_prompt_length_after_the_first_render_records_nothing(stub_torch,assert handle.stats["length_eager"] == 3+def _planned_len_handle(stub_torch, monkeypatch):+ import contextlib++ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)+ handle = _armed(_len_dit("QwenImage21Transformer2DModel"))+ orig = handle.orig+ handle.plan = lambda mod, args, kwargs: (orig, {"hidden_states": args[0], **kwargs})+ monkeypatch.setattr(_FakeTensor, "is_inference", lambda self: False, raising = False)+ monkeypatch.setattr(+ stub_torch, "inference_mode", lambda *a, **k: contextlib.nullcontext(), raising = False+ )+ monkeypatch.setattr(cg, "_graph_without_flush", stub_torch.cuda.graph)+ return handle+++def test_a_planned_negative_of_another_length_records_on_the_first_render(stub_torch, monkeypatch):+ """The negative is still warming when the positive's replay seals the scope; it must still record."""+ handle = _planned_len_handle(stub_torch, monkeypatch)+ for _ in range(2):+ _render(handle, 3, steps = 4)+ cg.seal_lengths((handle,))+ assert handle.length_sealed is True+ assert handle.stats["captures"] == 2 and handle.stats["shape_warmups"] == 1+ assert handle.stats["length_eager"] == 0+ assert handle.stats["replays"] == 2 * 4 * 2 - 1+ _render(handle, 15, steps = 2, negative_len = 3)+ assert handle.stats["captures"] == 2 and handle.stats["length_eager"] == 2+++def test_a_warmup_from_before_a_reset_does_not_reopen_the_sealed_scope(stub_torch, monkeypatch):+ handle = _planned_len_handle(stub_torch, monkeypatch)+ _step(handle, 3)+ _step(handle, 7)+ assert handle.stats["captures"] == 1 and handle.stats["shape_warmups"] == 1+ handle.reset()+ for i in range(3):+ _step(handle, 3, value = float(i))+ cg.seal_lengths((handle,))+ assert handle.length_sealed is True+ captures = handle.stats["captures"]+ for i in range(3):+ _step(handle, 7, value = float(i))+ assert handle.stats["captures"] == captures+ assert handle.stats["length_eager"] == 3+++def test_a_warmup_from_an_earlier_render_does_not_reopen_the_sealed_scope(stub_torch, monkeypatch):+ handle = _planned_len_handle(stub_torch, monkeypatch)+ _step(handle, 3)+ _step(handle, 7)+ cg.seal_lengths((handle,))+ assert handle.length_sealed is True+ _render(handle, 3, steps = 2)+ assert handle.stats["captures"] == 1 and handle.stats["length_eager"] == 2++def test_the_ungraphed_step_returns_what_the_step_itself_returns(stub_torch, monkeypatch):monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)handle = _armed(_len_dit("ZImageTransformer2DModel"))diff --git a/studio/backend/tests/test_diffusion_qwenimage21_graph.py b/studio/backend/tests/test_diffusion_qwenimage21_graph.pyindex 1e139bc0888..9d08b6abca5 100644--- a/studio/backend/tests/test_diffusion_qwenimage21_graph.py+++ b/studio/backend/tests/test_diffusion_qwenimage21_graph.py@@ -450,3 +450,48 @@ def test_offload_placement_names_a_forward_that_cannot_record_under_the_hooks(moassert cg._forward_refusal(m, "model") is Nonemonkeypatch.setattr(cs, "resolve", lambda cls: (None, "X forward is not capture-safe (why)"))assert cg._forward_refusal(m, "model") == "X forward is not capture-safe (why)"++[email protected](not _CUDA, reason = "needs CUDA")[email protected]("every_length", [False, True])+def test_true_cfg_negative_of_another_length_records_on_the_first_render(monkeypatch, every_length):+ if every_length:+ monkeypatch.setenv(cg.EVERY_LENGTH_ENV, "1")+ else:+ monkeypatch.delenv(cg.EVERY_LENGTH_ENV, raising = False)+ m = _model().to("cuda")+ cond, uncond = _cuda_inputs(text = 9, seed = 1), _cuda_inputs(text = 13, seed = 2)+ steps = 4++ def cfg_render():+ out = []+ kvs = [qmod.QwenImage21KVCache(len(m.transformer_blocks)) for _ in range(2)]+ lat = cond["latents"]+ with torch.inference_mode():+ for i in range(steps):+ t = torch.full((1,), 1.0 - i / steps, device = "cuda")+ mode = "extract" if i == 0 else "cached"+ a = m(**_call_kwargs(cond, lat, t, kvs[0], mode))[0][:, -lat.shape[1] :]+ b = m(**_call_kwargs(uncond, lat, t, kvs[1], mode))[0][:, -lat.shape[1] :]+ out += [a.clone(), b.clone()]+ lat = lat - 0.1 * (a - b)+ return out++ ref = cfg_render()+ assert q.install()+ handle = _graphed(m)+ assert handle.length_varies is (not every_length)+ try:+ got = []+ for _ in range(2):+ got.append(cfg_render())+ cg.seal_lengths([handle])+ finally:+ cg.uninstall_all([handle])+ for render in got:+ for a, b in zip(ref, render):+ assert torch.equal(a, b)+ assert not handle.poisoned, handle.capture_error+ stats = {k: handle.stats[k] for k in ("captures", "replays", "shape_warmups", "length_eager")}+ assert (stats["captures"], stats["shape_warmups"], stats["length_eager"]) == (2, 1, 0), stats+ assert handle.stats["replays"] == 2 * (steps - 1) * 2 - 1