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
Diffusion LMs: fast inference, live denoising frames and in-loop cancellation (#13592)
Daniel Hanf7980456ddc3
diff --git a/tests/diffusion/test_diffusion_infer.py b/tests/diffusion/test_diffusion_infer.pynew file mode 100644index 00000000000..28aaee17642--- /dev/null+++ b/tests/diffusion/test_diffusion_infer.py@@ -0,0 +1,362 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++from types import SimpleNamespace++import pytest+import torch++VOCAB, MASK_ID = 61, 60+++class _Bidirectional(torch.nn.Module):+ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed = torch.nn.Embedding(VOCAB, 16)+ self.mix = torch.nn.Linear(16, 16)+ self.head = torch.nn.Linear(16, VOCAB)+ self.config = SimpleNamespace(mask_token_id = MASK_ID)+ self.calls = 0++ def get_output_embeddings(self):+ return self.head++ def forward(+ self,+ input_ids,+ attention_mask = None,+ ):+ self.calls += 1+ h = self.embed(input_ids)+ h = h + self.mix(h.mean(dim = 1, keepdim = True))+ logits = self.head(torch.tanh(h))+ return SimpleNamespace(logits = logits)+++def _sample(+ model,+ progress = None,+ **overrides,+):+ from unsloth.models.diffusion_samplers import _llada_sample++ kwargs = dict(+ max_new_tokens = 16,+ steps = 16,+ block_length = 8,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ progress = progress,+ )+ kwargs.update(overrides)+ return _llada_sample(model, None, torch.tensor([[1, 7, 9]]), None, **kwargs)+++def test_block_head_matches_full_logits_without_building_them():+ from unsloth.models.diffusion_infer import BlockHead++ model = _Bidirectional()+ x = torch.randint(0, VOCAB, (2, 12))+ full = model(x).logits+ head = BlockHead(model)+ assert head.head is model.head+ seen = []+ model.head.register_forward_hook(lambda m, a, out: seen.append(tuple(out.shape)))+ model.head._forward_hooks.clear() # a hooked head is not fusable; check the fused path with a clean one+ model.__dict__.pop("_unsloth_diffusion_fused_head", None)+ head = BlockHead(model)+ block = head.logits(x, 4, 8)+ assert torch.allclose(block, full[:, 4:8], atol = 1e-6)+ # A head that is not a plain Linear keeps the model's own logits.+ model.__dict__["_unsloth_diffusion_fused_head"] = (model.head, None)+ fallback = BlockHead(model)+ assert fallback.head is None and torch.equal(fallback.logits(x, 4, 8), full[:, 4:8])+++def test_progress_throttles_forces_block_ends_and_stops_after_close():+ from unsloth.models.diffusion_infer import make_progress++ frames = []+ progress = make_progress(frames.append, None, interval = 3600, mask_id = MASK_ID, budget = 4)+ ids = torch.tensor([[5, MASK_ID, 7, MASK_ID, 9, 9]])+ progress.frame(0, 0, 4, ids) # first frame always goes out+ progress.frame(0, 1, 4, ids) # throttled+ progress.frame(0, 4, 4, ids, force = True)+ assert [(f["block"], f["step"]) for f in frames] == [(0, 0), (0, 4)]+ assert frames[0]["tokens"] == [5, MASK_ID, 7, MASK_ID] and frames[0]["mask_id"] == MASK_ID+ progress.close()+ progress.frame(1, 0, 4, ids, force = True)+ assert len(frames) == 2+++def test_progress_check_raises_once_stop_is_requested():+ from unsloth.models.diffusion_infer import DiffusionGenerationCancelled, make_progress+ from unsloth.models.diffusion_samplers import DiffusionGenerationCancelled as exported++ assert exported is DiffusionGenerationCancelled+ calls = []+ progress = make_progress(None, lambda: len(calls) >= 3 or calls.append(1), 0.0, MASK_ID, 4)+ model = _Bidirectional()+ with pytest.raises(DiffusionGenerationCancelled):+ _sample(model, progress)+ assert model.calls == 3 # checked in the step loop, before each forward+++def test_llada_frames_show_the_canvas_filling_in():+ from unsloth.models.diffusion_infer import make_progress++ model = _Bidirectional()+ frames = []+ progress = make_progress(frames.append, None, 0.0, MASK_ID, 16)+ out = _sample(model, progress)+ progress.close()+ assert all(len(f["tokens"]) == 16 for f in frames)+ masks = [sum(t == MASK_ID for t in f["tokens"]) for f in frames]+ assert masks[0] == 15 and masks[-1] == 0 and masks == sorted(masks, reverse = True)+ assert frames[-1]["tokens"] == out[0].tolist()+ ends = [f for f in frames if f["step"] == f["total"]]+ assert [f["block"] for f in ends] == [+ 0,+ 1,+ ] # exactly one block-end frame per block, step == total+ assert all(0 <= f["step"] < f["total"] for f in frames if f not in ends)+ # Frames never change what is generated.+ assert torch.equal(out, _sample(_Bidirectional()))+++def test_llada_projects_only_the_active_block():+ model = _Bidirectional()+ rows = []+ # Vocabulary projections only: inside the backbone forward the head returns its input (width 16).+ model.head.register_forward_hook(+ lambda m, a, out: rows.append(out.shape[1]) if out.shape[-1] == VOCAB else None+ )+ model.__dict__["_unsloth_diffusion_fused_head"] = (+ model.head,+ model.head,+ ) # the hook makes it look wrapped+ _sample(model)+ assert rows and set(rows) == {8} # block_length rows, never the 19-token canvas+++def test_inference_compile_restores_the_previous_call_path(monkeypatch):+ from unsloth.models import diffusion_infer++ compiled = []+ monkeypatch.setattr(+ diffusion_infer.torch, "compile", lambda fn, **kw: compiled.append(kw) or fn+ )+ model = torch.nn.Module()+ model.layers = torch.nn.ModuleList([torch.nn.Linear(2, 2), torch.nn.Linear(2, 2)])+ marker = object()+ model.layers[0]._compiled_call_impl = marker+ with diffusion_infer.inference_compile(model, "reduce-overhead") as count:+ assert count == 2+ assert all(layer._compiled_call_impl is not None for layer in model.layers)+ assert model.layers[0]._compiled_call_impl is marker+ assert model.layers[1]._compiled_call_impl is None+ with diffusion_infer.inference_compile(model, "reduce-overhead"):+ pass+ assert len(compiled) == 2 and compiled[0] == {"mode": "reduce-overhead", "dynamic": True}+ with diffusion_infer.inference_compile(model, None) as count:+ assert count == 0+++ "value, device, expected",+ [+ ("auto", "cuda", "graphs"),+ ("auto", "cpu", None),+ (True, "cuda", "graphs"),+ ("default", "cuda", "default"),+ (False, "cuda", None),+ ("reduce-overhead", "cuda", "reduce-overhead"),+ ],+)+def test_resolve_compile(value, device, expected):+ from unsloth.models.diffusion_infer import resolve_compile+ assert resolve_compile(value, torch.device(device)) == expected+++def test_graphed_forward_remembers_a_failed_capture_on_the_model():+ from unsloth.models.diffusion_infer import GraphedForward++ model = torch.nn.Module()+ model.__dict__["_unsloth_graph_capture_failed"] = "RuntimeError: host sync"+ calls = []+ graphed = GraphedForward(lambda x: calls.append(x) or x + 1, owner = model)+ assert graphed.failed is not None+ assert torch.equal(graphed(torch.zeros(2)), torch.ones(2)) and len(calls) == 1+ assert graphed.graphs == {}+++def test_block_head_graphs_are_freed_without_a_gc_pass():+ import gc+ import weakref++ from unsloth.models.diffusion_infer import BlockHead++ gc.disable()+ try:+ head = BlockHead(_Bidirectional(), graphs = True)+ graphed = weakref.ref(head.graphed)+ del head+ assert (+ graphed() is None+ ) # the CUDA Graphs and their pool go with the call, not at the next gc+ finally:+ gc.enable()+++def test_graphed_forward_cancel_during_capture_does_not_disable_graphs(monkeypatch):+ from unsloth.models.diffusion_infer import DiffusionGenerationCancelled, GraphedForward++ model = torch.nn.Module()+ graphed = GraphedForward(lambda x: x, owner = model)++ def cancelled(x):+ raise DiffusionGenerationCancelled("stop")++ monkeypatch.setattr(graphed, "_capture", cancelled)+ monkeypatch.setattr(torch.cuda, "synchronize", lambda *a, **k: None)+ with pytest.raises(DiffusionGenerationCancelled):+ graphed(torch.zeros(2))+ assert graphed.failed is None+ assert "_unsloth_graph_capture_failed" not in model.__dict__+++def test_graphed_forward_out_of_memory_is_not_remembered_on_the_model(monkeypatch):+ from unsloth.models.diffusion_infer import GraphedForward++ model = torch.nn.Module()+ graphed = GraphedForward(lambda x: x + 1, owner = model)++ def out_of_memory(x):+ raise torch.cuda.OutOfMemoryError("CUDA out of memory")++ monkeypatch.setattr(graphed, "_capture", out_of_memory)+ monkeypatch.setattr(torch.cuda, "synchronize", lambda *a, **k: None)+ assert torch.equal(graphed(torch.zeros(2)), torch.ones(2))+ assert "_unsloth_graph_capture_failed" not in model.__dict__+ assert GraphedForward(lambda x: x, owner = model).failed is None+++class _ToyNemotron(torch.nn.Module):+ """Nemotron-Labs-Diffusion's generate call pattern: prefill, per-step block denoise, block commit."""++ def __init__(self):+ super().__init__()+ self.config = type("Config", (), {"block_size": 4})()+ self.weight = torch.nn.Parameter(torch.zeros(1))++ def forward(+ self,+ ids,+ past_key_values = None,+ use_cache = False,+ use_causal_mask = False,+ ):+ return type("Out", (), {"past_key_values": object()})()++ def generate(+ self,+ prompt_ids,+ max_new_tokens,+ block_length,+ threshold = None,+ temperature = 0.0,+ eos_token_id = None,+ ):+ x = prompt_ids.clone()+ out = self(prompt_ids, use_cache = True, use_causal_mask = True)+ for block in range(max_new_tokens // block_length):+ x = torch.cat([x, torch.full((1, block_length), 99)], dim = 1)+ start = x.shape[1] - block_length+ for step in range(block_length):+ self(x[:, start:], past_key_values = out.past_key_values, use_cache = False)+ x[0, start + step] = 10 * block + step+ out = self(+ x[:, start:],+ past_key_values = out.past_key_values,+ use_cache = True,+ use_causal_mask = True,+ )+ return x, 0+++def test_nemotron_streams_frames_from_its_own_generate():+ from unsloth.models import diffusion_samplers+ from unsloth.models.diffusion_infer import make_progress++ frames = []+ progress = make_progress(frames.append, None, 0.0, 99, 6)+ model = _ToyNemotron()+ out = diffusion_samplers._nemotron_sample(+ model,+ None,+ torch.tensor([[1, 2, 3]]),+ None,+ max_new_tokens = 6,+ steps = None,+ block_length = 4,+ temperature = 0.0,+ mask_id = 99,+ eos_ids = [],+ progress = progress,+ )+ progress.close()+ ends = [f for f in frames if f["step"] == f["total"]]+ assert [f["block"] for f in ends] == [0, 1]+ assert ends[-1]["tokens"] == out[0, :6].tolist() == [0, 1, 2, 3, 10, 11]+ assert all(len(f["tokens"]) == 6 for f in frames)+ assert [f["step"] for f in frames if f["block"] == 0] == [0, 1, 2, 3, 4]+ assert frames[1]["tokens"] == [0, 99, 99, 99, 99, 99]+ assert not model._forward_pre_hooks+++def test_nemotron_without_on_frame_adds_no_hook():+ from unsloth.models import diffusion_samplers+ from unsloth.models.diffusion_infer import make_progress++ model = _ToyNemotron()+ seen = []+ model.register_forward_pre_hook(lambda m, a: seen.append(len(m._forward_pre_hooks)))+ diffusion_samplers._nemotron_sample(+ model,+ None,+ torch.tensor([[1]]),+ None,+ max_new_tokens = 4,+ steps = None,+ block_length = 4,+ temperature = 0.0,+ mask_id = 99,+ eos_ids = [],+ progress = make_progress(None, None, 0.0, 99, 4),+ )+ assert set(seen) == {1}+++def test_graphs_env_opt_out_also_covers_auto(monkeypatch):+ from unsloth.models.diffusion_infer import resolve_compile++ monkeypatch.setenv("UNSLOTH_DIFFUSION_CUDA_GRAPHS", "0")+ assert resolve_compile("auto", torch.device("cuda")) is None+ assert resolve_compile(True, torch.device("cuda")) is None+ assert resolve_compile("graphs", torch.device("cuda")) is None+ assert resolve_compile("reduce-overhead", torch.device("cuda")) == "reduce-overhead"+++def test_host_synced_moe_only_for_unstacked_expert_lists():+ from unsloth.models.diffusion_infer import host_synced_moe++ dense = torch.nn.Sequential(torch.nn.Linear(2, 2))+ assert not host_synced_moe(dense)+ moe = torch.nn.Module()+ moe.experts = torch.nn.ModuleList([torch.nn.Linear(2, 2)])+ model = torch.nn.Sequential(moe)+ assert host_synced_moe(model)+ moe.__dict__["_unsloth_grouped_experts"] = (torch.zeros(1),)+ assert not host_synced_moe(model)diff --git a/tests/diffusion/test_diffusion_infer_block.py b/tests/diffusion/test_diffusion_infer_block.pynew file mode 100644index 00000000000..3bb9af1f61d--- /dev/null+++ b/tests/diffusion/test_diffusion_infer_block.py@@ -0,0 +1,881 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Cached block diffusion (SDAR, LLaDA2) matches the recompute sampler, the Dream port matches Dream's own loop,+and the grouped MoE eval dispatch matches the remote per-expert loop."""++import math+from types import SimpleNamespace++import pytest+import torch+import torch.nn.functional as F++from unsloth.models import diffusion_samplers as S+from unsloth.models.diffusion_infer_block import (+ _Frames,+ _llada2_graph,+ _PrefixCache,+ _select,+ _StaticPrefixCache,+ cached_block_sample,+)+from unsloth.models.diffusion_infer_dream import dream_fast_sample, dream_fast_supported++VOCAB, MASK_ID, EOS_ID, HIDDEN = 53, 52, 2, 16+++def _prepare_4d_causal_attention_mask_for_sdpa(mask, shape, hidden, past):+ # The LLaDA2 runner looks this up in the model's module, as the remote code imports it.+ return mask+++class _Layer(torch.nn.Module):+ """One attention layer over a block-causal mask, with either cache protocol: SDAR's `store_kv` or a+ LLaDA2-style `past_key_value.update`."""++ def __init__(self):+ super().__init__()+ self.qkv = torch.nn.Linear(HIDDEN, 3 * HIDDEN)+ self.out = torch.nn.Linear(HIDDEN, HIDDEN)++ def forward(+ self,+ hidden,+ attention_mask = None,+ past_key_value = None,+ position_embeddings = None,+ store_kv = True,+ **unused,+ ):+ hidden = hidden + position_embeddings+ q, k, v = self.qkv(hidden)[:, None].chunk(3, dim = -1)+ if past_key_value is not None:+ if store_kv:+ k, v = past_key_value.update(k, v, 0)+ elif past_key_value.get_seq_length() > 0:+ layer = past_key_value.layers[0]+ k, v = torch.cat([layer.keys, k], dim = -2), torch.cat([layer.values, v], dim = -2)+ out = F.scaled_dot_product_attention(q, k, v, attn_mask = attention_mask)+ return (hidden + self.out(out[:, 0]),)+++class _Inner(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.word_embeddings = torch.nn.Embedding(VOCAB, HIDDEN)+ self.positions = torch.nn.Embedding(256, HIDDEN)+ self.layers = torch.nn.ModuleList([_Layer()])+ self.norm = torch.nn.LayerNorm(HIDDEN)++ def rotary_emb(self, hidden, position_ids):+ return self.positions(position_ids)+++class _ToyBlockModel(torch.nn.Module):+ def __init__(self, seed):+ super().__init__()+ torch.manual_seed(seed)+ self.model = _Inner()+ self.lm_head = torch.nn.Linear(HIDDEN, VOCAB)+ with torch.no_grad():+ self.lm_head.bias[MASK_ID] = -1e4+ self.config = SimpleNamespace(mask_token_id = MASK_ID, eos_token_id = EOS_ID)++ def forward(+ self,+ ids,+ attention_mask = None,+ position_ids = None,+ past_key_values = None,+ store_kv = True,+ **unused,+ ):+ hidden = self.model.layers[0](+ self.model.word_embeddings(ids),+ attention_mask = attention_mask,+ past_key_value = past_key_values,+ position_embeddings = self.model.rotary_emb(None, position_ids),+ store_kv = store_kv,+ )[0]+ return SimpleNamespace(logits = self.lm_head(self.model.norm(hidden)))+++ "family, block_length, steps", [("sdar", 4, 4), ("sdar", 8, 3), ("llada2", 8, 8)]+)[email protected]("prompt_length", [3, 8, 11, 16, 17])+def test_cached_block_sample_matches_recompute(family, block_length, steps, prompt_length):+ base = _ToyBlockModel(seed = prompt_length).eval()+ torch.manual_seed(1)+ ids = torch.randint(3, MASK_ID, (2, prompt_length))+ kwargs = dict(+ max_new_tokens = 13,+ steps = steps,+ block_length = block_length,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.3,+ )+ with torch.no_grad():+ reference = S._block_sample(+ base,+ None,+ ids,+ None,+ mask_format = "additive" if family == "llada2" else "bool",+ **kwargs,+ )+ cached = cached_block_sample(base, ids, family = family, **kwargs)+ assert torch.equal(reference, cached)+ assert not bool((cached == MASK_ID).any())+++def test_cached_block_sample_stops_after_eos_block():+ base = _ToyBlockModel(seed = 0).eval()+ with torch.no_grad():+ base.lm_head.bias[EOS_ID] = 50.0+ ids = torch.randint(3, MASK_ID, (1, 5))+ kwargs = dict(+ max_new_tokens = 30,+ steps = 4,+ block_length = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [EOS_ID],+ confidence_threshold = 0.9,+ )+ with torch.no_grad():+ reference = S._block_sample(base, None, ids, None, mask_format = "bool", **kwargs)+ cached = cached_block_sample(base, ids, family = "sdar", **kwargs)+ assert torch.equal(reference, cached) and cached.shape[1] == 3+++def test_cached_block_sample_frames_and_cancel():+ base = _ToyBlockModel(seed = 0).eval()+ ids = torch.randint(3, MASK_ID, (1, 5))+ frames = []+ out = cached_block_sample(+ base,+ ids,+ family = "sdar",+ max_new_tokens = 11,+ steps = 4,+ block_length = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.9,+ on_frame = frames.append,+ )+ ends = [f for f in frames if f["step"] == f["total"]]+ # Exactly one block-end frame per decoded block; in-block frames stay below total.+ assert [f["block"] for f in ends] == [1, 2, 3]+ assert all(0 <= f["step"] < f["total"] for f in frames if f not in ends)+ assert len(ends) == 3 and ends[-1]["tokens"] == out[0].tolist()+ assert all(set(f) == {"block", "step", "total", "tokens", "mask_id"} for f in frames)++ def cancel():+ raise RuntimeError("stop")++ with pytest.raises(RuntimeError):+ cached_block_sample(+ base,+ ids,+ family = "sdar",+ max_new_tokens = 11,+ steps = 4,+ block_length = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.9,+ check_stop = cancel,+ )+++def _reference_select(logits, mask_index, count, threshold):+ """The recompute sampler's per-row selection (greedy)."""+ probs = F.softmax(logits, dim = -1)+ x0 = probs.argmax(dim = -1)+ confidence = torch.where(mask_index, probs.gather(-1, x0[..., None])[..., 0], -math.inf)+ transfer = torch.zeros_like(mask_index)+ for row in range(logits.shape[0]):+ high = confidence[row] > threshold+ if int(high.sum()) >= count:+ transfer[row] = high+ else:+ k = min(count, int(mask_index[row].sum()))+ transfer[row, torch.topk(confidence[row], k).indices] = True+ return x0, transfer++[email protected]("count", [1, 2, 5])[email protected]("threshold", [0.0, 0.05, 0.99])+def test_select_matches_per_row_reference(count, threshold):+ torch.manual_seed(count)+ logits = torch.randn(3, 6, 11) * 3+ mask_index = torch.rand(3, 6) < 0.5+ mask_index[0] = True+ mask_index[1, :] = False+ mask_index[1, 2] = True+ x0, transfer = _select(logits, mask_index, 0.0, 0, 1.0, torch.full((3, 1), count), threshold)+ ref_x0, ref_transfer = _reference_select(logits, mask_index, count, threshold)+ assert torch.equal(x0, ref_x0)+ assert torch.equal(transfer, ref_transfer)+++def test_prefix_cache_reads_without_writing():+ cache = _PrefixCache()+ k = torch.ones(1, 1, 2, 4)+ cache.commit = True+ cache.update(k, k, 0)+ cache.commit = False+ key, _ = cache.update(2 * k, 2 * k, 0)+ assert key.shape[-2] == 4 and cache.get_seq_length() == 2+++def test_static_prefix_cache_writes_rows():+ cache = _StaticPrefixCache(8)+ cache.rows = torch.tensor([2, 3])+ key, value = cache.update(torch.ones(1, 1, 2, 4), 2 * torch.ones(1, 1, 2, 4), 0)+ assert key.shape == (1, 1, 8, 4)+ assert key[0, 0, :, 0].tolist() == [0, 0, 1, 1, 0, 0, 0, 0]+ assert value[0, 0, 3, 0] == 2+++def test_llada2_graph_only_on_cuda_without_adapters(monkeypatch):+ base = _ToyBlockModel(seed = 0)+ assert _llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cpu")) is None+ monkeypatch.setenv("UNSLOTH_DIFFUSION_CUDA_GRAPHS", "0")+ assert _llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cuda")) is None+++ "compile_mode, expected", [("graphs", True), (None, False), ("default", False)]+)+def test_llada2_graph_follows_generate_text_compile(monkeypatch, compile_mode, expected):+ from unsloth.models import diffusion_infer_block, diffusion_samplers, remote_moe_shims++ seen = {}+ monkeypatch.setattr(remote_moe_shims, "prepare_remote_moe_for_inference", lambda base: None)+ monkeypatch.setattr(+ diffusion_infer_block, "cached_block_sample", lambda base, ids, **kw: seen.update(kw)+ )+ diffusion_samplers._llada2_sample(+ None,+ None,+ torch.zeros(1, 3, dtype = torch.long),+ None,+ steps = None,+ block_length = None,+ max_new_tokens = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ compile_mode = compile_mode,+ )+ assert seen["cuda_graphs"] is expected and "compile_mode" not in seen+++def test_frames_throttle_and_stop():+ seen, stops = [], []+ frames = _Frames(seen.append, lambda: stops.append(1), interval = 3600)+ x = torch.arange(10)[None]+ for step in range(5):+ frames.step(x, 4, 8, 0, step, 5, MASK_ID)+ frames.step(x, 4, 8, 0, 5, 5, MASK_ID, force = True)+ assert len(stops) == 6+ assert [frame["step"] for frame in seen] == [0, 5]+ assert seen[-1]["tokens"] == [4, 5, 6, 7]++ def cancel():+ raise RuntimeError("stop")++ with pytest.raises(RuntimeError):+ _Frames(None, cancel).step(x, 4, 8, 0, 0, 5, MASK_ID)+++def test_cached_block_sample_frames_through_generate_text_progress():+ # generate_text hands samplers its Progress (not on_frame): frames must still reach the caller.+ from unsloth.models.diffusion_infer import make_progress++ base = _ToyBlockModel(seed = 0).eval()+ ids = torch.randint(3, MASK_ID, (1, 5))+ frames = []+ progress = make_progress(frames.append, None, 0.0, MASK_ID, 11)+ out = cached_block_sample(+ base,+ ids,+ family = "sdar",+ max_new_tokens = 11,+ steps = 4,+ block_length = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.9,+ progress = progress,+ )+ progress.close()+ ends = [f for f in frames if f["step"] == f["total"]]+ assert len(ends) == 3 and ends[-1]["tokens"] == out[0].tolist()[:11]+ assert all(0 <= f["step"] < f["total"] for f in frames if f not in ends)+ assert all(set(f) == {"block", "step", "total", "tokens", "mask_id"} for f in frames)+++class _ToyDream(torch.nn.Module):+ """Bidirectional toy with Dream's call shape: model(input_ids, attention_mask) -> (hidden,), lm_head."""++ def __init__(self):+ super().__init__()+ torch.manual_seed(0)+ self.embed = torch.nn.Embedding(VOCAB, HIDDEN)+ self.mix = torch.nn.Linear(HIDDEN, HIDDEN)+ self.lm_head = torch.nn.Linear(HIDDEN, VOCAB)+ with torch.no_grad():+ self.lm_head.bias[MASK_ID] = -1e4+ toy = self++ class _Model(torch.nn.Module):+ def forward(+ self,+ input_ids = None,+ attention_mask = None,+ ):+ h = toy.embed(input_ids)+ return (h + torch.tanh(toy.mix(h.mean(1, keepdim = True))),)++ self.model = _Model()++ def forward(+ self,+ x,+ attention_mask = None,+ tok_idx = None,+ ):+ return SimpleNamespace(logits = self.lm_head(self.model(x, attention_mask)[0]))+++def _dream_reference(+ model,+ input_ids,+ max_new_tokens,+ steps,+ alg,+ eps = 1e-3,+):+ """Dream generation_utils `_sample` at temperature 0, alg_temp 0 (official loop, full logits)."""+ x = F.pad(input_ids, (0, max_new_tokens), value = MASK_ID)+ timesteps = torch.linspace(1, eps, steps + 1)+ for i in range(steps):+ mask_index = x == MASK_ID+ logits = model(x, "full", None).logits+ logits = torch.cat([logits[:, :1], logits[:, :-1]], dim = 1)+ mask_logits = logits[mask_index]+ t, s = timesteps[i], timesteps[i + 1]+ probs = torch.softmax(mask_logits, dim = -1)+ confidence, x0 = probs.max(dim = -1)+ if alg == "topk_margin":+ top2 = torch.topk(probs, 2, dim = -1).values+ confidence = top2[..., 0] - top2[..., 1]+ elif alg == "entropy":+ confidence = torch.sum(probs * torch.log(probs + 1e-10), dim = -1)+ num_mask_token = mask_index.sum() / mask_index.shape[0]+ number_transfer_tokens = (+ int(num_mask_token * (1 - s / t)) if i < steps - 1 else int(num_mask_token)+ )+ full_confidence = torch.full_like(x, -torch.inf, dtype = logits.dtype)+ full_confidence[mask_index] = confidence+ if number_transfer_tokens > 0:+ _, transfer_index = torch.topk(full_confidence, number_transfer_tokens)+ x_ = torch.zeros_like(x) + MASK_ID+ x_[mask_index] = x0.clone()+ row_indices = torch.arange(x.size(0)).unsqueeze(1).expand_as(transfer_index)+ x[row_indices, transfer_index] = x_[row_indices, transfer_index]+ return x++[email protected]("alg", ["entropy", "maskgit_plus", "topk_margin"])[email protected]("max_new_tokens, steps", [(12, 12), (12, 5), (7, 3)])+def test_dream_fast_sample_matches_reference(alg, max_new_tokens, steps):+ model = _ToyDream().eval()+ ids = torch.randint(3, MASK_ID, (2, 5))+ with torch.no_grad():+ reference = _dream_reference(model, ids.clone(), max_new_tokens, steps, alg)+ fast = dream_fast_sample(+ model, ids, max_new_tokens = max_new_tokens, steps = steps, mask_id = MASK_ID, alg = alg+ )+ assert torch.equal(reference, fast)+++def test_dream_fast_sample_frames_contract():+ model = _ToyDream().eval()+ frames = []+ dream_fast_sample(+ model,+ torch.randint(3, MASK_ID, (1, 5)),+ max_new_tokens = 6,+ steps = 3,+ mask_id = MASK_ID,+ on_frame = frames.append,+ )+ ends = [f for f in frames if f["step"] == f["total"]]+ assert len(ends) == 1 and frames[-1] is ends[0]+ assert all(0 <= f["step"] < f["total"] for f in frames[:-1])+++def test_dream_fast_sample_defers_when_the_mask_is_proposed():+ model = _ToyDream().eval()+ with torch.no_grad():+ model.lm_head.bias[MASK_ID] = 1e4+ ids = torch.randint(3, MASK_ID, (1, 5))+ assert dream_fast_sample(model, ids, max_new_tokens = 6, steps = 3, mask_id = MASK_ID) is None+++def test_dream_fast_path_only_for_greedy_defaults():+ ids = torch.tensor([[5, 6]])+ assert dream_fast_supported(ids, None, MASK_ID, 0.0, None, None, "entropy", 0.0)+ assert not dream_fast_supported(ids, None, MASK_ID, 0.7, 0.95, None, "entropy", 0.0)+ assert not dream_fast_supported(ids, None, MASK_ID, 0.0, None, None, "origin", 0.0)+ assert not dream_fast_supported(ids, None, MASK_ID, 0.0, None, None, "entropy", 0.5)+ assert not dream_fast_supported(+ ids, torch.tensor([[0, 1]]), MASK_ID, 0.0, None, None, "entropy", 0.0+ )+ assert not dream_fast_supported(+ torch.tensor([[MASK_ID, 6]]), None, MASK_ID, 0.0, None, None, "entropy", 0.0+ )+++def test_dream_fast_path_rejects_an_empty_prompt():+ empty = torch.zeros((1, 0), dtype = torch.long)+ assert not dream_fast_supported(empty, None, MASK_ID, 0.0, None, None, "entropy", 0.0)+++def test_dream_fallback_frames_never_step_back():+ # The fast pass proposes the mask token and defers to diffusion_generate after streaming its own frames.+ from unsloth.models.diffusion_infer import make_progress+ from unsloth.models.diffusion_samplers import _dream_sample++ model = _ToyDream().eval()+ with torch.no_grad():+ model.lm_head.bias[MASK_ID] = 1e4++ def diffusion_generate(+ input_ids, *, max_new_tokens, steps, generation_tokens_hook_func, **kwargs+ ):+ x = generation_tokens_hook_func(+ None, F.pad(input_ids, (0, max_new_tokens), value = MASK_ID), None+ )+ for i in range(steps):+ x[:, input_ids.shape[1] + i] = 7+ x = generation_tokens_hook_func(i, x, None)+ return SimpleNamespace(sequences = x)++ model.diffusion_generate = diffusion_generate+ frames = []+ progress = make_progress(frames.append, None, 0.0, MASK_ID, 4)+ out = _dream_sample(+ model,+ None,+ torch.randint(3, MASK_ID, (1, 5)),+ None,+ max_new_tokens = 4,+ steps = 4,+ block_length = None,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ progress = progress,+ check_stop = progress.check,+ )+ progress.close()+ steps = [f["step"] for f in frames]+ assert steps == sorted(steps) and steps.count(4) == 1 and steps[-1] == 4+ assert frames[-1]["tokens"] == out[0].tolist() == [7, 7, 7, 7]+++def test_llada2_graph_recaptures_after_weights_move(monkeypatch):+ from unsloth.models import diffusion_infer_block++ built = []+ monkeypatch.setattr(+ diffusion_infer_block, "_Llada2Graph", lambda *args: built.append(args) or object()+ )+ base = _ToyBlockModel(seed = 0)+ device = torch.device("cuda")+ first = _llada2_graph(base, 1, 4, 16, torch.float32, device)+ assert _llada2_graph(base, 1, 4, 16, torch.float32, device) is first and len(built) == 1+ # model.to(...) and back re-points every parameter: the old graph would replay freed memory.+ with torch.no_grad():+ base.lm_head.weight.data = base.lm_head.weight.data.clone()+ assert _llada2_graph(base, 1, 4, 16, torch.float32, device) is not first and len(built) == 2+++class _Expert(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.gate_proj = torch.nn.Linear(8, 4, bias = False, dtype = torch.bfloat16)+ self.up_proj = torch.nn.Linear(8, 4, bias = False, dtype = torch.bfloat16)+ self.down_proj = torch.nn.Linear(4, 8, bias = False, dtype = torch.bfloat16)+ self.act_fn = torch.nn.SiLU()+++class _RemoteMoE(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.experts = torch.nn.ModuleList([_Expert() for _ in range(3)])++ def moe_infer(self, x, topk_ids, topk_weight):+ counts = topk_ids.bincount().cpu()+ return self.experts[0](x) * counts[0]+++_RemoteMoE.__module__ = "transformers_modules.toy.modeling"+++def _stack(monkeypatch, block):+ from unsloth.models import remote_moe_shims+ monkeypatch.setattr(remote_moe_shims, "_grouped_mm_for", lambda weights: "grouped_mm")+ return remote_moe_shims._grouped_experts(block)+++def test_grouped_experts_keep_parameters_and_alias_the_stack(monkeypatch):+ block = _RemoteMoE()+ params = [p for p in block.parameters()]+ values = [p.detach().clone() for p in params]+ gate, up, down, _ = _stack(monkeypatch, block)+ # Same Parameter objects (an optimizer made before generate keeps training them), now views of the stack.+ assert [p for p in block.parameters()] == params+ assert all(torch.equal(p, v) for p, v in zip(params, values))+ assert block.experts[2].down_proj.weight.data_ptr() == down[2].data_ptr()+++def test_prepare_drops_stale_grouped_experts(monkeypatch):+ from unsloth.models import remote_moe_shims++ block = _RemoteMoE()+ model = torch.nn.ModuleDict({"mlp": block})+ remote_moe_shims.prepare_remote_moe_for_inference(model)+ assert _stack(monkeypatch, block) is not None+ remote_moe_shims.prepare_remote_moe_for_inference(model)+ assert block.__dict__["_unsloth_grouped_experts"] is not None++ # model.to(...) and back: the cached stack no longer backs the weights, so it is not reused or kept alive.+ with torch.no_grad():+ for expert in block.experts:+ expert.up_proj.weight.data = expert.up_proj.weight.data.clone()+ remote_moe_shims.prepare_remote_moe_for_inference(model)+ assert "_unsloth_grouped_experts" not in block.__dict__+ assert _stack(monkeypatch, block) is not None++ # A LoRA wrap added after a generate: the grouped path would skip the adapters.+ class _Wrapped(torch.nn.Linear):+ pass++ for expert in block.experts:+ wrapped = _Wrapped(8, 4, bias = False, dtype = torch.bfloat16)+ wrapped.weight = expert.gate_proj.weight+ expert.gate_proj = wrapped+ assert remote_moe_shims._grouped_experts(block) is None+++def test_grouped_mm_for_refuses_cpu_weights():+ from unsloth.models import remote_moe_shims+ assert remote_moe_shims._grouped_mm_for((torch.zeros(4, 8, dtype = torch.bfloat16),)) is None+++ "capability, hip, choice, expected",+ [+ ((9, 0), None, "auto", ["torch", "triton"]),+ ((10, 0), None, "auto", ["torch", "triton"]),+ # A100 / L4 / RTX: torch._grouped_mm loops over host-copied offsets there (or raises on 2.8).+ ((8, 0), None, "auto", ["triton"]),+ ((8, 9), None, "auto", ["triton"]),+ ((12, 0), None, "auto", ["triton"]),+ ((7, 5), None, "auto", []),+ ((8, 0), None, "torch", ["torch"]),+ ((9, 0), None, "0", []),+ ((9, 4), "6.4", "auto", ["torch"]),+ ],+)+def test_grouped_mm_candidates_by_gpu(monkeypatch, capability, hip, choice, expected):+ from unsloth.models import remote_moe_shims++ monkeypatch.setattr(torch.cuda, "get_device_capability", lambda device = None: capability)+ monkeypatch.setattr(torch.version, "hip", hip)+ monkeypatch.setenv("UNSLOTH_MOE_INFER_GROUPED", choice)+ names = {+ remote_moe_shims._torch_grouped_mm: "torch",+ remote_moe_shims._triton_grouped_mm: "triton",+ }+ found = remote_moe_shims._grouped_mm_candidates(torch.zeros(1))+ assert [names[f] for f in found] == expected+++def test_grouped_mm_for_logs_once_and_falls_back(monkeypatch, capsys):+ from unsloth.models import remote_moe_shims++ def broken(inputs, weight, offsets):+ raise RuntimeError("grouped gemm is only supported on SM90")++ weight = torch.ones(4, 8, dtype = torch.bfloat16)+ monkeypatch.setattr(torch.Tensor, "is_cuda", property(lambda self: True))+ monkeypatch.setattr(remote_moe_shims, "_grouped_mm_candidates", lambda weight: [broken])+ monkeypatch.setattr(remote_moe_shims, "_FALLBACK_LOGGED", set())+ assert remote_moe_shims._grouped_mm_for((weight,)) is None+ assert remote_moe_shims._grouped_mm_for((weight,)) is None+ assert capsys.readouterr().out.count("keeps the per-expert loop") == 1++ def matmul(inputs, weight, offsets):+ return torch.cat([inputs[:1] @ weight[0], inputs[1:] @ weight[1]])++ monkeypatch.setattr(remote_moe_shims, "_grouped_mm_candidates", lambda weight: [broken, matmul])+ assert remote_moe_shims._grouped_mm_for((weight,)) is matmul+++def test_progress_frames_carry_the_whole_generated_region():+ # Later blocks are still masks in every frame, so the canvas length never changes mid-reply.+ from unsloth.models.diffusion_infer import make_progress++ base = _ToyBlockModel(seed = 0).eval()+ frames = []+ progress = make_progress(frames.append, None, 0.0, MASK_ID, 11)+ cached_block_sample(+ base,+ torch.randint(3, MASK_ID, (1, 5)),+ family = "sdar",+ max_new_tokens = 11,+ steps = 4,+ block_length = 4,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.9,+ progress = progress,+ )+ progress.close()+ assert {len(f["tokens"]) for f in frames} == {11}+ assert frames[0]["tokens"][-1] == MASK_ID+++def test_llada2_graph_cache_is_freed_once_adapters_appear():+ from unsloth.models import diffusion_infer_block++ base = _ToyBlockModel(seed = 0)+ base.__dict__["_unsloth_llada2_graphs"] = {"weights": (), (1, 4, 1024): object()}+ base.model.lora_A = torch.nn.Linear(1, 1)+ assert (+ diffusion_infer_block._llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cuda"))+ is None+ )+ assert "_unsloth_llada2_graphs" not in base.__dict__++[email protected]("error, latched", [(RuntimeError("host sync"), True), ("oom", False)])+def test_llada2_graph_latches_only_real_capture_failures(monkeypatch, error, latched):+ from unsloth.models import diffusion_infer_block++ if error == "oom":+ error = torch.cuda.OutOfMemoryError("CUDA out of memory")++ def capture(*args, **kwargs):+ raise error++ monkeypatch.setattr(diffusion_infer_block, "_Llada2Graph", capture)+ base = _ToyBlockModel(seed = 0)+ assert (+ diffusion_infer_block._llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cuda"))+ is None+ )+ assert bool(base.__dict__["_unsloth_llada2_graphs"].get("failed")) is latched+++def test_llada2_graph_capture_lets_a_stop_through(monkeypatch):+ from unsloth.models import diffusion_infer_block+ from unsloth.models.diffusion_infer import DiffusionGenerationCancelled++ def capture(*args, **kwargs):+ raise DiffusionGenerationCancelled("stop")++ monkeypatch.setattr(diffusion_infer_block, "_Llada2Graph", capture)+ base = _ToyBlockModel(seed = 0)+ with pytest.raises(DiffusionGenerationCancelled):+ diffusion_infer_block._llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cuda"))+ assert not base.__dict__["_unsloth_llada2_graphs"].get("failed")+++def test_llada2_graph_is_not_attempted_over_a_host_synced_expert_loop(monkeypatch):+ from unsloth.models import diffusion_infer_block++ monkeypatch.setattr(+ diffusion_infer_block, "_Llada2Graph", lambda *a, **k: pytest.fail("capture attempted")+ )+ base = _ToyBlockModel(seed = 0)+ base.model.moe = torch.nn.Module()+ base.model.moe.experts = torch.nn.ModuleList([torch.nn.Linear(2, 2)])+ assert (+ diffusion_infer_block._llada2_graph(base, 1, 4, 16, torch.float32, torch.device("cuda"))+ is None+ )+++ "config, fast, eps",+ [+ (SimpleNamespace(eps = 0.05, top_k = None), True, 0.05),+ (SimpleNamespace(eps = 1e-3, top_k = 5), False, None),+ (None, True, 1e-3),+ ],+)+def test_dream_fast_path_follows_the_generation_config(monkeypatch, config, fast, eps):+ from unsloth.models import diffusion_infer_dream++ seen = {}++ def fast_sample(base, input_ids, **kwargs):+ seen.update(kwargs)+ return torch.cat([input_ids, torch.full((1, kwargs["max_new_tokens"]), 7)], dim = 1)++ monkeypatch.setattr(diffusion_infer_dream, "dream_fast_sample", fast_sample)+ model = _ToyDream().eval()+ if config is not None:+ model.generation_config = config+ model.diffusion_generate = lambda input_ids, **kw: SimpleNamespace(+ sequences = torch.cat([input_ids, torch.full((1, kw["max_new_tokens"]), 8)], dim = 1)+ )+ out = S._dream_sample(+ model,+ None,+ torch.randint(3, MASK_ID, (1, 5)),+ None,+ max_new_tokens = 4,+ steps = 4,+ block_length = None,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ )+ assert out[0].tolist() == ([7] * 4 if fast else [8] * 4)+ assert seen.get("eps") == eps+++def test_llada2_cached_path_without_the_legacy_mask_helper(monkeypatch):+ # LLaDA2.1's remote code no longer exports _prepare_4d_causal_attention_mask_for_sdpa; the additive block+ # mask goes to the layers as built, and the result still matches the recompute sampler.+ import sys++ monkeypatch.delattr(sys.modules[__name__], "_prepare_4d_causal_attention_mask_for_sdpa")+ base = _ToyBlockModel(seed = 3).eval()+ torch.manual_seed(1)+ ids = torch.randint(3, MASK_ID, (2, 11))+ kwargs = dict(+ max_new_tokens = 13,+ steps = 8,+ block_length = 8,+ temperature = 0.0,+ mask_id = MASK_ID,+ eos_ids = [],+ confidence_threshold = 0.3,+ )+ with torch.no_grad():+ reference = S._block_sample(base, None, ids, None, mask_format = "additive", **kwargs)+ assert torch.equal(reference, cached_block_sample(base, ids, family = "llada2", **kwargs))+++def test_capture_lock_is_one_lock_per_device():+ from unsloth.models.diffusion_infer import capture_lock+ assert capture_lock("cuda:0") is capture_lock(torch.device("cuda", 0))+ assert capture_lock("cuda:0") is not capture_lock("cuda:1")+++def test_grouped_stack_is_dropped_when_the_block_moves(monkeypatch):+ # model.to(...) moves the experts' parameters but not the cached stack tuple; it must not outlive the move.+ block = _RemoteMoE()+ assert _stack(monkeypatch, block) is not None+ block.to(torch.float64)+ assert "_unsloth_grouped_experts" not in block.__dict__+ assert _stack(monkeypatch, block)[0].dtype == torch.float64+++def test_drop_on_move_forgets_only_the_registered_cache():+ from unsloth.models.diffusion_infer import drop_on_move++ class _Model(torch.nn.Module):+ def __init__(self):+ super().__init__()+ self.linear = torch.nn.Linear(2, 2)++ model = _Model()+ model.__dict__["_unsloth_llada2_graphs"] = {"key": object()}+ model.__dict__["_unrelated"] = 1+ drop_on_move(model, "_unsloth_llada2_graphs")+ model.to(torch.float64)+ assert "_unsloth_llada2_graphs" not in model.__dict__ and model._unrelated == 1+ assert model.linear.weight.dtype == torch.float64+++def test_concurrent_first_generates_stack_the_experts_once(monkeypatch):+ import threading+ import time++ from unsloth.models import remote_moe_shims++ def slow(weights):+ time.sleep(0.05)+ return "grouped_mm"++ monkeypatch.setattr(remote_moe_shims, "_grouped_mm_for", slow)+ block = _RemoteMoE()+ results = []+ threads = [+ threading.Thread(target = lambda: results.append(remote_moe_shims._grouped_experts(block)))+ for _ in range(4)+ ]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ assert len({id(result) for result in results}) == 1+++def test_graphed_commit_replay_checks_for_a_stop_first():+ # A stop asked for while the block-end frame is delivered must land before the commit forward.+ from unsloth.models import diffusion_infer_block++ calls, stop = [], []++ def graph(window, start):+ calls.append(start)+ logits = torch.full((window.shape[0], window.shape[1], VOCAB), -10.0)+ logits[..., 5] = 10.0+ return logits++ def check_stop():+ if stop:+ raise RuntimeError("stop")++ frames = _Frames(+ lambda frame: stop.append(1) if frame["step"] == frame["total"] else None, check_stop, 0.0+ )+ x = torch.full((1, 8), MASK_ID)+ with pytest.raises(RuntimeError):+ diffusion_infer_block._graph_block_sample(+ graph,+ x,+ prompt_length = 0,+ num_blocks = 2,+ block_length = 4,+ steps = 4,+ counts = torch.full((4, 1, 1), 1),+ temperature = 0.0,+ top_k = 0,+ top_p = 1.0,+ mask_id = MASK_ID,+ eos = None,+ confidence_threshold = 0.9,+ frames = frames,+ )+ assert calls == [0] # the block's one denoising forward, no commit replay after the stopdiff --git a/tests/diffusion/test_diffusion_samplers.py b/tests/diffusion/test_diffusion_samplers.pyindex 8eef60a0a9d..a7520e5a467 100644--- a/tests/diffusion/test_diffusion_samplers.py+++ b/tests/diffusion/test_diffusion_samplers.py@@ -59,7 +59,9 @@ def _load_official_generate():@pytest.mark.skipif(not _LLADA_GENERATE, reason = "set UNSLOTH_LLADA_GENERATE_PY to LLaDA's generate.py")[email protected]("temperature", [0.0, 0.7])+# Greedy only: the Gumbel noise is drawn for the active block, not the [B, L, V] canvas, so sampled runs share+# the reference's distribution but not its RNG stream (see test_llada_sampling_is_seeded_and_resolves_every_mask).[email protected]("temperature", [0.0])@pytest.mark.parametrize("remasking", ["low_confidence", "random"])def test_llada_sampler_matches_official(temperature, remasking):from unsloth.models.diffusion_samplers import _llada_sample@@ -95,6 +97,35 @@ def test_llada_sampler_matches_official(temperature, remasking):assert torch.equal(got, expected), (got, expected)[email protected]("remasking", ["low_confidence", "random"])+def test_llada_sampling_is_seeded_and_resolves_every_mask(remasking):+ from unsloth.models.diffusion_samplers import _llada_sample++ model = _TinyMaskPredictor()+ prompt = torch.tensor([[1, 7, 9, 11, 13], [3, 5, 7, 9, 11]])++ def sample(seed):+ torch.manual_seed(seed)+ return _llada_sample(+ model,+ None,+ prompt,+ None,+ max_new_tokens = 16,+ steps = 8,+ block_length = 8,+ temperature = 0.7,+ mask_id = MASK_ID,+ eos_ids = [],+ remasking = remasking,+ )++ first = sample(1)+ assert torch.equal(first, sample(1))+ assert first.shape == (2, 16) and not bool((first == MASK_ID).any())+ assert any(not torch.equal(first, sample(seed)) for seed in range(2, 6))++def test_llada_sampler_stops_after_eos_block():from unsloth.models.diffusion_samplers import _llada_samplediff --git a/unsloth/models/diffusion_infer.py b/unsloth/models/diffusion_infer.pynew file mode 100644index 00000000000..cc142eea696--- /dev/null+++ b/unsloth/models/diffusion_infer.py@@ -0,0 +1,331 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""Shared pieces of the diffusion samplers' fast path: in-loop cancellation and throttled canvas frames, the+active-block-only output head, and regional compile of the backbone for inference."""++import contextlib+import functools+import os+import threading+import time++import torch++from .diffusion_loss import (+ _decoder_layer_lists,+ _warm_rotary_caches,+ fusable_head,+ head_returns_hidden,+)++__all__ = [+ "DiffusionGenerationCancelled",+ "Progress",+ "make_progress",+ "BlockHead",+ "GraphedForward",+ "inference_compile",+ "resolve_compile",+]+++class DiffusionGenerationCancelled(RuntimeError):+ """Raised out of generate_text when stop_callback() returned True mid-generation."""+++class Progress:+ """Cancellation checks and canvas frames for one generate_text call.++ ``check()`` raises DiffusionGenerationCancelled once stop_callback() returns True. ``frame(...)`` hands+ on_frame a host copy of the generated region at most once per ``interval`` seconds (always when+ ``force``): the device copy is queued non-blocking into a pinned buffer and delivered on the next call,+ so the sampler never waits on it."""++ def __init__(self, on_frame, stop_callback, interval, mask_id, budget):+ self.on_frame = on_frame+ self.stop_callback = stop_callback+ self.interval = max(float(interval or 0.0), 0.0)+ self.mask_id = mask_id+ self.budget = int(budget)+ self._last = -float("inf")+ self._pending = None+ self.closed = False++ def check(self):+ if self.stop_callback is not None and self.stop_callback():+ raise DiffusionGenerationCancelled("Unsloth: diffusion generation cancelled.")++ def _emit(self, meta, tokens):+ if not self.closed:+ self.on_frame({**meta, "tokens": tokens, "mask_id": self.mask_id})++ def _flush(self, wait):+ if self._pending is None:+ return+ meta, buffer, event = self._pending+ if event is not None and not wait and not event.query():+ return+ if event is not None:+ event.synchronize()+ self._pending = None+ self._emit(meta, buffer.tolist())++ def frame(+ self,+ block,+ step,+ total,+ generated,+ force = False,+ ):+ """``generated`` is the first row's generated region ([L] or [1, L]); padding past the budget is cut."""+ if self.on_frame is None or self.closed:+ return+ self._flush(wait = force)+ now = time.monotonic()+ if not force and now - self._last < self.interval:+ return+ self._last = now+ row = generated.reshape(-1, generated.shape[-1])[0, : self.budget].detach()+ meta = {"block": int(block), "step": int(step), "total": int(total)}+ if row.device.type != "cuda":+ self._emit(meta, row.tolist())+ return+ # A one-row id snapshot: pinned host buffer + event, so the GPU never waits for the host.+ buffer = torch.empty(row.shape, dtype = row.dtype, pin_memory = True)+ with torch.cuda.device(+ row.device+ ): # the event must follow the copy on the canvas's own GPU+ buffer.copy_(row, non_blocking = True)+ event = torch.cuda.Event()+ event.record()+ self._pending = (meta, buffer, event)+ if force:+ self._flush(wait = True)++ def close(self):+ """Deliver the last queued frame, then never call on_frame again."""+ if self.on_frame is not None and not self.closed:+ self._flush(wait = True)+ self.closed = True+++def make_progress(+ on_frame,+ stop_callback,+ interval = 0.1,+ mask_id = None,+ budget = 0,+):+ return Progress(on_frame, stop_callback, interval, mask_id, budget)+++_SIDE_STREAMS = {}+_CAPTURE_LOCKS = {}+++def side_stream(device):+ """One warm-up / capture side stream per device for the whole process: cuBLAS keeps a workspace per stream,+ so a fresh stream per capture grows memory call after call."""+ device = torch.device(device)+ index = device.index if device.index is not None else torch.cuda.current_device()+ stream = _SIDE_STREAMS.get(index)+ if stream is None:+ stream = _SIDE_STREAMS[index] = torch.cuda.Stream(index)+ return stream+++def capture_lock(device):+ """Serialises warm-up + capture on a device's shared side stream: two first-time captures from different+ threads would otherwise interleave on it and invalidate each other."""+ device = torch.device(device)+ index = device.index if device.index is not None else torch.cuda.current_device()+ return _CAPTURE_LOCKS.setdefault(index, threading.Lock())+++def drop_on_move(module, attr):+ """Forget ``module.<attr>`` whenever the module's tensors are moved or cast (``to`` / ``cpu`` / ``cuda`` /+ ``half`` / ``float`` all go through ``Module._apply``): a cache kept as a plain attribute is not moved with+ them, so it would keep the old device's memory alive until the next generate."""+ cls = type(module)+ attrs = cls.__dict__.get("_unsloth_drop_on_apply")+ if attrs is None:+ attrs = set()+ original = cls._apply++ @functools.wraps(original)+ def _apply(self, *args, **kwargs):+ for name in attrs:+ self.__dict__.pop(name, None)+ return original(self, *args, **kwargs)++ cls._apply = _apply+ cls._unsloth_drop_on_apply = attrs+ attrs.add(attr)+++def graphs_disabled():+ return os.environ.get("UNSLOTH_DIFFUSION_CUDA_GRAPHS", "1") == "0"+++def host_synced_moe(base):+ """True when an MoE block would run an expert loop that copies counts to the host (not the grouped+ dispatch): that forward cannot be captured, and a failed capture is not free (on some torch versions it+ leaves the CUDA RNG unusable), so graphs are not attempted."""+ for module in base.modules():+ experts = getattr(module, "experts", None)+ if isinstance(experts, torch.nn.ModuleList) and len(experts):+ stacked = module.__dict__.get("_unsloth_grouped_experts")+ if not isinstance(stacked, tuple):+ return True+ return False+++class GraphedForward:+ """The backbone's eager forward captured into a CUDA Graph per input shape and replayed every step.++ Same kernels as eager, so the same numbers, without per-kernel launch overhead or a dynamo trace: a new+ canvas length costs two warm-up forwards and one capture. A forward that syncs with the host (an expert+ loop over ``torch.where``) cannot be captured: the first failure turns graphs off for this call."""++ def __init__(+ self,+ function,+ max_graphs = 2,+ owner = None,+ ):+ self.function = function+ self.max_graphs = max_graphs+ self.graphs = {}+ self.pool = None+ # Remembered on the model, so later calls skip straight to eager instead of re-trying the capture.+ self.owner = owner+ self.failed = None if owner is None else owner.__dict__.get("_unsloth_graph_capture_failed")++ def _capture(self, x):+ # The model's GPU, not whichever device is current: capture and warm-up streams live on one device.+ with capture_lock(x.device), torch.cuda.device(x.device):+ static_x = x.clone()+ stream = side_stream(x.device)+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(+ 2+ ): # warm-up outside capture: lazy buffers, cuBLAS handles, autotuned kernels+ self.function(static_x)+ torch.cuda.current_stream().wait_stream(stream)+ if self.pool is None:+ self.pool = torch.cuda.graph_pool_handle()+ graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(graph, pool = self.pool, stream = stream):+ static_out = self.function(static_x)+ return graph, static_x, static_out++ def __call__(self, x):+ if self.failed is not None:+ return self.function(x)+ key = (tuple(x.shape), x.dtype, x.device)+ entry = self.graphs.pop(key, None)+ if entry is None:+ try:+ entry = self._capture(x)+ except DiffusionGenerationCancelled:+ # stop_callback's forward hook fired during warm-up / capture: not a capture failure.+ self.graphs.clear()+ raise+ except Exception as error: # capture-unsafe forward: eager from here on+ self.failed = f"{type(error).__name__}: {error}"[:300]+ # Out of memory is transient (a shared card, a long canvas): eager for this call only.+ if self.owner is not None and not isinstance(error, torch.cuda.OutOfMemoryError):+ self.owner.__dict__["_unsloth_graph_capture_failed"] = self.failed+ self.graphs.clear()+ torch.cuda.synchronize()+ return self.function(x)+ while len(self.graphs) >= self.max_graphs:+ self.graphs.pop(next(iter(self.graphs)))+ self.graphs[key] = entry # most recently used last+ graph, static_x, static_out = entry+ static_x.copy_(x)+ with torch.cuda.device(x.device):+ graph.replay()+ return static_out+++class BlockHead:+ """Runs the backbone over the full canvas but projects only the requested rows to the vocabulary.++ With a plain nn.Linear head the model returns final hidden states and ``logits(x, start, end)`` applies the+ head to ``hidden[:, start:end]`` only: no [B, L, V] tensor. Any other head (tied, scaled, LoRA, quantized)+ keeps the model's own logits and slices them, so the result is the same either way. ``graphs`` replays the+ backbone from CUDA Graphs (``GraphedForward``)."""++ def __init__(+ self,+ base,+ cuda_graphs = False,+ graphs = False,+ ):+ self.base = base+ self.head = head = fusable_head(base, base)+ self.cuda_graphs = cuda_graphs++ def forward(x):+ if head is None:+ return base(x).logits+ with head_returns_hidden(head):+ return base(x).logits++ # Not a bound method: a BlockHead -> GraphedForward -> BlockHead cycle would keep the graphs and their+ # memory pool alive after the call until a full gc pass.+ self._forward = forward+ self.graphed = GraphedForward(forward, owner = base) if graphs else None++ def logits(self, x, start, end):+ if self.cuda_graphs:+ # Each step reuses the compiled graphs' output buffers; the previous step's outputs are dead by now.+ torch.compiler.cudagraph_mark_step_begin()+ out = self.graphed(x) if self.graphed is not None else self._forward(x)+ out = out[:, start:end]+ return out if self.head is None else self.head(out)+++def resolve_compile(compile, device):+ """How the backbone runs on this device. "auto" / True: eager kernels replayed from CUDA Graphs ("graphs",+ same numbers as eager); False / None, or anything off CUDA: plain eager. Other strings pick torch.compile:+ "cudagraphs" (dynamo backend, eager numerics, re-traced per canvas length) or an inductor mode such as+ "default" / "reduce-overhead" (fused kernels, so greedy output can drift from eager)."""+ if compile is None or compile is False or device.type != "cuda":+ return None+ if compile is True or compile in ("auto", "graphs"):+ return None if graphs_disabled() else "graphs"+ return str(compile)+++def inference_compile(base, mode):+ """Compile each decoder layer for this generate call and put the previous call path back afterwards, so a+ later training step never runs an inference-mode (CUDA Graph) layer. The compiled wrapper is cached on the+ layer, so dynamo reuses its graphs across calls. mode None does nothing."""+ if mode is None or mode == "graphs":+ yield 0+ return+ _warm_rotary_caches(base)+ saved = []+ for _, layers in _decoder_layer_lists(base):+ for layer in layers:+ cache = layer.__dict__.setdefault("_unsloth_infer_compiled", {})+ if mode not in cache:+ if mode == "cudagraphs":+ # Eager kernels replayed from CUDA Graphs: no inductor fusion, so eager numerics.+ options = {"backend": "cudagraphs", "dynamic": False}+ else:+ options = {"mode": None if mode == "default" else mode, "dynamic": True}+ cache[mode] = torch.compile(layer._call_impl, **options)+ saved.append((layer, layer._compiled_call_impl))+ layer._compiled_call_impl = cache[mode]+ try:+ yield len(saved)+ finally:+ for layer, previous in saved:+ layer._compiled_call_impl = previousdiff --git a/unsloth/models/diffusion_infer_block.py b/unsloth/models/diffusion_infer_block.pynew file mode 100644index 00000000000..b84700d2883--- /dev/null+++ b/unsloth/models/diffusion_infer_block.py@@ -0,0 +1,526 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.+"""Block diffusion decoding (SDAR, LLaDA2) with an exact prefix KV cache.++Attention is block-causal, so a committed block's keys and values never change: they are computed once, and each+denoising step forwards only the active block, and a finished block is committed in the same forward as the next+block's first step, so the forward count matches the recompute sampler. Token selection runs on the device; the+host syncs once per step (has the block finished early) and once per block (EOS)."""++import math+import sys+import threading+import time++import torch+import torch.nn.functional as F++from .diffusion_infer import (+ DiffusionGenerationCancelled,+ capture_lock,+ drop_on_move,+ graphs_disabled,+ host_synced_moe,+ side_stream,+)++__all__ = ["cached_block_sample"]++# The sampler kwargs cached_block_sample takes; other family kwargs are dropped as the recompute sampler does.+_CACHED_BLOCK_KWARGS = (+ "max_new_tokens",+ "temperature",+ "mask_id",+ "eos_ids",+ "confidence_threshold",+ "top_k",+ "top_p",+ "on_frame",+ "check_stop",+ "progress",+)+++class _Frames:+ """Throttled canvas snapshots and cancellation, host side and outside any compiled region."""++ def __init__(+ self,+ on_frame,+ check_stop,+ interval = 0.1,+ progress = None,+ ):+ self.on_frame, self.check_stop, self.interval = on_frame, check_stop, interval+ # generate_text's Progress: its own throttle, and the GPU never waits for a frame's host copy.+ self.progress = progress+ self.last = -math.inf # the first frame always goes out, however recently the clock started++ def check(self):+ if self.check_stop is not None:+ self.check_stop()++ def step(+ self,+ x,+ prompt_length,+ end,+ block,+ step,+ total,+ mask_id,+ force = False,+ ):+ if self.check_stop is not None:+ self.check_stop()+ if self.progress is not None:+ # The whole generated region (later blocks still masks), as generate_text's frame contract says.+ self.progress.frame(block, step, total, x[:, prompt_length:], force = force)+ return+ if self.on_frame is None:+ return+ now = time.monotonic()+ if not force and now - self.last < self.interval:+ return+ self.last = now+ self.on_frame(+ {+ "block": block,+ "step": step,+ "total": total,+ "tokens": x[0, prompt_length:end].tolist(),+ "mask_id": mask_id,+ }+ )+++class _PrefixCache:+ """Committed keys / values per layer. A denoising step reads them without writing, so nothing is cropped."""++ def __init__(self):+ self.keys, self.values, self.commit = {}, {}, False++ def update(+ self,+ key,+ value,+ layer_idx,+ cache_kwargs = None,+ ):+ if layer_idx in self.keys:+ key = torch.cat([self.keys[layer_idx], key], dim = -2)+ value = torch.cat([self.values[layer_idx], value], dim = -2)+ if self.commit:+ self.keys[layer_idx], self.values[layer_idx] = key, value+ return key, value++ def get_seq_length(self, layer_idx = 0):+ return self.keys[layer_idx].shape[-2] if layer_idx in self.keys else 0++ def crop(self, tokens_to_remove):+ # Negative: drop that many trailing tokens (what DynamicCache.crop does with a negative value).+ for layer_idx in self.keys:+ self.keys[layer_idx] = self.keys[layer_idx][..., :tokens_to_remove, :]+ self.values[layer_idx] = self.values[layer_idx][..., :tokens_to_remove, :]+++def _llada2_runner(base, ids, mask, position_ids, cache):+ """LLaDA2's model forward only takes a square [B, 1, L, L] mask, so a cached step drives its layers directly+ with the same mask preparation and logits dtype as its forward."""+ inner = base.model+ hidden = inner.word_embeddings(ids)+ # LLaDA2.0's remote code prepares the 4D additive mask with this helper; LLaDA2.1's dropped it+ # (create_bidirectional_mask) and its layers add the 4D mask as given, as the graph path passes it.+ prepare = getattr(+ sys.modules.get(type(inner).__module__), "_prepare_4d_causal_attention_mask_for_sdpa", None+ )+ if prepare is not None:+ past = cache.get_seq_length() if cache is not None else 0+ mask = prepare(mask, ids.shape, hidden, past)+ position_embeddings = inner.rotary_emb(hidden, position_ids)+ for layer in inner.layers:+ hidden = layer(+ hidden,+ attention_mask = mask,+ position_ids = position_ids,+ past_key_value = cache,+ use_cache = cache is not None,+ position_embeddings = position_embeddings,+ )[0]+ return base.lm_head(inner.norm(hidden)).float()+++class _StaticPrefixCache:+ """Fixed-capacity keys / values per layer, written at `rows` (absolute positions). Positions after the+ active block hold stale values, which the block-causal mask never lets a query read."""++ def __init__(self, capacity):+ self.capacity, self.keys, self.values, self.rows = capacity, {}, {}, None++ def update(+ self,+ key,+ value,+ layer_idx,+ cache_kwargs = None,+ ):+ if layer_idx not in self.keys:+ shape = (key.shape[0], key.shape[1], self.capacity, key.shape[3])+ self.keys[layer_idx] = torch.zeros(shape, dtype = key.dtype, device = key.device)+ self.values[layer_idx] = torch.zeros(shape, dtype = value.dtype, device = value.device)+ self.keys[layer_idx].index_copy_(2, self.rows, key)+ self.values[layer_idx].index_copy_(2, self.rows, value)+ return self.keys[layer_idx], self.values[layer_idx]++ def get_seq_length(self, layer_idx = 0):+ return 0+++class _Llada2Graph:+ """One LLaDA2 block forward (embed, layers, head) over a static cache, captured as a CUDA graph. Shapes+ depend only on (batch, block, capacity), so a graph serves every request that fits."""++ def __init__(self, base, batch, block_length, capacity, dtype, device):+ inner = base.model+ num_blocks = capacity // block_length+ allowed = torch.tril(torch.ones(num_blocks, num_blocks, device = device, dtype = torch.bool))+ allowed = allowed.repeat_interleave(block_length, 0).repeat_interleave(block_length, 1)+ self.mask = torch.zeros(allowed.shape, dtype = dtype, device = device).masked_fill(+ ~allowed, torch.finfo(dtype).min+ )[None, None]+ self.cache = _StaticPrefixCache(capacity)+ self.ids = torch.zeros((batch, block_length), dtype = torch.long, device = device)+ self.rows = torch.arange(block_length, device = device)+ self.offsets = torch.arange(block_length, device = device)++ def forward():+ self.cache.rows = self.rows+ hidden = inner.word_embeddings(self.ids)+ position_ids = self.rows[None]+ position_embeddings = inner.rotary_emb(hidden, position_ids)+ mask = self.mask.index_select(2, self.rows)+ for layer in inner.layers:+ hidden = layer(+ hidden,+ attention_mask = mask,+ position_ids = position_ids,+ past_key_value = self.cache,+ use_cache = True,+ position_embeddings = position_embeddings,+ )[0]+ return base.lm_head(inner.norm(hidden)).float()++ self.device = device+ # One generate at a time per graph: its inputs, cache and logits are shared buffers.+ self.lock = threading.Lock()+ with capture_lock(device), torch.cuda.device(device):+ stream = side_stream(device)+ stream.wait_stream(torch.cuda.current_stream())+ with torch.cuda.stream(stream):+ for _ in range(2):+ forward()+ torch.cuda.current_stream().wait_stream(stream)+ self.graph = torch.cuda.CUDAGraph()+ with torch.cuda.graph(self.graph, stream = stream):+ self.logits = forward()++ def __call__(self, ids, start):+ self.ids.copy_(ids)+ torch.add(self.offsets, start, out = self.rows)+ with torch.cuda.device(self.device):+ self.graph.replay()+ return self.logits+++def _llada2_graph(base, batch, block_length, total_length, dtype, device):+ """A cached graph for this shape, or None when graphs are off, unavailable, or the model carries adapters+ (capture would freeze their enabled / disabled state)."""+ if any(hasattr(module, "lora_A") for module in base.modules()):+ # Adapters were added (typically for training): free any graph captured before, with its pool and cache.+ base.__dict__.pop("_unsloth_llada2_graphs", None)+ return None+ if graphs_disabled() or device.type != "cuda":+ return None+ # Decide the grouped MoE dispatch now (it is otherwise decided on the first forward): an expert loop that+ # copies counts to the host cannot be captured, so it is not attempted.+ from .remote_moe_shims import _grouped_experts++ for module in base.modules():+ if getattr(type(module).__dict__.get("moe_infer"), "_unsloth_grouped_moe_infer", False):+ _grouped_experts(module)+ if host_synced_moe(base):+ return None+ # Power-of-two capacity (at least 1024) keeps the number of captured graphs small.+ capacity = max(1024, 1 << (total_length - 1).bit_length())+ capacity = -(-capacity // block_length) * block_length+ key = (batch, block_length, capacity, dtype, device)+ graphs = base.__dict__.setdefault("_unsloth_llada2_graphs", {})+ # A graph replays raw weight addresses: once any parameter or buffer was re-pointed (`model.to(...)` there+ # and back, a reload with assign, a re-stacked MoE), every captured graph would read freed memory.+ if graphs.get("weights") not in (None, _weight_addresses(base)):+ graphs.clear()+ graph = graphs.get(key)+ if graph is None:+ if graphs.get("failed"):+ return None+ try:+ graph = _Llada2Graph(base, batch, block_length, capacity, dtype, device)+ except DiffusionGenerationCancelled:+ raise # a stop during warm-up / capture, not a capture failure+ except torch.cuda.OutOfMemoryError:+ return None # transient: eager for this call, capture again next time+ except Exception as error:+ graphs["failed"] = True+ print(+ f"Unsloth: LLaDA2 CUDA graph capture failed ({type(error).__name__}: {error}); running eager."+ )+ return None+ # Keep the latest two shapes: each holds its own memory pool.+ for old in [k for k in graphs if isinstance(k, tuple)][:-1]:+ graphs.pop(old)+ graphs[key] = graph+ # Taken after capture: its warm-up may re-point weights (the MoE shim stacks experts lazily).+ graphs["weights"] = _weight_addresses(base)+ # model.to("cpu") does not see this dict: drop the graphs, their pool and static cache with the move.+ drop_on_move(base, "_unsloth_llada2_graphs")+ return graph+++def _weight_addresses(base):+ return tuple(tensor.data_ptr() for tensor in base.parameters()) + tuple(+ tensor.data_ptr() for tensor in base.buffers()+ )+++def _sdar_runner(base, ids, mask, position_ids, cache, store_kv):+ return base(+ ids,+ attention_mask = mask,+ position_ids = position_ids,+ past_key_values = cache,+ use_cache = True,+ store_kv = store_kv,+ ).logits.float()+++def _select(logits, mask_index, temperature, top_k, top_p, count, threshold):+ """The block sampler's per-step choice, on the device: sample / argmax, then accept every masked token above+ `threshold`, or else the `count` most confident (never more than the masks left)."""+ if temperature > 0:+ logits = logits / temperature+ if top_k and top_k > 0:+ kth = torch.topk(logits, top_k).values[..., -1, None]+ logits = logits.masked_fill(logits < kth, -math.inf)+ if top_p is not None and top_p < 1.0:+ sorted_logits, order = torch.sort(logits, descending = True)+ drop = F.softmax(sorted_logits, dim = -1).cumsum(-1) > top_p+ drop[..., 1:] = drop[..., :-1].clone()+ drop[..., 0] = False+ logits = logits.masked_fill(drop.scatter(-1, order, drop), -math.inf)+ probs = F.softmax(logits, dim = -1)+ x0 = torch.multinomial(probs.flatten(0, 1), 1).view(probs.shape[:-1])+ else:+ probs = F.softmax(logits, dim = -1)+ x0 = probs.argmax(dim = -1)+ x0_p = probs.gather(-1, x0.unsqueeze(-1)).squeeze(-1)+ confidence = torch.where(mask_index, x0_p, -math.inf)+ high = confidence > threshold+ use_high = high.sum(-1, keepdim = True) >= count+ k = torch.minimum(count, mask_index.sum(-1, keepdim = True))+ order = torch.topk(confidence, confidence.shape[-1]).indices+ rank = torch.empty_like(order).scatter_(+ -1, order, torch.arange(order.shape[-1], device = order.device).expand_as(order)+ )+ transfer = torch.where(use_high, high, rank < k)+ return x0, transfer++[email protected]_grad()+def cached_block_sample(+ base,+ input_ids,+ *,+ family,+ max_new_tokens,+ steps,+ block_length,+ temperature,+ mask_id,+ eos_ids,+ confidence_threshold,+ top_k = 0,+ top_p = 1.0,+ on_frame = None,+ check_stop = None,+ progress = None,+ cuda_graphs = True,+):+ from transformers import DynamicCache++ batch, prompt_length = input_ids.shape+ num_blocks = (prompt_length + max_new_tokens + block_length - 1) // block_length+ total_length = num_blocks * block_length+ device = input_ids.device+ block_causal = torch.tril(torch.ones(num_blocks, num_blocks, device = device, dtype = torch.bool))+ allowed = block_causal.repeat_interleave(block_length, 0).repeat_interleave(block_length, 1)[+ None, None+ ]+ graph = None+ if family == "llada2":+ dtype = next(base.parameters()).dtype+ graph = (+ _llada2_graph(base, input_ids.shape[0], block_length, total_length, dtype, device)+ if cuda_graphs+ else None+ )+ attention = torch.zeros(allowed.shape, dtype = dtype, device = device).masked_fill(+ ~allowed, torch.finfo(dtype).min+ )++ def run(ids, start, end, cache, store):+ cache.commit = store+ return _llada2_runner(+ base, ids, attention[..., start:end, :end], position_ids[:, start:end], cache+ )+ else:+ attention = allowed++ def run(ids, start, end, cache, store):+ return _sdar_runner(+ base, ids, attention[..., start:end, :end], position_ids[:, start:end], cache, store+ )++ position_ids = torch.arange(total_length, device = device)[None]+ x = torch.full((batch, total_length), mask_id, dtype = torch.long, device = device)+ x[:, :prompt_length] = input_ids+ schedule = torch.full((steps,), block_length // steps, dtype = torch.long)+ schedule[: block_length % steps] += 1+ counts = schedule.to(device)[:, None, None].expand(steps, batch, 1)+ frames = _Frames(on_frame, check_stop, progress = progress)+ eos = torch.tensor(eos_ids, device = device) if eos_ids else None++ if graph is not None and graph.lock.acquire(blocking = False):+ try:+ return _graph_block_sample(+ graph,+ x,+ prompt_length = prompt_length,+ num_blocks = num_blocks,+ block_length = block_length,+ steps = steps,+ counts = counts,+ temperature = temperature,+ top_k = top_k,+ top_p = top_p,+ mask_id = mask_id,+ eos = eos,+ confidence_threshold = confidence_threshold,+ frames = frames,+ )+ finally:+ graph.lock.release()+ cache = _PrefixCache() if family == "llada2" else DynamicCache()++ def commit_then_step(commit_start, start, end):+ """Commit x[:, commit_start:start] and run the first denoising step of x[:, start:end] in one forward,+ then drop the active block's keys / values again: the active rows attend exactly as in a step forward."""+ logits = run(x[:, commit_start:end], commit_start, end, cache, True)+ cache.crop(-(end - start))+ return logits[:, start - commit_start :]++ first = prompt_length // block_length+ pending = None+ if first > 0 and first < num_blocks:+ # A prompt block only attends to earlier prompt blocks, so it is committed once up front.+ pending = commit_then_step(0, first * block_length, (first + 1) * block_length)+ for block in range(first, num_blocks):+ start, end = block * block_length, (block + 1) * block_length+ window = x[:, start:end]+ for step in range(steps + 1):+ mask_index = window == mask_id+ if not bool(mask_index.any()):+ break+ # In-block frames keep step < total; the block end sends step == total once.+ frames.step(x, prompt_length, end, block, min(step, steps - 1), steps, mask_id)+ logits = pending if pending is not None else run(window, start, end, cache, False)+ pending = None+ x0, transfer = _select(+ logits,+ mask_index,+ temperature,+ top_k,+ top_p,+ counts[min(step, steps - 1)],+ confidence_threshold,+ )+ window.copy_(torch.where(transfer, x0, window))+ pending = None+ frames.step(x, prompt_length, end, block, steps, steps, mask_id, force = True)+ if eos is not None and bool(torch.isin(x[:, prompt_length:end], eos).any()):+ return x[:, prompt_length:end]+ if block + 1 < num_blocks:+ # The next block is all masks: its first step rides along with this block's commit.+ pending = commit_then_step(start, end, end + block_length)+ return x[:, prompt_length:]+++def _graph_block_sample(+ graph,+ x,+ *,+ prompt_length,+ num_blocks,+ block_length,+ steps,+ counts,+ temperature,+ top_k,+ top_p,+ mask_id,+ eos,+ confidence_threshold,+ frames,+):+ """cached_block_sample's loop on a captured block forward. A finished block is committed by one more+ forward of its final tokens (same graph); prompt blocks are committed the same way."""+ first = prompt_length // block_length+ for block in range(first):+ frames.check() # replay runs no forward hooks, so the stop check is explicit+ graph(x[:, block * block_length : (block + 1) * block_length], block * block_length)+ for block in range(first, num_blocks):+ start, end = block * block_length, (block + 1) * block_length+ window = x[:, start:end]+ for step in range(steps + 1):+ mask_index = window == mask_id+ if not bool(mask_index.any()):+ break+ # In-block frames keep step < total; the block end sends step == total once.+ frames.step(x, prompt_length, end, block, min(step, steps - 1), steps, mask_id)+ logits = graph(window, start)+ x0, transfer = _select(+ logits,+ mask_index,+ temperature,+ top_k,+ top_p,+ counts[min(step, steps - 1)],+ confidence_threshold,+ )+ window.copy_(torch.where(transfer, x0, window))+ frames.step(x, prompt_length, end, block, steps, steps, mask_id, force = True)+ if eos is not None and bool(torch.isin(x[:, prompt_length:end], eos).any()):+ return x[:, prompt_length:end]+ if block + 1 < num_blocks:+ frames.check() # replay runs no forward hooks: a stop asked for at the block-end frame lands here+ graph(window, start)+ return x[:, prompt_length:]diff --git a/unsloth/models/diffusion_infer_dream.py b/unsloth/models/diffusion_infer_dream.pynew file mode 100644index 00000000000..b97ac7fa6e3--- /dev/null+++ b/unsloth/models/diffusion_infer_dream.py@@ -0,0 +1,101 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.+# This program is free software: you can redistribute it and/or modify+# it under the terms of the GNU Affero General Public License as published by+# the Free Software Foundation, either version 3 of the License, or+# (at your option) any later version.+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU Affero General Public License for more details.+# You should have received a copy of the GNU Affero General Public License+# along with this program. If not, see <https://www.gnu.org/licenses/>.+"""Dream's greedy diffusion_generate (generation_utils.py `_sample`, alg entropy / maskgit_plus / topk_margin,+alg_temp 0), with logits only for the generated region and the transfer schedule worked out up front.++The reference projects every position to the vocabulary each step and reads the masked count back to the host.+The masked count drops by exactly the scheduled amount unless the model proposes the mask token itself, so the+schedule is worked out before the loop; a run where that happened returns None and the caller falls back."""++import math++import torch+import torch.nn.functional as F++from .diffusion_infer_block import _Frames++__all__ = ["dream_fast_supported", "dream_fast_sample"]++_ALGS = ("entropy", "maskgit_plus", "topk_margin")+++def dream_fast_supported(+ input_ids, attention_mask, mask_id, temperature, top_p, top_k, alg, alg_temp+):+ # An empty prompt is left to the reference: its position 0 reads its own logits, not a shifted row.+ return (+ input_ids.shape[1] > 0+ and not temperature+ and top_p is None+ and top_k is None+ and alg in _ALGS+ and not alg_temp+ and (attention_mask is None or bool(attention_mask.all()))+ and not bool((input_ids == mask_id).any())+ )++[email protected]_grad()+def dream_fast_sample(+ base,+ input_ids,+ *,+ max_new_tokens,+ steps,+ mask_id,+ alg = "entropy",+ eps = 1e-3,+ on_frame = None,+ check_stop = None,+ progress = None,+):+ batch, prompt_length = input_ids.shape+ x = F.pad(input_ids, (0, max_new_tokens), value = mask_id)+ # The reference's own float32 timesteps, read back once.+ timesteps = torch.linspace(1, eps, steps + 1, device = x.device).cpu()+ masked = torch.tensor(max_new_tokens * batch) / batch+ counts = []+ for i in range(steps):+ t, s = timesteps[i], timesteps[i + 1]+ count = int(masked * (1 - s / t)) if i < steps - 1 else int(masked)+ counts.append(count)+ masked = masked - count+ frames = _Frames(on_frame, check_stop, progress = progress)+ generated = x[:, prompt_length:]+ remasked = torch.zeros((), dtype = torch.bool, device = x.device)+ for i, count in enumerate(counts):+ frames.step(x, prompt_length, x.shape[1], 0, i, steps, mask_id)+ mask_index = generated == mask_id+ hidden = base.model(input_ids = x, attention_mask = "full")[0]+ # Position j reads the logits of j - 1 (Dream shifts them right by one).+ logits = base.lm_head(hidden[:, prompt_length - 1 : -1])+ probs = torch.softmax(logits, dim = -1)+ confidence, x0 = probs.max(dim = -1)+ if alg == "topk_margin":+ top2 = torch.topk(probs, 2, dim = -1).values+ confidence = top2[..., 0] - top2[..., 1]+ elif alg == "entropy":+ confidence = torch.sum(probs * torch.log(probs + 1e-10), dim = -1)+ if count > 0:+ # Full canvas width (prompt at -inf) so ties break exactly as in the reference's topk.+ full = F.pad(+ torch.where(mask_index, confidence, -math.inf), (prompt_length, 0), value = -math.inf+ )+ index = torch.topk(full, count).indices - prompt_length+ chosen = torch.where(mask_index, x0, mask_id).gather(1, index)+ remasked |= (chosen == mask_id).any()+ generated.scatter_(1, index, chosen)+ if bool(remasked):+ return None+ frames.step(x, prompt_length, x.shape[1], 0, steps, steps, mask_id, force = True)+ return xdiff --git a/unsloth/models/diffusion_samplers.py b/unsloth/models/diffusion_samplers.pyindex 72e3f5bf86c..e24f181a99f 100644--- a/unsloth/models/diffusion_samplers.py+++ b/unsloth/models/diffusion_samplers.py@@ -12,15 +12,19 @@ import mathimport torchimport torch.nn.functional as F+from .diffusion_infer import (+ BlockHead,+ DiffusionGenerationCancelled,+ host_synced_moe,+ inference_compile,+ make_progress,+ resolve_compile,+)from .diffusion_profiles import resolve_diffusion_profile, unwrap_diffusion_model__all__ = ["DiffusionGenerationCancelled", "generate_text", "diffusion_profile_name"]-class DiffusionGenerationCancelled(RuntimeError):- """Raised out of generate_text when stop_callback() returned True mid-generation."""--_SAMPLERS = {}@@ -164,55 +168,76 @@ def _llada_sample(eos_ids,remasking = "low_confidence",eos_early_stop = True,+ progress = None,+ compile_mode = None,**unused,):"""Semi-autoregressive low-confidence remasking (LLaDA generate.py, also LLaDA-MoE's model card):- blocks of `block_length` masks, a linear schedule unmasking the most confident predictions each step."""+ blocks of `block_length` masks, a linear schedule unmasking the most confident predictions each step.++ The backbone still sees the whole canvas (bidirectional), but only the active block is projected to the+ vocabulary; everything outside it scored -inf in the reference, so the picks are the same."""block_length = int(block_length or 32)gen_length = _round_up(max_new_tokens, block_length)num_blocks = gen_length // block_lengthsteps = _round_up(int(steps or gen_length), num_blocks)steps_per_block = steps // num_blocksbatch, prompt_length = input_ids.shape- x = torch.full(- (batch, prompt_length + gen_length), mask_id, dtype = torch.long, device = input_ids.device- )+ total_length = prompt_length + gen_length+ x = torch.full((batch, total_length), mask_id, dtype = torch.long, device = input_ids.device)x[:, :prompt_length] = input_ids- for block in range(num_blocks):- start = prompt_length + block * block_length- end = start + block_length- remaining = (x[:, start:end] == mask_id).sum(dim = 1, keepdim = True)- schedule = remaining // steps_per_block + (- torch.arange(steps_per_block, device = x.device)[None, :] < remaining % steps_per_block- )- for step in range(steps_per_block):- mask_index = x == mask_id- logits = base(x).logits- if temperature > 0:- # Gumbel-max in float64: low precision noise hurts MDM generation quality (arXiv:2409.02908).- noisy = logits.to(torch.float64)- noisy = noisy.exp() / (-torch.log(torch.rand_like(noisy))) ** temperature- else:- noisy = logits- x0 = noisy.argmax(dim = -1)- if remasking == "low_confidence":- probs = F.softmax(logits, dim = -1)- x0_p = probs.gather(-1, x0.unsqueeze(-1)).squeeze(-1)- elif remasking == "random":- x0_p = torch.rand(x0.shape, device = x0.device)- else:- raise ValueError(f"Unsloth: unknown LLaDA remasking {remasking!r}.")- x0_p[:, end:] = -math.inf- x0 = torch.where(mask_index, x0, x)- confidence = torch.where(mask_index, x0_p, -math.inf)- transfer = torch.zeros_like(x0, dtype = torch.bool)- for row in range(batch):- _, index = torch.topk(confidence[row], k = int(schedule[row, step]))- transfer[row, index] = True- x[transfer] = x0[transfer]- if eos_early_stop and _contains_any(x[:, prompt_length:end], eos_ids):- # Later blocks never change earlier ones, so stopping here only drops text after the EOS.- return x[:, prompt_length:end]+ head = BlockHead(+ base,+ cuda_graphs = compile_mode in ("reduce-overhead", "cudagraphs"),+ graphs = compile_mode == "graphs" and not host_synced_moe(base),+ )+ # Each block starts fully masked, so the reference's per-row schedule is the same host-side list for every row.+ base_count, extra = divmod(block_length, steps_per_block)+ schedule = [base_count + (step < extra) for step in range(steps_per_block)]+ with inference_compile(base, compile_mode):+ for block in range(num_blocks):+ start = prompt_length + block * block_length+ end = start + block_length+ for step in range(steps_per_block):+ if progress is not None:+ progress.check()+ window = x[:, start:end]+ mask_index = window == mask_id+ logits = head.logits(x, start, end)+ if temperature > 0:+ # Gumbel-max in float64: low precision noise hurts MDM generation quality (arXiv:2409.02908).+ # Drawn for the active block only, not the [B, L, V] canvas, so a seed's samples differ from+ # the reference's while the distribution is the same.+ noisy = logits.to(torch.float64)+ noisy = noisy.exp() / (-torch.log(torch.rand_like(noisy))) ** temperature+ else:+ noisy = logits+ x0 = noisy.argmax(dim = -1)+ if remasking == "low_confidence":+ x0_p = F.softmax(logits, dim = -1).gather(-1, x0.unsqueeze(-1)).squeeze(-1)+ elif remasking == "random":+ # The reference draws over the whole canvas; slicing keeps its RNG stream (it is only [B, L]).+ x0_p = torch.rand((batch, total_length), device = x0.device)[:, start:end]+ else:+ raise ValueError(f"Unsloth: unknown LLaDA remasking {remasking!r}.")+ # Full-length row as in the reference, so topk sees identical input and breaks ties identically.+ confidence = torch.full(+ (batch, total_length), -math.inf, dtype = x0_p.dtype, device = x.device+ )+ confidence[:, start:end] = torch.where(mask_index, x0_p, -math.inf)+ transfer = torch.zeros_like(x, dtype = torch.bool)+ for row in range(batch):+ transfer[row, torch.topk(confidence[row], k = schedule[step]).indices] = True+ x[:, start:end] = torch.where(transfer[:, start:end] & mask_index, x0, window)+ if progress is not None:+ progress.frame(block, step, steps_per_block, x[:, prompt_length:])+ if progress is not None:+ progress.frame(+ block, steps_per_block, steps_per_block, x[:, prompt_length:], force = True+ )+ if eos_early_stop and _contains_any(x[:, prompt_length:end], eos_ids):+ # Later blocks never change earlier ones, so stopping here only drops text after the EOS.+ return x[:, prompt_length:end]return x[:, prompt_length:]@@ -315,15 +340,28 @@ def _sdar_sample(base, tokenizer, input_ids, attention_mask, *, steps, block_len"""SDAR model card / generate.py defaults: block 4, steps = block length, threshold 0.85."""block_length = int(block_length or getattr(base.config, "block_size", None) or 4)kwargs.setdefault("confidence_threshold", 0.85)- return _block_sample(+ import os++ if os.environ.get("UNSLOTH_DIFFUSION_KV_CACHE", "1") == "0":+ return _block_sample(+ base,+ tokenizer,+ input_ids,+ attention_mask,+ steps = int(steps or block_length),+ block_length = block_length,+ mask_format = "bool",+ **kwargs,+ )+ from .diffusion_infer_block import _CACHED_BLOCK_KWARGS, cached_block_sample++ return cached_block_sample(base,- tokenizer,input_ids,- attention_mask,+ family = "sdar",steps = int(steps or block_length),block_length = block_length,- mask_format = "bool",- **kwargs,+ **{k: v for k, v in kwargs.items() if k in _CACHED_BLOCK_KWARGS},)@@ -343,15 +381,34 @@ def _llada2_sample("""LLaDA2 model card defaults: block 32, steps 32, threshold 0.95. Its own generate builds a bfloat16 mask(fails on fp16 / fp32 weights) and samples even at temperature 0, so the shared block sampler runs instead."""kwargs.setdefault("confidence_threshold", threshold)- return _block_sample(+ from .remote_moe_shims import prepare_remote_moe_for_inference++ # Eval routing without a per-layer host sync (no-op once patched or for non-LLaDA2 MoE code).+ prepare_remote_moe_for_inference(base)+ import os++ if os.environ.get("UNSLOTH_DIFFUSION_KV_CACHE", "1") == "0":+ return _block_sample(+ base,+ tokenizer,+ input_ids,+ attention_mask,+ steps = int(steps or 32),+ block_length = int(block_length or 32),+ mask_format = "additive",+ **kwargs,+ )+ from .diffusion_infer_block import _CACHED_BLOCK_KWARGS, cached_block_sample++ return cached_block_sample(base,- tokenizer,input_ids,- attention_mask,+ family = "llada2",steps = int(steps or 32),block_length = int(block_length or 32),- mask_format = "additive",- **kwargs,+ # generate_text's compile: "auto" / True replay the block forward from a CUDA Graph, False stays eager.+ cuda_graphs = kwargs.get("compile_mode", "graphs") == "graphs",+ **{k: v for k, v in kwargs.items() if k in _CACHED_BLOCK_KWARGS},)@@ -375,21 +432,72 @@ def _dream_sample(**unused,):"""Dream's own diffusion_generate (model card: steps = max_new_tokens, alg "entropy", alg_temp 0)."""+ from .diffusion_infer_block import _Frames+ from .diffusion_infer_dream import dream_fast_sample, dream_fast_supported+if top_p is None and temperature > 0:top_p = 0.95+ steps = int(steps or max_new_tokens)+ on_frame, check_stop = unused.get("on_frame"), unused.get("check_stop")+ progress = unused.get("progress")+ prompt_length = input_ids.shape[1]+ fast_ran = False+ # diffusion_generate reads eps and top_k from the model's generation_config: the fast path must too.+ config = getattr(base, "generation_config", None)+ eps = getattr(config, "eps", None) or 1e-3+ if dream_fast_supported(+ input_ids,+ attention_mask,+ mask_id,+ temperature,+ top_p,+ getattr(config, "top_k", None),+ alg,+ alg_temp,+ ):+ out = dream_fast_sample(+ base,+ input_ids,+ max_new_tokens = max_new_tokens,+ steps = steps,+ mask_id = mask_id,+ alg = alg,+ eps = eps,+ on_frame = on_frame,+ check_stop = check_stop,+ progress = progress,+ )+ # None: the model proposed its own mask token, which changes the reference's schedule.+ if out is not None:+ return out[:, prompt_length:]+ fast_ran = True+ frames = _Frames(on_frame, check_stop, progress = progress)++ def hook(step, x, logits):+ if step is not None and fast_ran and step + 1 < steps:+ # The fast pass already streamed steps 0..steps - 1: only the final canvas, so steps never go back.+ if check_stop is not None:+ check_stop()+ elif step is not None:+ frames.step(+ x, prompt_length, x.shape[1], 0, step + 1, steps, mask_id, step + 1 == steps+ )+ return x+out = base.diffusion_generate(input_ids,attention_mask = None if attention_mask is None else attention_mask.to(input_ids.device),max_new_tokens = max_new_tokens,- steps = int(steps or max_new_tokens),+ steps = steps,temperature = temperature,top_p = top_p,alg = alg,alg_temp = alg_temp,output_history = False,return_dict_in_generate = True,+ generation_tokens_hook_func = hook,)- return out.sequences[:, input_ids.shape[1] :]+ return out.sequences[:, prompt_length:]@_register("nemotron_labs_diffusion")@@ -411,17 +519,55 @@ def _nemotron_sample():"""Nemotron-Labs-Diffusion's own generate: block diffusion with a causal context between blocks."""block_length = int(block_length or getattr(base.config, "block_size", None) or 32)- output_ids, _nfe = base.generate(- input_ids,- max_new_tokens = _round_up(max_new_tokens, block_length),- block_length = block_length,- threshold = threshold,- temperature = temperature,- eos_token_id = eos_ids[0] if eos_ids else None,- )+ progress = unused.get("progress")+ with _nemotron_frames(base, progress, block_length, int(max_new_tokens), mask_id):+ output_ids, _nfe = base.generate(+ input_ids,+ max_new_tokens = _round_up(max_new_tokens, block_length),+ block_length = block_length,+ threshold = threshold,+ temperature = temperature,+ eos_token_id = eos_ids[0] if eos_ids else None,+ )return output_ids[:, input_ids.shape[1] :]+def _nemotron_frames(base, progress, block_length, budget, mask_id):+ """Canvas frames from Nemotron's own generate without touching its loop. It makes three kinds of forward:+ the prompt prefill (no cache yet), a denoising step on the active block (cache, use_cache=False) and a+ commit of the finished block (cache, use_cache=True). A pre-hook reads which one from the kwargs."""+ if progress is None or progress.on_frame is None:+ yield+ return+ committed, state = [], {"step": 0}++ def canvas(block):+ done = sum(part.shape[1] for part in committed) + block.shape[1]+ pad = block.new_full((block.shape[0], max(budget - done, 0)), mask_id)+ return torch.cat([*committed, block, pad], dim = 1)++ def hook(module, args, kwargs):+ ids = args[0] if args else kwargs.get("input_ids")+ if kwargs.get("past_key_values") is None or ids is None or ids.shape[1] != block_length:+ return None+ if kwargs.get("use_cache"):+ # The finished block: one block-end frame, then it joins the committed prefix.+ progress.frame(len(committed), block_length, block_length, canvas(ids), force = True)+ committed.append(ids.clone())+ state["step"] = 0+ else:+ progress.frame(len(committed), state["step"], block_length, canvas(ids))+ state["step"] += 1+ return None++ handle = base.register_forward_pre_hook(hook, with_kwargs = True)+ try:+ yield+ finally:+ handle.remove()++@_register("diffusion_gemma")@torch.no_grad()def _diffusion_gemma_sample(@@ -509,12 +655,25 @@ def generate_text(temperature = 0.0,stop_callback = None,seed = None,+ on_frame = None,+ frame_interval_s = 0.1,+ compile = "auto",**kwargs,):"""Decode one completion with the model family's diffusion sampler and return it as text (promptremoved, cut at the first EOS, special tokens skipped). stop_callback() is checked before every forward;returning True raises DiffusionGenerationCancelled. `steps` / `block_length` default to each family's- published settings; extra kwargs go to the family sampler (e.g. remasking, threshold, top_p, alg)."""+ published settings; extra kwargs go to the family sampler (e.g. remasking, threshold, top_p, alg).++ on_frame(frame) receives the canvas while it denoises: {"block", "step", "total", "tokens" (the generated+ region, `max_new_tokens` ids, unresolved slots = "mask_id"), "mask_id"}, at most once per+ `frame_interval_s` plus once per finished block, always on this thread and never after return. Every+ family streams frames except DiffusionGemma (transformers' own generate) and the+ UNSLOTH_DIFFUSION_KV_CACHE=0 block fallback; stop_callback works for all of them.+ `compile`: "auto" (default; CUDA Graph replay of the unchanged forward where it is exact and faster: the+ LLaDA backbone and LLaDA2's cached block), True / "graphs" (the same), False (eager). A torch.compile mode+ such as "reduce-overhead" compiles the LLaDA / LLaDA-MoE decoder layers (fused kernels, so greedy output+ can drift); the other families run their own fastest exact path and ignore it."""name = diffusion_profile_name(model)sampler = _SAMPLERS.get(name)if sampler is None:@@ -535,22 +694,36 @@ def generate_text(if seed is not Noneelse contextlib.nullcontext())- with rng, _eval_mode(base), _restore_attention_modes(base), _cancellation(base, stop_callback):- if seed is not None:- torch.manual_seed(int(seed))- generated = sampler(- base,- tokenizer,- input_ids,- attention_mask,- max_new_tokens = int(max_new_tokens),- steps = steps,- block_length = block_length,- temperature = float(temperature or 0.0),- mask_id = mask_id,- eos_ids = eos_ids,- **kwargs,- )+ progress = make_progress(+ on_frame, stop_callback, frame_interval_s, mask_id, int(max_new_tokens)+ )+ try:+ with (+ rng,+ _eval_mode(base),+ _restore_attention_modes(base),+ _cancellation(base, stop_callback),+ ):+ if seed is not None:+ torch.manual_seed(int(seed))+ generated = sampler(+ base,+ tokenizer,+ input_ids,+ attention_mask,+ max_new_tokens = int(max_new_tokens),+ steps = steps,+ block_length = block_length,+ temperature = float(temperature or 0.0),+ mask_id = mask_id,+ eos_ids = eos_ids,+ progress = progress,+ check_stop = progress.check,+ compile_mode = resolve_compile(compile, device),+ **kwargs,+ )+ finally:+ progress.close()tokens = generated[0][: int(max_new_tokens)].tolist()for index, token in enumerate(tokens):if token in eos_ids:diff --git a/unsloth/models/remote_moe_shims.py b/unsloth/models/remote_moe_shims.pyindex cafaf8a98a4..31f0392dc6f 100644--- a/unsloth/models/remote_moe_shims.py+++ b/unsloth/models/remote_moe_shims.py@@ -15,6 +15,8 @@ asserts `not self.training` and whose block only computes under no-grad `moe_infstructure, never repo name; no-op for transformers' own models."""import functools+import os+import threadingimport torch@@ -23,6 +25,7 @@ __all__ = ["is_remote_deepseek_gate","is_remote_deepseek_moe","packed_expert_target_parameters",+ "prepare_remote_moe_for_inference",]@@ -319,3 +322,233 @@ def packed_expert_target_parameters(model, target_parameters, requested_leaves):else:kept.extend(f"{stack}.{projection}" for stack in chosen)return kept or None+++# Eval routing without a host sync. The remote `moe_infer` reads per-expert token counts back to the host and+# loops over experts, so each MoE layer syncs and launches one GEMM chain per active expert. The grouped version+# keeps the counts on the device and runs every expert in three grouped GEMMs; every routed token is computed.+++_EXPERT_PROJECTIONS = ("gate_proj", "up_proj", "down_proj")+_STACK_LOCK = threading.Lock()+++def _plain_expert(expert, dtype):+ names = _EXPERT_PROJECTIONS+ return all(+ type(getattr(expert, name, None)) is torch.nn.Linear+ and getattr(expert, name).bias is None+ and getattr(expert, name).weight.dtype == dtype+ for name in names+ ) and hasattr(expert, "act_fn")+++def _torch_grouped_mm(inputs, weight, offsets):+ return torch._grouped_mm(inputs, weight, offs = offsets)+++def _triton_grouped_mm(inputs, weight, offsets):+ from unsloth_zoo.temporary_patches.moe_grouped_fp16 import generic_grouped_mm+ return generic_grouped_mm(inputs, weight, offsets)+++_FALLBACK_LOGGED = set()+++def _log_fallback(reason):+ if reason not in _FALLBACK_LOGGED:+ _FALLBACK_LOGGED.add(reason)+ print(+ f"Unsloth: MoE eval routing keeps the per-expert loop ({reason}); generation is slower."+ )+++def _grouped_mm_candidates(weight):+ """Grouped GEMMs that keep the offsets on the device, best first. torch._grouped_mm only has a real kernel on+ sm90 / sm100 (and ROCm): elsewhere torch 2.9+ loops over host-copied offsets (a sync per layer that also+ breaks CUDA Graph capture) and 2.8 raises, so sm80 / sm89 / sm120 use unsloth_zoo's Triton grouped GEMM.+ UNSLOTH_MOE_INFER_GROUPED=torch|triton|0 forces one or turns the grouped path off."""+ choice = os.environ.get("UNSLOTH_MOE_INFER_GROUPED", "auto").strip().lower()+ if choice in ("0", "false", "off"):+ return []+ candidates = []+ if hasattr(torch, "_grouped_mm") and choice in ("auto", "torch"):+ native = torch.version.hip is not None or torch.cuda.get_device_capability(weight.device)[+ 0+ ] in (9, 10)+ if native or choice == "torch":+ candidates.append(_torch_grouped_mm)+ if choice in ("auto", "triton") and torch.version.hip is None:+ if torch.cuda.get_device_capability(weight.device) >= (8, 0):+ candidates.append(_triton_grouped_mm)+ return candidates+++def _grouped_mm_for(weights):+ """The first grouped GEMM that reproduces a plain matmul on these weights' device / dtype / layout (a tiny+ call each), or None, logged once, so a refusal keeps the original loop instead of failing generation."""+ first = weights[0]+ if not first.is_cuda:+ return None+ if first.dtype not in (torch.bfloat16, torch.float16):+ _log_fallback(f"expert weights are {first.dtype}, not bfloat16 / float16")+ return None+ errors = []+ for grouped_mm in _grouped_mm_candidates(first):+ try:+ offsets = torch.tensor([1, 2], dtype = torch.int32, device = first.device)+ for weight in weights:+ weight = weight.detach()+ # Deterministic inputs: the global RNG stream a seeded sample relies on stays untouched.+ inputs = torch.arange(2 * weight.shape[1], device = weight.device).view(2, -1)+ inputs = inputs.float().sin().div(weight.shape[1] ** 0.5).to(weight.dtype)+ stacked = torch.stack([weight, weight.flip(0)])+ out = grouped_mm(inputs, stacked.transpose(-2, -1), offsets)+ reference = torch.cat([inputs[:1] @ weight.T, inputs[1:] @ weight.flip(0).T])+ if not torch.allclose(out.float(), reference.float(), rtol = 2e-2, atol = 2e-2):+ raise RuntimeError("mismatch against a plain matmul")+ return grouped_mm+ except Exception as error:+ errors.append(+ f"{grouped_mm.__name__.strip('_')}: {type(error).__name__}: {error}"[:200]+ )+ _log_fallback("; ".join(errors) or "no grouped GEMM for this GPU")+ return None+++def _grouped_experts_live(+ block,+ stacked,+ every = True,+):+ """The experts are still plain linears whose weights alias `stacked`. A LoRA wrap, `model.to(...)` or a+ reload breaks the alias; `every = False` checks only the first expert (cheap, per forward)."""+ experts = block.experts+ if len(experts) != stacked[0].shape[0]:+ return False+ for buffer, name in zip(stacked, _EXPERT_PROJECTIONS):+ for index in range(len(experts) if every else 1):+ linear = getattr(experts[index], name, None)+ if (+ type(linear) is not torch.nn.Linear+ or linear.weight.dtype != buffer.dtype+ or linear.weight.data_ptr() != buffer[index].data_ptr()+ ):+ return False+ return True+++def _grouped_experts(block):+ """Stack the expert weights once into [E, out, in] buffers and point each expert's weights at its slice,+ so no weight is held twice. The Parameter objects stay the same (an optimizer built earlier still owns+ them). None when the experts are not plain bf16 / fp16 linears on a device torch._grouped_mm serves."""+ cached = block.__dict__.get("_unsloth_grouped_experts", _MISSING)+ if cached is not _MISSING and (+ cached is None or _grouped_experts_live(block, cached, every = False)+ ):+ return cached+ # One thread stacks and re-points the weights; a concurrent first generate waits instead of capturing a+ # graph over half re-pointed experts.+ with _STACK_LOCK:+ cached = block.__dict__.get("_unsloth_grouped_experts", _MISSING)+ if cached is not _MISSING and (+ cached is None or _grouped_experts_live(block, cached, every = False)+ ):+ return cached+ return _stack_experts(block)+++def _stack_experts(block):+ from .diffusion_infer import drop_on_move++ experts = block.experts+ stacked = grouped_mm = None+ first = experts[0] if isinstance(experts, torch.nn.ModuleList) and len(experts) else None+ if (+ first is not None+ and isinstance(getattr(first, "gate_proj", None), torch.nn.Linear)+ and all(_plain_expert(expert, first.gate_proj.weight.dtype) for expert in experts)+ ):+ grouped_mm = _grouped_mm_for((first.gate_proj.weight, first.down_proj.weight))+ elif first is not None and any(p.is_cuda for p in first.parameters()):+ _log_fallback("experts are not plain bias-free nn.Linear layers (quantized or adapters)")+ if grouped_mm is not None:+ stacked = []+ for name in _EXPERT_PROJECTIONS:+ buffer = torch.stack([getattr(expert, name).weight.detach() for expert in experts])+ for index, expert in enumerate(experts):+ getattr(expert, name).weight.data = buffer[index]+ stacked.append(buffer)+ stacked = (*stacked, grouped_mm)+ # model.to("cpu") moves the experts' parameters but not this tuple: drop it so the GPU stack is freed.+ drop_on_move(block, "_unsloth_grouped_experts")+ block.__dict__["_unsloth_grouped_experts"] = stacked+ return stacked+++def _grouped_moe_infer(original):+ @functools.wraps(original)+ def moe_infer(self, x, topk_ids, topk_weight):+ stacked = None+ if not self.training and not torch.is_grad_enabled():+ stacked = _grouped_experts(self)+ if stacked is None or x.dtype != stacked[0].dtype:+ return original(self, x, topk_ids, topk_weight)+ gate, up, down, grouped_mm = stacked+ num_experts = gate.shape[0]+ counts = topk_ids.new_zeros((topk_ids.shape[0], num_experts))+ counts.scatter_(1, topk_ids, 1)+ offsets = counts.sum(dim = 0).cumsum(0).to(torch.int32)+ order = topk_ids.view(-1).argsort()+ sorted_tokens = x[order // topk_ids.shape[1]]+ act = self.experts[0].act_fn+ hidden = act(grouped_mm(sorted_tokens, gate.transpose(-2, -1), offsets))+ hidden = hidden * grouped_mm(sorted_tokens, up.transpose(-2, -1), offsets)+ outs = grouped_mm(hidden, down.transpose(-2, -1), offsets)+ new_x = torch.empty_like(outs)+ new_x[order] = outs+ return (+ new_x.view(*topk_ids.shape, -1)+ .type(topk_weight.dtype)+ .mul_(topk_weight.unsqueeze(dim = -1))+ .sum(dim = 1)+ .type(new_x.dtype)+ )++ moe_infer._unsloth_grouped_moe_infer = True+ return moe_infer+++def _is_host_synced_moe_infer(cls) -> bool:+ import inspect++ infer = cls.__dict__.get("moe_infer")+ if infer is None or getattr(infer, "_unsloth_grouped_moe_infer", False):+ return False+ try:+ source = inspect.getsource(infer)+ except (OSError, TypeError):+ return False+ # The DeepSeek-style loop: counts to the host, then one expert at a time.+ return ".cpu()" in source and "self.experts[" in source+++def prepare_remote_moe_for_inference(model):+ """Patch remote MoE blocks whose eval `moe_infer` syncs the host per layer (LLaDA2) to the grouped dispatch.+ Training, LoRA-wrapped or quantized experts and CPU tensors keep the original path."""+ patched = []+ for module in model.modules():+ cls = type(module)+ if (+ _is_remote_code(cls)+ and isinstance(getattr(module, "experts", None), torch.nn.ModuleList)+ and _is_host_synced_moe_infer(cls)+ ):+ cls.moe_infer = _grouped_moe_infer(cls.__dict__["moe_infer"])+ patched.append(cls.__name__)+ # Re-decide stacks that went stale (LoRA added, model moved or reloaded, dtype changed) or were+ # refused earlier (e.g. first seen on the CPU), so a stale buffer is neither used nor kept alive.+ cached = module.__dict__.get("_unsloth_grouped_experts", _MISSING)+ if cached is not _MISSING and (cached is None or not _grouped_experts_live(module, cached)):+ module.__dict__.pop("_unsloth_grouped_experts")+ return patched