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
Fix Nemotron loss normalization across gradient accumulation (#14002)
cherry77-cloud7ec86bbc716b
diff --git a/tests/diffusion/test_diffusion_masked.py b/tests/diffusion/test_diffusion_masked.pyindex b23b20941db..dc4b1094aab 100644--- a/tests/diffusion/test_diffusion_masked.py+++ b/tests/diffusion/test_diffusion_masked.py@@ -619,3 +619,44 @@ def test_fused_head_rechecked_after_head_is_replaced():assert fusable_head(model, model) is model.headmodel.head = torch.nn.Sequential(model.head)assert fusable_head(model, model) is None+++def _window_trainer(model, world = 1):+ from collections import defaultdict+ from unsloth.models.diffusion_trainer import DiffusionTrainer++ trainer = DiffusionTrainer.__new__(DiffusionTrainer)+ trainer.diffusion_profile = _profile("nemotron_labs_diffusion")+ trainer.model, trainer._diffusion_metrics = model, defaultdict(list)+ trainer.args = SimpleNamespace(average_tokens_across_devices = True, world_size = world)+ trainer.accelerator = SimpleNamespace(num_processes = world, gather = lambda t: t.reshape(1))+ trainer._prepare_inputs = lambda inputs: inputs+ return trainer+++def test_nemotron_accumulation_window_matches_one_batch():+ # Nemotron's forward returns (sum_loss, num_mask_tokens): one shared count per accumulation window.+ inputs, _ = _batch()+ rows = [{k: v[i : i + 1] for k, v in inputs.items()} for i in range(len(inputs["input_ids"]))]+ model, reference = _Bidirectional(), _Bidirectional()+ trainer = _window_trainer(model)+ torch.manual_seed(5)+ samples, count = trainer.get_batch_samples(iter(rows), len(rows), "cpu")+ masks = [s["_diffusion_masked_batch"][3] for s in samples]+ assert int(count) == sum(int(m.sum()) for m in masks) and len({int(m.sum()) for m in masks}) > 1+ total = sum(trainer.compute_loss(model, s, num_items_in_batch = count) for s in samples)+ total.backward()++ prepared = [+ None if parts[0] is None else torch.cat(parts)+ for parts in zip(*(s["_diffusion_masked_batch"] for s in samples))+ ]+ full = {**inputs, "_diffusion_masked_batch": tuple(prepared)}+ loss, _, _ = trainer.diffusion_profile.compute_loss(reference, full, None)+ loss.backward()+ torch.testing.assert_close(total, loss, rtol = 1e-6, atol = 1e-6)+ for (n, a), b in zip(model.named_parameters(), reference.parameters()):+ torch.testing.assert_close(a.grad, b.grad, rtol = 1e-5, atol = 1e-7, msg = n)+ assert trainer.compute_loss(model, samples[0]).item() == pytest.approx(+ trainer.diffusion_profile.compute_loss(model, samples[0], None)[0].item()+ )diff --git a/unsloth/models/diffusion_masked.py b/unsloth/models/diffusion_masked.pyindex 947dabc99f0..2460d9978c6 100644--- a/unsloth/models/diffusion_masked.py+++ b/unsloth/models/diffusion_masked.py@@ -156,7 +156,8 @@ class MaskedDiffusionProfile(DiffusionProfile):# Dream is adapted from an AR model: position i's logits predict token i + 1 (Dream src/trainer).shift_logits: bool = False# "answer_length": LLaDA GUIDELINES.md SFT, each example / its answer length, mean over the batch.- # "masked_tokens": Dream / Nemotron, summed then divided by the number of masked tokens.+ # "masked_tokens": Dream, summed then divided by the number of masked tokens.+ # "global_masked_tokens": Nemotron, using the whole accumulation window's masked-token count.loss_normalization: str = "answer_length"# LLaDA and Dream train on EOS-filled, attended padding so the model learns where answers stop.pad_with_eos: bool = True@@ -237,24 +238,14 @@ class MaskedDiffusionProfile(DiffusionProfile):eos_id = eos_id[0]return mask_id, eos_id- def compute_loss(- self,- model,- inputs,- args,- num_items_in_batch = None,- ):+ def prepare_batch(self, model, inputs, args):+ """Draw noise once, so the Trainer can count masked tokens before any backward pass."""input_ids = inputs["input_ids"]attention_mask = inputs.get("attention_mask")batch, length = input_ids.shapedevice = input_ids.device- mask_id, eos_id = self._token_ids(model, args)+ _, eos_id = self._token_ids(model, args)eps = float(self.option(args, "diffusion_eps"))- weighting = self.option(args, "diffusion_time_weighting")- if weighting not in ("inverse_t", "none", None):- raise ValueError(- f"Unsloth: {self.name} does not support diffusion_time_weighting={weighting!r}."- )maskable = response_mask(inputs)forward_mask = attention_mask@@ -270,6 +261,27 @@ class MaskedDiffusionProfile(DiffusionProfile):t = torch.rand(batch, device = device)p_mask = ((1 - eps) * t + eps)[:, None].expand(batch, length)masked = (torch.rand((batch, length), device = device) < p_mask) & maskable+ return input_ids, forward_mask, maskable, masked, p_mask++ def compute_loss(+ self,+ model,+ inputs,+ args,+ num_items_in_batch = None,+ ):+ weighting = self.option(args, "diffusion_time_weighting")+ if weighting not in ("inverse_t", "none", None):+ raise ValueError(+ f"Unsloth: {self.name} does not support diffusion_time_weighting={weighting!r}."+ )+ prepared = inputs.get("_diffusion_masked_batch")+ if prepared is None:+ prepared = self.prepare_batch(model, inputs, args)+ input_ids, forward_mask, maskable, masked, p_mask = prepared+ batch = input_ids.shape[0]+ device = input_ids.device+ mask_id, _ = self._token_ids(model, args)noisy = torch.where(masked, mask_id, input_ids)model_inputs = {"input_ids": noisy}@@ -298,7 +310,10 @@ class MaskedDiffusionProfile(DiffusionProfile):if self.loss_normalization == "answer_length":loss = weightedelse:- loss = weighted / count.clamp_min(1)+ denominator = count+ if self.loss_normalization == "global_masked_tokens" and num_items_in_batch is not None:+ denominator = torch.as_tensor(num_items_in_batch, device = device)+ loss = weighted / denominator.clamp_min(1)metrics = {"masked_fraction": (count / maskable.sum().clamp_min(1)).detach(),@@ -357,7 +372,7 @@ register_diffusion_profile(lora_target_modules = list(_ATTENTION_AND_MLP),# Keep `diffusion_head` 16-bit like every other head, so the loss can take hidden states.quant_skip_modules = ["lm_head", "embed_tokens", "diffusion_head"],- loss_normalization = "masked_tokens",+ loss_normalization = "global_masked_tokens",auto_class = "AutoModel",compile_backbone = True,)diff --git a/unsloth/models/diffusion_trainer.py b/unsloth/models/diffusion_trainer.pyindex 2a89effb2a7..e457999b82e 100644--- a/unsloth/models/diffusion_trainer.py+++ b/unsloth/models/diffusion_trainer.py@@ -114,11 +114,42 @@ class DiffusionTrainer(UnslothTrainer):self._diffusion_metrics = defaultdict(list)diffusion_compile_mode(args) # reject a bad value before any worksuper().__init__(model, args, *pos, **kwargs)- # The loss is ours, so the Trainer must scale it for gradient accumulation itself.- self.model_accepts_loss_kwargs = False+ # A globally normalized loss already includes gradient accumulation in its denominator.+ self.model_accepts_loss_kwargs = self._uses_global_masked_tokens()if diffusion_compile_mode(args) == "full" and profile.compile_backbone:compile_backbone_layers(unwrap_diffusion_model(self.model))+ def _uses_global_masked_tokens(self):+ return getattr(self.diffusion_profile, "loss_normalization", None) == "global_masked_tokens"++ def get_batch_samples(+ self,+ epoch_iterator,+ num_batches,+ device = None,+ ):+ if not self._uses_global_masked_tokens():+ return super().get_batch_samples(epoch_iterator, num_batches, device)++ # Labels count eligible targets, not the random subset used by the diffusion loss.+ batch_samples = []+ counts = []+ for _ in range(num_batches):+ try:+ inputs = next(epoch_iterator)+ except StopIteration:+ break+ inputs = self._prepare_inputs(inputs)+ prepared = self.diffusion_profile.prepare_batch(self.model, inputs, self.args)+ batch_samples.append({**inputs, "_diffusion_masked_batch": prepared})+ counts.append(prepared[3].sum())+ if not counts:+ return batch_samples, None+ num_items_in_batch = torch.stack(counts).sum()+ if self.args.average_tokens_across_devices and self.args.world_size > 1:+ num_items_in_batch = self.accelerator.gather(num_items_in_batch).sum()+ return batch_samples, num_items_in_batch+def compute_loss(self,model,@@ -129,6 +160,13 @@ class DiffusionTrainer(UnslothTrainer):loss, outputs, metrics = self.diffusion_profile.compute_loss(model, inputs, self.args, num_items_in_batch = num_items_in_batch)+ if (+ self._uses_global_masked_tokens()+ and num_items_in_batch is not None+ and self.args.average_tokens_across_devices+ ):+ # DDP averages gradients; a denominator gathered across ranks needs a summed numerator.+ loss = loss * self.accelerator.num_processesmode = "train" if model.training else "eval"# Kept on device; one host sync per log() instead of one per metric per micro-batch.for key, value in (metrics or {}).items():