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: align GKD Liger loss with the native objective (#12007)

cherry77-cloud87964a36b828
diff --git a/tests/python/test_gkd_liger_objective.py b/tests/python/test_gkd_liger_objective.py
new file mode 100644
index 00000000000..88c81eebf5b
--- /dev/null
+++ b/tests/python/test_gkd_liger_objective.py
@@ -0,0 +1,62 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team.
+"""GKD on TRL < 1.7 masks generated prompt labels (#12007)."""
+
+from __future__ import annotations
+
+import os
+import textwrap
+
+import pytest
+
+os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")
+import unsloth.models.rl_replacements as rl
+
+# TRL 0.22.2 - 1.6.0 generate_on_policy_outputs, trimmed to the label lines.
+LEGACY = textwrap.dedent(
+ """
+ def generate_on_policy_outputs(model, inputs, generation_config, pad_token_id=None):
+ generated_tokens = model.generate(input_ids=inputs["prompts"]).sequences
+ new_attention_mask = torch.ones_like(generated_tokens)
+ new_labels = generated_tokens.clone()
+ if pad_token_id is not None:
+ new_labels[new_labels == pad_token_id] = -100
+ return generated_tokens, new_attention_mask, new_labels
+ """
+)
+MASK = 'new_labels[:, : inputs["prompts"].shape[1]] = -100'
+
+
+def test_legacy_prompt_labels_are_masked_once():
+ out = rl.gkd_trainer_mask_prompt("generate_on_policy_outputs", LEGACY)
+ compile(out, "gkd", "exec")
+ assert out.count(MASK) == 1
+ assert out.index("new_labels = generated_tokens.clone()") < out.index(MASK)
+ assert rl.gkd_trainer_mask_prompt("generate_on_policy_outputs", out) == out
+
+
+def test_upstream_mask_and_other_functions_untouched():
+ upstream = LEGACY.replace(
+ " return generated_tokens",
+ " new_labels[:, :prompt_length] = -100\n return generated_tokens",
+ )
+ assert rl.gkd_trainer_mask_prompt("generate_on_policy_outputs", upstream) == upstream
+ assert rl.gkd_trainer_mask_prompt("compute_loss", LEGACY) == LEGACY
+
+
+def test_mask_matches_generated_layout():
+ torch = pytest.importorskip("torch")
+ ns = {"torch": torch}
+ exec(rl.gkd_trainer_mask_prompt("generate_on_policy_outputs", LEGACY), ns)
+
+ class Model:
+ def generate(self, input_ids):
+ completion = torch.full((input_ids.shape[0], 3), 7)
+ return type("O", (), {"sequences": torch.cat([input_ids, completion], 1)})()
+
+ prompts = torch.tensor([[0, 0, 5], [3, 4, 5]])
+ _, _, labels = ns["generate_on_policy_outputs"](
+ Model(), {"prompts": prompts}, None, pad_token_id = 0
+ )
+ assert (labels[:, :3] == -100).all()
+ assert (labels[:, 3:] == 7).all()
diff --git a/unsloth/models/rl.py b/unsloth/models/rl.py
index 403ad71fb25..2bd2ba61270 100644
--- a/unsloth/models/rl.py
+++ b/unsloth/models/rl.py
@@ -2728,6 +2728,15 @@ def _patch_trl_rl_trainers_impl(trainer_file = "grpo_trainer"):
"pass\n"
)
+ if trainer_file == "gkd_trainer":
+ # Match native GKD's pure JSD at T=1 without changing the generation temperature.
+ RLTrainer_post += (
+ "if getattr(self, 'liger_jsd_loss', None) is not None:\n"
+ " self.liger_jsd_loss.weight_hard_loss = 0.0\n"
+ " self.liger_jsd_loss.weight_soft_loss = 1.0\n"
+ " self.liger_jsd_loss.temperature = 1.0\n"
+ )
+
other_metrics_processor = ""
if trainer_file in RL_METRICS_CHANGES:
process_extra_args = RL_METRICS_CHANGES[trainer_file]
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 97d8939b814..75753881a9d 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -157,6 +157,22 @@ def grpo_config_fix_vllm_top_k(old_RLTrainer_source, old_RLConfig_source):
RL_CONFIG_CHANGES["grpo_trainer"].append(grpo_config_fix_vllm_top_k)
+def gkd_trainer_mask_prompt(function_name, function):
+ if function_name != "generate_on_policy_outputs":
+ return function
+ prompt_mask = 'new_labels[:, : inputs["prompts"].shape[1]] = -100'
+ if prompt_mask in function or "new_labels[:, :prompt_length] = -100" in function:
+ return function
+ for line in function.splitlines():
+ if line.strip() == "new_labels = generated_tokens.clone()":
+ indent = line.partition("new_labels")[0]
+ return function.replace(line, f"{line}\n{indent}{prompt_mask}", 1)
+ return function
+
+
+RL_FUNCTIONS["gkd_trainer"].append(gkd_trainer_mask_prompt)
+
+
def dpo_trainer_fix_columns(call_args, extra_args):
if "model" in call_args and "train_dataset" in call_args:
fix_dpo = (