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: live denoising canvas for transformers diffusion LMs (#13593)
Daniel Hanadd9d2ab14fc
diff --git a/studio/backend/core/inference/inference.py b/studio/backend/core/inference/inference.pyindex 3db5be503af..a1497e8e69d 100644--- a/studio/backend/core/inference/inference.py+++ b/studio/backend/core/inference/inference.py@@ -705,6 +705,108 @@ def _without_image_parts(messages) -> list[dict]:return out+_CANVAS_MASK = "\u2591"+_CANVAS_FRAME_INTERVAL_S = 0.1+++def _accepts_on_frame(generate_text) -> bool:+ """An older core would swallow on_frame unused."""+ import inspect++ candidates = [generate_text]+ try:+ from unsloth.models import diffusion_samplers+ candidates.append(diffusion_samplers.generate_text)+ except ImportError:+ pass+ for fn in candidates:+ try:+ if "on_frame" in inspect.signature(fn).parameters:+ return True+ except (TypeError, ValueError):+ continue+ return False+++def _render_canvas(tokenizer, tokens, mask_id) -> str:+ tokenizer = getattr(tokenizer, "tokenizer", tokenizer)+ parts, run = [], []+ for token in tokens:+ if mask_id is not None and token == mask_id:+ if run:+ parts.append(tokenizer.decode(run, skip_special_tokens = True))+ run = []+ parts.append(_CANVAS_MASK)+ else:+ run.append(token)+ if run:+ parts.append(tokenizer.decode(run, skip_special_tokens = True))+ return "".join(parts)+++def _diffusion_eos_ids(model, tokenizer, chat) -> tuple:+ """The ids ``generate_text`` cuts its reply at; empty on an older core."""+ import importlib+ try:+ samplers = importlib.import_module("unsloth.models.diffusion_samplers")+ base = samplers.unwrap_diffusion_model(model)+ ids = list(samplers._eos_ids(base, tokenizer))+ if chat:+ ids += [i for i in samplers._turn_end_ids(tokenizer) if i not in ids]+ return tuple(ids)+ except Exception:+ return ()+++def _diffusion_frame_relay(+ tokenizer,+ sink,+ interval_s = None,+ stop = None,+ eos_ids = (),+):+ """on_frame for the core sampler: one frame per interval to ``sink``, cut where the final reply is.+ Never raises into the sampler."""+ import time++ last = [float("-inf")]+ if interval_s is None:+ interval_s = _CANVAS_FRAME_INTERVAL_S++ def on_frame(frame):+ now = time.monotonic()+ # A block's last step is never throttled: later frames build on it.+ block_end = int(frame.get("step", 0)) >= int(frame.get("total", 0)) > 0+ if now - last[0] < interval_s and not block_end:+ return+ last[0] = now+ try:+ tokens = list(frame.get("tokens") or ())+ for index, token in enumerate(tokens):+ if token in eos_ids:+ tokens = tokens[:index]+ break+ text = _render_canvas(tokenizer, tokens, frame.get("mask_id"))+ for sequence in stop or ():+ if sequence and sequence in text:+ text = text[: text.index(sequence)]+ total = int(frame.get("total", 0))+ sink(+ {+ "type": "diffusion_frame",+ "block": int(frame.get("block", 0)),+ # Zero-based for the canvas; the sampler's block-end frame is step == total.+ "step": max(min(int(frame.get("step", 0)), total - 1), 0),+ "total": total,+ "text": text,+ }+ )+ except Exception as exc:+ logger.debug("Dropped a diffusion canvas frame: %s", exc)++ return on_frame++class InferenceBackend:"""Unified inference backend supporting text, vision, and LoRA models"""@@ -723,6 +825,8 @@ class InferenceBackend:self.device = get_device().valueself._audio_codec_manager = AudioCodecManager()self.last_generation_stats = None+ # Set by the worker for one request that asked for canvas frames.+ self.diffusion_frame_sink = None# _generation_lock serializes model.generate(). Plain Lock (NOT RLock):# RLock reentrancy would let concurrent compare-mode requests race on@@ -2642,6 +2746,17 @@ class InferenceBackend:)except ImportError: # an older core: no cancellation error to catchcancelled_error = ()+ frame_kwargs = {}+ sink = getattr(self, "diffusion_frame_sink", None)+ if sink is not None and _accepts_on_frame(generate_text):+ frame_kwargs["on_frame"] = _diffusion_frame_relay(+ model_info["tokenizer"],+ sink,+ stop = stop,+ eos_ids = _diffusion_eos_ids(+ model_info["model"], model_info["tokenizer"], messages is not None+ ),+ )with self._generation_lock:if _adapter_state is not None:self._apply_adapter_state(_adapter_state)@@ -2654,6 +2769,7 @@ class InferenceBackend:max_new_tokens = int(max_new_tokens or 256),temperature = float(temperature or 0.0),stop_callback = (lambda: cancel_event is not None and cancel_event.is_set()),+ **frame_kwargs,)except cancelled_error:returndiff --git a/studio/backend/core/inference/orchestrator.py b/studio/backend/core/inference/orchestrator.pyindex e8dac030283..5604869e83b 100644--- a/studio/backend/core/inference/orchestrator.py+++ b/studio/backend/core/inference/orchestrator.py@@ -1428,6 +1428,7 @@ class InferenceOrchestrator:video_b64: Optional[str] = None,response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,+ diffusion_frames: bool = False,) -> dict:"""Build the 'generate' command shared by the locked and dispatched paths."""cmd = {@@ -1474,6 +1475,8 @@ class InferenceOrchestrator:cmd["rows"] = rowsif tool_protocol_active is not None:cmd["tool_protocol_active"] = tool_protocol_active+ if diffusion_frames and not rows:+ cmd["diffusion_frames"] = Truereturn cmddef _consume_token_stream(@@ -1488,8 +1491,9 @@ class InferenceOrchestrator:read_timeout: float = 30.0,mark_started: bool = True,rows: Optional[int] = None,+ frames: bool = False,) -> Generator[Any, None, None]:- """Yield tokens from a response stream until gen_done/gen_error."""+ """Yield tokens until gen_done/gen_error; with ``frames``, also diffusion_frame event dicts."""# Latch this stream's subprocess/queue: if a wedged worker is torn down and a later load spawns a fresh one,# bail rather than re-block on the new queue under _gen_lock (deadlock).initial_proc = self._proc@@ -1577,6 +1581,11 @@ class InferenceOrchestrator:yield int(resp.get("row", 0)), resp.get("text", "")else:yield resp.get("text", "")+ elif rtype == "diffusion_frame":+ if frames and rows is None and not stop_sent:+ yield {+ key: value for key, value in resp.items() if key not in ("request_id", "ts")+ }elif rtype == "gen_done":if stats_holder is not None and rows is None:stats_holder["stats"] = resp.get("stats")@@ -1715,6 +1724,7 @@ class InferenceOrchestrator:video: Optional[str] = None,response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,+ diffusion_frames: bool = False,) -> Generator[Any, None, None]:"""Dispatched generation, sending the command without holding _gen_lock. Uses a per-requestmailbox for tokens so two compare-mode requests can be queued at once. The subprocess@@ -1771,6 +1781,7 @@ class InferenceOrchestrator:seed = seed,rows = rows,video_b64 = video,+ diffusion_frames = diffusion_frames,)mailbox = _WorkerMailbox(self._proc)@@ -1843,6 +1854,7 @@ class InferenceOrchestrator:read_timeout = _DISPATCH_READ_TIMEOUT,mark_started = False,rows = len(rows) if rows else None,+ frames = diffusion_frames,)finally:# Covers streams that end without a gen_done (never sent, cancel, disconnect, dead worker).@@ -2985,6 +2997,7 @@ class InferenceOrchestrator:video: Optional[str] = None,response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,+ diffusion_frames: bool = False,) -> Generator[str, None, None]:"""Generate response, streaming tokens from subprocess. ``tools`` / ``enable_thinking`` /``reasoning_effort`` / ``preserve_thinking`` are forwarded so the template can render@@ -3021,6 +3034,7 @@ class InferenceOrchestrator:response_format = response_format,reasoning_is_extracted = reasoning_is_extracted,video = video,+ diffusion_frames = diffusion_frames,)def generate_chat_batch(@@ -3398,6 +3412,7 @@ class InferenceOrchestrator:video: Optional[str] = None,response_format: Optional[dict] = None,reasoning_is_extracted: bool = False,+ diffusion_frames: bool = False,) -> Generator[Any, None, None]:"""Inner generation logic: sends the command to the subprocess and yields tokens. Serializedby _gen_lock (one generation at a time) so concurrent readers don't consume each other's@@ -3405,7 +3420,7 @@ class InferenceOrchestrator:managed = getattr(self, "_managed_engine", None)if managed is not None:kwargs = dict(locals())- for key in ("self", "managed", "kwargs"):+ for key in ("self", "managed", "kwargs", "diffusion_frames"):kwargs.pop(key, None)from .engine_transport import EngineHTTPError@@ -3460,6 +3475,7 @@ class InferenceOrchestrator:video = video,response_format = response_format,reasoning_is_extracted = reasoning_is_extracted,+ diffusion_frames = diffusion_frames,)return@@ -3501,6 +3517,7 @@ class InferenceOrchestrator:seed = seed,rows = rows,video_b64 = video,+ diffusion_frames = diffusion_frames,)read_one, drain, release_mailbox = self._direct_reader(request_id, cancel_event)@@ -3521,6 +3538,7 @@ class InferenceOrchestrator:cancel_event = cancel_event,stats_holder = stats_holder,rows = len(rows) if rows else None,+ frames = diffusion_frames,)finally:self._release_worker(cancel_event)diff --git a/studio/backend/core/inference/worker.py b/studio/backend/core/inference/worker.pyindex b719b600364..89da9328f47 100644--- a/studio/backend/core/inference/worker.py+++ b/studio/backend/core/inference/worker.py@@ -1150,6 +1150,12 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:one-at-a-time loop the shared event alone. Nothing is asked during the prefill."""request_id = cmd.get("request_id", "")+ # Scoped to this request: cleared when it ends.+ frames = bool(cmd.get("diffusion_frames")) and hasattr(backend, "diffusion_frame_sink")+ if frames:+ backend.diffusion_frame_sink = lambda frame: _send_response(+ resp_queue, {**frame, "request_id": request_id}+ )try:gen_kwargs = _generation_kwargs(backend, cmd, cancel_event)@@ -1199,6 +1205,9 @@ def _handle_generate(backend, cmd: dict, resp_queue: Any, cancel_event) -> None:except Exception as exc:logger.error("Generation error: %s", exc, exc_info = True)_send_response(resp_queue, _generation_error_payload(request_id, exc))+ finally:+ if frames:+ backend.diffusion_frame_sink = Nonedef _handle_count_tokens(backend, cmd: dict, resp_queue: Any) -> None:diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 6d4b6f88a35..ed47c0a7fef 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -30370,6 +30370,14 @@ def _ui_stream_events_enabled(request: Optional[Request]) -> bool:return (value or "").strip() == "1"+def _accepts_keyword(fn, name: str) -> bool:+ import inspect+ try:+ return name in inspect.signature(fn).parameters+ except (TypeError, ValueError):+ return False++# The loaded model serves the request, so a caller that cannot use speech says so per request.REQUIRE_TEXT_HEADER = "X-Unsloth-Require-Text"@@ -34701,6 +34709,16 @@ async def produce_openai_chat_completions(# Request-scoped usage/timings receptacle (filled at gen_done).stats_holder: dict = {}_sf_context_truncation_holder: dict = {"value": None}+ # Diffusion canvas frames only for a streaming, single-choice reply to a client rendering Studio events.+ _sf_ui_events = _ui_stream_events_enabled(request)+ _sf_frame_kwargs = (+ {"diffusion_frames": True}+ if payload.stream+ and _sf_ui_events+ and (payload.n or 1) == 1+ and _accepts_keyword(backend.generate_chat_response, "diffusion_frames")+ else {}+ )if payload.use_adapter is not None:@@ -34709,6 +34727,7 @@ async def produce_openai_chat_completions(use_adapter = payload.use_adapter,cancel_event = cancel_event,stats_holder = stats_holder,+ **_sf_frame_kwargs,**kw,)else:@@ -34717,6 +34736,7 @@ async def produce_openai_chat_completions(return backend.generate_chat_response(cancel_event = cancel_event,stats_holder = stats_holder,+ **_sf_frame_kwargs,**kw,)@@ -34849,6 +34869,12 @@ async def produce_openai_chat_completions(model_name,{key: value for key, value in cumulative.items() if key != "type"},)+ elif cumulative.get("type") == "diffusion_frame":+ # As on the GGUF path: never in the transcript.+ if _sf_ui_events:+ yield f"data: {json.dumps(cumulative)}\n\n"+ elif _drop_keepalive.due():+ yield _OPENAI_PASSTHROUGH_SSE_KEEPALIVEcontinueif isinstance(cumulative, GenStreamError):backend.reset_generation_state(cancel_event)diff --git a/studio/backend/tests/test_diffusion_lm_studio.py b/studio/backend/tests/test_diffusion_lm_studio.pyindex f45344099ae..3e7b4ebbe3b 100644--- a/studio/backend/tests/test_diffusion_lm_studio.py+++ b/studio/backend/tests/test_diffusion_lm_studio.py@@ -811,3 +811,235 @@ def test_formatting_retries_in_one_process_when_workers_cannot_pickle():len,{"num_proc": 4},)+++class _FrameSampler:+ calls = []++ @staticmethod+ def generate_text(+ model,+ tokenizer,+ prompt = None,+ messages = None,+ stop_callback = None,+ on_frame = None,+ **kwargs,+ ):+ _FrameSampler.calls.append({"on_frame": on_frame, **kwargs})+ if on_frame is not None:+ on_frame({"block": 0, "step": 1, "total": 4, "tokens": [7, 99, 99, 8], "mask_id": 99})+ on_frame({"block": 0, "step": 2, "total": 4, "tokens": [7, 5, 99, 8], "mask_id": 99})+ return "The answer is 4."+++class _CanvasTokenizer:+ def decode(+ self,+ ids,+ skip_special_tokens = True,+ ):+ return "".join(f"<{i}>" for i in ids)+++@_needs_torch+def test_canvas_frames_reach_the_sink_rendered_with_mask_glyphs(monkeypatch):+ from core.inference import inference as inference_mod++ backend, _ = _inference_backend(monkeypatch)+ backend.models["m"]["tokenizer"] = _CanvasTokenizer()+ monkeypatch.setattr(diffusion_lm, "require_diffusion_api", lambda name: _FrameSampler)+ monkeypatch.setattr(inference_mod, "_CANVAS_FRAME_INTERVAL_S", 0.0)+ frames = []+ backend.diffusion_frame_sink = frames.append+ out = list(backend.generate_stream("x", max_new_tokens = 8))+ assert out == ["The answer is 4."]+ glyph = inference_mod._CANVAS_MASK+ assert [f["text"] for f in frames] == [f"<7>{glyph}{glyph}<8>", f"<7><5>{glyph}<8>"]+ assert frames[0] == {+ "type": "diffusion_frame",+ "block": 0,+ "step": 1,+ "total": 4,+ "text": frames[0]["text"],+ }++ # No sink (a strict client, or the request did not ask): the sampler gets no callback.+ backend.diffusion_frame_sink = None+ _FrameSampler.calls = []+ assert list(backend.generate_stream("x", max_new_tokens = 8)) == ["The answer is 4."]+ assert _FrameSampler.calls[-1]["on_frame"] is None+++@_needs_torch+def test_an_older_core_without_on_frame_is_never_passed_one(monkeypatch):+ backend, _ = _inference_backend(monkeypatch)+ backend.diffusion_frame_sink = lambda frame: None+ from core.inference import inference as inference_mod++ monkeypatch.setattr(inference_mod, "_accepts_on_frame", lambda fn: False)+ assert list(backend.generate_stream("x", max_new_tokens = 8))+ assert "on_frame" not in _Sampler.calls[-1]+++def test_frame_relay_throttles_and_never_raises_into_the_sampler():+ from core.inference.inference import _diffusion_frame_relay++ sent = []+ relay = _diffusion_frame_relay(_CanvasTokenizer(), sent.append, interval_s = 3600)+ relay({"block": 0, "step": 0, "total": 2, "tokens": [1], "mask_id": None})+ relay({"block": 0, "step": 1, "total": 2, "tokens": [2], "mask_id": None})+ assert [f["text"] for f in sent] == ["<1>"]+ # A block's last step is never throttled away.+ relay({"block": 0, "step": 2, "total": 2, "tokens": [3], "mask_id": None})+ assert [f["text"] for f in sent] == ["<1>", "<3>"]++ def broken(frame):+ raise OSError("queue closed")++ _diffusion_frame_relay(_CanvasTokenizer(), broken, interval_s = 0)(+ {"block": 0, "step": 0, "total": 1, "tokens": [1], "mask_id": None}+ )+++def test_frame_relay_sends_zero_based_steps_and_honours_stop_sequences():+ from core.inference.inference import _diffusion_frame_relay++ sent = []+ relay = _diffusion_frame_relay(_CanvasTokenizer(), sent.append, interval_s = 0, stop = ["<2>"])+ relay({"block": 0, "step": 0, "total": 2, "tokens": [1], "mask_id": None})+ relay({"block": 0, "step": 2, "total": 2, "tokens": [1, 2, 3], "mask_id": None})+ # The canvas renders step + 1 of total: the block-end frame reads 2/2, not 3/2.+ assert [f["step"] for f in sent] == [0, 1]+ # Nothing past a stop sequence is shown, as the final reply is cut there too.+ assert sent[-1]["text"] == "<1>"+++def test_frame_relay_cuts_frames_at_the_first_eos():+ from core.inference.inference import _diffusion_frame_relay++ sent = []+ relay = _diffusion_frame_relay(_CanvasTokenizer(), sent.append, interval_s = 0, eos_ids = (9,))+ # A masked slot before the EOS stays a placeholder; nothing after the EOS is shown.+ relay({"block": 0, "step": 0, "total": 2, "tokens": [1, 0, 9, 4, 5], "mask_id": 0})+ assert sent[-1]["text"] == "<1>\u2591"+++def test_diffusion_eos_ids_match_the_sampler_cut(monkeypatch):+ from core.inference import inference as inference_mod++ samplers = types.ModuleType("unsloth.models.diffusion_samplers")+ samplers.unwrap_diffusion_model = lambda model: model+ samplers._eos_ids = lambda base, tokenizer: [7]+ samplers._turn_end_ids = lambda tokenizer: [7, 8]+ monkeypatch.setitem(sys.modules, "unsloth.models.diffusion_samplers", samplers)+ assert inference_mod._diffusion_eos_ids(object(), object(), chat = True) == (7, 8)+ assert inference_mod._diffusion_eos_ids(object(), object(), chat = False) == (7,)+ # A core without these helpers shows frames uncut rather than failing.+ monkeypatch.setitem(sys.modules, "unsloth.models.diffusion_samplers", types.ModuleType("old"))+ assert inference_mod._diffusion_eos_ids(object(), object(), chat = True) == ()+++def test_worker_installs_the_frame_sink_only_for_the_requesting_generation():+ from core.inference import worker as worker_mod+ class _Backend:+ diffusion_frame_sink = None+ last_generation_stats = None++ def generate_chat_response(self, **kwargs):+ if self.diffusion_frame_sink is not None:+ self.diffusion_frame_sink(+ {"type": "diffusion_frame", "block": 0, "step": 0, "total": 1, "text": "a"}+ )+ yield "done"++ for asked in (True, False):+ backend, sent = _Backend(), []+ cmd = {"request_id": "r1", "messages": [{"role": "user", "content": "hi"}]}+ if asked:+ cmd["diffusion_frames"] = True+ worker_mod._handle_generate(+ backend, cmd, SimpleNamespace(put = sent.append), threading.Event()+ )+ types = [r["type"] for r in sent]+ assert types == (+ ["diffusion_frame", "token", "gen_done"] if asked else ["token", "gen_done"]+ )+ if asked:+ assert sent[0]["request_id"] == "r1" and sent[0]["text"] == "a"+ assert backend.diffusion_frame_sink is None+++def test_token_stream_yields_frames_only_when_asked():+ from core.inference import orchestrator as orch++ def run(frames):+ events = iter(+ [+ {+ "type": "diffusion_frame",+ "request_id": "r",+ "block": 0,+ "step": 0,+ "total": 2,+ "text": "a",+ "ts": 1,+ },+ {"type": "token", "request_id": "r", "text": "final"},+ {"type": "gen_done", "request_id": "r", "stats": None},+ ]+ )+ stream = orch.InferenceOrchestrator._consume_token_stream(+ SimpleNamespace(+ _proc = None,+ _resp_queue = None,+ _mark_worker_started = lambda _event: None,+ _forget_request = lambda *_a: None,+ ),+ lambda _timeout: next(events),+ lambda: None,+ crash_context = "test",+ frames = frames,+ )+ return list(stream)++ assert run(True) == [+ {"type": "diffusion_frame", "block": 0, "step": 0, "total": 2, "text": "a"},+ "final",+ ]+ assert run(False) == ["final"]+++def test_the_command_asks_for_frames_only_for_a_single_reply():+ from core.inference import orchestrator as orch++ build = orch.InferenceOrchestrator._build_generate_cmd+ me = SimpleNamespace(effective_parallel_slots = 1)+ assert build(me, "r", None, diffusion_frames = True)["diffusion_frames"] is True+ assert "diffusion_frames" not in build(me, "r", None)+ assert "diffusion_frames" not in build(me, "r", None, diffusion_frames = True, rows = [{}, {}])+++def test_plain_stream_forwards_frames_only_to_event_clients():+ from routes import inference as routes_mod++ src = inspect.getsource(routes_mod)+ branch = src[src.index("# As on the GGUF path: never in the transcript.") :][:400]+ assert "if _sf_ui_events:" in branch and "_drop_keepalive.due()" in branch+ gate = src[+ src.index("_sf_frame_kwargs = (") : src.index(+ "if payload.use_adapter is not None:", src.index("_sf_frame_kwargs = (")+ )+ ]+ assert "payload.stream" in gate and "_sf_ui_events" in gate and "(payload.n or 1) == 1" in gate+++def test_adapter_controlled_stream_forwards_frames_too():+ from routes import inference as routes_mod++ src = inspect.getsource(routes_mod)+ start = src.index("if payload.use_adapter is not None:", src.index("_sf_frame_kwargs = ("))+ adapter_branch = src[start : src.index("else:", start)]+ assert (+ "generate_with_adapter_control" in adapter_branch and "**_sf_frame_kwargs" in adapter_branch+ )