Skip to content

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.

Fix DiffusionGemma sampled-prefix cache retention (#13780)

cherry77-cloud3f502e26c50c
diff --git a/tests/diffusion/test_diffusion_gemma.py b/tests/diffusion/test_diffusion_gemma.py
index 590360cacd9..e3938ce5b57 100644
--- a/tests/diffusion/test_diffusion_gemma.py
+++ b/tests/diffusion/test_diffusion_gemma.py
@@ -139,9 +139,8 @@ def test_parity_with_trl_reference(model, prediction_type):
for a, b in zip(our_grads, ref_grads):
if a is None or b is None:
assert a is None and b is None
- elif prediction_type == "mean":
- torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-7)
else:
+ # Right-aligned prefix cache slots reorder the attention sums: ~1.5e-7 apart on near-zero grads.
torch.testing.assert_close(a, b, rtol = 1e-5, atol = 1e-6)
@@ -197,6 +196,45 @@ def test_loss_through_distributed_wrapper(model):
torch.testing.assert_close(wrapped, plain)
[email protected]("attn", ["eager", "sdpa"])
+def test_decoder_sees_the_prefix_window_inference_sees(attn):
+ # The encoder runs on the whole sequence, but sliding decoder layers must keep the window ending at the
+ # sampled block, as inference does after encoding only the prefix.
+ cfg = transformers.AutoConfig.from_pretrained(TINY)
+ cfg.text_config.sliding_window = 8
+ m = transformers.DiffusionGemmaForBlockDiffusion.from_pretrained(
+ TINY, config = cfg, dtype = torch.float32, attn_implementation = attn
+ ).train()
+ m._unsloth_diffusion_eos_token_id = 1
+ rows = [(5, 100), (40, 70), (3, 20), (60, 60)]
+ batch = _batch(cfg.text_config.vocab_size, cfg.canvas_length, max_length = 120, rows = rows)
+ seen = {}
+ forward = m.forward
+
+ def spy(**kw):
+ out = forward(**kw)
+ seen.update(kw = kw, logits = out.logits.detach())
+ return out
+
+ m.forward = spy
+ torch.manual_seed(5)
+ DIFFUSION_GEMMA_PROFILE.compute_loss(
+ m, batch, _args(max_length = 120, diffusion_self_conditioning_p = 0.0)
+ )
+ del m.forward
+ kw = seen["kw"]
+ encoder_len = kw["decoder_position_ids"][:, 0].tolist()
+ assert max(encoder_len) > cfg.text_config.sliding_window
+ with torch.no_grad():
+ for i, n in enumerate(encoder_len):
+ ref = m(
+ input_ids = batch["input_ids"][i : i + 1, :n],
+ decoder_input_ids = kw["decoder_input_ids"][i : i + 1],
+ decoder_position_ids = kw["decoder_position_ids"][i : i + 1],
+ ).logits
+ torch.testing.assert_close(seen["logits"][i : i + 1], ref, rtol = 1e-5, atol = 1e-5)
+
+
def test_row_without_supervised_tokens_adds_no_canvas_loss(model):
batch = _batch(model.config.text_config.vocab_size, model.config.canvas_length, rows = [(6, 0)])
torch.manual_seed(0)
diff --git a/unsloth/models/diffusion_gemma_objective.py b/unsloth/models/diffusion_gemma_objective.py
index 3eee02e1700..95ecc8d04c4 100644
--- a/unsloth/models/diffusion_gemma_objective.py
+++ b/unsloth/models/diffusion_gemma_objective.py
@@ -8,6 +8,7 @@ import contextlib
import torch
import torch.nn.functional as F
+from transformers.cache_utils import DynamicCache
from .diffusion_loss import chunked_cross_entropy, compile_loss
from .diffusion_profiles import DiffusionProfile, register_diffusion_profile, unwrap_diffusion_model
@@ -57,6 +58,31 @@ def _eos_token_id(model):
return int(eos)
+class _DiffusionGemmaPrefixCache(DynamicCache):
+ """Keep the sampled prefix for decoding while the encoder processes the full AR sequence."""
+
+ def __init__(
+ self,
+ ddp_cache_data = None,
+ *,
+ config = None,
+ prefix_indices = None,
+ ):
+ super().__init__(ddp_cache_data = ddp_cache_data, config = config)
+ self.prefix_indices = prefix_indices
+
+ def update(self, key_states, value_states, layer_idx, *args, **kwargs):
+ # The encoder attends to the full returned K/V; only the stored decoder context is regathered.
+ keys, values = super().update(key_states, value_states, layer_idx, *args, **kwargs)
+ layer = self.layers[layer_idx]
+ cache_length = layer.keys.shape[-2]
+ indices = self.prefix_indices[:, self.prefix_indices.shape[1] - cache_length :]
+ indices = indices.to(keys.device)[:, None, :, None]
+ layer.keys = keys.gather(2, indices.expand(-1, keys.shape[1], -1, keys.shape[-1]))
+ layer.values = values.gather(2, indices.expand(-1, values.shape[1], -1, values.shape[-1]))
+ return keys, values
+
+
class DiffusionGemmaProfile(DiffusionProfile):
def prepare_model(self, model, tokenizer):
tok = getattr(tokenizer, "tokenizer", tokenizer)
@@ -130,7 +156,10 @@ class DiffusionGemmaProfile(DiffusionProfile):
random_tokens = torch.randint(vocab_size, (batch_size, block_size), device = device)
canvas_ids = torch.where(corrupt, random_tokens, canvas_target)
- cache_mask = positions < encoder_len[:, None]
+ # Right-align each prefix so sliding layers keep the window ending at the sampled block, as inference does.
+ prefix_positions = positions + encoder_len[:, None] - seq_len
+ prefix_indices = prefix_positions.clamp(min = 0)
+ cache_mask = (prefix_positions >= 0) & attention_mask.bool().gather(1, prefix_indices)
canvas_mask = torch.ones(batch_size, block_size, dtype = torch.bool, device = device)
model_kwargs = {
"input_ids": input_ids,
@@ -142,9 +171,19 @@ class DiffusionGemmaProfile(DiffusionProfile):
# Two-pass self-conditioning: a no-grad first pass supplies the logits, kept per example with prob p.
if sc_p > 0:
with torch.no_grad():
- model_kwargs["self_conditioning_logits"] = model(**model_kwargs).logits
+ model_kwargs["self_conditioning_logits"] = model(
+ **model_kwargs,
+ past_key_values = _DiffusionGemmaPrefixCache(
+ config = text_config, prefix_indices = prefix_indices
+ ),
+ ).logits
model_kwargs["self_conditioning_mask"] = torch.rand(batch_size, device = device) < sc_p
- outputs = model(**model_kwargs)
+ outputs = model(
+ **model_kwargs,
+ past_key_values = _DiffusionGemmaPrefixCache(
+ config = text_config, prefix_indices = prefix_indices
+ ),
+ )
# Flat CE over the whole canvas, corrupted and clean alike: the uniform kernel's ELBO has no 1/t weight.
diffusion_target = canvas_target.masked_fill(truncated[:, None] & ~in_response, -100)