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.

DiffusionGemma: build the prefix cache per DataParallel replica (#14942)

Daniel Han02ddfff02d9a
diff --git a/tests/diffusion/test_diffusion_gemma.py b/tests/diffusion/test_diffusion_gemma.py
index e3938ce5b57..6dc8994154d 100644
--- a/tests/diffusion/test_diffusion_gemma.py
+++ b/tests/diffusion/test_diffusion_gemma.py
@@ -196,6 +196,51 @@ def test_loss_through_distributed_wrapper(model):
torch.testing.assert_close(wrapped, plain)
+class _ScatteringDataParallel(torch.nn.DataParallel):
+ """nn.DataParallel's contract without GPUs: tensors split on dim 0, every other object shared by all replicas."""
+
+ def __init__(
+ self,
+ inner,
+ replicas = 2,
+ ):
+ torch.nn.Module.__init__(self)
+ self.module = inner
+ self.replicas = replicas
+
+ def forward(self, **kwargs):
+ rows = next(v for v in kwargs.values() if torch.is_tensor(v)).shape[0]
+ bounds = torch.arange(rows).chunk(self.replicas)
+ outs = [
+ self.module(
+ **{
+ k: v[b[0] : b[-1] + 1]
+ if torch.is_tensor(v) and v.dim() and v.shape[0] == rows
+ else v
+ for k, v in kwargs.items()
+ }
+ )
+ for b in bounds
+ ]
+ return types.SimpleNamespace(
+ logits = torch.cat([o.logits for o in outs]),
+ encoder_last_hidden_state = torch.cat([o.encoder_last_hidden_state for o in outs]),
+ )
+
+
+def test_loss_through_data_parallel_scatter(model):
+ # Each replica must decode from a cache holding its own rows, not one built for the whole batch.
+ batch = _batch(model.config.text_config.vocab_size, model.config.canvas_length)
+ torch.manual_seed(0)
+ plain = DIFFUSION_GEMMA_PROFILE.compute_loss(model, batch, _args())[0]
+ torch.manual_seed(0)
+ wrapped = DIFFUSION_GEMMA_PROFILE.compute_loss(_ScatteringDataParallel(model), batch, _args())[
+ 0
+ ]
+ torch.testing.assert_close(wrapped, plain)
+ assert not model._forward_pre_hooks and not model._forward_hooks
+
+
@pytest.mark.parametrize("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
diff --git a/unsloth/models/diffusion_gemma_objective.py b/unsloth/models/diffusion_gemma_objective.py
index 95ecc8d04c4..d4ca337bfc6 100644
--- a/unsloth/models/diffusion_gemma_objective.py
+++ b/unsloth/models/diffusion_gemma_objective.py
@@ -8,7 +8,7 @@ import contextlib
import torch
import torch.nn.functional as F
-from transformers.cache_utils import DynamicCache
+from transformers.cache_utils import Cache, DynamicCache
from .diffusion_loss import chunked_cross_entropy, compile_loss
from .diffusion_profiles import DiffusionProfile, register_diffusion_profile, unwrap_diffusion_model
@@ -83,6 +83,44 @@ class _DiffusionGemmaPrefixCache(DynamicCache):
return keys, values
+_PREFIX_INDICES_KWARG = "_unsloth_diffusion_prefix_indices"
+
+
+def _forward_with_prefix_cache(model, model_kwargs, text_config, prefix_indices):
+ if not isinstance(model, torch.nn.DataParallel):
+ return model(
+ **model_kwargs,
+ past_key_values = _DiffusionGemmaPrefixCache(
+ config = text_config, prefix_indices = prefix_indices
+ ),
+ )
+
+ # DataParallel scatters tensors but shares Python objects: pass the indices as a tensor, build a cache per replica.
+ def build_cache(module, args, kwargs):
+ indices = kwargs.pop(_PREFIX_INDICES_KWARG, None)
+ if indices is not None:
+ kwargs["past_key_values"] = _DiffusionGemmaPrefixCache(
+ config = text_config, prefix_indices = indices
+ )
+ return args, kwargs
+
+ # DataParallel cannot gather DynamicCache outputs, and the loss never reads them.
+ def drop_cache(module, args, output):
+ if isinstance(output, dict) and any(isinstance(v, Cache) for v in output.values()):
+ output = type(output)(**{k: v for k, v in output.items() if not isinstance(v, Cache)})
+ return output
+
+ handles = (
+ model.module.register_forward_pre_hook(build_cache, with_kwargs = True),
+ model.module.register_forward_hook(drop_cache),
+ )
+ try:
+ return model(**model_kwargs, **{_PREFIX_INDICES_KWARG: prefix_indices})
+ finally:
+ for handle in handles:
+ handle.remove()
+
+
class DiffusionGemmaProfile(DiffusionProfile):
def prepare_model(self, model, tokenizer):
tok = getattr(tokenizer, "tokenizer", tokenizer)
@@ -171,19 +209,11 @@ 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,
- past_key_values = _DiffusionGemmaPrefixCache(
- config = text_config, prefix_indices = prefix_indices
- ),
+ model_kwargs["self_conditioning_logits"] = _forward_with_prefix_cache(
+ model, model_kwargs, text_config, prefix_indices
).logits
model_kwargs["self_conditioning_mask"] = torch.rand(batch_size, device = device) < sc_p
- outputs = model(
- **model_kwargs,
- past_key_values = _DiffusionGemmaPrefixCache(
- config = text_config, prefix_indices = prefix_indices
- ),
- )
+ outputs = _forward_with_prefix_cache(model, model_kwargs, text_config, 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)