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
GKD: right-align left-padded rows before the student forward (#12200)
Daniel Han05d47bde3b95
diff --git a/tests/python/test_gkd_chunked_jsd.py b/tests/python/test_gkd_chunked_jsd.pyindex 47c751075d3..7060f406125 100644--- a/tests/python/test_gkd_chunked_jsd.py+++ b/tests/python/test_gkd_chunked_jsd.py@@ -576,3 +576,87 @@ def test_prediction_head_before_the_decoder_falls_back():model.decoder = decodermodel.get_output_embeddings = lambda: model.decoderassert rl._unsloth_gkd_dense_head(model) is None+++class _MaskBlindLM(_TinyLM):+ """Causal and position aware, and like Unsloth's training forward it ignores ``attention_mask``."""++ def forward(self, input_ids, attention_mask):+ x = self.embed[input_ids]+ steps = torch.arange(1, x.shape[1] + 1, dtype = x.dtype).view(1, -1, 1)+ hidden = torch.tanh((x.cumsum(dim = 1) / steps + 0.1 * steps) @ self.mix)+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":+ return types.SimpleNamespace(logits = hidden)+ return types.SimpleNamespace(logits = self.lm_head(hidden))++[email protected]("shift", ["prompt", "shift"])+def test_left_padded_rows_score_as_if_unpadded(shift, monkeypatch):+ """TRL's DataCollatorForChatML left-pads; a mask-blind forward must not see the pads."""+ monkeypatch.setenv("UNSLOTH_GKD_CHUNK_SIZE", "8")+ vocab, pad = 97, 0+ student, teacher = _MaskBlindLM(vocab, 16, 0.0, 1), _MaskBlindLM(vocab, 24, 0.0, 2)+ g = torch.Generator().manual_seed(0)+ # (prompt, completion) lengths; row 2's completion starts before the padded prompt width.+ rows = [(5, 7), (3, 4), (2, 9)]+ width, prompt_width = max(p + c for p, c in rows), max(p for p, _ in rows)+ input_ids = torch.full((3, width), pad)+ attention_mask = torch.zeros_like(input_ids)+ labels = torch.full_like(input_ids, -100)+ for i, (p, c) in enumerate(rows):+ ids = torch.randint(1, vocab, (p + c,), generator = g)+ input_ids[i, width - p - c :], attention_mask[i, width - p - c :] = ids, 1+ labels[i, width - c :] = ids[p:]+ inputs = {+ "input_ids": input_ids,+ "attention_mask": attention_mask,+ "labels": labels,+ "prompts": input_ids[:, :prompt_width],+ }+ scored = labels.clone()+ if shift == "prompt":+ scored[:, :prompt_width] = -100++ # Reference: each row alone, pads stripped, TRL's own per-token JSD summed then averaged.+ monkeypatch.setenv("UNSLOTH_RETURN_HIDDEN_STATES", "0")+ total, count = 0.0, 0+ for i in range(3):+ keep = attention_mask[i].bool()+ ids, lab = input_ids[i, keep][None], scored[i, keep][None]+ s = student(ids, None).logits[:, :-1]+ with torch.no_grad():+ t = teacher(ids, None).logits[:, :-1]+ total = total + GKDTrainer.generalized_jsd_loss(+ s, t, labels = lab[:, 1:], beta = 0.5, reduction = "sum"+ )+ count += int((lab[:, 1:] != -100).sum())+ want = total / count++ # Through the generated compute_loss: the chunked path, then TRL's own body as every fallback runs it.+ namespace = dict(vars(rl), GKDTrainer = GKDTrainer, empty_cache = lambda: None)+ source = PROMPT_LAYOUT if shift == "prompt" else SHIFT_LAYOUT+ exec(+ "class _Generated(GKDTrainer):\n" + rl.gkd_trainer_compute_loss("compute_loss", source),+ namespace,+ )+ trainer = namespace["_Generated"].__new__(namespace["_Generated"])+ trainer.__dict__.update(_trainer(0.5, student, teacher).__dict__)+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES")+ torch.testing.assert_close(+ trainer.compute_loss(student, inputs).double(), want, rtol = 1e-5, atol = 1e-7+ )+ if shift == "prompt":+ monkeypatch.setenv("UNSLOTH_GKD_CHUNKED", "0")+ torch.testing.assert_close(+ trainer.compute_loss(student, inputs), want, rtol = 1e-5, atol = 1e-7+ )+ # TRL's Liger branch has no prompt slice: its rows are rolled, every label kept.+ liger = rl._unsloth_gkd_right_align(+ inputs, {"shift": shift, "num_items_in_batch": False}, liger = True+ )+ assert liger["prompts"] is inputs["prompts"]+ for i in range(3):+ keep = attention_mask[i].bool()+ width = int(keep.sum())+ assert torch.equal(liger["labels"][i, :width], labels[i, keep])+ assert torch.equal(liger["input_ids"][i, :width], input_ids[i, keep])diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 183b42f9aa7..97d8939b814 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -4031,6 +4031,38 @@ def _unsloth_gkd_chunk_size(vocab_size):return int(min(1024, max(64, 1 << (max(rows, 1).bit_length() - 1))))+def _unsloth_gkd_right_align(+ inputs,+ layout,+ liger = False,+):+ """Roll left-padded rows (TRL's ChatML collator and generate both left-pad) so they start at column 0: Unsloth's training forward drops the 2D mask (#11885).+ The prompt layout's ``[:, P:]`` slice becomes ``labels[:, :P] = -100`` plus a one-column ``prompts``; TRL's Liger branch scores every label with no slice, so it only rolls.+ """+ try:+ attention_mask = inputs["attention_mask"]+ left_pad = (attention_mask.cumsum(dim = 1) == 0).sum(dim = 1, keepdim = True)+ except Exception:+ return inputs+ if not bool(left_pad.any()):+ return inputs+ aligned = dict(inputs)+ labels = inputs["labels"]+ if layout["shift"] == "prompt" and not liger:+ labels = labels.clone()+ labels[:, : inputs["prompts"].shape[1]] = -100+ aligned["prompts"] = inputs["prompts"][:, :1]+ width = attention_mask.shape[1]+ index = (torch.arange(width, device = attention_mask.device).unsqueeze(0) + left_pad) % width+ for key, value in (+ ("input_ids", inputs["input_ids"]),+ ("attention_mask", attention_mask),+ ("labels", labels),+ ):+ aligned[key] = value.gather(1, index)+ return aligned++def _unsloth_gkd_chunked_loss(self, model, inputs, num_items_in_batch, layout):"""TRL's GKD loss without either full logits tensor, or ``None`` to run TRL's own ``compute_loss``."""if layout is None:@@ -4191,6 +4223,9 @@ def gkd_trainer_compute_loss(function_name, function):"def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):\n"" # Unsloth: chunked generalized JSD over hidden states; TRL's own loss below is the fallback.\n"" if not return_outputs:\n"+ f" inputs = _unsloth_gkd_right_align(\n"+ f" inputs, {layout!r}, getattr(self, 'use_liger_gkd_loss', False),\n"+ " )\n"" loss = _unsloth_gkd_chunked_loss(\n"f" self, model, inputs, num_items_in_batch, {layout!r},\n"" )\n"@@ -4219,6 +4254,7 @@ for _gkd_item in (_unsloth_gkd_logit_transforms,_unsloth_gkd_project,_unsloth_gkd_chunk_size,+ _unsloth_gkd_right_align,_unsloth_gkd_chunked_loss,):RL_PRE_ITEMS["gkd_trainer"].append(inspect.getsource(_gkd_item))