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
Route ORPO, CPO, KTO, DPO and TRL 1.15's fused head to the zoo fused linear kernel (#14185)
Daniel Hane6a58b7673a7
diff --git a/tests/python/test_fused_linear_dpo_compute_loss.py b/tests/python/test_fused_linear_dpo_compute_loss.pynew file mode 100644index 00000000000..16b0b98fe50--- /dev/null+++ b/tests/python/test_fused_linear_dpo_compute_loss.py@@ -0,0 +1,318 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL 0.29 - 1.14 DPO ``_compute_loss`` scored from hidden states by unsloth_zoo's fused linear op: the rewritten+TRL body against TRL's own body on the same tiny model (loss, gradients and every logged metric), plus the legacy+(TRL 1.1 - 1.14) ``_ChunkedLogProbFunction`` signature for the fused-head adapter."""++from __future__ import annotations++import ast+import importlib.util+import os+import textwrap+import types+from collections import defaultdict++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl as unsloth_rl+import unsloth.models.rl_replacements as rl++fused_linear = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")++H, V = 16, 37+++def _trl_compute_loss_source():+ """TRL's own ``DPOTrainer._compute_loss`` read from its file (importing unsloth rebinds DPOTrainer)."""+ pytest.importorskip("trl")+ spec = importlib.util.find_spec("trl.trainer.dpo_trainer")+ text = open(spec.origin, encoding = "utf-8").read()+ if "add_fused_lm_head" in text:+ pytest.skip(reason = "TRL >= 1.15 fuses the head itself")+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.FunctionDef) and node.name == "_compute_loss":+ return textwrap.dedent(ast.get_source_segment(text, node, padded = True))+ pytest.skip(reason = "TRL < 0.29 scores DPO in concatenated_forward")+++class _TinyLM(torch.nn.Module):+ """Honours ``UNSLOTH_RETURN_HIDDEN_STATES`` like an Unsloth-compiled forward: ``.logits`` holds the hidden states."""++ is_gradient_checkpointing = False++ def __init__(self, seed):+ super().__init__()+ from transformers import LlamaConfig++ gen = torch.Generator().manual_seed(seed)+ self.config = LlamaConfig(+ vocab_size = V, hidden_size = H, num_hidden_layers = 1, num_attention_heads = 2+ )+ self.embed = torch.nn.Embedding(V, H)+ self.mix = torch.nn.Linear(H, H)+ self.lm_head = torch.nn.Linear(H, V, bias = False)+ with torch.no_grad():+ for p in self.parameters():+ p.copy_(torch.randn(p.shape, generator = gen) * 0.7)++ def get_output_embeddings(self):+ return self.lm_head++ def forward(+ self,+ input_ids = None,+ attention_mask = None,+ use_cache = None,+ **kwargs,+ ):+ hidden = torch.tanh(self.mix(self.embed(input_ids)))+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":+ return types.SimpleNamespace(logits = hidden)+ return types.SimpleNamespace(logits = self.lm_head(hidden))+++class _Accelerator:+ device = torch.device("cpu")++ def unwrap_model(self, model):+ return model++ def gather_for_metrics(self, x):+ return x.reshape(-1) if torch.is_tensor(x) else x++ gather = gather_for_metrics+++def _trainer(loss_types, use_weighting = False):+ model, ref = _TinyLM(0), _TinyLM(1)+ ref.requires_grad_(False)+ trainer = types.SimpleNamespace(+ model = model,+ ref_model = ref,+ accelerator = _Accelerator(),+ beta = 0.1,+ ld_alpha = None,+ loss_types = loss_types,+ loss_weights = [1.0] * len(loss_types),+ precompute_ref_logps = False,+ f_divergence_type = "reverse_kl",+ f_alpha_divergence_coef = 1.0,+ label_smoothing = 0.0,+ use_weighting = use_weighting,+ aux_loss_enabled = False,+ use_liger_kernel = False,+ is_fsdp_enabled = False,+ args = types.SimpleNamespace(gradient_checkpointing_kwargs = None, discopop_tau = 0.05),+ _metrics = {"train": defaultdict(list), "eval": defaultdict(list)},+ _total_train_tokens = 0,+ _tp_size = 1,+ padding_free = False,+ is_encoder_decoder = False,+ )+ trainer._truncate_inputs = lambda *xs: xs+ return trainer+++def _inputs():+ gen = torch.Generator().manual_seed(3)+ input_ids = torch.randint(0, V, (4, 13), generator = gen) # [chosen x2, rejected x2]+ completion_mask = torch.zeros_like(input_ids)+ for row, (start, end) in enumerate(((5, 13), (4, 10), (6, 12), (3, 13))):+ completion_mask[row, start:end] = 1+ # Every other next token is the policy's argmax (the model is per-position), so token accuracy is not 0.+ policy = _TinyLM(0)+ with torch.no_grad():+ for t in range(0, input_ids.shape[1] - 1, 2):+ input_ids[:, t + 1] = policy(input_ids[:, t : t + 1]).logits[:, 0].argmax(-1)+ attention_mask = torch.ones_like(input_ids)+ attention_mask[1, 10:] = 0+ attention_mask[2, 12:] = 0+ return {+ "input_ids": input_ids,+ "attention_mask": attention_mask,+ "completion_mask": completion_mask,+ }+++def _bind(source):+ import trl.trainer.dpo_trainer as dpo++ ns = dict(vars(dpo))+ ns.update({name: getattr(rl, name) for name in dir(rl) if name.startswith("_unsloth_")})+ exec(compile(source, "<dpo_compute_loss>", "exec"), ns)+ return ns["_compute_loss"]+++def _run(+ source,+ loss_types,+ use_weighting = False,+):+ trainer = _trainer(loss_types, use_weighting)+ loss = _bind(source)(trainer, trainer.model, _inputs(), False)+ loss.backward()+ grads = {n: p.grad.clone() for n, p in trainer.model.named_parameters()}+ metrics = {k: v[-1] for k, v in trainer._metrics["train"].items()}+ return loss.detach(), grads, metrics, trainer+++def test_compute_loss_is_rewritten_once():+ source = _trl_compute_loss_source()+ new = rl.dpo_trainer_compute_loss_chunked("_compute_loss", source)+ assert new != source and "_unsloth_dpo_loss_stats" in new+ compile(new, "<dpo>", "exec")+ assert rl.dpo_trainer_compute_loss_chunked("_compute_loss", new) == new+ assert rl.dpo_trainer_compute_loss_chunked("compute_loss", source) == source+ # Another full-logits reader the rewrite does not know leaves TRL's body alone.+ extra = source.replace(+ " return (loss, outputs)",+ " _ = shift_logits.sum()\n return (loss, outputs)",+ )+ assert extra != source and rl.dpo_trainer_compute_loss_chunked("_compute_loss", extra) == extra++[email protected]("loss_types", [["sigmoid"], ["sigmoid", "sft"], ["ipo"]])+def test_rewritten_compute_loss_matches_trl(loss_types):+ source = _trl_compute_loss_source()+ new = rl.dpo_trainer_compute_loss_chunked("_compute_loss", source)+ want_loss, want_grads, want_metrics, _ = _run(source, loss_types)+ calls = fused_linear.CALLS["logprobs"]+ got_loss, got_grads, got_metrics, trainer = _run(new, loss_types)+ assert fused_linear.CALLS["logprobs"] == calls + 2+ assert trainer._unsloth_dpo_chunked_calls == 2+ assert not getattr(trainer, "_unsloth_dpo_chunked_fallbacks", {})+ torch.testing.assert_close(got_loss, want_loss, atol = 1e-5, rtol = 1e-5)+ for name, grad in want_grads.items():+ torch.testing.assert_close(got_grads[name], grad, atol = 1e-5, rtol = 1e-4, msg = name)+ assert set(got_metrics) == set(want_metrics)+ for key, value in want_metrics.items():+ assert got_metrics[key] == pytest.approx(value, rel = 1e-5, abs = 1e-5), key+ assert {+ "entropy",+ "logits/chosen",+ "logits/rejected",+ "mean_token_accuracy",+ } <= set(got_metrics)+ assert 0.0 < got_metrics["mean_token_accuracy"] < 1.0++[email protected]("reason", ["use_weighting", "kill_switch"])+def test_rewritten_compute_loss_keeps_trl_path(reason, monkeypatch):+ source = _trl_compute_loss_source()+ new = rl.dpo_trainer_compute_loss_chunked("_compute_loss", source)+ weighting = reason == "use_weighting"+ if reason == "kill_switch":+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ want_loss, _, want_metrics, _ = _run(source, ["sigmoid"], use_weighting = weighting)+ calls = fused_linear.CALLS["logprobs"]+ got_loss, _, got_metrics, trainer = _run(new, ["sigmoid"], use_weighting = weighting)+ assert fused_linear.CALLS["logprobs"] == calls+ assert trainer._unsloth_dpo_chunked_fallbacks+ assert torch.equal(got_loss, want_loss) and got_metrics == want_metrics+++def _run_with(source, setup):+ trainer = _trainer(["sigmoid"])+ setup(trainer)+ loss = _bind(source)(trainer, trainer.model, _inputs(), False)+ loss.backward()+ return loss.detach(), trainer+++def _shared_head(trainer):+ trainer.ref_model = trainer.model+++def _trainable_ref(trainer):+ trainer.ref_model.requires_grad_(True)+++ "setup", [_shared_head, _trainable_ref], ids = ["shared_head", "trainable_ref"]+)+def test_reference_pass_gets_no_gradient(setup):+ """TRL scores the reference under no_grad: neither a trainable reference head nor the policy's own head (adapter+ disabled reference) may get a gradient from it."""+ source = _trl_compute_loss_source()+ new = rl.dpo_trainer_compute_loss_chunked("_compute_loss", source)+ want_loss, want = _run_with(source, setup)+ got_loss, got = _run_with(new, setup)+ assert got._unsloth_dpo_chunked_calls == 2+ torch.testing.assert_close(got_loss, want_loss, atol = 1e-5, rtol = 1e-5)+ for (name, w), g in zip(want.model.named_parameters(), got.model.parameters()):+ torch.testing.assert_close(g.grad, w.grad, atol = 1e-5, rtol = 1e-4, msg = name)+ if want.ref_model is not want.model:+ assert all(p.grad is None for p in want.ref_model.parameters())+ assert all(p.grad is None for p in got.ref_model.parameters())+++def test_hooked_head_keeps_trl_path():+ """The fused op reads the head's weight directly: a forward hook on it would be skipped."""+ source = _trl_compute_loss_source()+ new = rl.dpo_trainer_compute_loss_chunked("_compute_loss", source)++ def setup(trainer):+ for model in (trainer.model, trainer.ref_model):+ model.lm_head.register_forward_hook(lambda module, args, output: output * 0.5)++ want_loss, _ = _run_with(source, setup)+ calls = fused_linear.CALLS["logprobs"]+ got_loss, trainer = _run_with(new, setup)+ assert fused_linear.CALLS["logprobs"] == calls+ assert "output head has hooks or a patched forward" in trainer._unsloth_dpo_chunked_fallbacks+ torch.testing.assert_close(got_loss, want_loss)+++class _LegacyKernel:+ """TRL 1.1 - 1.14's ``_ChunkedLogProbFunction``: no ``outputs`` argument, returns ``(log_probs, entropy)``."""++ @staticmethod+ def forward(+ ctx,+ last_hidden,+ weight,+ bias,+ targets,+ temperature,+ chunk_size,+ final_logit_softcapping = None,+ logit_scale = 1.0,+ ):+ raise AssertionError("not reached")++ @staticmethod+ def apply(*args):+ assert len(args) == 8+ return "trl_logps", "trl_entropy"+++def test_adapter_keeps_the_legacy_kernel_contract():+ gen = torch.Generator().manual_seed(7)+ hidden = torch.randn(9, H, generator = gen, requires_grad = True)+ weight = torch.randn(V, H, generator = gen)+ targets = torch.randint(0, V, (9,), generator = gen)+ adapter = unsloth_rl._UnslothFusedLinearHead(_LegacyKernel)+ assert adapter._legacy+ calls = fused_linear.CALLS["logprobs"]+ logps, entropy = adapter.apply(hidden, weight, None, targets, 0.8, 4096, None, 1.0)+ assert fused_linear.CALLS["logprobs"] == calls + 1+ log_p = (hidden.detach().double() @ weight.double().t() / 0.8).log_softmax(-1)+ torch.testing.assert_close(+ logps.detach().double(),+ log_p.gather(-1, targets[:, None]).squeeze(-1),+ atol = 1e-5,+ rtol = 1e-5,+ )+ torch.testing.assert_close(+ entropy.detach().double(), -(log_p.exp() * log_p).sum(-1), atol = 1e-5, rtol = 1e-5+ )+ (logps.sum() + entropy.sum()).backward()+ assert hidden.grad is not None and hidden.grad.isfinite().all()+ # A call it cannot reproduce still reaches TRL with TRL's 8 arguments.+ assert adapter.apply(hidden, weight, None, targets, 1.0, 4096, None, 0.0) == (+ "trl_logps",+ "trl_entropy",+ )diff --git a/tests/python/test_fused_linear_grpo_scorer_parity.py b/tests/python/test_fused_linear_grpo_scorer_parity.pynew file mode 100644index 00000000000..df354815a6a--- /dev/null+++ b/tests/python/test_fused_linear_grpo_scorer_parity.py@@ -0,0 +1,87 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""GRPO old / ref logps must use the policy pass scorer, else the importance ratio starts away from 1."""++from __future__ import annotations++import inspect+import os+import textwrap+import types++import pytest+import torch++import unsloth.models.rl_replacements as rl++zoo_rl = pytest.importorskip("unsloth_zoo.rl_replacements")+if not hasattr(zoo_rl, "grpo_chunked_hidden_states_logprobs"):+ pytest.skip("zoo without the fused GRPO scorer", allow_module_level = True)+++def _resolve_scorer(trainer):+ src = rl.grpo_trainer__get_per_token_logps_and_entropies(+ "_get_per_token_logps_and_entropies", None+ )+ start = src.index("from unsloth_zoo.rl_replacements import (\n")+ start = src.rindex("\n", 0, start) + 1+ end = src.index("output_embeddings = unwrapped_model.get_output_embeddings()")+ block = textwrap.dedent(src[start:end])+ assert "chunked_hidden_states_selective_log_softmax" in block+ ns = {"os": os, "self": trainer}+ exec(block, ns)+ return ns["chunked_hidden_states_selective_log_softmax"]+++def _trainer():+ args = types.SimpleNamespace(top_k = None, top_p = 1.0, min_p = None)+ return types.SimpleNamespace(args = args)+++def test_old_ref_scorer_is_the_policy_scorer(monkeypatch):+ monkeypatch.delenv("UNSLOTH_GRPO_LOGPROB_RECOMPUTE", raising = False)+ assert _resolve_scorer(_trainer()) is zoo_rl.grpo_chunked_hidden_states_logprobs+++def test_recompute_mode_matches_policy_scorer(monkeypatch):+ monkeypatch.setenv("UNSLOTH_GRPO_LOGPROB_RECOMPUTE", "1")+ monkeypatch.setattr(zoo_rl, "grpo_truncated_support_kwargs", lambda trainer: {})+ assert (+ _resolve_scorer(_trainer()) is zoo_rl.chunked_hidden_states_selective_log_softmax_recompute+ )+ # zoo's policy pass falls back to the plain helper for truncated support under recompute.+ monkeypatch.setattr(+ zoo_rl, "grpo_truncated_support_kwargs", lambda trainer: {"support_top_k": 4}+ )+ assert _resolve_scorer(_trainer()) is zoo_rl.chunked_hidden_states_selective_log_softmax+++def test_no_grad_scores_equal_policy_scores(monkeypatch):+ """The ratio of identical policies is exactly 1 with the shared scorer (bf16 head)."""+ monkeypatch.delenv("UNSLOTH_GRPO_LOGPROB_RECOMPUTE", raising = False)+ scorer = _resolve_scorer(_trainer())+ device = "cuda" if torch.cuda.is_available() else "cpu"+ g = torch.Generator().manual_seed(0)+ hidden = (torch.randn(2, 16, 64, generator = g) * 4).to(torch.bfloat16).to(device)+ head = (torch.randn(512, 64, generator = g) * 4).to(torch.bfloat16).to(device)+ index = torch.randint(0, 512, (2, 16), generator = g).to(device)+ with torch.no_grad():+ old = scorer(hidden, head, index, 4)+ policy = zoo_rl.grpo_chunked_hidden_states_logprobs(+ hidden.clone().requires_grad_(True), head, index, 4+ )+ torch.testing.assert_close(policy.detach(), old, rtol = 0, atol = 1e-6)+ if device == "cuda":+ # The legacy helper rounds logits to bf16 on CUDA, so it cannot stand in for the policy scorer.+ with torch.no_grad():+ # A zoo with the fused public scorer needs fused_linear = False for its own chunked path.+ kw = (+ {"fused_linear": False}+ if "fused_linear"+ in inspect.signature(zoo_rl.chunked_hidden_states_selective_log_softmax).parameters+ else {}+ )+ legacy = zoo_rl.chunked_hidden_states_selective_log_softmax(+ hidden, head, index, 4, **kw+ )+ assert (policy.detach() - legacy).abs().max().item() > 1e-3diff --git a/tests/python/test_fused_linear_kto_compute_loss.py b/tests/python/test_fused_linear_kto_compute_loss.pynew file mode 100644index 00000000000..7eac54abf30--- /dev/null+++ b/tests/python/test_fused_linear_kto_compute_loss.py@@ -0,0 +1,693 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL 1.6 - 1.14 KTO ``_compute_loss`` + ``_compute_kl_logps`` and TRL 0.29 - 1.14 DPO precomputed reference+log-probs scored from hidden states by unsloth_zoo's fused linear op: TRL's own methods against the rewritten+ones on the same tiny model (loss, gradients, every logged metric), plus sabotaged rewrites the comparison must+catch."""++from __future__ import annotations++import ast+import importlib+import importlib.util+import re+import inspect+import os+import textwrap+import types+from collections import defaultdict++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl_replacements as rl++fused_linear = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")+dpo_test = pytest.importorskip("tests.python.test_fused_linear_dpo_compute_loss")+_TinyLM, _Accelerator = dpo_test._TinyLM, dpo_test._Accelerator+V = dpo_test.V++_METHODS = ("_compute_loss", "_compute_kl_logps")+_MASK = re.compile(+ r'(batch\["(?:KL_)?completion_mask"\]\[:, 1:\]|shift_completion_mask|inputs\["completion_mask"\]\[\.\.\., 1:\]),?$'+)+++def _break_mask(source, anchor):+ """Score every row in the fused call that follows ``anchor`` instead of TRL's completion mask."""+ start = source.index(anchor)+ end = source.index("\n", start)+ line = source[start:end]+ mask = _MASK.search(line).group(1)+ return source[:start] + line.replace(mask, f"torch.ones_like({mask})") + source[end:]+++def _kto_module():+ """TRL's KTO trainer module that defines ``_compute_kl_logps`` (1.6 - 1.9: experimental, 1.10+: trainer)."""+ pytest.importorskip("trl")+ for name in ("trl.trainer.kto_trainer", "trl.experimental.kto.kto_trainer"):+ try:+ spec = importlib.util.find_spec(name)+ except Exception:+ spec = None+ if spec is None or spec.origin is None:+ continue+ text = open(spec.origin, encoding = "utf-8").read()+ if "def _compute_kl_logps" in text and "def _compute_loss(" in text:+ return name, text+ pytest.skip(reason = "TRL < 1.6 KTO scores through get_batch_logps (rewritten elsewhere)")+++def _kto_sources():+ name, text = _kto_module()+ if "selective_log_softmax" not in text or "add_fused_lm_head" in text:+ pytest.skip(reason = "TRL >= 1.15 fuses the head itself")+ out = {}+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == "KTOTrainer":+ for fn in node.body:+ if isinstance(fn, ast.FunctionDef) and fn.name in _METHODS:+ out[fn.name] = ast.get_source_segment(text, fn, padded = True)+ assert set(out) == set(_METHODS)+ return name, out+++def _rewritten(sources):+ new = {k: rl.kto_trainer_compute_loss_chunked(k, v) for k, v in sources.items()}+ for k in _METHODS:+ assert new[k] != sources[k] and "_unsloth_fused_pass_logps" in new[k], k+ return new+++def _bind(module_name, sources):+ module = importlib.import_module(module_name)+ ns = dict(vars(module))+ ns.update({name: getattr(rl, name) for name in dir(rl) if name.startswith("_unsloth_")})+ for name, src in sources.items():+ exec(compile(textwrap.dedent(src), f"<kto {name}>", "exec"), ns)+ return {name: ns[name] for name in sources}+++def _batch(old_keys, label_list):+ gen = torch.Generator().manual_seed(5)+ ids = torch.randint(0, V, (4, 11), generator = gen)+ kl_ids = torch.randint(0, V, (4, 12), generator = gen)+ mask = torch.zeros_like(ids)+ kl_mask = torch.zeros_like(kl_ids)+ for row, (a, b) in enumerate(((4, 11), (3, 9), (5, 10), (2, 11))):+ mask[row, a:b] = 1+ for row, (a, b) in enumerate(((3, 12), (5, 10), (4, 12), (6, 11))):+ kl_mask[row, a:b] = 1+ # KL completions the policy (not the reference) likes, so the clamped KL term is not 0.+ policy = _TinyLM(0)+ with torch.no_grad():+ for t in range(kl_ids.shape[1] - 1):+ kl_ids[:, t + 1] = policy(kl_ids[:, t : t + 1]).logits[:, 0].argmax(-1)+ attn = torch.ones_like(ids)+ attn[1, 9:] = 0+ kl_attn = torch.ones_like(kl_ids)+ kl_attn[1, 10:] = 0+ labels = [True, False, True, False]+ prefix = "completion_" if old_keys else ""+ return {+ f"{prefix}input_ids": ids,+ f"{prefix}attention_mask": attn,+ "completion_mask": mask,+ f"KL_{prefix}input_ids": kl_ids,+ f"KL_{prefix}attention_mask": kl_attn,+ "KL_completion_mask": kl_mask,+ "label": labels if label_list else torch.tensor(labels),+ }+++def _run(+ module_name,+ sources,+ loss_type = "kto",+):+ methods = _bind(module_name, sources)+ model, ref = _TinyLM(0), _TinyLM(1)+ ref.requires_grad_(False)+ trainer = types.SimpleNamespace(+ model = model,+ ref_model = ref,+ accelerator = _Accelerator(),+ beta = 0.1,+ loss_type = loss_type,+ desirable_weight = 1.0,+ undesirable_weight = 1.3,+ calculate_KL = loss_type == "kto",+ precompute_ref_logps = False,+ aux_loss_enabled = False,+ use_liger_kernel = False,+ is_fsdp_enabled = False,+ is_encoder_decoder = False,+ args = types.SimpleNamespace(gradient_checkpointing_kwargs = None),+ _metrics = {"train": defaultdict(list), "eval": defaultdict(list)},+ _total_train_tokens = 0,+ _tp_size = 1,+ )+ trainer._compute_kl_logps = types.MethodType(methods["_compute_kl_logps"], trainer)+ text = sources["_compute_loss"]+ batch = _batch('"KL_completion_input_ids"' in text, 'torch.tensor(batch["label"])' in text)+ calls = fused_linear.CALLS["logprobs"]+ loss = methods["_compute_loss"](trainer, model, batch, False)+ used = fused_linear.CALLS["logprobs"] - calls+ loss.backward()+ grads = {n: p.grad.clone() for n, p in model.named_parameters()}+ metrics = {k: v[-1] for k, v in trainer._metrics["train"].items()}+ return loss.detach(), grads, metrics, trainer, used+++def _compare(want, got):+ want_loss, want_grads, want_metrics = want[:3]+ got_loss, got_grads, got_metrics = got[:3]+ torch.testing.assert_close(got_loss, want_loss, atol = 1e-5, rtol = 1e-5)+ for name, grad in want_grads.items():+ torch.testing.assert_close(got_grads[name], grad, atol = 1e-5, rtol = 1e-4, msg = name)+ assert set(got_metrics) == set(want_metrics)+ for key, value in want_metrics.items():+ assert got_metrics[key] == pytest.approx(value, rel = 1e-5, abs = 1e-5), key+++def test_kto_rewrite_is_anchored():+ _, sources = _kto_sources()+ new = _rewritten(sources)+ for name in _METHODS:+ compile(textwrap.dedent(new[name]), name, "exec")+ assert rl.kto_trainer_compute_loss_chunked(name, new[name]) == new[name]+ assert rl.kto_trainer_compute_loss_chunked("compute_loss", sources[name]) == sources[name]+ # Another reader of the policy logits the rewrite does not know leaves TRL's body alone.+ extra = sources["_compute_loss"].replace(+ " return (loss, outputs)",+ " _ = outputs.logits.sum()\n return (loss, outputs)",+ )+ assert extra != sources["_compute_loss"]+ assert rl.kto_trainer_compute_loss_chunked("_compute_loss", extra) == extra+ extra = sources["_compute_kl_logps"].replace(+ " return KL_logps", " _ = shift_KL_logits.sum()\n return KL_logps"+ )+ assert extra != sources["_compute_kl_logps"]+ assert rl.kto_trainer_compute_loss_chunked("_compute_kl_logps", extra) == extra++[email protected]("loss_type", ["kto", "apo_zero_unpaired"])+def test_kto_rewrite_matches_trl(loss_type):+ module_name, sources = _kto_sources()+ want = _run(module_name, sources, loss_type)+ got = _run(module_name, _rewritten(sources), loss_type)+ trainer = got[3]+ kl_passes = 2 if loss_type == "kto" else 0+ assert trainer._unsloth_dpo_chunked_calls == 2 + kl_passes+ assert got[4] >= 2 + kl_passes and want[4] == 0+ assert not getattr(trainer, "_unsloth_dpo_chunked_fallbacks", {})+ _compare(want, got)+ metrics = got[2]+ assert {"logps/chosen", "logps/rejected", "logits/chosen", "logits/rejected", "kl"} <= set(+ metrics+ )+ if loss_type == "kto":+ assert metrics["kl"] > 0 # the KL pass reaches the loss+ if (+ "entropy_from_logits" in sources["_compute_loss"]+ or "_and_entropy" in sources["_compute_loss"]+ ):+ assert "entropy" in metrics+++ "sabotage",+ ["kl_mask", "policy_mask", "ref_mask", "entropy", "logits_metric"],+)+def test_kto_comparison_catches_a_broken_rewrite(sabotage, monkeypatch):+ module_name, sources = _kto_sources()+ new = _rewritten(sources)+ if sabotage in ("kl_mask", "policy_mask", "ref_mask"):+ var = {+ "kl_mask": "_unsloth_kto_kl, shift_KL_logits",+ "policy_mask": "_unsloth_kto_chunked, shift_logits",+ "ref_mask": "_unsloth_kto_ref, ref_shift_logits",+ }+ method = "_compute_kl_logps" if sabotage == "kl_mask" else "_compute_loss"+ new[method] = _break_mask(new[method], f"self, {var[sabotage]}, ")+ else:+ real = rl._unsloth_fused_pass_logps++ def broken(*args, **kwargs):+ out = real(*args, **kwargs)+ if not kwargs.get("stats"):+ return out+ logps, entropy, mean_logits = out+ if sabotage == "entropy":+ return logps, entropy * 1.001, mean_logits+ return logps, entropy, mean_logits * 1.001++ monkeypatch.setattr(rl, "_unsloth_fused_pass_logps", broken)+ stats = "stats = True" in new["_compute_loss"]+ if sabotage == "entropy" and not stats:+ pytest.skip(reason = "this TRL logs no entropy")+ # TRL 1.6 - 1.8 log the logits sums over every position instead of the masked row means.+ if sabotage == "logits_metric" and "_unsloth_fused_pass_vocab_sums" in new["_compute_loss"]:+ real_sums = rl._unsloth_fused_pass_vocab_sums+ monkeypatch.setattr(+ rl, "_unsloth_fused_pass_vocab_sums", lambda *a: real_sums(*a) * 1.001+ )+ want = _run(module_name, sources)+ got = _run(module_name, new)+ with pytest.raises(AssertionError):+ _compare(want, got)++[email protected]("reason", ["kill_switch", "use_liger_kernel"])+def test_kto_rewrite_keeps_trl_path(reason, monkeypatch):+ module_name, sources = _kto_sources()+ new = _rewritten(sources)+ if reason == "kill_switch":+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ want = _run(module_name, sources)+ got = _run(module_name, new)+ else:+ # The liger branches need liger; only check the head decision keeps TRL's path.+ trainer = types.SimpleNamespace(use_liger_kernel = True)+ assert rl._unsloth_fused_pass_head(trainer, None, {}, False, "_compute_loss") is None+ assert trainer._unsloth_dpo_chunked_fallbacks+ return+ assert got[4] == 0 and got[3]._unsloth_dpo_chunked_fallbacks+ assert torch.equal(got[0], want[0]) and got[2] == want[2]+++def _dpo_ref_source():+ pytest.importorskip("trl")+ spec = importlib.util.find_spec("trl.trainer.dpo_trainer")+ text = open(spec.origin, encoding = "utf-8").read()+ if "add_fused_lm_head" in text or "def _compute_loss(" not in text:+ pytest.skip(reason = "TRL >= 1.15 fuses the head; TRL < 0.29 scores in concatenated_forward")+ name = (+ "_compute_ref_log_probs"+ if "def _compute_ref_log_probs" in text+ else "compute_ref_log_probs"+ )+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == "DPOTrainer":+ for fn in node.body:+ if isinstance(fn, ast.FunctionDef) and fn.name == name:+ return name, ast.get_source_segment(text, fn, padded = True)+ pytest.fail("no compute_ref_log_probs")+++def _dpo_ref_run(name, source):+ import trl.trainer.dpo_trainer as dpo++ ns = dict(vars(dpo))+ ns.update({k: getattr(rl, k) for k in dir(rl) if k.startswith("_unsloth_")})+ exec(compile(textwrap.dedent(source), "<dpo ref>", "exec"), ns)+ trainer = dpo_test._trainer(["sigmoid"])+ trainer.ref_model.requires_grad_(+ True+ ) # a trainable head must still get no graph from the reference pass+ args = (trainer.ref_model,) if "model" in inspect.signature(ns[name]).parameters else ()+ calls = fused_linear.CALLS["logprobs"]+ chosen, rejected = ns[name](trainer, *args, dpo_test._inputs())+ return torch.cat([chosen, rejected]), fused_linear.CALLS["logprobs"] - calls, trainer+++def test_dpo_precomputed_reference_matches_trl(monkeypatch):+ name, source = _dpo_ref_source()+ new = rl.dpo_trainer_ref_log_probs_chunked(name, source)+ assert new != source and "_unsloth_fused_pass_logps" in new+ assert rl.dpo_trainer_ref_log_probs_chunked(name, new) == new+ want, want_calls, _ = _dpo_ref_run(name, source)+ got, got_calls, trainer = _dpo_ref_run(name, new)+ assert want_calls == 0 and got_calls == 1 and trainer._unsloth_dpo_chunked_calls == 1+ assert not got.requires_grad+ torch.testing.assert_close(got, want, atol = 1e-5, rtol = 1e-5)+ # Broken: score every row, not only the completion.+ bad, _, _ = _dpo_ref_run(name, _break_mask(new, "self, _unsloth_dpo_ref, ref_shift_logits, "))+ with pytest.raises(AssertionError):+ torch.testing.assert_close(bad, want, atol = 1e-5, rtol = 1e-5)+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ off, off_calls, _ = _dpo_ref_run(name, new)+ assert off_calls == 0 and torch.equal(off, want)+++_KTO_REF_NAMES = ("_compute_ref_log_probs", "compute_ref_log_probs", "compute_reference_log_probs")+++def _kto_ref_source(text = None):+ """``(module, name, source)`` of TRL's KTO reference log-prob precompute that builds the logits: TRL < 1.6+ ``compute_reference_log_probs``, 1.6 - 1.13 ``compute_ref_log_probs``, 1.14 ``_compute_ref_log_probs``. ``text``+ scores another TRL's file in the installed module's namespace (historical layouts)."""+ pytest.importorskip("trl")+ module = None+ for name in ("trl.trainer.kto_trainer", "trl.experimental.kto.kto_trainer"):+ try:+ spec = importlib.util.find_spec(name)+ except Exception:+ spec = None+ if spec is None or spec.origin is None:+ continue+ own = open(spec.origin, encoding = "utf-8").read()+ if "class KTOTrainer" in own and any(f"def {n}(" in own for n in _KTO_REF_NAMES):+ module = importlib.import_module(name)+ text = own if text is None else text+ break+ if module is None:+ pytest.skip(reason = "no KTOTrainer")+ fns = {}+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == "KTOTrainer":+ for fn in node.body:+ if isinstance(fn, ast.FunctionDef) and fn.name in _KTO_REF_NAMES:+ fns[fn.name] = ast.get_source_segment(text, fn, padded = True)+ name = next((n for n in _KTO_REF_NAMES if n in fns), None)+ if name is None:+ pytest.fail("no KTO reference log-prob method")+ if "fused_lm_head=True" in fns[name]:+ pytest.skip(reason = "TRL >= 1.15 fuses the head itself")+ return module, name, fns[name]+++def _kto_ref_batch():+ gen = torch.Generator().manual_seed(7)+ ids = torch.randint(0, V, (4, 11), generator = gen)+ kl_ids = torch.randint(0, V, (4, 12), generator = gen)+ mask, kl_mask = torch.zeros_like(ids), torch.zeros_like(kl_ids)+ for row, (a, b) in enumerate(((4, 11), (3, 9), (5, 10), (2, 11))):+ mask[row, a:b] = 1+ for row, (a, b) in enumerate(((3, 12), (5, 10), (4, 12), (6, 11))):+ kl_mask[row, a:b] = 1+ attn, kl_attn = torch.ones_like(ids), torch.ones_like(kl_ids)+ attn[1, 9:] = 0+ kl_attn[1, 10:] = 0+ batch = {"completion_mask": mask, "KL_completion_mask": kl_mask}+ # TRL < 1.8 names the ids completion_*; TRL < 1.6 scores completion_labels (-100 outside the completion).+ for prefix in ("", "completion_"):+ batch[f"{prefix}input_ids"], batch[f"{prefix}attention_mask"] = ids, attn+ batch[f"KL_{prefix}input_ids"], batch[f"KL_{prefix}attention_mask"] = kl_ids, kl_attn+ batch["completion_labels"] = ids.masked_fill(mask == 0, -100)+ batch["KL_completion_labels"] = kl_ids.masked_fill(kl_mask == 0, -100)+ return batch+++def _kto_ref_run(module, name, source, calculate_KL, peft):+ import contextlib++ ns = dict(vars(module))+ ns.update({k: getattr(rl, k) for k in dir(rl) if k.startswith("_unsloth_")})+ exec(compile(textwrap.dedent(source), f"<kto {name}>", "exec"), ns)+ if peft:+ peft_lib = pytest.importorskip("peft")+ config = peft_lib.LoraConfig(target_modules = ["mix"], r = 4, init_lora_weights = False)+ model, ref = peft_lib.get_peft_model(_TinyLM(0), config), None+ else:+ model, ref = _TinyLM(0), _TinyLM(1)+ # A trainable reference head must still get no graph from the precompute.+ ref.requires_grad_(True)+ trainer = types.SimpleNamespace(+ model = model,+ ref_model = ref,+ accelerator = _Accelerator(),+ calculate_KL = calculate_KL,+ is_encoder_decoder = False,+ label_pad_token_id = -100,+ aux_loss_enabled = False,+ use_liger_kernel = False,+ is_fsdp_enabled = False,+ is_deepspeed_enabled = False,+ args = types.SimpleNamespace(gradient_checkpointing_kwargs = None),+ get_batch_logps = getattr(module.KTOTrainer, "get_batch_logps", None),+ null_ref_context = lambda: model.disable_adapter() if peft else contextlib.nullcontext(),+ )+ args = ()+ if "model" in inspect.signature(ns[name]).parameters:+ args = (ref if ref is not None else model,)+ calls = fused_linear.CALLS["logprobs"]+ logps, kl_logps = ns[name](trainer, *args, _kto_ref_batch())+ return logps, kl_logps, fused_linear.CALLS["logprobs"] - calls, trainer+++def _kto_ref_case(+ calculate_KL,+ peft,+ monkeypatch,+ text = None,+):+ module, name, source = _kto_ref_source(text)+ new = rl.kto_trainer_ref_log_probs_chunked(name, source)+ assert new != source and "_unsloth_kto_ref_chunked_forward" in new+ assert rl.kto_trainer_ref_log_probs_chunked(name, new) == new+ want = _kto_ref_run(module, name, source, calculate_KL, peft)+ got = _kto_ref_run(module, name, new, calculate_KL, peft)+ passes = 2 if calculate_KL else 1+ assert want[2] == 0 and got[2] == passes and got[3]._unsloth_dpo_chunked_calls == passes+ assert not getattr(got[3], "_unsloth_dpo_chunked_fallbacks", {})+ assert not got[0].requires_grad+ torch.testing.assert_close(got[0], want[0], atol = 1e-5, rtol = 1e-5)+ if calculate_KL:+ assert not got[1].requires_grad+ torch.testing.assert_close(got[1], want[1], atol = 1e-5, rtol = 1e-5)+ else:+ assert want[1] is None and got[1] is None+ # Broken: score every row, not only the completion; the comparison must catch it.+ real = rl._unsloth_fused_pass_logps++ def no_mask(self, chunked, hidden_states, labels, mask, *args, **kwargs):+ return real(self, chunked, hidden_states, labels, torch.ones_like(mask), *args, **kwargs)++ with monkeypatch.context() as patch:+ patch.setattr(rl, "_unsloth_fused_pass_logps", no_mask)+ bad = _kto_ref_run(module, name, new, calculate_KL, peft)+ with pytest.raises(AssertionError):+ torch.testing.assert_close(bad[0], want[0], atol = 1e-5, rtol = 1e-5)+ # Kill switch: TRL's path, bit for bit.+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ off = _kto_ref_run(module, name, new, calculate_KL, peft)+ assert off[2] == 0 and off[3]._unsloth_dpo_chunked_fallbacks+ assert torch.equal(off[0], want[0])+ assert (off[1] is None) if not calculate_KL else torch.equal(off[1], want[1])++[email protected]("calculate_KL", [True, False], ids = ["kl", "no_kl"])[email protected]("peft", [False, True], ids = ["ref_model", "peft_adapter_ref"])+def test_kto_precomputed_reference_matches_trl(calculate_KL, peft, monkeypatch):+ _kto_ref_case(calculate_KL, peft, monkeypatch)+++def test_kto_precomputed_reference_rewrite_is_anchored():+ _, name, source = _kto_ref_source()+ new = rl.kto_trainer_ref_log_probs_chunked(name, source)+ compile(textwrap.dedent(new), name, "exec")+ assert rl.kto_trainer_ref_log_probs_chunked("compute_loss", source) == source+ # Another reader of the logits leaves TRL's body alone.+ extra = source.replace(+ " return completion_logps, KL_logps",+ " _ = completion_logits.sum()\n return completion_logps, KL_logps",+ )+ assert extra != source+ assert rl.kto_trainer_ref_log_probs_chunked(name, extra) == extra+ # A second completion log-prob statement (anchor no longer unique) leaves it alone too.+ stmt = (rl._KTO_REF_BATCH_LOGPS.search(source) or rl._KTO_REF_LOGPS_RE.search(source)).group(0)+ twice = source.replace(stmt, stmt + stmt, 1)+ assert rl.kto_trainer_ref_log_probs_chunked(name, twice) == twice+ # The rewritten method runs through the full RL_FUNCTIONS chain unchanged by later edits.+ chained = source+ for edit in rl.RL_FUNCTIONS["kto_trainer"]:+ chained = edit(name, chained)+ assert chained == new+++# TRL 1.6's KTOTrainer.compute_ref_log_probs (trl/experimental/kto/kto_trainer.py, v1.6.0), verbatim: the only+# layout kto_trainer_align_completion_logps clamps, which its fallback branch must keep doing.+_TRL16_KTO_REF = '''+ def compute_ref_log_probs(self, inputs):+ """Computes reference log probabilities for a single padded batch."""+ with torch.no_grad(), disable_gradient_checkpointing(self.model, self.args.gradient_checkpointing_kwargs):+ if self.ref_model is None:+ if is_peft_model(self.model):+ model = self.accelerator.unwrap_model(self.model)+ with use_adapter(model, adapter_name="ref" if "ref" in model.peft_config else None):+ completion_logits = self.model(+ inputs["completion_input_ids"],+ attention_mask=inputs["completion_attention_mask"],+ ).logits++ if self.calculate_KL:+ KL_logits = self.model(+ inputs["KL_completion_input_ids"],+ attention_mask=inputs["KL_completion_attention_mask"],+ ).logits+ else:+ completion_logits = self.model(+ inputs["completion_input_ids"],+ attention_mask=inputs["completion_attention_mask"],+ ).logits++ if self.calculate_KL:+ KL_logits = self.model(+ inputs["KL_completion_input_ids"],+ attention_mask=inputs["KL_completion_attention_mask"],+ ).logits+ else:+ completion_logits = self.ref_model(+ inputs["completion_input_ids"], attention_mask=inputs["completion_attention_mask"]+ ).logits++ if self.calculate_KL:+ KL_logits = self.ref_model(+ inputs["KL_completion_input_ids"],+ attention_mask=inputs["KL_completion_attention_mask"],+ ).logits++ shift_logits = completion_logits[:, :-1, :].contiguous()+ per_token_logps = selective_log_softmax(shift_logits, inputs["completion_input_ids"][:, 1:].contiguous())+ per_token_logps[inputs["completion_mask"][:, 1:] == 0] = 0.0+ completion_logps = per_token_logps.sum(-1)++ if self.calculate_KL:+ shift_KL_logits = KL_logits[:, :-1, :].contiguous()+ KL_per_token_logps = selective_log_softmax(+ shift_KL_logits, inputs["KL_completion_input_ids"][:, 1:].contiguous()+ )+ KL_per_token_logps[inputs["KL_completion_mask"][:, 1:] == 0] = 0.0+ KL_logps = KL_per_token_logps.sum(-1)+ else:+ KL_logps = None++ return completion_logps, KL_logps+'''+++class _TruncatingLM(_TinyLM):+ """Drops input_ids past ``max_len`` like an Unsloth forward capped at max_seq_length: logits are shorter."""++ max_len = 9++ def forward(+ self,+ input_ids = None,+ attention_mask = None,+ **kwargs,+ ):+ return super().forward(input_ids[:, : self.max_len], attention_mask, **kwargs)+++def _kto_ref16_run(source, calculate_KL = True):+ import contextlib++ module = importlib.import_module("trl.trainer.utils")+ ns = {"torch": torch, "selective_log_softmax": module.selective_log_softmax}+ ns.update(+ disable_gradient_checkpointing = lambda *a, **k: contextlib.nullcontext(),+ is_peft_model = lambda m: hasattr(m, "peft_config"),+ use_adapter = lambda *a, **k: contextlib.nullcontext(),+ )+ ns.update({k: getattr(rl, k) for k in dir(rl) if k.startswith("_unsloth_")})+ exec(compile(textwrap.dedent(source), "<kto 1.6 ref>", "exec"), ns)+ model, ref = _TruncatingLM(0), _TruncatingLM(1)+ ref.requires_grad_(False)+ trainer = types.SimpleNamespace(+ model = model,+ ref_model = ref,+ accelerator = _Accelerator(),+ calculate_KL = calculate_KL,+ is_encoder_decoder = False,+ aux_loss_enabled = False,+ use_liger_kernel = False,+ is_fsdp_enabled = False,+ is_deepspeed_enabled = False,+ args = types.SimpleNamespace(gradient_checkpointing_kwargs = None),+ )+ calls = fused_linear.CALLS["logprobs"]+ out = ns["compute_ref_log_probs"](trainer, _kto_ref_batch())+ return out, fused_linear.CALLS["logprobs"] - calls+++def _kto_chain(name, source):+ for edit in rl.RL_FUNCTIONS["kto_trainer"]:+ source = edit(name, source)+ return source++[email protected]("fallback", ["kill_switch", "hooked_head", "fused"])+def test_kto16_reference_fallback_keeps_truncation_clamp(fallback, monkeypatch):+ """TRL 1.6 + a model that truncates input_ids: the rewritten method's TRL branch keeps the clamp the pre-PR+ pipeline (kto_trainer_align_completion_logps alone) gave it, and the fused branch agrees with it."""+ pytest.importorskip("trl")+ source = textwrap.indent(textwrap.dedent(_TRL16_KTO_REF).strip("\n") + "\n", " ")+ pre_pr = rl.kto_trainer_align_completion_logps("compute_ref_log_probs", source)+ assert pre_pr != source and "_uns_n" in pre_pr and "_uns_kl_n" in pre_pr+ new = _kto_chain("compute_ref_log_probs", source)+ assert "_unsloth_kto_ref_chunked_forward" in new+ # The fallback branches carry the clamp exactly once each (not on the fused branch).+ assert new.count("_uns_n = min(") == 1 and new.count("_uns_kl_n = min(") == 1+ with pytest.raises(Exception):+ _kto_ref16_run(source) # TRL alone breaks on the shorter logits: the case is real+ want, _ = _kto_ref16_run(pre_pr)+ if fallback == "kill_switch":+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ elif fallback == "hooked_head":+ monkeypatch.setattr(_TruncatingLM, "__init__", _hooked_init)+ got, calls = _kto_ref16_run(new)+ if fallback == "fused":+ assert calls == 2+ for a, b in zip(got, want):+ torch.testing.assert_close(a, b, atol = 1e-5, rtol = 1e-5)+ else:+ assert calls == 0+ assert all(torch.equal(a, b) for a, b in zip(got, want))+++_TRL16_KTO_KL = '''+def _compute_kl_logps(self, model, batch):+ """Compute KL log probabilities for a given batch."""+ KL_logps = None+ if self.calculate_KL:+ _non_model_keys = {+ "completion_input_ids",+ "completion_attention_mask",+ "completion_mask",+ "KL_completion_mask",+ "KL_completion_token_type_ids",+ "KL_completion_mm_token_type_ids",+ "label",+ "ref_logps",+ "ref_KL_logps",+ }+ KL_model_kwargs = {k: v for k, v in batch.items() if k not in _non_model_keys}+ KL_model_kwargs["input_ids"] = KL_model_kwargs.pop("KL_completion_input_ids")+ KL_model_kwargs["attention_mask"] = KL_model_kwargs.pop("KL_completion_attention_mask")+ # KL sequences have different widths from the main completion after flush_left; override token-type+ # tensors with the KL-specific ones the collator built for exactly this purpose.+ if "KL_completion_token_type_ids" in batch:+ KL_model_kwargs["token_type_ids"] = batch["KL_completion_token_type_ids"]+ if "KL_completion_mm_token_type_ids" in batch:+ KL_model_kwargs["mm_token_type_ids"] = batch["KL_completion_mm_token_type_ids"]++ with torch.no_grad():+ KL_logits = model(**KL_model_kwargs).logits++ shift_KL_logits = KL_logits[:, :-1, :].contiguous()+ KL_per_token_logps = selective_log_softmax(+ shift_KL_logits, batch["KL_completion_input_ids"][:, 1:].contiguous()+ )+ KL_per_token_logps[batch["KL_completion_mask"][:, 1:] == 0] = 0.0+ KL_logps = KL_per_token_logps.sum(-1)+ return KL_logps'''+++def test_kto16_kl_fallback_keeps_truncation_clamp():+ """TRL 1.6's _compute_kl_logps: kto_trainer_align_completion_logps clamps the KL logits to the ids it is given;+ the rewritten method's TRL branch must keep that clamp (the rewrite moves those lines into its else branch)."""+ source = textwrap.indent(textwrap.dedent(_TRL16_KTO_KL).strip("\n") + "\n", " ")+ pre_pr = rl.kto_trainer_align_completion_logps("_compute_kl_logps", source)+ assert pre_pr != source and "_uns_kl_n = min(" in pre_pr+ new = _kto_chain("_compute_kl_logps", source)+ assert "_unsloth_fused_pass_logps" in new+ assert new.count("_uns_kl_n = min(") == 1+ compile(textwrap.dedent(new), "<kl>", "exec")+++def _hooked_init(self, seed):+ _TinyLM.__init__(self, seed)+ self.lm_head.register_forward_hook(lambda module, args, output: None)diff --git a/tests/python/test_fused_linear_trl_routes.py b/tests/python/test_fused_linear_trl_routes.pynew file mode 100644index 00000000000..4c0bd33bde9--- /dev/null+++ b/tests/python/test_fused_linear_trl_routes.py@@ -0,0 +1,485 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL >= 1.15's fused lm_head served by unsloth_zoo's fused linear kernel, and KTO's no-grad KL pass scored from+hidden states."""++from __future__ import annotations++import inspect+import os+import sys+import textwrap+import types++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl as unsloth_rl+import unsloth.models.rl_replacements as rl++fused_linear = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")++N, H, V = 11, 8, 29+++class _Kernel:+ """Stands in for TRL's ChunkedLogProbFunction and records every call it serves."""++ _calls = 0+ _last = ()++ @classmethod+ def apply(cls, *args):+ cls._calls += 1+ cls._last = args+ return ("trl",) * 5+++def _reference(hidden, weight, bias, targets, temperature, softcap, logit_scale):+ """TRL's outputs in float64: scale, softcap, then temperature; mean_logits after the temperature."""+ z = hidden.double() @ weight.double().t() + bias.double()+ z = z * logit_scale+ if softcap is not None:+ z = softcap * torch.tanh(z / softcap)+ z = z / temperature+ log_p = z.log_softmax(-1)+ logps = log_p.gather(-1, targets[:, None]).squeeze(-1)+ entropy = -(log_p.exp() * log_p).sum(-1)+ lssp = (2 * log_p).logsumexp(-1)+ mean = z.mean(-1)+ top1 = z.argmax(-1) == targets+ return logps, entropy, lssp, mean, top1+++def _inputs(seed = 0):+ gen = torch.Generator().manual_seed(seed)+ hidden = torch.randn(N, H, generator = gen, requires_grad = True)+ weight = torch.randn(V, H, generator = gen)+ bias = torch.randn(V, generator = gen)+ targets = torch.randint(0, V, (N,), generator = gen)+ return hidden, weight, bias, targets+++def test_adapter_matches_trl_semantics():+ hidden, weight, bias, targets = _inputs()+ adapter = unsloth_rl._UnslothFusedLinearHead(_Kernel)+ before = _Kernel._calls+ calls = fused_linear.CALLS["logprobs"]+ got = adapter.apply(+ hidden,+ weight,+ bias,+ targets,+ 0.7,+ 4096,+ 5.0,+ 1.5,+ ("log_probs", "entropy", "log_sum_sq_probs", "mean_logits", "is_top1"),+ )+ assert _Kernel._calls == before and fused_linear.CALLS["logprobs"] == calls + 1+ want = _reference(hidden.detach(), weight, bias, targets, 0.7, 5.0, 1.5)+ for g, w in zip(got[:4], want[:4]):+ torch.testing.assert_close(g.detach().double(), w, atol = 1e-5, rtol = 1e-5)+ assert torch.equal(got[4], want[4])+ (got[0].sum() + got[1].sum()).backward()+ assert hidden.grad is not None and hidden.grad.isfinite().all()+++def _lazy_zoo():+ return int(str(getattr(fused_linear, "_LP_OP", "")).rsplit("_v", 1)[-1]) >= 4+++def test_adapter_logged_entropy_keeps_the_forward_gradient():+ """TRL 1.15 DPO asks for the entropy and detaches it (a metric): a frozen head must then take the forward+ gradient, with no recompute backward, as TRL's kernel skips its entropy work when no gradient arrives."""+ if not _lazy_zoo():+ pytest.skip("unsloth_zoo without the lazy entropy gradient")+ hidden, weight, bias, targets = _inputs(4)+ bwd = fused_linear.CALLS["logprobs_bwd"]+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden,+ weight,+ bias,+ targets,+ 0.7,+ 4096,+ None,+ 1.0,+ ("log_probs", "entropy", "mean_logits", "is_top1"),+ )+ (logged := got[1].detach()) # noqa: B018+ got[0].sum().backward()+ assert (+ fused_linear.CALLS["logprobs_bwd"] == bwd+ and hidden.grad.isfinite().all()+ and logged.isfinite().all()+ )+++def test_adapter_entropy_gradient_when_used():+ """TRL's GRPO entropy bonus backpropagates the entropy: it still gets its gradient."""+ hidden, weight, bias, targets = _inputs(5)+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, bias, targets, 0.7, 4096, None, 1.0, ("log_probs", "entropy")+ )+ (got[0].sum() + 0.3 * got[1].sum()).backward()+ hd = hidden.detach().double().requires_grad_(True)+ z = (hd @ weight.double().t() + bias.double()) / 0.7+ logp = torch.log_softmax(z, -1)+ ent = -(logp.exp() * logp).sum(-1)+ (logp.gather(-1, targets[:, None]).sum() + 0.3 * ent.sum()).backward()+ torch.testing.assert_close(hidden.grad.double(), hd.grad, atol = 1e-4, rtol = 1e-4)+++def test_adapter_returns_none_for_unrequested_outputs():+ hidden, weight, bias, targets = _inputs(1)+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, None, targets, 1.0, 4096, None, 1.0, ()+ )+ assert len(got) == 5 and got[0] is not None and all(x is None for x in got[1:])++[email protected]("case", ["zero_scale", "fp32_hidden_half_head", "unknown_output"])+def test_adapter_hands_unreproduced_calls_to_trl(case):+ hidden, weight, bias, targets = _inputs(2)+ scale, outputs = 1.0, ("log_probs",)+ if case == "zero_scale":+ scale = 0.0+ elif case == "fp32_hidden_half_head":+ weight = weight.bfloat16()+ else:+ outputs = ("log_probs", "something_new")+ before = _Kernel._calls+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, bias, targets, 1.0, 4096, None, scale, outputs+ )+ assert _Kernel._calls == before + 1 and got[0] == "trl"+++def test_adapter_hands_support_ids_calls_to_trl():+ """TRL > 1.16 passes a 10th argument, ``support_ids`` (score over a per-row kept set): the zoo kernel scores the+ full vocabulary, so those calls go to TRL's kernel with every argument; calls without it stay on the zoo kernel."""+ hidden, weight, bias, targets = _inputs(3)+ support = torch.zeros(hidden.shape[0], 4, dtype = torch.long)+ before = _Kernel._calls+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, bias, targets, 1.0, 4096, None, 1.0, ("log_probs",), support+ )+ assert _Kernel._calls == before + 1 and got[0] == "trl" and _Kernel._last[-1] is support+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, bias, targets, 1.0, 4096, None, 1.0, ("log_probs",), None+ )+ assert _Kernel._calls == before + 1 and got[0] is not None and got[0] != "trl"+++def test_patch_is_idempotent(monkeypatch):+ utils = types.ModuleType("trl.trainer.utils")+ utils._ChunkedLogProbFunction = _Kernel+ monkeypatch.setitem(sys.modules, "trl.trainer.utils", utils)+ trainer = sys.modules.get("trl.trainer")+ if trainer is not None:+ monkeypatch.setattr(trainer, "utils", utils, raising = False)+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ first = utils._ChunkedLogProbFunction+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ assert (+ isinstance(first, unsloth_rl._UnslothFusedLinearHead)+ and utils._ChunkedLogProbFunction is first+ )+ assert first.function is _Kernel++[email protected]("kernel", ["modern", "no_bias"])+def test_device_and_fused_head_wrappers_see_each_other(kernel, monkeypatch):+ """A split model's device wrapper and the fused head adapter, in either order and patched again: no nesting, and+ a TRL 1.1 - 1.13 kernel (no ``bias``) never gets the adapter."""+ base = _Kernel if kernel == "modern" else _NoBiasKernel+ utils = types.ModuleType("trl.trainer.utils")+ utils._ChunkedLogProbFunction = unsloth_rl._ApplyOnInputDevice(base)+ monkeypatch.setitem(sys.modules, "trl.trainer.utils", utils)+ trainer = sys.modules.get("trl.trainer")+ if trainer is not None:+ monkeypatch.setattr(trainer, "utils", utils, raising = False)+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ first = utils._ChunkedLogProbFunction+ if kernel == "no_bias":+ assert isinstance(first, unsloth_rl._ApplyOnInputDevice)+ else:+ assert isinstance(first, unsloth_rl._UnslothFusedLinearHead)+ assert getattr(first, "_unsloth_device_patched", False)+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ assert utils._ChunkedLogProbFunction is first+ wrapped = unsloth_rl._ApplyOnInputDevice(unsloth_rl._UnslothFusedLinearHead(base))+ assert getattr(wrapped, "_unsloth_fused_linear", False)+++def test_stock_logps_hook_finds_fused_pass_rewrites():+ """A rewritten method that only calls the fused-pass helpers (KTO _compute_kl_logps, DPO ref precompute) is still+ the owner, so a subclass overriding get_batch_logps below it is detected."""+ from unsloth.models import rl_replacements as rr++ class Rewritten:+ def _compute_kl_logps(self, model, batch):+ return _unsloth_fused_pass_logps(self, model, batch) # noqa: F821 (only its name is read)++ class Sub(Rewritten):+ def get_batch_logps(self, *args):+ return None++ assert rr._unsloth_stock_logps_hook(Rewritten(), "_compute_kl_logps", ("get_batch_logps",))+ assert not rr._unsloth_stock_logps_hook(Sub(), "_compute_kl_logps", ("get_batch_logps",))+++def test_adapter_honours_the_kill_switch_after_install(monkeypatch):+ """UNSLOTH_FUSED_LINEAR=0 set after the adapter was installed (a notebook re-run) still serves TRL's kernel."""+ hidden, weight, bias, targets = _inputs(4)+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ before = _Kernel._calls+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, bias, targets, 1.0, 4096, None, 1.0, ("log_probs",)+ )+ assert _Kernel._calls == before + 1 and got[0] == "trl"+++def test_patch_respects_the_kill_switch(monkeypatch):+ utils = types.ModuleType("trl.trainer.utils")+ utils._ChunkedLogProbFunction = _Kernel+ monkeypatch.setitem(sys.modules, "trl.trainer.utils", utils)+ trainer = sys.modules.get("trl.trainer")+ if trainer is not None:+ monkeypatch.setattr(trainer, "utils", utils, raising = False)+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ assert utils._ChunkedLogProbFunction is _Kernel+++class _NoBiasKernel(_Kernel):+ """TRL 1.1 - 1.13's ``_ChunkedLogProbFunction``: no ``bias`` (and no ``outputs``) argument."""++ @staticmethod+ def forward(+ ctx,+ last_hidden,+ weight,+ targets,+ temperature,+ chunk_size,+ final_logit_softcapping = None,+ logit_scale = 1.0,+ ):+ raise AssertionError("not reached")+++def test_patch_leaves_kernels_without_bias(monkeypatch):+ """The adapter's positional layout has ``bias`` third: wrapping an older kernel would shift every argument."""+ utils = types.ModuleType("trl.trainer.utils")+ utils._ChunkedLogProbFunction = _NoBiasKernel+ monkeypatch.setitem(sys.modules, "trl.trainer.utils", utils)+ trainer = sys.modules.get("trl.trainer")+ if trainer is not None:+ monkeypatch.setattr(trainer, "utils", utils, raising = False)+ unsloth_rl.patch_trl_fused_lm_head_kernel()+ assert utils._ChunkedLogProbFunction is _NoBiasKernel+++class _HeadLM(torch.nn.Module):+ def __init__(self):+ super().__init__()+ from transformers import LlamaConfig++ self.config = LlamaConfig(+ vocab_size = V, hidden_size = H, num_hidden_layers = 1, num_attention_heads = 2+ )+ self.lm_head = torch.nn.Linear(H, V, bias = False)++ def get_output_embeddings(self):+ return self.lm_head+++def _selector_trainer():+ return types.SimpleNamespace(accelerator = types.SimpleNamespace(unwrap_model = lambda m: m))+++def _selected(selector, trainer, model):+ if selector == "orpo_cpo":+ return rl._unsloth_pref_chunked_head(trainer, model) is not None+ return rl._unsloth_dpo_chunked_head(trainer, model, {}) is not None++[email protected]("selector", ["orpo_cpo", "dpo_kto"])+def test_preference_selectors_respect_the_kill_switch(selector, monkeypatch):+ model, trainer = _HeadLM(), _selector_trainer()+ assert _selected(selector, trainer, model)+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ assert not _selected(selector, trainer, model)++[email protected]("selector", ["orpo_cpo", "dpo_kto"])+ "hook",+ ["forward_hook", "forward_pre_hook", "patched_forward", "backward_hook", "backward_pre_hook"],+)+def test_preference_selectors_reject_hooked_heads(selector, hook):+ """The chunked / fused kernels read the head's weight directly, skipping whatever its forward would add."""+ model, trainer = _HeadLM(), _selector_trainer()+ assert _selected(selector, trainer, model)+ head = model.lm_head+ if hook == "forward_hook":+ head.register_forward_hook(lambda module, args, output: output * 0.5)+ elif hook == "forward_pre_hook":+ head.register_forward_pre_hook(lambda module, args: (args[0] * 2,))+ elif hook == "backward_hook":+ # Reading the weight directly would skip it: the head's gradients would silently change.+ head.register_full_backward_hook(+ lambda module, grad_in, grad_out: tuple(None if g is None else g * 0.5 for g in grad_in)+ )+ elif hook == "backward_pre_hook":+ head.register_full_backward_pre_hook(+ lambda module, grad_out: tuple(g * 0.5 for g in grad_out)+ )+ else:+ head.forward = lambda x: torch.nn.functional.linear(x, head.weight) * 0.5+ assert not _selected(selector, trainer, model)+++def _kto_kl_source():+ """TRL's own _compute_kl_logps, read from its file: importing unsloth rebinds KTOTrainer to the generated class."""+ import ast+ import importlib.util++ pytest.importorskip("trl")+ for name in ("trl.trainer.kto_trainer", "trl.experimental.kto.kto_trainer"):+ try:+ spec = importlib.util.find_spec(name)+ except Exception:+ spec = None+ if spec is None or spec.origin is None:+ continue+ text = open(spec.origin, encoding = "utf-8").read()+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.FunctionDef) and node.name == "_compute_kl_logps":+ return textwrap.dedent(ast.get_source_segment(text, node, padded = True))+ pytest.skip(reason = "this TRL computes KTO's KL term elsewhere")+++def test_kto_kl_pass_is_rewritten_once():+ source = _kto_kl_source()+ from packaging.version import Version+ import trl++ if Version(trl.__version__) >= Version("1.6"):+ pytest.skip(reason = "the KL rewrite targets TRL < 1.6, whose KL pass calls get_batch_logps")+ new = rl.kto_trainer_chunked_kl_logps("_compute_kl_logps", source)+ assert new != source and "_unsloth_kto_hidden_logps" in new+ compile(new, "<kto_kl>", "exec")+ assert rl.kto_trainer_chunked_kl_logps("_compute_kl_logps", new) == new+ assert rl.kto_trainer_chunked_kl_logps("forward", source) == source+ assert rl.kto_trainer_chunked_kl_logps in rl.RL_FUNCTIONS["kto_trainer"]+++def test_kto_scores_completion_tokens_only():+ """The KTO helper sends only completion positions to the head and keeps the per-position vocab sums exact."""+ gen = torch.Generator().manual_seed(5)+ hidden = torch.randn(2, 9, H, generator = gen)+ head = torch.nn.Linear(H, V, bias = False)+ labels = torch.randint(0, V, (2, 9), generator = gen)+ labels[:, :4] = -100+ before = fused_linear.CALLS["logprobs"]+ logps, sums = rl._unsloth_kto_hidden_logps(+ types.SimpleNamespace(), (None, head, (0.0, 0.0, 0.0)), hidden, labels, -100+ )+ assert fused_linear.CALLS["logprobs"] == before + 1+ z = hidden.double() @ head.weight.double().t()+ log_p = z[:, :-1].log_softmax(-1)+ shifted = labels[:, 1:]+ mask = shifted != -100+ want = (log_p.gather(-1, shifted.clamp(min = 0)[..., None]).squeeze(-1) * mask).sum(-1)+ torch.testing.assert_close(logps.detach().double(), want, atol = 1e-5, rtol = 1e-5)+ torch.testing.assert_close(sums.squeeze(-1).double(), z.sum(-1), atol = 1e-3, rtol = 1e-5)+++def _buffer_bytes(monkeypatch):+ """Records the bytes of every logits buffer the zoo kernel allocates."""+ sizes = []+ init = fused_linear._Buffers.__init__++ def spy(self, *args, **kwargs):+ init(self, *args, **kwargs)+ sizes.append(self.buf.numel() * self.buf.element_size())++ monkeypatch.setattr(fused_linear._Buffers, "__init__", spy)+ return sizes+++def _bounded_inputs(trainable_head, seed = 3):+ gen = torch.Generator().manual_seed(seed)+ hidden = torch.randn(64, 8, generator = gen, requires_grad = True)+ weight = torch.randn(1000, 8, generator = gen, requires_grad = trainable_head)+ targets = torch.randint(0, 1000, (64,), generator = gen)+ return hidden, weight, targets++[email protected]("grad", [False, True])[email protected]("trainable_head", [False, True])+def test_adapter_bounds_its_logits_buffer_by_chunk_size(trainable_head, grad, monkeypatch):+ # TRL's tile is [min(N, TOKEN_CHUNK_SIZE), chunk_size] in the compute dtype: chunk_size counts vocab columns.+ # Recompute tiles shrunk to 8 KiB (TRL's 32768-column tile covers the zoo's 256 MiB ones at N >= 4096), so only+ # the [rows, V] chunked forward needs the row cap.+ monkeypatch.setattr(fused_linear, "_BWD_TILE_BYTES", 8 * 1024)+ hidden, weight, targets = _bounded_inputs(trainable_head)+ n, v, chunk_size = hidden.shape[0], weight.shape[0], 100+ trl_bytes = n * chunk_size * hidden.element_size()+ sizes = _buffer_bytes(monkeypatch)+ kwargs = []+ zoo = fused_linear.fused_linear_logprobs+ monkeypatch.setattr(+ fused_linear,+ "fused_linear_logprobs",+ lambda *a, **k: kwargs.append(k) or zoo(*a, **k),+ )+ adapter = unsloth_rl._UnslothFusedLinearHead(_Kernel)+ before = _Kernel._calls+ with torch.set_grad_enabled(grad):+ got = adapter.apply(hidden, weight, None, targets, 1.0, chunk_size, None, 1.0, ("entropy",))+ if grad:+ (got[0].sum() + got[1].sum()).backward()+ assert _Kernel._calls == before+ assert sizes and max(sizes) <= trl_bytes, (sizes, trl_bytes)+ assert kwargs[-1]["max_rows_per_chunk"] == trl_bytes // (v * 4)+ want = _reference(hidden.detach(), weight.detach(), torch.zeros(v), targets, 1.0, None, 1.0)+ torch.testing.assert_close(got[0].detach().double(), want[0], atol = 1e-5, rtol = 1e-5)+ torch.testing.assert_close(got[1].detach().double(), want[1], atol = 1e-5, rtol = 1e-5)++ # TRL's default (32768 columns) is a bigger tile than the zoo kernel's own buffer here: no cap.+ sizes.clear()+ with torch.set_grad_enabled(grad):+ adapter.apply(hidden, weight, None, targets, 1.0, 32768, None, 1.0, ("entropy",))+ assert kwargs[-1]["max_rows_per_chunk"] is None and max(sizes) == n * v * 4++[email protected]("grad", [False, True])[email protected]("chunk_size", [1, 100])+def test_adapter_hands_tiles_below_its_own_to_trl(chunk_size, grad):+ # Recompute tiles cannot shrink below min(N x V, 256 MiB) without starving the GEMM: TRL serves the shape, for+ # the no-grad pass too.+ hidden, weight, targets = _bounded_inputs(False, seed = 4)+ before = _Kernel._calls+ with torch.set_grad_enabled(grad):+ got = unsloth_rl._UnslothFusedLinearHead(_Kernel).apply(+ hidden, weight, None, targets, 1.0, chunk_size, None, 1.0, ("log_probs",)+ )+ assert _Kernel._calls == before + 1 and got[0] == "trl"+++def test_adapter_keeps_its_own_budget_at_trls_default_chunk_size():+ # At TRL's default the zoo kernel's whole-call peak is already below TRL's (frozen / trainable heads), so only an+ # explicitly smaller chunk_size bounds it: 8k tokens x 152k vocab would otherwise cap the no-grad pass at 441 rows.+ adapter = unsloth_rl._UnslothFusedLinearHead(_Kernel)+ hidden = torch.zeros(8192, 8, dtype = torch.bfloat16)+ weight = torch.zeros(151936, 8, dtype = torch.bfloat16)+ with torch.no_grad():+ assert adapter._row_cap(hidden, weight, None, adapter._default_chunk, ("log_probs",)) == 0+ assert (+ adapter._row_cap(hidden, weight, None, adapter._default_chunk // 2, ("log_probs",)) != 0+ )diff --git a/tests/python/test_preference_chunked_compile.py b/tests/python/test_preference_chunked_compile.pynew file mode 100644index 00000000000..ede8afb40c8--- /dev/null+++ b/tests/python/test_preference_chunked_compile.py@@ -0,0 +1,226 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""ORPO / CPO hidden-state scoring traces as one graph (no data-dependent branch, no boolean slice assignment) and+matches TRL's math in fp64, eager and compiled. CPU only: the helper is lifted from source via ast and the zoo+kernels are replaced by dense references, so no package import, model or GPU is needed."""++from __future__ import annotations++import ast+import os+import types+from pathlib import Path++import pytest++torch = pytest.importorskip("torch")+F = torch.nn.functional++SOURCE = Path(__file__).resolve().parents[2] / "unsloth" / "models" / "rl_replacements.py"+VOCAB, HIDDEN, SEQ, PAIRS = 23, 8, 7, 2+++def _transform(logits, multiply, divide, softcap):+ if multiply:+ logits = logits * multiply+ if divide:+ logits = logits / divide+ if softcap:+ logits = softcap * torch.tanh(logits / softcap)+ return logits+++def _logits(+ hidden,+ weight,+ bias,+ multiply = 0.0,+ divide = 0.0,+ softcap = 0.0,+):+ return _transform(F.linear(hidden, weight, bias), multiply, divide, softcap)+++def _chunked(+ hidden,+ weight,+ index,+ return_mean_logits = False,+ lm_head_bias = None,+ logit_scale_multiply = 0.0,+ logit_scale_divide = 0.0,+ logit_softcapping = 0.0,+ **_,+):+ logits = _logits(+ hidden, weight, lm_head_bias, logit_scale_multiply, logit_scale_divide, logit_softcapping+ )+ logps = logits.log_softmax(-1).gather(-1, index.unsqueeze(-1)).squeeze(-1)+ return (logps, logits.mean(-1)) if return_mean_logits else logps+++def _masked(+ hidden,+ weight,+ labels,+ mask = None,+ **kwargs,+):+ return torch.where(mask, _chunked(hidden, weight, labels, **kwargs), 0.0)+++def _mean_logits(hidden, weight, bias, multiply, divide, softcap):+ return _logits(hidden, weight, bias, multiply, divide, softcap).mean(-1)+++TRANSFORMS = (0.7, 0.0, 3.0)+++def _load(masked_kernel):+ tree = ast.parse(SOURCE.read_text(encoding = "utf-8"))+ node = next(+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_pref_chunked_forward"+ )+ ns = {+ "torch": torch,+ "os": os,+ "unsloth_chunked_logprobs": _chunked,+ "_unsloth_pref_masked_logprobs": _masked if masked_kernel else None,+ "_unsloth_linear_mean_logits": _mean_logits if masked_kernel else None,+ "_unsloth_pref_logit_transforms": lambda model: TRANSFORMS,+ "_unsloth_pref_returns_hidden_states": lambda model, tensor, weight: True,+ }+ exec(compile(ast.Module(body = [node], type_ignores = []), str(SOURCE), "exec"), ns)+ return ns["_unsloth_pref_chunked_forward"]+++class _Trainer:+ def __init__(+ self,+ cpo_alpha = 1.0,+ loss_type = "sigmoid",+ ):+ self.cpo_alpha = cpo_alpha+ self.loss_type = loss_type+ self.accelerator = types.SimpleNamespace(+ unwrap_model = lambda m: m, device = torch.device("cpu")+ )+++def _batch(split):+ g = torch.Generator().manual_seed(0)+ rows = 2 * PAIRS+ input_ids = torch.randint(1, VOCAB, (rows, SEQ), generator = g)+ attention_mask = torch.ones(rows, SEQ, dtype = torch.long)+ attention_mask[0, -2:] = 0 # right padding on a chosen row+ attention_mask[PAIRS + 1, -1:] = 0 # and on a rejected row+ labels = torch.where(attention_mask == 1, input_ids, -100)+ labels[:, :3] = -100 # prompt+ if split:+ # A completion token scored against a label other than its input id: ORPO needs a second NLL pass.+ labels[0, 4] = (input_ids[0, 4] + 1) % VOCAB+ states = torch.randn(rows, SEQ, HIDDEN, generator = g, dtype = torch.float64, requires_grad = True)+ head = torch.nn.Linear(HIDDEN, VOCAB, bias = True).double()+ with torch.no_grad():+ head.weight.copy_(torch.randn(VOCAB, HIDDEN, generator = g, dtype = torch.float64))+ head.bias.copy_(torch.randn(VOCAB, generator = g, dtype = torch.float64))+ batch = {+ "concatenated_input_ids": input_ids,+ "concatenated_labels": labels,+ "concatenated_attention_mask": attention_mask,+ }+ return head, batch, states+++def _oracle(kind, trainer, head, batch, states):+ """TRL's ORPO / CPO concatenated_forward math on dense logits."""+ logits = _logits(states, head.weight, head.bias, *TRANSFORMS)+ labels = batch["concatenated_labels"]+ shifted, scored = labels[:, 1:], logits[:, :-1]+ mask = shifted != -100+ per_token = scored.log_softmax(-1).gather(-1, shifted.clamp(min = 0).unsqueeze(-1)).squeeze(-1)+ logps = (per_token * mask).sum(-1)+ if kind == "orpo" or trainer.loss_type in ("ipo", "simpo"):+ logps = logps / mask.sum(-1)+ if kind == "orpo":+ nll_labels = torch.where(+ batch["concatenated_attention_mask"] == 1, batch["concatenated_input_ids"], -100+ )+ nll = F.cross_entropy(scored[:PAIRS].flatten(0, 1), nll_labels[:PAIRS, 1:].flatten())+ means = scored.mean(-1)+ else:+ nll = F.cross_entropy(scored[:PAIRS].flatten(0, 1), shifted[:PAIRS].flatten())+ if trainer.cpo_alpha == 0:+ nll = torch.tensor(0.0) # TRL: torch.tensor(0.0).to(self.accelerator.device)+ means = logits.mean(-1)+ return logps[:PAIRS], logps[PAIRS:], means[:PAIRS], means[PAIRS:], nll+++def _scalar(outputs):+ weights = (1.0, -0.5, 0.25, 0.125, 2.0)+ return sum(w * o.sum() for w, o in zip(weights, outputs))+++def _grads(fn, head, states):+ head.zero_grad(set_to_none = True)+ states.grad = None+ outputs = fn()+ _scalar(outputs).backward()+ return [o.detach() for o in outputs], [+ states.grad.clone(),+ head.weight.grad.clone(),+ head.bias.grad.clone(),+ ]+++CASES = [+ ("orpo", {}, False),+ ("orpo", {}, True),+ ("cpo", {"cpo_alpha": 1.0, "loss_type": "sigmoid"}, False),+ ("cpo", {"cpo_alpha": 1.0, "loss_type": "simpo"}, True),+ ("cpo", {"cpo_alpha": 0.0, "loss_type": "sigmoid"}, False),+]++[email protected]("masked_kernel", [True, False], ids = ["masked", "dense"])[email protected]("kind,kwargs,split", CASES)+def test_traces_without_graph_breaks_and_matches_trl(kind, kwargs, split, masked_kernel):+ forward = _load(masked_kernel)+ trainer = _Trainer(**kwargs)+ head, batch, states = _batch(split)++ def body(states, input_ids, labels, attention_mask):+ concatenated = {+ "concatenated_input_ids": input_ids,+ "concatenated_labels": labels,+ "concatenated_attention_mask": attention_mask,+ }+ outputs, _ = forward(trainer, head, head, concatenated, PAIRS, states, kind)+ return outputs++ args = (+ states,+ batch["concatenated_input_ids"],+ batch["concatenated_labels"],+ batch["concatenated_attention_mask"],+ )++ torch._dynamo.reset()+ explained = torch._dynamo.explain(body)(*args)+ assert explained.graph_break_count == 0, explained.break_reasons+ assert explained.graph_count == 1++ want, want_grads = _grads(lambda: _oracle(kind, trainer, head, batch, states), head, states)+ got, got_grads = _grads(lambda: body(*args), head, states)+ for a, b in zip(got + got_grads, want + want_grads):+ torch.testing.assert_close(a, b, rtol = 1e-10, atol = 1e-12)++ for dynamic in (False, True):+ torch._dynamo.reset()+ compiled = torch.compile(body, fullgraph = True, backend = "aot_eager", dynamic = dynamic)+ out, grads = _grads(lambda: compiled(*args), head, states)+ for a, b in zip(out + grads, got + got_grads):+ torch.testing.assert_close(a, b, rtol = 1e-10, atol = 1e-12)+ torch._dynamo.reset()diff --git a/tests/python/test_preference_chunked_logprobs.py b/tests/python/test_preference_chunked_logprobs.pynew file mode 100644index 00000000000..2da23c061fc--- /dev/null+++ b/tests/python/test_preference_chunked_logprobs.py@@ -0,0 +1,392 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""ORPO / CPO concatenated_forward scores from hidden states through the chunked log-prob head and matches TRL."""++from __future__ import annotations++import ast+import functools+import importlib.util+import os+import textwrap+import types++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl_replacements as rl++trl = pytest.importorskip("trl")++if rl.unsloth_chunked_logprobs is None:+ # Skip because the kernel ships in unsloth_zoo (unslothai/unsloth-zoo#1803).+ pytest.skip(+ reason = "installed unsloth_zoo predates unsloth_chunked_logprobs", allow_module_level = True+ )+++def _trl_class(kind):+ """TRL's own class and the source of its concatenated_forward, read from the file (importing unsloth may+ already have rebound the class to the patched one)."""+ for name in (f"trl.experimental.{kind}.{kind}_trainer", f"trl.trainer.{kind}_trainer"):+ try:+ spec = importlib.util.find_spec(name)+ except Exception:+ spec = None+ if spec is None or spec.origin is None:+ continue+ text = open(spec.origin, encoding = "utf-8").read()+ node = next(+ (+ n+ for n in ast.walk(ast.parse(text))+ if isinstance(n, ast.FunctionDef) and n.name == "concatenated_forward"+ ),+ None,+ )+ if node is None:+ continue+ module = importlib.import_module(name)+ cls = getattr(module, "ORPOTrainer" if kind == "orpo" else "CPOTrainer")+ return cls, ast.get_source_segment(text, node, padded = True)+ # Skip because this TRL ships no such trainer (CPO / ORPO left trl.trainer in 0.29).+ pytest.skip(reason = f"no {kind} trainer in the installed TRL")+++def _compile(source, rows_per_chunk = None):+ ns = dict(vars(rl))+ ns["nn"] = torch.nn+ if rows_per_chunk is not None:+ ns["unsloth_chunked_logprobs"] = functools.partial(+ rl.unsloth_chunked_logprobs, rows_per_chunk = rows_per_chunk+ )+ exec(textwrap.dedent(source), ns)+ return ns["concatenated_forward"]+++class _HiddenStatesLM(torch.nn.Module):+ """Wraps a causal LM the way Unsloth's forwards behave: with UNSLOTH_RETURN_HIDDEN_STATES=1 the final-norm hidden+ states come back as ``.logits``."""++ __UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ = True++ def __init__(+ self,+ lm,+ honour = True,+ ):+ super().__init__()+ self.lm = lm+ self.honour = honour+ self.config = lm.config++ def get_output_embeddings(self):+ return self.lm.get_output_embeddings()++ def forward(+ self,+ input_ids,+ attention_mask = None,+ use_cache = False,+ ):+ if self.honour and os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":+ return types.SimpleNamespace(logits = self.lm.hidden(input_ids, attention_mask))+ return types.SimpleNamespace(logits = self.lm.logits(input_ids, attention_mask))+++class _QwenLM(torch.nn.Module):+ def __init__(self, model):+ super().__init__()+ self.model = model+ self.config = model.config++ def get_output_embeddings(self):+ return self.model.get_output_embeddings()++ def hidden(self, input_ids, attention_mask):+ body = self.model.get_base_model().model+ return body(input_ids = input_ids, attention_mask = attention_mask).last_hidden_state++ def logits(self, input_ids, attention_mask):+ return self.model(+ input_ids = input_ids, attention_mask = attention_mask, use_cache = False+ ).logits+++class _ToyLM(torch.nn.Module):+ """Head with a bias, a logit scale and a soft cap, applied in the model's own order (scale, then cap)."""++ def __init__(+ self,+ vocab = 61,+ hidden = 12,+ ):+ super().__init__()+ g = torch.Generator().manual_seed(1)+ self.embed = torch.nn.Parameter(torch.randn(vocab, hidden, generator = g))+ self.mix = torch.nn.Parameter(torch.randn(hidden, hidden, generator = g) / hidden**0.5)+ self.lm_head = torch.nn.Linear(hidden, vocab, bias = True)+ with torch.no_grad():+ self.lm_head.weight.copy_(torch.randn(vocab, hidden, generator = g))+ self.lm_head.bias.copy_(torch.randn(vocab, generator = g))+ self.config = types.SimpleNamespace(+ model_type = "cohere", logit_scale = 0.7, final_logit_softcapping = 3.0+ )++ def get_output_embeddings(self):+ return self.lm_head++ def hidden(self, input_ids, attention_mask):+ return torch.tanh(self.embed[input_ids] @ self.mix)++ def logits(self, input_ids, attention_mask):+ z = self.lm_head(self.hidden(input_ids, attention_mask)) * self.config.logit_scale+ cap = self.config.final_logit_softcapping+ return cap * torch.tanh(z / cap)+++def _qwen_lora():+ transformers = pytest.importorskip("transformers")+ peft = pytest.importorskip("peft")+ try:+ model = transformers.AutoModelForCausalLM.from_pretrained(+ "trl-internal-testing/tiny-Qwen3ForCausalLM", torch_dtype = torch.float32+ )+ except Exception as error:+ # Skip because the offline checkpoint is missing, not a code failure.+ pytest.skip(reason = f"tiny Qwen3 checkpoint unavailable: {error}")+ torch.manual_seed(0)+ model = peft.get_peft_model(+ model, peft.LoraConfig(r = 4, lora_alpha = 8, target_modules = ["q_proj", "v_proj", "down_proj"])+ )+ # Non-zero B so LoRA A also gets a gradient.+ with torch.no_grad():+ for name, p in model.named_parameters():+ if "lora_B" in name:+ p.normal_(0, 0.05)+ return _QwenLM(model)+++def _batch(vocab, seed = 0):+ """ORPO/CPO collator layout: right-padded rows, prompt labels -100, chosen and rejected of different widths."""+ g = torch.Generator().manual_seed(seed)+ B, prompt = 3, 4+ out = {}+ for side, lengths, width in (("chosen", (9, 7, 11), 11), ("rejected", (12, 6, 10), 12)):+ ids = torch.zeros(B, width, dtype = torch.long)+ mask = torch.zeros(B, width, dtype = torch.long)+ labels = torch.full((B, width), -100, dtype = torch.long)+ for i, n in enumerate(lengths):+ ids[i, :n] = torch.randint(1, vocab, (n,), generator = g)+ mask[i, :n] = 1+ labels[i, prompt:n] = ids[i, prompt:n]+ out[f"{side}_input_ids"], out[f"{side}_attention_mask"], out[f"{side}_labels"] = (+ ids,+ mask,+ labels,+ )+ return out+++def _trainer(+ cls,+ kind,+ loss_type = "sigmoid",+ cpo_alpha = 1.0,+ alpha = 0.0,+):+ trainer = cls.__new__(cls)+ trainer.__dict__.update(+ is_encoder_decoder = False,+ label_pad_token_id = -100,+ padding_value = 0,+ pad_token_id = 0,+ aux_loss_enabled = False,+ aux_loss_coef = 0.0,+ beta = 0.2,+ loss_type = loss_type,+ cpo_alpha = cpo_alpha,+ alpha = alpha,+ simpo_gamma = 0.5,+ label_smoothing = 0.1 if loss_type == "sigmoid" else 0.0,+ accelerator = types.SimpleNamespace(+ device = torch.device("cpu"),+ unwrap_model = lambda m: m,+ gather_for_metrics = lambda x: x,+ ),+ )+ return trainer+++def _run(trainer, forward, model, batch, params):+ trainer.concatenated_forward = types.MethodType(forward, trainer)+ loss, metrics = trainer.get_batch_loss_metrics(model, batch)+ grads = torch.autograd.grad(loss, params)+ return loss.detach(), metrics, grads+++CASES = [+ ("orpo", {}),+ ("cpo", {"loss_type": "sigmoid"}),+ ("cpo", {"loss_type": "hinge"}),+ ("cpo", {"loss_type": "ipo"}),+ ("cpo", {"loss_type": "simpo"}),+ ("cpo", {"loss_type": "simpo", "cpo_alpha": 0.0, "alpha": 0.25}), # AlphaPO+ ("cpo", {"loss_type": "sigmoid", "cpo_alpha": 0.0}),+]++[email protected]("model_name", ["qwen3_lora", "toy_bias_scale_softcap"])[email protected]("kind,kwargs", CASES)+def test_matches_trl(kind, kwargs, model_name, monkeypatch):+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES", raising = False)+ cls, source = _trl_class(kind)+ patched_source = getattr(rl, f"{kind}_trainer_concatenated_forward")(+ "concatenated_forward", source+ )+ assert (+ patched_source != source+ ), "rewrite did not recognise the installed TRL concatenated_forward"+ stock, patched = _compile(source), _compile(patched_source, rows_per_chunk = 5)++ lm = _qwen_lora() if model_name == "qwen3_lora" else _ToyLM()+ model = _HiddenStatesLM(lm)+ params = [p for p in model.parameters() if p.requires_grad]+ vocab = model.get_output_embeddings().weight.shape[0]+ batch = _batch(min(vocab, 1000))++ trainer = _trainer(cls, kind, **kwargs)+ want_loss, want_metrics, want_grads = _run(trainer, stock, model, batch, params)+ assert getattr(trainer, "_unsloth_pref_chunked_calls", 0) == 0+ got_loss, got_metrics, got_grads = _run(trainer, patched, model, batch, params)+ assert trainer._unsloth_pref_chunked_calls == 1, "chunked path did not run"+ assert "UNSLOTH_RETURN_HIDDEN_STATES" not in os.environ, "flag not restored"++ torch.testing.assert_close(got_loss, want_loss, rtol = 1e-5, atol = 1e-6)+ assert got_metrics.keys() == want_metrics.keys()+ for key in want_metrics:+ torch.testing.assert_close(+ torch.tensor(float(got_metrics[key])),+ torch.tensor(float(want_metrics[key])),+ # AlphaPO margins subtract two rewards of magnitude ~5: a few fp32 ulps.+ rtol = 1e-5,+ atol = 1e-5,+ msg = lambda m: f"{key}: {m}",+ )+ for g, w in zip(got_grads, want_grads):+ torch.testing.assert_close(g, w, rtol = 1e-4, atol = 1e-6)+++def test_forward_ignoring_the_flag_runs_trl_math(monkeypatch):+ monkeypatch.setenv("UNSLOTH_RETURN_HIDDEN_STATES", "0")+ cls, source = _trl_class("orpo")+ stock = _compile(source)+ patched = _compile(rl.orpo_trainer_concatenated_forward("concatenated_forward", source))+ model = _HiddenStatesLM(_ToyLM(), honour = False)+ params = list(model.parameters())+ batch = _batch(61)+ trainer = _trainer(cls, "orpo")+ want = _run(trainer, stock, model, batch, params)+ got = _run(trainer, patched, model, batch, params)+ assert getattr(trainer, "_unsloth_pref_chunked_calls", 0) == 0+ assert os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] == "0", "prior flag value not restored"+ assert torch.equal(got[0], want[0]) and got[1] == want[1]+ for g, w in zip(got[2], want[2]):+ assert torch.equal(g, w)+++def test_labels_differing_from_input_ids_take_a_second_nll_pass(monkeypatch):+ """ORPO's NLL reads input_ids, the log-probs read labels; a row where they disagree must score both."""+ monkeypatch.delenv("UNSLOTH_RETURN_HIDDEN_STATES", raising = False)+ cls, source = _trl_class("orpo")+ stock = _compile(source)+ patched = _compile(rl.orpo_trainer_concatenated_forward("concatenated_forward", source))+ model = _HiddenStatesLM(_ToyLM())+ params = list(model.parameters())+ batch = _batch(61)+ batch["chosen_labels"][0, 6] = (batch["chosen_input_ids"][0, 6] + 1) % 61+ trainer = _trainer(cls, "orpo")+ want = _run(trainer, stock, model, batch, params)+ got = _run(trainer, patched, model, batch, params)+ assert trainer._unsloth_pref_chunked_calls == 1+ torch.testing.assert_close(got[0], want[0], rtol = 1e-5, atol = 1e-6)+ for key in want[1]:+ assert abs(got[1][key] - want[1][key]) <= 1e-5 * max(1.0, abs(want[1][key])), key+ for g, w in zip(got[2], want[2]):+ torch.testing.assert_close(g, w, rtol = 1e-4, atol = 1e-6)+++def test_declines_without_kernel_or_on_unsupported_setups(monkeypatch):+ cls, _ = _trl_class("orpo")+ model = _HiddenStatesLM(_ToyLM())+ assert rl._unsloth_pref_chunked_head(_trainer(cls, "orpo"), model) is not None+ for attr, value in (+ ("is_encoder_decoder", True),+ ("aux_loss_enabled", True),+ ("label_pad_token_id", -1),+ ("is_deepspeed_enabled", True),+ ):+ trainer = _trainer(cls, "orpo")+ setattr(trainer, attr, value)+ assert rl._unsloth_pref_chunked_head(trainer, model) is None, attr+ # A subclass reading the full chosen / rejected logits, or scoring its own log-probs, keeps TRL's path.+ for hook in ("get_batch_loss_metrics", "get_batch_logps", "concatenated_forward"):+ sub = type("Sub", (cls,), {hook: lambda self, *a, **k: None})+ assert rl._unsloth_pref_chunked_head(_trainer(sub, "orpo"), model) is None, hook+ monkeypatch.setenv("UNSLOTH_PREFERENCE_CHUNKED", "0")+ assert rl._unsloth_pref_chunked_head(_trainer(cls, "orpo"), model) is None+ monkeypatch.delenv("UNSLOTH_PREFERENCE_CHUNKED")+ monkeypatch.setattr(rl, "unsloth_chunked_logprobs", None)+ assert rl._unsloth_pref_chunked_head(_trainer(cls, "orpo"), model) is None++[email protected]("kind", ["orpo", "cpo"])+def test_rewrite_is_idempotent_and_leaves_other_layouts(kind):+ _, source = _trl_class(kind)+ rewrite = getattr(rl, f"{kind}_trainer_concatenated_forward")+ once = rewrite("concatenated_forward", source)+ assert rewrite("concatenated_forward", once) == once+ assert rewrite("get_batch_loss_metrics", source) == source+ changed = source.replace("average_log_prob=", "average_log_prob=not ", 1)+ assert rewrite("concatenated_forward", changed) == changed+++def test_generated_items_are_self_contained():+ for trainer in ("orpo_trainer", "cpo_trainer"):+ pre = "\n".join(rl.RL_PRE_ITEMS[trainer])+ for name in (+ "_unsloth_pref_chunked_head",+ "_unsloth_pref_chunked_forward",+ "_unsloth_pref_logit_transforms",+ "_unsloth_gkd_dense_head",+ "_unsloth_grpo_returns_hidden_states",+ "_unsloth_grpo_hidden_states_signal",+ "_unsloth_pref_returns_hidden_states",+ "_unsloth_get_model_config",+ "_unsloth_text_configs",+ ):+ assert f"def {name}(" in pre, (trainer, name)+ assert (+ "from unsloth_zoo.fused_losses.chunked_logprob import unsloth_chunked_logprobs" in pre+ )+++def test_square_head_needs_an_affirmative_hidden_state_signal():+ # vocab_size == hidden_size: the width cannot tell hidden states from logits. A forward with no marker ignored+ # UNSLOTH_RETURN_HIDDEN_STATES, so projecting its output again would score logits through the head twice.+ class Plain(torch.nn.Module):+ def forward(self, x):+ return x++ square, wide = torch.zeros(8, 8), torch.zeros(10, 8)+ out = torch.zeros(1, 2, 8)+ plain = Plain()+ assert rl._unsloth_pref_returns_hidden_states(plain, out, square) is False+ assert rl._unsloth_pref_returns_hidden_states(plain, out, wide) is True+ assert rl._unsloth_pref_returns_hidden_states(plain, torch.zeros(1, 2, 10), wide) is False+ marked = Plain()+ marked.__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ = True+ assert rl._unsloth_pref_returns_hidden_states(marked, out, square) is True+ # GRPO keeps its leniency for a zoo too old to write the marker.+ assert rl._unsloth_grpo_returns_hidden_states(plain, out, square) is Truediff --git a/tests/python/test_sentence_transformer_max_seq_length.py b/tests/python/test_sentence_transformer_max_seq_length.pyindex 8c6261c362d..69385e5bb17 100644--- a/tests/python/test_sentence_transformer_max_seq_length.py+++ b/tests/python/test_sentence_transformer_max_seq_length.py@@ -114,3 +114,34 @@ def test_router_uses_the_smallest_encoder_position_limit(tmp_path):model = _load(str(path), max_seq_length = 4096, for_inference = True)assert model.max_seq_length == 24assert {route[0].max_seq_length for route in model[0].sub_modules.values()} == {24}+++def test_compile_disable_keeps_fast_encoder_and_skips_compile(tmp_path, monkeypatch):+ """UNSLOTH_COMPILE_DISABLE=1 keeps the fast encoder path (SDPA, unpadding) and skips only its torch.compile."""+ path = _save_encoder_sentence_model(tmp_path, "bert")+ monkeypatch.setenv("UNSLOTH_COMPILE_DISABLE", "1")+ model = _load(path)+ assert getattr(model, "_unsloth_fast_encoder", False) is True++ from unsloth import FastSentenceTransformer++ inner = model[0].auto_model+ assert FastSentenceTransformer._apply_torch_compile(model) is model+ assert model[0].auto_model is inner+ assert "_orig_mod" not in model.__dict__++[email protected](not has_real_accelerator(), reason = "bitsandbytes 8-bit loading needs a GPU")+def test_compile_disable_keeps_8bit_encoders_on_the_loader_that_forwards_it(tmp_path, monkeypatch):+ """The fast encoder path builds no 8-bit config; with UNSLOTH_COMPILE_DISABLE=1 an 8-bit request stays on the+ fallback loader (as before that switch kept the fast path) and loads quantized."""+ bnb = pytest.importorskip("bitsandbytes")+ path = _save_encoder_sentence_model(tmp_path, "bert")+ monkeypatch.setenv("UNSLOTH_COMPILE_DISABLE", "1")+ from unsloth import FastSentenceTransformer++ model = FastSentenceTransformer.from_pretrained(+ path, load_in_8bit = True, load_in_16bit = False, full_finetuning = False+ )+ assert getattr(model, "_unsloth_fast_encoder", False) is False+ assert any(isinstance(m, bnb.nn.Linear8bitLt) for m in model.modules())diff --git a/tests/test_dpo_chunked_logprobs.py b/tests/test_dpo_chunked_logprobs.pynew file mode 100644index 00000000000..f7af8269ad5--- /dev/null+++ b/tests/test_dpo_chunked_logprobs.py@@ -0,0 +1,620 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""DPO concatenated_forward scored from hidden states (TRL < 0.29) must match TRL's own logits path: loss, every+metric and every gradient. CPU only: the rl_replacements helpers are lifted via ast and the zoo kernel is loaded by+path, so neither package import (which wants a GPU) runs."""++from __future__ import annotations++import ast+import copy+import importlib.util+import inspect+import os+import re+import subprocess+import sys+import textwrap+import types+from pathlib import Path++import pytest+from real_accelerator import has_real_cuda++torch = pytest.importorskip("torch")+trl = pytest.importorskip("trl")++REPO = Path(__file__).resolve().parents[1]+SOURCE_PATH = REPO / "unsloth" / "models" / "rl_replacements.py"+TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM"++HELPERS = (+ "_unsloth_get_model_config",+ "_unsloth_text_configs",+ "_unsloth_get_final_logit_softcapping",+ "_unsloth_resolve_logit_scales",+ "_unsloth_grpo_returns_hidden_states",+ "_unsloth_grpo_hidden_states_signal",+ "_unsloth_pref_returns_hidden_states",+ "_unsloth_gkd_dense_head",+ "_unsloth_gkd_logit_transforms",+ "_unsloth_pref_logit_transforms",+ "_unsloth_stock_logps_hook",+ "_unsloth_dpo_chunked_head",+ "_unsloth_dpo_model_forward",+ "_unsloth_dpo_returns_hidden_states",+ "_unsloth_dpo_hidden_logps",+ "_unsloth_dpo_nll",+ "dpo_trainer_chunked_logprobs",+ "_unsloth_kto_hidden_logps",+ "kto_trainer_chunked_logprobs",+)+CONSTANTS = (+ "_DPO_VISION_KEYS",+ "_DPO_CF_FORWARD",+ "_DPO_CF_LOGPS",+ "_DPO_CF_START",+ "_DPO_CF_CHOSEN",+ "_DPO_CF_CE",+ "_KTO_FORWARD",+ "_KTO_LOGPS",+)+++def _zoo_kernel():+ zoo = os.environ.get("UNSLOTH_ZOO_PATH")+ candidates = [Path(zoo)] if zoo else []+ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is not None and spec.submodule_search_locations:+ candidates += [Path(p).parent for p in spec.submodule_search_locations]+ for root in candidates:+ path = root / "unsloth_zoo" / "fused_losses" / "chunked_logprob.py"+ if path.exists():+ break+ else:+ pytest.skip(reason = "unsloth_zoo has no fused_losses/chunked_logprob.py")+ os.environ["UNSLOTH_COMPILE_DISABLE"] = "1"+ stub = types.ModuleType("unsloth_zoo.temporary_patches.common")+ stub.torch_compile_options = {}+ stub.CHUNK_ALIGN_ROWS = 1 # UNSLOTH_CE_CHUNK_ALIGN off (unsloth-zoo#1773)+ saved = {+ k: sys.modules.get(k)+ for k in ("unsloth_zoo", "unsloth_zoo.temporary_patches", stub.__name__)+ }+ sys.modules.setdefault("unsloth_zoo", types.ModuleType("unsloth_zoo"))+ sys.modules.setdefault(+ "unsloth_zoo.temporary_patches", types.ModuleType("unsloth_zoo.temporary_patches")+ )+ sys.modules[stub.__name__] = stub+ try:+ module_spec = importlib.util.spec_from_file_location("_zoo_chunked_logprob", path)+ module = importlib.util.module_from_spec(module_spec)+ module_spec.loader.exec_module(module)+ finally:+ for k, v in saved.items():+ if v is None:+ sys.modules.pop(k, None)+ else:+ sys.modules[k] = v+ return module+++def _helpers():+ tree = ast.parse(SOURCE_PATH.read_text(encoding = "utf-8"))+ nodes = [+ n+ for n in tree.body+ if (isinstance(n, ast.FunctionDef) and n.name in HELPERS)+ or (+ isinstance(n, ast.Assign)+ and any(isinstance(t, ast.Name) and t.id in CONSTANTS for t in n.targets)+ )+ ]+ ns = {+ "os": os,+ "re": re,+ "torch": torch,+ "inspect": inspect,+ "textwrap": textwrap,+ "detect_logit_transforms": None,+ }+ exec(compile(ast.Module(body = nodes, type_ignores = []), str(SOURCE_PATH), "exec"), ns)+ missing = [n for n in HELPERS + CONSTANTS if n not in ns]+ assert not missing, missing+ kernel = _zoo_kernel()+ ns["_unsloth_masked_logprobs"] = kernel.unsloth_masked_logprobs+ ns["_unsloth_chunked_logprobs"] = kernel.unsloth_chunked_logprobs+ try:+ from unsloth_zoo.fused_losses.preference_loss import linear_mean_logits+ except Exception:+ linear_mean_logits = None+ ns["_unsloth_linear_mean_logits"] = linear_mean_logits+ return ns+++_STOCK = {}+++def _stock_module(mod):+ """A fresh copy of TRL's module: importing unsloth (conftest does, for its import fixes) replaces the trainer+ classes in TRL's modules with Unsloth's generated ones, so re-execute TRL's own file under a sibling name."""+ if mod.__name__ not in _STOCK:+ import importlib.util++ spec = importlib.util.spec_from_file_location(mod.__name__ + "_stock", mod.__file__)+ fresh = importlib.util.module_from_spec(spec)+ # Registered, so datasets' dill pickles its map functions by reference, not by value with every global.+ sys.modules[spec.name] = fresh+ spec.loader.exec_module(fresh)+ _STOCK[mod.__name__] = fresh+ return _STOCK[mod.__name__]+++def _stock(mod, name):+ return getattr(_stock_module(mod), name)++[email protected](scope = "module")+def env():+ import trl.import_utils as iu++ iu._mergekit_available = False # a broken mergekit dist-info here would fail the trainer import+ import trl.trainer.dpo_trainer as dpo_mod++ if not hasattr(_stock(dpo_mod, "DPOTrainer"), "concatenated_forward"):+ pytest.skip(reason = "TRL >= 0.29 has no concatenated_forward")+ ns = _helpers()+ source = inspect.getsource(_stock(dpo_mod, "DPOTrainer").concatenated_forward)+ # Class-indented, as unsloth/models/rl.py hands it to RL_FUNCTIONS.+ patched = ns["dpo_trainer_chunked_logprobs"]("concatenated_forward", source)+ assert patched != source, "rewrite did not apply to the installed TRL"+ g = dict(vars(_stock_module(dpo_mod)))+ g.update({k: v for k, v in ns.items() if not k.startswith("__")})+ exec(compile(textwrap.dedent(patched), "<patched concatenated_forward>", "exec"), g)+ return dpo_mod, g["concatenated_forward"]+++def _honour_hidden_states(model):+ """What Unsloth's forward does under UNSLOTH_RETURN_HIDDEN_STATES=1: the final hidden states as ``.logits``."""+ original = model.forward++ def forward(*args, **kwargs):+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") != "1":+ return original(*args, **kwargs)+ kwargs["output_hidden_states"] = True+ out = original(*args, **kwargs)+ out.logits = out.hidden_states[-1]+ return out++ model.forward = forward+ return model+++def _dataset():+ from datasets import Dataset++ g = torch.Generator().manual_seed(0)+ words = "the of and to in is that for it as with was on be by this are from at or an".split()++ def text(n):+ return " ".join(words[i] for i in torch.randint(len(words), (n,), generator = g).tolist())++ return Dataset.from_list(+ [+ {"prompt": text(5 + i), "chosen": text(9 + 2 * i), "rejected": text(4 + 3 * i)}+ for i in range(4)+ ]+ )+++def _run(+ dpo_mod,+ forward,+ cfg_kwargs,+ chunked,+ ref = "model",+ honour = True,+ peft_ref = False,+):+ from transformers import AutoModelForCausalLM, AutoTokenizer++ torch.manual_seed(0)+ model = AutoModelForCausalLM.from_pretrained(TINY, torch_dtype = torch.float32)+ if not hasattr(model, "warnings_issued"):+ model.warnings_issued = {} # transformers 5 dropped it; stock TRL < 0.26 still writes to it+ tok = AutoTokenizer.from_pretrained(TINY)+ ref_model = copy.deepcopy(model) if ref == "model" else None+ with torch.no_grad(): # a ref that differs from the policy, so the margins are not all zero+ for p in model.parameters():+ p.add_(0.02 * torch.randn_like(p))+ if honour:+ _honour_hidden_states(model)+ if ref_model is not None:+ _honour_hidden_states(ref_model)+ cls = _stock(dpo_mod, "DPOTrainer")+ if chunked:+ cls = type(+ "PatchedDPOTrainer", (_stock(dpo_mod, "DPOTrainer"),), {"concatenated_forward": forward}+ )+ cfg = dpo_mod.DPOConfig(+ output_dir = str(REPO / ".pytest_dpo_chunked"),+ per_device_train_batch_size = 4,+ report_to = "none",+ use_cpu = True,+ max_length = 64,+ dataset_num_proc = None,+ **cfg_kwargs,+ )+ # In process: a worker pool would pickle the map function, whose globals hold torch's config module.+ cfg.dataset_num_proc = None+ trainer = cls(+ model = model, ref_model = ref_model, args = cfg, train_dataset = _dataset(), processing_class = tok+ )+ batch = next(iter(trainer.get_train_dataloader()))+ loss, metrics = trainer.get_batch_loss_metrics(trainer.model, batch, train_eval = "train")+ loss.backward()+ grads = {n: p.grad.clone() for n, p in trainer.model.named_parameters() if p.grad is not None}+ return trainer, loss.detach(), metrics, grads+++CASES = {+ "sigmoid": {"loss_type": "sigmoid"},+ "ipo": {"loss_type": "ipo"},+ "hinge_rpo": {"loss_type": "hinge", "rpo_alpha": 0.5},+ "sigmoid_sft": {"loss_type": ["sigmoid", "sft"], "loss_weights": [1.0, 0.7]},+ "robust_ld": {"loss_type": "robust", "ld_alpha": 0.5},+ "precompute": {"loss_type": "sigmoid", "precompute_ref_log_probs": True},+}++[email protected]("case", list(CASES))+def test_matches_trl(env, case):+ dpo_mod, forward = env+ kwargs = dict(CASES[case])+ if "ld_alpha" in kwargs and "ld_alpha" not in dpo_mod.DPOConfig.__dataclass_fields__:+ pytest.skip(reason = "this TRL has no ld_alpha field")+ if (+ isinstance(kwargs.get("loss_type"), list)+ and "loss_weights" not in dpo_mod.DPOConfig.__dataclass_fields__+ ):+ pytest.skip(reason = "this TRL has no multi-loss DPO")+ _, base_loss, base_metrics, base_grads = _run(dpo_mod, forward, kwargs, chunked = False)+ trainer, loss, metrics, grads = _run(dpo_mod, forward, kwargs, chunked = True)+ assert trainer._unsloth_dpo_chunked_calls >= 1+ assert torch.allclose(loss, base_loss, atol = 1e-5, rtol = 1e-5), (case, loss, base_loss)+ assert metrics.keys() == base_metrics.keys()+ for k in base_metrics:+ assert abs(metrics[k] - base_metrics[k]) <= 1e-5 + 1e-5 * abs(base_metrics[k]), (+ case,+ k,+ metrics[k],+ base_metrics[k],+ )+ assert grads.keys() == base_grads.keys()+ worst = max(+ (grads[n] - base_grads[n]).abs().max().item() / (base_grads[n].abs().max().item() + 1e-12)+ for n in grads+ )+ assert worst < 1e-4, (case, worst)+ print(+ f"{case}: loss {loss.item():.6f} vs {base_loss.item():.6f}, worst rel grad diff {worst:.2e}, calls {trainer._unsloth_dpo_chunked_calls}"+ )+++def test_forward_without_flag_keeps_trl_math(env):+ dpo_mod, forward = env+ _, base_loss, _, _ = _run(+ dpo_mod, forward, {"loss_type": "sigmoid"}, chunked = False, honour = False+ )+ trainer, loss, _, _ = _run(+ dpo_mod, forward, {"loss_type": "sigmoid"}, chunked = True, honour = False+ )+ assert getattr(trainer, "_unsloth_dpo_chunked_calls", 0) == 0+ assert (+ trainer._unsloth_dpo_chunked_fallbacks.get("forward returned logits, not hidden states", 0)+ >= 1+ )+ assert torch.allclose(loss, base_loss, atol = 1e-6)+ assert "UNSLOTH_RETURN_HIDDEN_STATES" not in os.environ+++def test_use_weighting_falls_back(env):+ dpo_mod, forward = env+ _, base_loss, _, _ = _run(dpo_mod, forward, {"use_weighting": True}, chunked = False)+ trainer, loss, _, _ = _run(dpo_mod, forward, {"use_weighting": True}, chunked = True)+ assert getattr(trainer, "_unsloth_dpo_chunked_calls", 0) == 0+ assert "use_weighting needs full-vocabulary log-probs" in trainer._unsloth_dpo_chunked_fallbacks+ assert torch.allclose(loss, base_loss, atol = 1e-6)+++TRL_TAGS = [+ "v0.18.2",+ "v0.19.1",+ "v0.20.0",+ "v0.21.0",+ "v0.22.2",+ "v0.23.1",+ "v0.24.0",+ "v0.25.1",+ "v0.26.2",+ "v0.27.2",+ "v0.28.0",+]++[email protected]("tag", TRL_TAGS)+def test_rewrite_applies_across_trl(tag):+ repo = os.environ.get("TRL_HISTORY")+ if not repo or not Path(repo, ".git").exists():+ pytest.skip(reason = "set TRL_HISTORY to a huggingface/trl clone")+ text = subprocess.run(+ ["git", "-C", repo, "show", f"{tag}:trl/trainer/dpo_trainer.py"],+ capture_output = True,+ text = True,+ check = True,+ ).stdout+ cls = next(+ n for n in ast.parse(text).body if isinstance(n, ast.ClassDef) and n.name == "DPOTrainer"+ )+ fn = next(+ n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "concatenated_forward"+ )+ source = (+ "\n".join(text.splitlines()[fn.lineno - 1 - len(fn.decorator_list) : fn.end_lineno]) + "\n"+ )+ ns = _helpers()+ patched = ns["dpo_trainer_chunked_logprobs"]("concatenated_forward", source)+ assert patched != source+ compile(textwrap.dedent(patched), tag, "exec")+ assert patched.count("_unsloth_dpo_hidden") >= 5+ assert "_unsloth_dpo_nll(_unsloth_dpo_chosen_logps, chosen_labels)" in patched+ assert ns["dpo_trainer_chunked_logprobs"]("concatenated_forward", patched) == patched+++def _trl_source(tag, paths, cls_name, fn_name):+ repo = os.environ.get("TRL_HISTORY")+ if not repo or not Path(repo, ".git").exists():+ pytest.skip(reason = "set TRL_HISTORY to a huggingface/trl clone")+ for path in paths:+ r = subprocess.run(+ ["git", "-C", repo, "show", f"{tag}:{path}"], capture_output = True, text = True+ )+ if r.returncode == 0 and f"class {cls_name}" in r.stdout:+ text = r.stdout+ break+ else:+ return None+ cls = next(+ n for n in ast.parse(text).body if isinstance(n, ast.ClassDef) and n.name == cls_name+ )+ fn = next((n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == fn_name), None)+ if fn is None:+ return None+ return (+ "\n".join(text.splitlines()[fn.lineno - 1 - len(fn.decorator_list) : fn.end_lineno]) + "\n"+ )+++KTO_PATHS = ("trl/experimental/kto/kto_trainer.py", "trl/trainer/kto_trainer.py")++[email protected]("tag", TRL_TAGS + ["v0.29.1", "v1.0.0", "v1.5.0"])+def test_kto_rewrite_applies_across_trl(tag):+ source = _trl_source(tag, KTO_PATHS, "KTOTrainer", "forward")+ ns = _helpers()+ patched = ns["kto_trainer_chunked_logprobs"]("forward", source)+ assert patched != source+ compile(textwrap.dedent(patched), tag, "exec")+ assert "_unsloth_kto_hidden_logps(" in patched and "self.get_batch_logps(" in patched+ assert ns["kto_trainer_chunked_logprobs"]("forward", patched) == patched++[email protected]("tag", ["v1.10.0", "v1.14.2", "v1.15.0"])+def test_kto_newer_trl_untouched(tag):+ source = _trl_source(tag, KTO_PATHS, "KTOTrainer", "forward")+ if source is None:+ return+ assert _helpers()["kto_trainer_chunked_logprobs"]("forward", source) == source+++def _kto_run(+ cfg_kwargs,+ chunked,+ honour = True,+):+ import trl.import_utils as iu++ iu._mergekit_available = False+ from datasets import Dataset+ from transformers import AutoModelForCausalLM, AutoTokenizer++ try:+ import trl.experimental.kto.kto_trainer as kto_mod+ except ImportError:+ import trl.trainer.kto_trainer as kto_mod+ ns = _helpers()+ stock_forward = getattr(_stock(kto_mod, "KTOTrainer"), "forward", None)+ if stock_forward is None:+ pytest.skip(reason = "installed KTOTrainer has no forward (TRL >= 1.10)")+ source = inspect.getsource(stock_forward)+ patched = ns["kto_trainer_chunked_logprobs"]("forward", source)+ if patched == source:+ # Skip because TRL >= 1.10 restructured KTO; the release-tag test covers the rewrite.+ pytest.skip(+ reason = "installed KTOTrainer.forward has no rewritable get_batch_logps call (TRL >= 1.10)"+ )+ g = dict(vars(_stock_module(kto_mod)))+ g.update({k: v for k, v in ns.items() if not k.startswith("__")})+ exec(compile(textwrap.dedent(patched), "<patched kto forward>", "exec"), g)++ torch.manual_seed(0)+ model = AutoModelForCausalLM.from_pretrained(TINY, torch_dtype = torch.float32)+ if not hasattr(model, "warnings_issued"):+ model.warnings_issued = {} # transformers 5 dropped it; stock TRL < 0.26 still writes to it+ tok = AutoTokenizer.from_pretrained(TINY)+ ref_model = copy.deepcopy(model)+ with torch.no_grad():+ for p in model.parameters():+ p.add_(0.02 * torch.randn_like(p))+ if honour:+ _honour_hidden_states(model)+ _honour_hidden_states(ref_model)+ cls = _stock(kto_mod, "KTOTrainer")+ if chunked:+ cls = type("PatchedKTOTrainer", (_stock(kto_mod, "KTOTrainer"),), {"forward": g["forward"]})+ rows = _dataset()+ ds = Dataset.from_list(+ [+ {+ "prompt": r["prompt"],+ "completion": r["chosen" if i % 2 else "rejected"],+ "label": bool(i % 2),+ }+ for i, r in enumerate(rows)+ ]+ )+ cfg = kto_mod.KTOConfig(+ output_dir = str(REPO / ".pytest_kto_chunked"),+ per_device_train_batch_size = 4,+ report_to = "none",+ use_cpu = True,+ max_length = 64,+ # TRL 0.29 dropped KTOConfig.max_prompt_length.+ **(+ {"max_prompt_length": 32}+ if "max_prompt_length" in kto_mod.KTOConfig.__dataclass_fields__+ else {}+ ),+ dataset_num_proc = None,+ **cfg_kwargs,+ )+ # In process: a worker pool would pickle the map function, whose globals hold torch's config module.+ cfg.dataset_num_proc = None+ trainer = cls(+ model = model, ref_model = ref_model, args = cfg, train_dataset = ds, processing_class = tok+ )+ batch = next(iter(trainer.get_train_dataloader()))+ loss, metrics = trainer.get_batch_loss_metrics(trainer.model, batch)+ loss.backward()+ grads = {n: p.grad.clone() for n, p in trainer.model.named_parameters() if p.grad is not None}+ return trainer, loss.detach(), metrics, grads++[email protected]("cfg", [{}, {"loss_type": "apo_zero_unpaired"}])+def test_kto_matches_trl(cfg):+ _, base_loss, base_metrics, base_grads = _kto_run(cfg, chunked = False)+ trainer, loss, metrics, grads = _kto_run(cfg, chunked = True)+ assert trainer._unsloth_dpo_chunked_calls >= 1+ assert torch.allclose(loss, base_loss, atol = 1e-5, rtol = 1e-5), (loss, base_loss)+ assert metrics.keys() == base_metrics.keys()+ for k in base_metrics:+ assert abs(metrics[k] - base_metrics[k]) <= 1e-4 + 1e-5 * abs(base_metrics[k]), (+ k,+ metrics[k],+ base_metrics[k],+ )+ worst = max(+ (grads[n] - base_grads[n]).abs().max().item() / (base_grads[n].abs().max().item() + 1e-12)+ for n in grads+ )+ assert worst < 1e-4, worst+ print(+ f"kto {cfg}: loss {loss.item():.6f} vs {base_loss.item():.6f}, worst rel grad diff {worst:.2e}"+ )+++def test_stock_logps_hook_detects_overrides():+ hook = _helpers()["_unsloth_stock_logps_hook"]++ class Stock:+ def get_batch_logps(self):+ pass++ def concatenated_forward(self):+ pass++ class Patched(Stock):+ def concatenated_forward(self):+ return _unsloth_dpo_chunked_head # noqa: F821 (only the name matters)++ class UserOverride(Patched):+ def get_batch_logps(self):+ pass++ class NoHook:+ def concatenated_forward(self):+ pass++ assert hook(Stock(), "concatenated_forward")+ assert hook(Patched(), "concatenated_forward")+ assert not hook(UserOverride(), "concatenated_forward")+ assert hook(NoHook(), "concatenated_forward")++ class MetricsOverride(Patched):+ def get_batch_loss_metrics(self):+ pass++ both = ("get_batch_logps", "get_batch_loss_metrics")+ assert hook(MetricsOverride(), "concatenated_forward")+ assert not hook(MetricsOverride(), "concatenated_forward", both)+ assert hook(Patched(), "concatenated_forward", both)++ class WrapsForwardAndHook(Patched):+ def concatenated_forward(self):+ return super().concatenated_forward()++ def get_batch_logps(self):+ pass++ assert not hook(WrapsForwardAndHook(), "concatenated_forward")++ class WrapsForward(Patched):+ def concatenated_forward(self):+ return super().concatenated_forward()++ stand_ins = both + ("concatenated_forward",)+ assert hook(WrapsForward(), "concatenated_forward")+ assert not hook(WrapsForward(), "concatenated_forward", stand_ins)+ assert hook(Patched(), "concatenated_forward", stand_ins)+++def test_router_aux_loss_falls_back():+ ns = _helpers()++ class Trainer:+ aux_loss_enabled = True++ trainer = Trainer()+ assert ns["_unsloth_dpo_chunked_head"](trainer, None, {}) is None+ assert "router aux loss needs the stock forward" in trainer._unsloth_dpo_chunked_fallbacks+++def test_kto_scores_the_common_length_when_the_model_truncates():+ ns = _helpers()+ torch.manual_seed(0)+ head = torch.nn.Linear(8, 20, bias = False)+ hidden = torch.randn(2, 5, 8)+ labels = torch.randint(0, 20, (2, 7))+ labels[:, :2] = -100+ full, _ = ns["_unsloth_kto_hidden_logps"](+ None, (None, head, (0.0, 0.0, 0.0)), hidden, labels[:, :5], -100+ )+ clamped, stand_in = ns["_unsloth_kto_hidden_logps"](+ None, (None, head, (0.0, 0.0, 0.0)), hidden, labels, -100+ )+ torch.testing.assert_close(clamped, full)+ assert stand_in.shape[:2] == (2, 5)++[email protected](not has_real_cuda(), reason = "needs a second device for the head")+def test_kto_returns_on_the_hidden_state_device():+ # A dispatched model hands hidden states back on its input device while the head sits elsewhere.+ ns = _helpers()+ head = torch.nn.Linear(8, 20, bias = False).cuda()+ hidden = torch.randn(2, 5, 8)+ labels = torch.randint(0, 20, (2, 5))+ logps, stand_in = ns["_unsloth_kto_hidden_logps"](+ None, (None, head, (0.0, 0.0, 0.0)), hidden, labels, -100+ )+ assert logps.device == hidden.device and stand_in.device == hidden.devicediff --git a/unsloth/models/rl.py b/unsloth/models/rl.pyindex e3f893f655f..22c4122b2fb 100644--- a/unsloth/models/rl.py+++ b/unsloth/models/rl.py@@ -4616,6 +4616,12 @@ class _ApplyOnInputDevice:def __init__(self, function):self.function = function+ def __getattr__(self, name):+ # The wrapped kernel's sentinels and ``forward`` stay visible: the fused head adapter reads them.+ if name == "function":+ raise AttributeError(name)+ return getattr(self.function, name)+def apply(self, hidden, *args):device = hidden.devicebackend = getattr(torch, device.type, None) if device.type in ("cuda", "xpu") else None@@ -4670,6 +4676,209 @@ def patch_trl_fused_lm_head_devices():setattr(_mod, "add_fused_lm_head", add_fused_lm_head)+class _UnslothFusedLinearHead:+ """TRL >= 1.15's ``_ChunkedLogProbFunction`` slot, served by unsloth_zoo's fused linear kernel (no backward+ recompute for a frozen head, fp32 logits on CUDA). Anything it does not reproduce exactly goes to TRL's kernel."""++ _unsloth_fused_linear = True++ def __init__(self, function):+ self.function = function+ # TRL 1.14's kernel (1.1 - 1.13 take no bias and are not wrapped) takes no ``outputs`` and returns ``(log_probs, entropy)``.+ try:+ forward = getattr(function, "forward", None)+ self._legacy = (+ forward is not None and "outputs" not in inspect.signature(forward).parameters+ )+ except (TypeError, ValueError):+ self._legacy = False+ module = sys.modules.get(getattr(function, "__module__", None) or "")+ # TRL tiles the projection as [min(N, TOKEN_CHUNK_SIZE), chunk_size]: chunk_size counts vocab columns.+ self._token_rows = int(getattr(module, "TOKEN_CHUNK_SIZE", 4096))+ self._default_chunk = int(+ getattr(sys.modules.get("trl.trainer.utils"), "_CHUNKED_LOGPROB_CHUNK_SIZE", 32768)+ )+ # zoo op v4+ reads entropy_requires_grad=None as "gradient only if one arrives"; older zoos as "none".+ try:+ from unsloth_zoo.fused_losses import fused_linear as _fl+ self._lazy_entropy = int(str(getattr(_fl, "_LP_OP", "")).rsplit("_v", 1)[-1]) >= 4+ except Exception:+ self._lazy_entropy = False++ def __getattr__(self, name):+ # Keep TRL's attributes visible so a later patch pass recognises what it already wrapped.+ if name == "function":+ raise AttributeError(name)+ return getattr(self.function, name)++ def _row_cap(self, hidden, weight, bias, chunk_size, outputs):+ """``max_rows_per_chunk`` keeping the zoo kernel's logits buffer within TRL's tile for the same call+ ([min(N, TOKEN_CHUNK_SIZE), chunk_size] in the compute dtype): 0 = no cap, None = TRL serves the call."""+ # TRL's default tile: keep the zoo budget (lower peak); only an explicitly smaller chunk_size is honoured.+ if int(chunk_size) >= self._default_chunk:+ return 0+ from unsloth_zoo.fused_losses import fused_linear as fl++ N, H = hidden.shape[0], hidden.shape[-1]+ V = weight.shape[0]+ device_type = hidden.device.type+ if torch.is_autocast_enabled(device_type):+ compute_dtype = torch.get_autocast_dtype(device_type)+ else:+ compute_dtype = hidden.dtype+ budget = min(N, self._token_rows) * int(chunk_size) * compute_dtype.itemsize+ split_cols = int(getattr(fl, "_SPLIT_COLS", 16384))+ cols = -(-V // 8) * 8+ tiled_vocab = device_type == "cuda" and split_cols > 0 and V > 2 * split_cols+ # Recompute tiles cannot fit a budget below _BWD_TILE_BYTES without being 2-8x slower: TRL serves those+ # shapes. Decided from shapes alone, so a batch's no-grad and gradient passes pick the same kernel.+ padded = -(-V // split_cols) * split_cols if tiled_vocab else cols+ tile_bytes = getattr(fl, "_BWD_TILE_BYTES", 256 * 1024**2)+ if min(tile_bytes, N * padded * 4) > budget:+ return None+ # Chunked forward (no grad, or frozen head without entropy grad): [rows, V] fp32 logits.+ grad = torch.is_grad_enabled() and (+ hidden.requires_grad+ or weight.requires_grad+ or (bias is not None and bias.requires_grad)+ )+ # A lazy entropy (see apply) leaves a frozen head on the chunked forward gradient even when it is returned.+ head_grad = weight.requires_grad or (bias is not None and bias.requires_grad)+ tiled = (+ tiled_vocab+ and grad+ and (head_grad or ("entropy" in outputs and not self._lazy_entropy))+ )+ if tiled or fl.fused_linear_rows(N, H, V, 4, hidden.device) * cols * 4 <= budget:+ return 0+ cap = budget // (cols * 4)+ return cap if cap >= 1 else None++ def apply(+ self,+ hidden,+ weight,+ bias,+ targets,+ temperature,+ chunk_size,+ final_logit_softcapping = None,+ logit_scale = 1.0,+ outputs = ("entropy", "log_sum_sq_probs", "mean_logits", "is_top1"),+ support_ids = None,+ ):+ if self._legacy:+ args = (+ hidden,+ weight,+ bias,+ targets,+ temperature,+ chunk_size,+ final_logit_softcapping,+ logit_scale,+ )+ outputs = ("log_probs", "entropy")+ else:+ args = (+ hidden,+ weight,+ bias,+ targets,+ temperature,+ chunk_size,+ final_logit_softcapping,+ logit_scale,+ outputs,+ )+ # support_ids (TRL > 1.16, per-row kept set) and a late UNSLOTH_FUSED_LINEAR=0 go to TRL's kernel.+ if support_ids is not None:+ return self.function.apply(*args, support_ids)+ if os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ return self.function.apply(*args)+ try:+ from unsloth_zoo.fused_losses.fused_linear import fused_linear_logprobs+ except Exception:+ return self.function.apply(*args)+ device_type = hidden.device.type+ if (+ # 0.0 means "off" to the zoo kernel, a real multiplier to TRL.+ logit_scale == 0.0+ # TRL casts the head to the hidden dtype outside autocast (cast_lm_head_to_fp32); the zoo kernel the reverse.+ or (not torch.is_autocast_enabled(device_type) and hidden.dtype != weight.dtype)+ # DeepSpeed ZeRO-3 partitions the head again once TRL's gather context exits.+ or hasattr(weight, "ds_id")+ or any(+ name not in ("log_probs", "entropy", "log_sum_sq_probs", "mean_logits", "is_top1")+ for name in outputs+ )+ ):+ return self.function.apply(*args)+ row_cap = self._row_cap(hidden, weight, bias, chunk_size, outputs)+ if row_cap is None:+ return self.function.apply(*args)+ want = {+ name: name in outputs+ for name in ("entropy", "mean_logits", "log_sum_sq_probs", "is_top1")+ }+ result = fused_linear_logprobs(+ hidden,+ weight,+ targets,+ bias = bias,+ temperature = temperature,+ logit_scale_multiply = 0.0 if logit_scale == 1.0 else float(logit_scale),+ logit_softcapping = float(final_logit_softcapping or 0.0),+ return_entropy = want["entropy"],+ # TRL's kernel skips the entropy gradient when none arrives (DPO / KTO log it); None does the same.+ **({"entropy_requires_grad": None} if self._lazy_entropy else {}),+ return_mean_logits = want["mean_logits"],+ return_log_sum_sq_probs = want["log_sum_sq_probs"],+ return_is_top1 = want["is_top1"],+ max_rows_per_chunk = row_cap or None,+ )+ result = iter(result if isinstance(result, tuple) else (result,))+ log_probs = next(result)+ extra = {name: next(result) if flag else None for name, flag in want.items()}+ if extra["mean_logits"] is not None and temperature != 1.0:+ # TRL averages the logits after the temperature, the zoo kernel (like logits.mean()) before it.+ extra["mean_logits"] = extra["mean_logits"] / temperature+ if self._legacy:+ return log_probs, extra["entropy"]+ return (+ log_probs,+ extra["entropy"],+ extra["log_sum_sq_probs"],+ extra["mean_logits"],+ extra["is_top1"],+ )+++def patch_trl_fused_lm_head_kernel():+ # UNSLOTH_FUSED_LINEAR=0 keeps TRL's own chunked log-prob kernel.+ if os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ return+ try:+ import trl.trainer.utils as _tu+ except ImportError:+ return+ kernel = getattr(_tu, "_ChunkedLogProbFunction", None)+ if kernel is None or getattr(kernel, "_unsloth_fused_linear", False):+ return+ # TRL 1.1 - 1.13's kernel takes no ``bias``: the adapter would shift every argument after ``weight``.+ forward = getattr(kernel, "forward", None)+ try:+ if forward is not None and "bias" not in inspect.signature(forward).parameters:+ return+ except (TypeError, ValueError):+ return+ try:+ import unsloth_zoo.fused_losses.fused_linear # noqa: F401+ except Exception:+ return+ _tu._ChunkedLogProbFunction = _UnslothFusedLinearHead(kernel)++def patch_trl_openenv():for function in RL_ADDITIONAL_FUNCTIONS["openenv"]:logger.info(f"Unsloth: Patching trl openenv with function: {function.__name__}")@@ -5240,6 +5449,10 @@ def PatchFastRL(algorithm = None, FastLanguageModel = None):patch_trl_fused_lm_head_devices()except Exception as e:logger.info(f"Unsloth: Could not patch trl add_fused_lm_head for split models: {e}")+ try:+ patch_trl_fused_lm_head_kernel()+ except Exception as e:+ logger.info(f"Unsloth: Could not route trl's fused lm_head to unsloth_zoo's kernel: {e}")# Also before patch_trl_rl_trainers, so the generated trainers import the wrapped helpers.try:from ._trl_tool_templates import patch_trl_tool_chat_templatesdiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 84f63a3f400..a36c9961e21 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -3100,6 +3100,21 @@ def grpo_trainer__get_per_token_logps_and_entropies(function_name, function):chunked_selective_log_softmax,)+ # Old / ref logps must use the policy pass's scorer, else the ratio starts away from 1 and the KL is biased.+ try:+ if os.environ.get("UNSLOTH_GRPO_LOGPROB_RECOMPUTE", "0") == "1":+ from unsloth_zoo.rl_replacements import grpo_truncated_support_kwargs+ if not grpo_truncated_support_kwargs(self):+ from unsloth_zoo.rl_replacements import (+ chunked_hidden_states_selective_log_softmax_recompute as chunked_hidden_states_selective_log_softmax,+ )+ else:+ from unsloth_zoo.rl_replacements import (+ grpo_chunked_hidden_states_logprobs as chunked_hidden_states_selective_log_softmax,+ )+ except ImportError:+ pass+output_embeddings = unwrapped_model.get_output_embeddings()lm_head = output_embeddings.weightlm_head_bias = getattr(output_embeddings, "bias", None)@@ -3942,6 +3957,16 @@ def _unsloth_grpo_returns_hidden_states(model, tensor, lm_head):return _unsloth_grpo_hidden_states_signal(model) is not False+def _unsloth_pref_returns_hidden_states(model, tensor, lm_head):+ """``_unsloth_grpo_returns_hidden_states`` for the preference routes, which need a zoo that writes the hidden-state+ markers: a square head with no signal is a forward that ignored the flag, so its output is real logits."""+ if tensor.shape[-1] != lm_head.shape[1]:+ return False+ if lm_head.shape[0] != lm_head.shape[1]:+ return True+ return _unsloth_grpo_hidden_states_signal(model) is True++def _unsloth_grpo_hidden_states_signal(model):"""``True``/``False`` if the forward honours ``UNSLOTH_RETURN_HIDDEN_STATES``, ``None`` when neither marker is present. See ``_unsloth_grpo_returns_hidden_states`` for where each marker is set. Walks the wrapper chain because the markers are set on whichever object the trainer saw, which may be the DDP module or the PEFT base model rather than the object handed to the logprob loop."""candidates = []@@ -5767,3 +5792,1729 @@ RL_PRE_ITEMS["gkd_trainer"].append("except Exception:\n"" distillation_chunked_jsd = None\n")+++# ORPO / CPO: log-probs from hidden states via a chunked head; anything not reproduced exactly runs TRL's body.+try:+ from unsloth_zoo.fused_losses.chunked_logprob import unsloth_chunked_logprobs+except Exception:+ unsloth_chunked_logprobs = None+# Scored positions only, with the logits/* means from the head's affine mean (no backward); older zoo scores every row.+try:+ from unsloth_zoo.fused_losses.chunked_logprob import (+ unsloth_masked_logprobs as _unsloth_pref_masked_logprobs,+ )+ from unsloth_zoo.fused_losses.preference_loss import (+ linear_mean_logits as _unsloth_linear_mean_logits,+ )+except Exception:+ _unsloth_pref_masked_logprobs = _unsloth_linear_mean_logits = None+++def _unsloth_stock_logps_hook(+ self,+ method,+ hooks = ("get_batch_logps",),+):+ """False when a subclass overrides one of ``hooks`` below the class whose ``method`` is the rewritten one: TRL's+ body would call the override (or it reads the full logits the chunked path replaces with stand-ins)."""+ owner = None+ for klass in type(self).__mro__:+ # The rewritten body calls a chunked or fused-pass helper; a subclass method wrapping it via super() does not.+ names = getattr(getattr(vars(klass).get(method), "__code__", None), "co_names", ())+ if any(+ name.startswith("_unsloth_") and ("chunked" in name or "fused_pass" in name)+ for name in names+ ):+ owner = klass+ break+ if owner is None:+ return True+ for name in hooks:+ hook = next((klass for klass in type(self).__mro__ if name in vars(klass)), None)+ if hook is not None and hook not in owner.__mro__:+ return False+ return True+++def _unsloth_pref_chunked_head(self, model):+ """The dense output head when this concatenated_forward can score from hidden states, else ``None``."""+ if unsloth_chunked_logprobs is None or os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ return None+ if os.environ.get("UNSLOTH_PREFERENCE_CHUNKED", "1").lower() in ("0", "false", "no", "off"):+ return None+ if getattr(self, "is_encoder_decoder", False) or getattr(self, "aux_loss_enabled", False):+ return None+ # Listing the method itself rejects a subclass wrapping it: it would see stand-in logits.+ if not _unsloth_stock_logps_hook(+ self,+ "concatenated_forward",+ ("get_batch_logps", "get_batch_loss_metrics", "concatenated_forward"),+ ):+ return None+ # TRL <= 0.25 scores labels against label_pad_token_id but nn.CrossEntropyLoss always ignores -100.+ if getattr(self, "label_pad_token_id", -100) != -100:+ return None+ if getattr(self, "is_fsdp_enabled", False) or getattr(self, "is_deepspeed_enabled", False):+ return None+ try:+ unwrapped = self.accelerator.unwrap_model(model)+ except Exception:+ return None+ head = _unsloth_gkd_dense_head(unwrapped)+ if head is None:+ return None+ # The kernel reads weight / bias directly: a hooked head (accelerate, forward / backward hooks) is not+ # F.linear(h, W, b), and its backward hooks would never see the gradient.+ if (+ hasattr(head, "_hf_hook")+ or "forward" in vars(head)+ or head._forward_hooks+ or head._forward_pre_hooks+ or head._backward_hooks+ or getattr(head, "_backward_pre_hooks", None)+ ):+ return None+ # MiniCPM3 divides hidden states by logits_scaling before the head.+ for config in _unsloth_text_configs(_unsloth_get_model_config(unwrapped)):+ if getattr(config, "model_type", None) == "minicpm3":+ return None+ # DDP(find_unused_parameters=True) marks a head skipped in forward as unused, then its grad hook fires twice.+ if getattr(model, "find_unused_parameters", False) and any(+ p is not None and p.requires_grad for p in (head.weight, head.bias)+ ):+ return None+ return head+++def _unsloth_pref_logit_transforms(model):+ """``(multiply, divide, softcap)`` for the chunked kernel, from the GKD resolver (one scale, 0.0 = off)."""+ scale, softcap = _unsloth_gkd_logit_transforms(model)+ return (0.0 if scale == 1.0 else scale), 0.0, softcap+++def _unsloth_pref_chunked_forward(self, model, head, concatenated_batch, len_chosen, states, kind):+ """``(outputs, all_logits)``: ``outputs`` is TRL's return tuple computed from hidden states, or ``None`` with+ ``all_logits`` holding real logits for TRL's own body (the forward ignored the flag, or a shape TRL rejects)."""+ unwrapped = self.accelerator.unwrap_model(model)+ multiply, divide, softcap = _unsloth_pref_logit_transforms(unwrapped)+ if not _unsloth_pref_returns_hidden_states(unwrapped, states, head.weight):+ return None, states+ input_ids = concatenated_batch["concatenated_input_ids"]+ labels = concatenated_batch["concatenated_labels"]+ if states.dim() != 3 or states.shape[:2] != labels.shape or labels.shape != input_ids.shape:+ # TRL raises or reads these itself: hand it the logits it expects.+ logits = torch.nn.functional.linear(+ states.to(device = head.weight.device, dtype = head.weight.dtype), head.weight, head.bias+ )+ if multiply:+ logits = logits * multiply+ if divide:+ logits = logits / divide+ if softcap:+ logits = softcap * torch.tanh(logits / softcap)+ return None, logits++ device = states.device+ labels = labels.to(device)+ input_ids = input_ids.to(device)+ shifted = labels[:, 1:]+ label_mask = shifted != -100+ # cat, not boolean slice assignment: CPU Inductor fails to vectorise that (VecMask<long int, 2> vs VecMask<float, 1>).+ rejected_off = torch.zeros_like(label_mask[len_chosen:])+ if kind == "orpo":+ # ORPO's NLL scores every attended token of prompt + chosen, from input_ids.+ nll_targets = input_ids[:, 1:]+ attention_mask = concatenated_batch["concatenated_attention_mask"].to(device)+ nll_mask = torch.cat((attention_mask[:len_chosen, 1:] == 1, rejected_off), dim = 0)+ average_log_prob = True+ # Checking for a second NLL pass needs a host sync, so compiled graphs always take it (correct either way).+ is_compiling = getattr(getattr(torch, "compiler", None), "is_compiling", None)+ if is_compiling is not None and is_compiling():+ split_nll = True+ else:+ split_nll = bool((label_mask & nll_mask & (shifted != nll_targets)).any())+ else:+ nll_targets = shifted+ if self.cpo_alpha != 0:+ nll_mask = torch.cat((label_mask[:len_chosen], rejected_off), dim = 0)+ else:+ nll_mask = torch.zeros_like(label_mask)+ average_log_prob = self.loss_type in ["ipo", "simpo"]+ split_nll = False+ targets = torch.where(label_mask, shifted, torch.where(nll_mask, nll_targets, 0))++ # CPO's logits metric averages every position, ORPO's all but the last.+ rows = states if kind == "cpo" else states[:, :-1]+ kwargs = dict(+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ lm_head_bias = head.bias,+ )+ if _unsloth_pref_masked_logprobs is not None and _unsloth_linear_mean_logits is not None:+ # Prompt and padding rows (often most of each row) never reach the head; they only feed the mean metric.+ per_token = _unsloth_pref_masked_logprobs(+ states[:, :-1],+ head.weight,+ targets,+ mask = label_mask if split_nll else label_mask | nll_mask,+ **kwargs,+ )+ mean_logits = _unsloth_linear_mean_logits(+ rows, head.weight, head.bias, multiply, divide, softcap+ )+ if split_nll:+ nll_per_token = _unsloth_pref_masked_logprobs(+ states[:len_chosen, :-1],+ head.weight,+ nll_targets[:len_chosen],+ mask = nll_mask[:len_chosen],+ **kwargs,+ )+ else:+ nll_per_token = per_token[:len_chosen]+ else:+ if kind == "cpo":+ targets = torch.nn.functional.pad(targets, (0, 1))+ per_token, mean_logits = unsloth_chunked_logprobs(+ rows, head.weight, targets, return_mean_logits = True, **kwargs+ )+ if kind == "cpo":+ per_token = per_token[:, :-1]+ if split_nll:+ nll_per_token = unsloth_chunked_logprobs(+ states[:len_chosen, :-1],+ head.weight,+ torch.where(nll_mask, nll_targets, 0)[:len_chosen],+ **kwargs,+ )+ else:+ nll_per_token = per_token[:len_chosen]++ loss_mask = label_mask.to(per_token.dtype)+ all_logps = (per_token * loss_mask).sum(-1)+ if average_log_prob:+ all_logps = all_logps / loss_mask.sum(-1)+ chosen_nll_mask = nll_mask[:len_chosen].to(per_token.dtype)+ if kind == "cpo" and self.cpo_alpha == 0:+ nll_loss = torch.tensor(0.0).to(self.accelerator.device)+ else:+ nll_loss = -(nll_per_token * chosen_nll_mask).sum() / chosen_nll_mask.sum()+ try:+ self._unsloth_pref_chunked_calls = getattr(self, "_unsloth_pref_chunked_calls", 0) + 1+ except Exception:+ pass+ # Stand-ins: TRL only reads chosen/rejected logits as .detach().mean().+ return (+ all_logps[:len_chosen],+ all_logps[len_chosen:],+ mean_logits[:len_chosen],+ mean_logits[len_chosen:],+ nll_loss,+ ), states+++_PREF_LAYOUTS = {+ "orpo": (+ "labels = torch.where(attention_mask == 1, labels,",+ "chosen_nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])",+ "average_log_prob=True",+ "chosen_logits = all_logits[:len_chosen, :-1, :]",+ "rejected_logits = all_logits[len_chosen:, :-1, :]",+ "return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, chosen_nll_loss)",+ ),+ "cpo": (+ "labels = concatenated_batch['concatenated_labels'].clone()",+ "nll_loss = cross_entropy_loss(all_logits[:len_chosen], labels[:len_chosen])",+ "average_log_prob=self.loss_type in ['ipo', 'simpo']",+ "chosen_logits = all_logits[:len_chosen]\n",+ "rejected_logits = all_logits[len_chosen:]\n",+ "return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss)",+ ),+}+_PREF_COMMON = (+ "len_chosen = batch['chosen_labels'].shape[0]",+ "all_logps = self.get_batch_logps(all_logits, concatenated_batch['concatenated_labels'], average_log_prob=",+ "chosen_logps = all_logps[:len_chosen]",+ "rejected_logps = all_logps[len_chosen:]",+ "loss_fct = nn.CrossEntropyLoss()",+)+++def _unsloth_pref_rewrite_concatenated_forward(function, kind):+ canonical = _unsloth_gkd_canonical(function)+ if canonical is None or "_unsloth_pref_chunked_forward" in function:+ return function+ if not all(x in canonical for x in _PREF_COMMON + _PREF_LAYOUTS[kind]):+ return function+ pattern = re.compile(+ r"(?ms)^([ \t]*)(outputs = model\(\n.*?^\1\)\n)\1all_logits = outputs\.logits\n"+ )+ matches = list(pattern.finditer(function))+ if len(matches) != 1:+ return function+ match = matches[0]+ indent = match.group(1)+ call = textwrap.indent(match.group(2), " ")+ block = (+ "_unsloth_pref_head = _unsloth_pref_chunked_head(self, model)\n"+ "_unsloth_pref_prior = os.environ.get('UNSLOTH_RETURN_HIDDEN_STATES')\n"+ "if _unsloth_pref_head is not None:\n"+ " os.environ['UNSLOTH_RETURN_HIDDEN_STATES'] = '1'\n"+ "try:\n"+ f"{call}"+ "finally:\n"+ " if _unsloth_pref_head is not None:\n"+ " if _unsloth_pref_prior is None:\n"+ " os.environ.pop('UNSLOTH_RETURN_HIDDEN_STATES', None)\n"+ " else:\n"+ " os.environ['UNSLOTH_RETURN_HIDDEN_STATES'] = _unsloth_pref_prior\n"+ "all_logits = outputs.logits\n"+ "if _unsloth_pref_head is not None:\n"+ " _unsloth_pref_out, all_logits = _unsloth_pref_chunked_forward(\n"+ f" self, model, _unsloth_pref_head, concatenated_batch, len_chosen, all_logits, {kind!r}\n"+ " )\n"+ " if _unsloth_pref_out is not None:\n"+ " return _unsloth_pref_out\n"+ )+ return function[: match.start()] + textwrap.indent(block, indent) + function[match.end() :]+++def orpo_trainer_concatenated_forward(function_name, function):+ if function_name != "concatenated_forward":+ return function+ return _unsloth_pref_rewrite_concatenated_forward(function, "orpo")+++def cpo_trainer_concatenated_forward(function_name, function):+ if function_name != "concatenated_forward":+ return function+ return _unsloth_pref_rewrite_concatenated_forward(function, "cpo")+++RL_FUNCTIONS["orpo_trainer"].append(orpo_trainer_concatenated_forward)+RL_FUNCTIONS["cpo_trainer"].append(cpo_trainer_concatenated_forward)+for _pref_trainer in ("orpo_trainer", "cpo_trainer"):+ for _pref_item in (+ _unsloth_get_model_config,+ _unsloth_text_configs,+ _unsloth_get_final_logit_softcapping,+ _unsloth_resolve_logit_scales,+ _unsloth_grpo_returns_hidden_states,+ _unsloth_grpo_hidden_states_signal,+ _unsloth_pref_returns_hidden_states,+ _unsloth_gkd_dense_head,+ _unsloth_stock_logps_hook,+ _unsloth_pref_chunked_head,+ _unsloth_gkd_logit_transforms,+ _unsloth_pref_logit_transforms,+ _unsloth_pref_chunked_forward,+ ):+ RL_PRE_ITEMS[_pref_trainer].append(inspect.getsource(_pref_item))+ RL_PRE_ITEMS[_pref_trainer].append(+ "try:\n"+ " from unsloth_zoo.device_map_planner import detect_logit_transforms\n"+ "except Exception:\n"+ " detect_logit_transforms = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.chunked_logprob import unsloth_chunked_logprobs\n"+ "except Exception:\n"+ " unsloth_chunked_logprobs = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.chunked_logprob import unsloth_masked_logprobs as _unsloth_pref_masked_logprobs\n"+ " from unsloth_zoo.fused_losses.preference_loss import linear_mean_logits as _unsloth_linear_mean_logits\n"+ "except Exception:\n"+ " _unsloth_pref_masked_logprobs = _unsloth_linear_mean_logits = None\n"+ )+++# DPO (TRL < 0.29, concatenated_forward): log-probs from hidden states; TRL >= 1.15 fuses the head itself.+try:+ from unsloth_zoo.fused_losses.chunked_logprob import (+ unsloth_masked_logprobs as _unsloth_masked_logprobs,+ )+except Exception:+ _unsloth_masked_logprobs = None+++def _unsloth_dpo_chunked_head(+ self,+ model,+ concatenated_batch,+ method = "concatenated_forward",+):+ """``(unwrapped_model, head, (multiply, divide, softcap))`` when concatenated_forward can score from hidden+ states, else ``None`` (TRL's own logits path runs). Decided before the forward, which then skips the logits."""+ reason = None+ if _unsloth_masked_logprobs is None:+ reason = "unsloth_zoo has no chunked_logprob"+ elif os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ reason = "UNSLOTH_FUSED_LINEAR=0"+ elif os.environ.get("UNSLOTH_DPO_CHUNKED", "1").lower() in ("0", "false", "no", "off"):+ reason = "UNSLOTH_DPO_CHUNKED=0"+ elif getattr(self, "is_encoder_decoder", False):+ reason = "encoder-decoder"+ elif getattr(self, "aux_loss_enabled", False):+ reason = "router aux loss needs the stock forward"+ elif not _unsloth_stock_logps_hook(+ self,+ method,+ ("get_batch_logps",)+ if method == "concatenated_forward"+ else ("get_batch_logps", "get_batch_loss_metrics", method),+ ):+ # KTO hands its callers logits stand-ins; DPO's outputs are exact, so a DPO wrapper is fine.+ reason = "get_batch_logps / get_batch_loss_metrics overridden"+ elif getattr(self, "padding_free", False):+ reason = "padding_free"+ elif getattr(self, "use_weighting", False):+ reason = "use_weighting needs full-vocabulary log-probs"+ elif getattr(self, "is_fsdp_enabled", False) or getattr(self, "is_deepspeed_enabled", False):+ reason = "FSDP / DeepSpeed"+ elif any(+ k in concatenated_batch+ for k in ("pixel_values", "pixel_attention_mask", "image_sizes", "token_type_ids")+ + tuple(_DPO_VISION_KEYS)+ ):+ reason = "vision inputs"+ if reason is None:+ try:+ unwrapped = self.accelerator.unwrap_model(model)+ except Exception:+ unwrapped = None+ reason = "unwrap_model"+ if reason is None:+ head = _unsloth_gkd_dense_head(unwrapped)+ if head is None:+ reason = "output head is not a dense nn.Linear"+ # The kernel reads weight / bias directly: a hooked head (accelerate, forward / backward hooks) is not+ # F.linear(h, W, b), and its backward hooks would never see the gradient.+ elif (+ hasattr(head, "_hf_hook")+ or "forward" in vars(head)+ or head._forward_hooks+ or head._forward_pre_hooks+ or head._backward_hooks+ or getattr(head, "_backward_pre_hooks", None)+ ):+ reason = "output head has hooks or a patched forward"+ if reason is None:+ for config in _unsloth_text_configs(_unsloth_get_model_config(unwrapped)):+ if getattr(config, "model_type", None) == "minicpm3":+ reason = "minicpm3 scales hidden states before the head"+ if reason is None and getattr(model, "find_unused_parameters", False):+ if any(p is not None and p.requires_grad for p in (head.weight, head.bias)):+ reason = "DDP find_unused_parameters with a trainable head"+ if reason is not None:+ try:+ fallbacks = self.__dict__.setdefault("_unsloth_dpo_chunked_fallbacks", {})+ fallbacks[reason] = fallbacks.get(reason, 0) + 1+ except Exception:+ pass+ return None+ return unwrapped, head, _unsloth_pref_logit_transforms(unwrapped)+++def _unsloth_dpo_model_forward(model, input_ids, model_kwargs, want_hidden_states):+ if not want_hidden_states:+ return model(input_ids, **model_kwargs)+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ return model(input_ids, **model_kwargs)+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+++def _unsloth_dpo_returns_hidden_states(self, chunked, logits):+ if chunked is None:+ return False+ unwrapped, head, _ = chunked+ hidden = _unsloth_pref_returns_hidden_states(unwrapped, logits, head.weight)+ if not hidden:+ fallbacks = self.__dict__.setdefault("_unsloth_dpo_chunked_fallbacks", {})+ reason = "forward returned logits, not hidden states"+ fallbacks[reason] = fallbacks.get(reason, 0) + 1+ return hidden+++def _unsloth_dpo_hidden_logps(self, chunked, hidden_states, labels, loss_mask):+ """``(per_token_logps [B, S], mean_logits [B, S, 1])`` where TRL computes ``selective_log_softmax(logits, labels)``+ and later reads ``logits[mask].mean()``. Rows outside ``loss_mask`` are 0 and never reach the head; the mean over+ a masked row's vocab equals TRL's element mean, so the stand-in keeps the ``logits/*`` metrics exact."""+ _, head, (multiply, divide, softcap) = chunked+ per_token_logps, mean_logits = _unsloth_masked_logprobs(+ hidden_states.to(head.weight.device),+ head.weight,+ labels,+ mask = loss_mask,+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ lm_head_bias = head.bias,+ return_mean_logits = True,+ )+ try:+ self._unsloth_dpo_chunked_calls = getattr(self, "_unsloth_dpo_chunked_calls", 0) + 1+ except Exception:+ pass+ return per_token_logps.to(labels.device), mean_logits.unsqueeze(-1).to(labels.device)+++def _unsloth_dpo_nll(chosen_logps, chosen_labels):+ """``F.cross_entropy(chosen_logits, chosen_labels, ignore_index=0)`` from the per-token log-probs at the same+ positions (TRL zeroes masked labels, so 0 is its ignore index)."""+ keep = chosen_labels != 0+ return -(chosen_logps * keep).sum() / keep.sum()+++_DPO_CF_FORWARD = (+ " outputs = model(input_ids, **model_kwargs)\n logits = outputs.logits\n"+)+_DPO_CF_LOGPS = " per_token_logps = selective_log_softmax(logits, labels)\n"+_DPO_CF_START = ' num_examples = batch["prompt_input_ids"].shape[0]\n'+_DPO_CF_CHOSEN = re.compile(r"^(?P<indent>[ \t]*)chosen_logits = (?P<expr>[^\n]+)\n", re.MULTILINE)+_DPO_CF_CE = re.compile(+ r"F\.cross_entropy\(\s*torch\.flatten\(chosen_logits, end_dim=1\),\s*"+ r"torch\.flatten\(chosen_labels, end_dim=1\),\s*ignore_index=0\s*\)"+)+++def dpo_trainer_chunked_logprobs(function_name, function):+ """Rewrite TRL < 0.29's concatenated_forward to score from hidden states. Every anchor must match exactly once,+ else TRL's source is returned untouched; at run time ``_unsloth_dpo_chunked_head`` keeps TRL's math for any+ feature that needs the full logits, and a forward that ignored the flag still takes TRL's path."""+ if function_name != "concatenated_forward" or _unsloth_masked_logprobs is None:+ return function+ if "_unsloth_dpo_hidden" in function:+ return function+ if any(function.count(a) != 1 for a in (_DPO_CF_FORWARD, _DPO_CF_LOGPS, _DPO_CF_START)):+ return function+ chosen = list(_DPO_CF_CHOSEN.finditer(function))+ if len(chosen) != 1 or len(_DPO_CF_CE.findall(function)) != 1:+ return function+ # Other full-logits readers: padding_free / use_weighting (refused at run time) and the stand-in mean metrics.+ expr = chosen[0].group("expr")+ if "logits" not in expr or "shape" in expr:+ return function+ new = function.replace(+ _DPO_CF_START,+ _DPO_CF_START + " _unsloth_dpo_hidden = False\n",+ )+ new = new.replace(+ _DPO_CF_FORWARD,+ " _unsloth_dpo_chunked = _unsloth_dpo_chunked_head(self, model, concatenated_batch)\n"+ " outputs = _unsloth_dpo_model_forward(\n"+ " model, input_ids, model_kwargs, _unsloth_dpo_chunked is not None\n"+ " )\n"+ " logits = outputs.logits\n"+ " _unsloth_dpo_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_chunked, logits)\n",+ )+ new = new.replace(+ _DPO_CF_LOGPS,+ " if _unsloth_dpo_hidden:\n"+ " per_token_logps, logits = _unsloth_dpo_hidden_logps(\n"+ " self, _unsloth_dpo_chunked, logits, labels, loss_mask\n"+ " )\n"+ " _unsloth_dpo_token_logps = per_token_logps\n"+ " else:\n"+ " per_token_logps = selective_log_softmax(logits, labels)\n",+ )+ indent = chosen[0].group("indent")+ chosen_logps_expr = re.sub(r"\blogits\b", "_unsloth_dpo_token_logps", expr)+ new = _DPO_CF_CHOSEN.sub(+ lambda m: m.group(0)+ + f"{indent}if _unsloth_dpo_hidden:\n"+ + f"{indent} _unsloth_dpo_chosen_logps = {chosen_logps_expr}\n",+ new,+ count = 1,+ )+ new = _DPO_CF_CE.sub(+ lambda m: "(\n"+ " _unsloth_dpo_nll(_unsloth_dpo_chosen_logps, chosen_labels)\n"+ " if _unsloth_dpo_hidden\n"+ f" else {m.group(0)}\n"+ " )",+ new,+ count = 1,+ )+ return new+++RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_chunked_logprobs)+++# DPO (TRL 0.29 - 1.14, _compute_loss): log-probs, entropy, logits/* means and token accuracy from hidden states.+try:+ from unsloth_zoo.fused_losses.fused_linear import (+ fused_linear_logprobs as _unsloth_fused_linear_logprobs,+ )+except Exception:+ _unsloth_fused_linear_logprobs = None+++def _unsloth_dpo_forward(model, model_kwargs, want_hidden_states):+ if not want_hidden_states:+ return model(**model_kwargs)+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ return model(**model_kwargs)+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+++def _unsloth_dpo_loss_head(+ self,+ model,+ inputs,+ return_outputs = False,+):+ """``_unsloth_dpo_chunked_head`` for TRL 0.29 - 1.14's ``_compute_loss``, which also needs the fused linear op+ (entropy and argmax match) and must not hand hidden states back as ``outputs.logits``."""+ reason = None+ if _unsloth_fused_linear_logprobs is None:+ reason = "unsloth_zoo has no fused_linear_logprobs"+ elif os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ reason = "UNSLOTH_FUSED_LINEAR=0"+ elif return_outputs:+ reason = "return_outputs needs the logits"+ if reason is not None:+ try:+ fallbacks = self.__dict__.setdefault("_unsloth_dpo_chunked_fallbacks", {})+ fallbacks[reason] = fallbacks.get(reason, 0) + 1+ except Exception:+ pass+ return None+ return _unsloth_dpo_chunked_head(self, model, inputs, "_compute_loss")+++def _unsloth_dpo_loss_stats(+ self,+ chunked,+ hidden_states,+ labels,+ mask,+ ref = False,+):+ """TRL's per-token statistics of ``logits = head(hidden_states)`` at completion positions (``mask``), the rest 0:+ ``(log_probs, entropy, mean_logits [.., 1], is_top1)``, or the log-probs alone for ``ref``. ``mean_logits`` stands+ in for the logits: ``x[mask].mean(-1)`` on it is TRL's vocab mean. No temperature: TRL's DPO scores at 1.0."""+ _, head, (multiply, divide, softcap) = chunked+ # TRL projects the reference logits inside its no_grad forward: a trainable (or shared) head gets no gradient.+ with torch.set_grad_enabled(torch.is_grad_enabled() and not ref):+ out = _unsloth_fused_linear_logprobs(+ hidden_states,+ head.weight,+ labels,+ bias = head.bias,+ mask = mask,+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ return_entropy = not ref,+ return_mean_logits = not ref,+ return_is_top1 = not ref,+ entropy_requires_grad = False,+ )+ try:+ self._unsloth_dpo_chunked_calls = getattr(self, "_unsloth_dpo_chunked_calls", 0) + 1+ except Exception:+ pass+ if ref:+ return out+ logps, entropy, mean_logits, is_top1 = out+ return logps, entropy, mean_logits.unsqueeze(-1), is_top1+++_DPO_CL_MODE = re.compile(+ r'^(?P<i>[ \t]*)mode = "train" if self\.model\.training else "eval"\n', re.MULTILINE+)+_DPO_CL_FORWARD = re.compile(r"^(?P<i>[ \t]*)outputs = model\(\*\*model_kwargs\)\n", re.MULTILINE)+_DPO_CL_SHIFT = re.compile(+ r"^[ \t]*shift_logits = outputs\.logits\[\.\.\., :-1, :\](?:\.contiguous\(\))?\n",+ re.MULTILINE,+)+# TRL < 1.14: separate log-prob and entropy calls; 1.14: one fused call with a row mask.+_DPO_CL_LOGPS = re.compile(+ r"^(?P<i>[ \t]*)per_token_logps = selective_log_softmax\(shift_logits, shift_labels\)\n",+ re.MULTILINE,+)+_DPO_CL_ENTROPY = re.compile(+ r"^(?P<i>[ \t]*)per_token_entropy = entropy_from_logits\(shift_logits\.detach\(\)\)\n",+ re.MULTILINE,+)+_DPO_CL_LOGPS_ENT = re.compile(+ r"^(?P<i>[ \t]*)per_token_logps, per_token_entropies = selective_log_softmax_and_entropy\(\s*"+ r"shift_logits, shift_labels, entropy_requires_grad=False, row_mask=shift_completion_mask\s*\)\n",+ re.MULTILINE,+)+_DPO_CL_REF_FORWARD = re.compile(+ r"^(?P<i>[ \t]*)ref_outputs = (?P<model>self\.model|self\.ref_model)\(\*\*(?P<kw>model_kwargs|ref_model_kwargs)\)\n",+ re.MULTILINE,+)+_DPO_CL_REF_LOGPS = re.compile(+ r"^(?P<i>[ \t]*)ref_per_token_logps = selective_log_softmax\(\s*ref_shift_logits, shift_labels"+ r"(?P<row_mask>, row_mask=shift_completion_mask)?\s*\)\n",+ re.MULTILINE,+)+_DPO_CL_ARGMAX = re.compile(+ r"^(?P<i>[ \t]*)predictions = chosen_logits\.argmax\(dim=-1\)\n", re.MULTILINE+)+_DPO_CL_SFT = (+ "F.cross_entropy(chosen_logits[chosen_mask.bool()], chosen_labels[chosen_mask.bool()])"+)+++def dpo_trainer_compute_loss_chunked(function_name, function):+ """Rewrite TRL 0.29 - 1.14's ``_compute_loss`` to score from hidden states: it projects every position of the+ policy and reference passes to ``[B, S, V]`` logits, then reads log-probs, entropy, the ``logits/*`` means, the+ argmax token accuracy and the ``sft`` loss term from them. One fused linear call returns all of them at the+ completion positions (the only ones TRL reads), so neither pass materializes logits. Every anchor must match+ exactly once (each reference forward at most once), else TRL's source is returned untouched; at run time+ ``_unsloth_dpo_loss_head`` keeps TRL's path for anything that needs the full logits (``use_weighting``, aux loss,+ ``return_outputs``, vision, ...) and a forward that ignored the flag still takes TRL's path."""+ if function_name != "_compute_loss" or _unsloth_fused_linear_logprobs is None:+ return function+ if "_unsloth_dpo_hidden" in function:+ return function+ fused_entropy = len(_DPO_CL_LOGPS_ENT.findall(function)) == 1+ single = [+ _DPO_CL_MODE,+ _DPO_CL_FORWARD,+ _DPO_CL_SHIFT,+ _DPO_CL_ARGMAX,+ _DPO_CL_REF_LOGPS,+ ]+ single += [] if fused_entropy else [_DPO_CL_LOGPS, _DPO_CL_ENTROPY]+ if any(len(p.findall(function)) != 1 for p in single) or function.count(_DPO_CL_SFT) != 1:+ return function+ ref_forwards = _DPO_CL_REF_FORWARD.findall(function)+ if not 1 <= len(ref_forwards) <= 2 or len({m[1] for m in ref_forwards}) != len(ref_forwards):+ return function+ # Any other reader of the full logits would see the stand-in.+ if function.count("outputs.logits") != 2 or function.count("shift_logits") != (+ 8 if fused_entropy else 9+ ):+ return function++ def _sub(pattern, make, text):+ return pattern.sub(lambda m: make(m.group("i"), m), text, count = 1)++ new = _sub(+ _DPO_CL_MODE,+ lambda i, m: m.group(0) + f"{i}_unsloth_dpo_hidden = _unsloth_dpo_ref_hidden = False\n",+ function,+ )+ new = _sub(+ _DPO_CL_FORWARD,+ lambda i, m: (+ f"{i}_unsloth_dpo_chunked = _unsloth_dpo_loss_head(self, model, inputs, return_outputs)\n"+ f"{i}outputs = _unsloth_dpo_forward(model, model_kwargs, _unsloth_dpo_chunked is not None)\n"+ f"{i}_unsloth_dpo_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_chunked, outputs.logits)\n"+ ),+ new,+ )+ stats = (+ "{i}if _unsloth_dpo_hidden:\n"+ "{i} {lhs}, shift_logits, _unsloth_dpo_top1 = _unsloth_dpo_loss_stats(\n"+ "{i} self, _unsloth_dpo_chunked, shift_logits, shift_labels, shift_completion_mask\n"+ "{i} )\n"+ "{i}else:\n"+ )+ if fused_entropy:+ new = _sub(+ _DPO_CL_LOGPS_ENT,+ lambda i, m: stats.format(i = i, lhs = "per_token_logps, per_token_entropies")+ + textwrap.indent(m.group(0)[len(i) :], i + " "),+ new,+ )+ else:+ new = _sub(+ _DPO_CL_LOGPS,+ lambda i, m: stats.format(i = i, lhs = "per_token_logps, _unsloth_dpo_entropy")+ + f"{i} {m.group(0).lstrip()}",+ new,+ )+ new = _sub(+ _DPO_CL_ENTROPY,+ lambda i, m: (+ f"{i}if _unsloth_dpo_hidden:\n"+ f"{i} per_token_entropy = _unsloth_dpo_entropy\n"+ f"{i}else:\n"+ f"{i} {m.group(0).lstrip()}"+ ),+ new,+ )++ def _ref_forward(m):+ i, model, kw = m.group("i"), m.group("model"), m.group("kw")+ return (+ f"{i}_unsloth_dpo_ref = (\n"+ f'{i} _unsloth_dpo_chunked_head(self, {model}, inputs, "_compute_loss") if _unsloth_dpo_hidden else None\n'+ f"{i})\n"+ f"{i}ref_outputs = _unsloth_dpo_forward({model}, {kw}, _unsloth_dpo_ref is not None)\n"+ f"{i}_unsloth_dpo_ref_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_ref, ref_outputs.logits)\n"+ )++ new = _DPO_CL_REF_FORWARD.sub(_ref_forward, new)+ new = _sub(+ _DPO_CL_REF_LOGPS,+ lambda i, m: (+ f"{i}if _unsloth_dpo_ref_hidden:\n"+ f"{i} ref_per_token_logps = _unsloth_dpo_loss_stats(\n"+ f"{i} self, _unsloth_dpo_ref, ref_shift_logits, shift_labels, shift_completion_mask, ref = True\n"+ f"{i} )\n"+ f"{i}else:\n" + textwrap.indent(m.group(0)[len(i) :], i + " ")+ ),+ new,+ )+ # TRL's argmax ties go to the first index, as does is_top1; -1 is never a token id.+ new = _sub(+ _DPO_CL_ARGMAX,+ lambda i, m: (+ f"{i}if _unsloth_dpo_hidden:\n"+ f"{i} predictions = torch.where(\n"+ f"{i} _unsloth_dpo_top1[: len(_unsloth_dpo_top1) // 2], shift_labels[: len(shift_labels) // 2], -1\n"+ f"{i} )\n"+ f"{i}else:\n"+ f"{i} {m.group(0).lstrip()}"+ ),+ new,+ )+ # The sft term: mean NLL of the chosen completion tokens, from the log-probs already computed.+ new = new.replace(+ _DPO_CL_SFT,+ "(\n"+ " -per_token_logps[: len(per_token_logps) // 2][chosen_mask.bool()].mean()\n"+ " if _unsloth_dpo_hidden\n"+ f" else {_DPO_CL_SFT}\n"+ " )",+ 1,+ )+ return new+++RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_compute_loss_chunked)+for _dpo_item in (+ _unsloth_get_model_config,+ _unsloth_text_configs,+ _unsloth_get_final_logit_softcapping,+ _unsloth_resolve_logit_scales,+ _unsloth_grpo_returns_hidden_states,+ _unsloth_grpo_hidden_states_signal,+ _unsloth_pref_returns_hidden_states,+ _unsloth_gkd_dense_head,+ _unsloth_gkd_logit_transforms,+ _unsloth_pref_logit_transforms,+ _unsloth_stock_logps_hook,+ _unsloth_dpo_chunked_head,+ _unsloth_dpo_model_forward,+ _unsloth_dpo_returns_hidden_states,+ _unsloth_dpo_hidden_logps,+ _unsloth_dpo_nll,+ _unsloth_dpo_forward,+ _unsloth_dpo_loss_head,+ _unsloth_dpo_loss_stats,+):+ RL_PRE_ITEMS["dpo_trainer"].append(inspect.getsource(_dpo_item))+RL_PRE_ITEMS["dpo_trainer"].append(+ "try:\n"+ " from unsloth_zoo.device_map_planner import detect_logit_transforms\n"+ "except Exception:\n"+ " detect_logit_transforms = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.chunked_logprob import (\n"+ " unsloth_masked_logprobs as _unsloth_masked_logprobs,\n"+ " )\n"+ "except Exception:\n"+ " _unsloth_masked_logprobs = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.fused_linear import (\n"+ " fused_linear_logprobs as _unsloth_fused_linear_logprobs,\n"+ " )\n"+ "except Exception:\n"+ " _unsloth_fused_linear_logprobs = None\n"+ f"_DPO_VISION_KEYS = {tuple(_DPO_VISION_KEYS)!r}\n"+)+++# KTO (TRL < 1.10, forward + get_batch_logps): the policy pass, the only one that keeps its logits for backward.+try:+ from unsloth_zoo.fused_losses.chunked_logprob import (+ unsloth_chunked_logprobs as _unsloth_chunked_logprobs,+ )+except Exception:+ _unsloth_chunked_logprobs = None+++def _unsloth_kto_hidden_logps(self, chunked, hidden_states, labels, label_pad_token_id):+ """``(completion_logps [B], logits stand-in [B, S, 1])`` for TRL's ``get_batch_logps(logits, labels,+ average_log_prob=False)``. The stand-in holds each position's vocab sum of the logits, so the+ ``logits/chosen_sum`` metrics (a sum over every position) stay exact."""+ _, head, (multiply, divide, softcap) = chunked+ # The model may truncate input_ids (see kto_trainer_get_batch_logps): score the common length.+ n = min(hidden_states.shape[1], labels.shape[1])+ out_device = hidden_states.device+ hidden_states = hidden_states[:, :n]+ labels = labels[:, :n].to(head.weight.device)+ shifted = labels[:, 1:]+ mask = shifted != label_pad_token_id+ if _unsloth_masked_logprobs is not None and _unsloth_linear_mean_logits is not None:+ # Only completion tokens reach the head; the logits/* sums come from the head's affine mean (no backward).+ hidden_states = hidden_states.to(head.weight.device)+ per_token_logps = _unsloth_masked_logprobs(+ hidden_states[:, :-1],+ head.weight,+ shifted,+ mask = mask,+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ lm_head_bias = head.bias,+ )+ mean_logits = _unsloth_linear_mean_logits(+ hidden_states, head.weight, head.bias, multiply, divide, softcap+ )+ else:+ index = torch.cat(+ (shifted.masked_fill(~mask, 0), shifted.new_zeros(shifted.shape[0], 1)), dim = 1+ )+ per_token_logps, mean_logits = _unsloth_chunked_logprobs(+ hidden_states.to(head.weight.device),+ head.weight,+ index,+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ lm_head_bias = head.bias,+ return_mean_logits = True,+ )+ per_token_logps = per_token_logps[:, :-1]+ try:+ self._unsloth_dpo_chunked_calls = getattr(self, "_unsloth_dpo_chunked_calls", 0) + 1+ except Exception:+ pass+ completion_logps = (per_token_logps * mask).sum(-1)+ logits_sum = (mean_logits * head.weight.shape[0]).unsqueeze(-1)+ return completion_logps.to(out_device), logits_sum.to(out_device)+++_KTO_FORWARD = re.compile(+ r"^(?P<indent>[ \t]+)outputs = model\(\n"+ r"[ \t]+batch\[\"completion_input_ids\"\],\n"+ r"[ \t]+attention_mask=batch\[\"completion_attention_mask\"\],\n"+ r"[ \t]+\*\*model_kwargs,\n"+ r"[ \t]+\)\n"+ r"[ \t]+completion_logits = outputs\.logits\n",+ re.MULTILINE,+)+_KTO_LOGPS = re.compile(+ r"^(?P<indent>[ \t]+)completion_logps = self\.get_batch_logps\(\n"+ r"[ \t]+completion_logits,\n"+ r"[ \t]+batch\[\"completion_labels\"\],\n"+ r"[ \t]+average_log_prob=False,\n"+ r"(?P<rest>(?:[ \t]+(?:is_encoder_decoder=self\.is_encoder_decoder|label_pad_token_id=self\.label_pad_token_id),\n)*)"+ r"[ \t]+\)\n",+ re.MULTILINE,+)+++def kto_trainer_chunked_logprobs(function_name, function):+ """Score KTO's policy completions from hidden states. ``completion_logits`` is then the per-position vocab sum,+ which is all TRL reads from it (``logits/*_sum`` metrics). Untouched unless both anchors match once."""+ if function_name != "forward" or _unsloth_chunked_logprobs is None:+ return function+ if "_unsloth_dpo_hidden" in function or "def get_batch_logps" in function:+ return function+ forward = list(_KTO_FORWARD.finditer(function))+ logps = list(_KTO_LOGPS.finditer(function))+ if len(forward) != 1 or len(logps) != 1:+ return function+ # completion_logits may only be read where a [B, S, 1] stand-in is exact: row selection for the metrics.+ tail = function[logps[0].end() :]+ reads = re.findall(r"[^\n]*\bcompletion_logits\b[^\n]*", tail)+ if any(+ not re.search(r"completion_logits(\.index_select\(0, \w+\)|\[\w+, \.\.\.\]|\.device)", line)+ for line in reads+ ):+ return function+ pad = "self.label_pad_token_id" if "label_pad_token_id" in logps[0].group("rest") else "-100"+ ind = forward[0].group("indent")+ new_forward = (+ f'{ind}_unsloth_dpo_chunked = _unsloth_dpo_chunked_head(self, model, batch, "forward")\n'+ f"{ind}outputs = _unsloth_dpo_model_forward(\n"+ f'{ind} model, batch["completion_input_ids"],\n'+ f'{ind} dict(model_kwargs, attention_mask=batch["completion_attention_mask"]),\n'+ f"{ind} _unsloth_dpo_chunked is not None,\n"+ f"{ind})\n"+ f"{ind}completion_logits = outputs.logits\n"+ f"{ind}_unsloth_dpo_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_chunked, completion_logits)\n"+ )+ ind2 = logps[0].group("indent")+ original_logps = textwrap.indent(textwrap.dedent(logps[0].group(0)), ind2 + " ")+ new_logps = (+ f"{ind2}if _unsloth_dpo_hidden:\n"+ f"{ind2} completion_logps, completion_logits = _unsloth_kto_hidden_logps(\n"+ f'{ind2} self, _unsloth_dpo_chunked, completion_logits, batch["completion_labels"], {pad}\n'+ f"{ind2} )\n"+ f"{ind2}else:\n"+ f"{original_logps}"+ )+ out = (+ function[: forward[0].start()] + new_forward + function[forward[0].end() : logps[0].start()]+ )+ return out + new_logps + function[logps[0].end() :]+++RL_FUNCTIONS["kto_trainer"].append(kto_trainer_chunked_logprobs)+++_KTO_KL = re.compile(+ r"^(?P<indent>[ \t]+)with torch\.no_grad\(\):\n"+ r"[ \t]+KL_logits = model\(\*\*KL_model_kwargs\)\.logits\n"+ r"\n?"+ r"(?P<logps>[ \t]+KL_logps = self\.get_batch_logps\(\n"+ r"[ \t]+KL_logits,\n"+ r"[ \t]+batch\[\"KL_completion_labels\"\],\n"+ r"[ \t]+average_log_prob=False,\n"+ r"(?P<rest>(?:[ \t]+(?:is_encoder_decoder=self\.is_encoder_decoder|label_pad_token_id=self\.label_pad_token_id),\n)*)"+ r"[ \t]+\)\n)",+ re.MULTILINE,+)+++def kto_trainer_chunked_kl_logps(function_name, function):+ """Score KTO's no-grad KL completions from hidden states too: TRL projects them to full ``[B, S, V]`` logits, the+ largest tensor of a KTO step once the policy pass is chunked. Untouched unless the anchor matches once."""+ if function_name != "_compute_kl_logps" or _unsloth_masked_logprobs is None:+ return function+ if "_unsloth_dpo_hidden" in function:+ return function+ matches = list(_KTO_KL.finditer(function))+ if len(matches) != 1:+ return function+ match = matches[0]+ ind = match.group("indent")+ pad = "self.label_pad_token_id" if "label_pad_token_id" in match.group("rest") else "-100"+ original_logps = textwrap.indent(textwrap.dedent(match.group("logps")), ind + " ")+ new = (+ f'{ind}_unsloth_dpo_chunked = _unsloth_dpo_chunked_head(self, model, batch, "_compute_kl_logps")\n'+ f"{ind}with torch.no_grad():\n"+ f"{ind} _unsloth_kl_outputs = _unsloth_dpo_model_forward(\n"+ f'{ind} model, KL_model_kwargs["input_ids"],\n'+ f'{ind} {{k: v for k, v in KL_model_kwargs.items() if k != "input_ids"}},\n'+ f"{ind} _unsloth_dpo_chunked is not None,\n"+ f"{ind} )\n"+ f"{ind} KL_logits = _unsloth_kl_outputs.logits\n"+ f"{ind} _unsloth_dpo_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_chunked, KL_logits)\n"+ f"{ind} if _unsloth_dpo_hidden:\n"+ f"{ind} KL_logps, _ = _unsloth_kto_hidden_logps(\n"+ f'{ind} self, _unsloth_dpo_chunked, KL_logits, batch["KL_completion_labels"], {pad}\n'+ f"{ind} )\n"+ f"{ind}if not _unsloth_dpo_hidden:\n"+ f"{original_logps}"+ )+ return function[: match.start()] + new + function[match.end() :]+++RL_FUNCTIONS["kto_trainer"].append(kto_trainer_chunked_kl_logps)+for _kto_item in (+ _unsloth_get_model_config,+ _unsloth_text_configs,+ _unsloth_get_final_logit_softcapping,+ _unsloth_resolve_logit_scales,+ _unsloth_grpo_returns_hidden_states,+ _unsloth_grpo_hidden_states_signal,+ _unsloth_pref_returns_hidden_states,+ _unsloth_gkd_dense_head,+ _unsloth_gkd_logit_transforms,+ _unsloth_pref_logit_transforms,+ _unsloth_stock_logps_hook,+ _unsloth_dpo_chunked_head,+ _unsloth_dpo_model_forward,+ _unsloth_dpo_returns_hidden_states,+ _unsloth_kto_hidden_logps,+):+ RL_PRE_ITEMS["kto_trainer"].append(inspect.getsource(_kto_item))+RL_PRE_ITEMS["kto_trainer"].append(+ "try:\n"+ " from unsloth_zoo.device_map_planner import detect_logit_transforms\n"+ "except Exception:\n"+ " detect_logit_transforms = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.chunked_logprob import (\n"+ " unsloth_chunked_logprobs as _unsloth_chunked_logprobs,\n"+ " unsloth_masked_logprobs as _unsloth_masked_logprobs,\n"+ " )\n"+ "except Exception:\n"+ " _unsloth_chunked_logprobs = _unsloth_masked_logprobs = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.preference_loss import linear_mean_logits as _unsloth_linear_mean_logits\n"+ "except Exception:\n"+ " _unsloth_linear_mean_logits = None\n"+ f"_DPO_VISION_KEYS = {tuple(_DPO_VISION_KEYS)!r}\n"+)+++# TRL 1.6 - 1.14 KTO and TRL 0.29 - 1.14 DPO ref log-probs: score from hidden states instead of [B, S, V] logits.+def _unsloth_fused_pass_head(self, model, inputs, return_outputs, method):+ """``_unsloth_dpo_chunked_head`` for a rewritten pass that also needs the fused linear op, keeps TRL's path for+ the kill switch, ``return_outputs`` (the caller reads ``outputs.logits``) and TRL's own liger / chunked head."""+ reason = None+ if _unsloth_fused_linear_logprobs is None:+ reason = "unsloth_zoo has no fused_linear_logprobs"+ elif os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ reason = "UNSLOTH_FUSED_LINEAR=0"+ elif return_outputs:+ reason = "return_outputs needs the logits"+ elif getattr(self, "use_liger_kernel", False):+ reason = "use_liger_kernel runs TRL's own chunked head"+ if reason is not None:+ try:+ fallbacks = self.__dict__.setdefault("_unsloth_dpo_chunked_fallbacks", {})+ fallbacks[reason] = fallbacks.get(reason, 0) + 1+ except Exception:+ pass+ return None+ return _unsloth_dpo_chunked_head(self, model, inputs, method)+++def _unsloth_fused_pass_logps(+ self,+ chunked,+ hidden_states,+ labels,+ mask,+ stats = False,+ grad = False,+):+ """TRL's ``selective_log_softmax(head(hidden_states), labels)`` with rows outside ``mask`` zeroed (TRL's+ ``row_mask`` or its ``logps[mask == 0] = 0.0``). ``stats`` also returns the entropy (no grad, as TRL computes it+ from detached logits) and the per-position vocab mean ``[.., 1]``: ``x[mask].mean(-1)`` on it is TRL's mean of+ the logits row. A shorter ``hidden_states`` (the model truncated input_ids) is scored over the common length and+ zero padded. Only the policy pass (``grad``) keeps a graph: TRL scores the reference / KL logits it built under+ no_grad, so a trainable head must get no gradient from them."""+ _, head, (multiply, divide, softcap) = chunked+ width = labels.shape[1]+ n = min(hidden_states.shape[1], width)+ with torch.set_grad_enabled(grad and torch.is_grad_enabled()):+ out = _unsloth_fused_linear_logprobs(+ hidden_states[:, :n],+ head.weight,+ labels[:, :n],+ bias = head.bias,+ mask = mask[:, :n].bool(),+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ return_entropy = stats,+ return_mean_logits = stats,+ entropy_requires_grad = False,+ )+ try:+ self._unsloth_dpo_chunked_calls = getattr(self, "_unsloth_dpo_chunked_calls", 0) + 1+ except Exception:+ pass+ out = out if isinstance(out, tuple) else (out,)+ out = tuple(torch.nn.functional.pad(x, (0, width - n)) if n != width else x for x in out)+ if not stats:+ return out[0].to(labels.device)+ logps, entropy, mean_logits = out+ return (+ logps.to(labels.device),+ entropy.to(labels.device),+ mean_logits.unsqueeze(-1).to(labels.device),+ )+++def _unsloth_fused_pass_vocab_sums(self, chunked, hidden_states):+ """``[B, S, 1]`` per-position vocab sums of ``head(hidden_states)`` (no grad): TRL 1.6 - 1.8 KTO logs+ ``logits.index_select(0, idx).nansum()``, a sum over every position and vocab entry, which this keeps exact."""+ _, head, (multiply, divide, softcap) = chunked+ with torch.no_grad():+ hidden_states = hidden_states.detach()+ _, mean_logits = _unsloth_fused_linear_logprobs(+ hidden_states,+ head.weight,+ torch.zeros(hidden_states.shape[:-1], dtype = torch.long, device = hidden_states.device),+ bias = head.bias,+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ return_mean_logits = True,+ )+ return (mean_logits * head.weight.shape[0]).unsqueeze(-1).to(hidden_states.device)+++_KTO_IDS = r'batch\["(?:KL_)?(?:completion_)?input_ids"\]\[:, 1:\](?:\.contiguous\(\))?'+_KTO_MASK = r'batch\["(?:KL_)?completion_mask"\]\[:, 1:\]'+_DPO_REF_IDS = r'(?:shift_labels|inputs\["input_ids"\]\[\.\.\., 1:\])'+_DPO_REF_MASK = r'(?:shift_completion_mask|inputs\["completion_mask"\]\[\.\.\., 1:\])'+++def _fused_pass_logps_re(ids, mask):+ # TRL 1.6 - 1.13: ``x = selective_log_softmax(logits, ids)`` then ``x[mask == 0] = 0.0``; 1.14: ``row_mask=``.+ return re.compile(+ r"^(?P<i>[ \t]*)(?P<lhs>(?P<out>\w+)(?:, (?P<out2>\w+))?) = "+ r"(?P<fn>selective_log_softmax(?:_and_entropy)?)\(\s*"+ r"(?P<logits>\w+),\s*(?P<ids>" + ids + r"),?\s*"+ r"(?P<ent>entropy_requires_grad=False,\s*)?"+ r"(?:row_mask=(?P<rm>" + mask + r"),?\s*)?\)\n"+ r"(?:(?P=i)(?P=out)\[(?P<zm>" + mask + r") == 0\] = 0\.0\n)?",+ re.MULTILINE,+ )+++_KTO_LOGPS_RE = _fused_pass_logps_re(_KTO_IDS, _KTO_MASK)+_DPO_REF_LOGPS_RE = _fused_pass_logps_re(_DPO_REF_IDS, _DPO_REF_MASK)+++def _fused_pass_logps_ok(m):+ """One mask, and a two-name target only for TRL 1.14's ``selective_log_softmax_and_entropy``."""+ if (m.group("rm") is None) == (m.group("zm") is None):+ return False+ both = m.group("fn") == "selective_log_softmax_and_entropy"+ return both == (m.group("out2") is not None) == (m.group("ent") is not None)+++def _fused_pass_mask(m):+ return m.group("rm") or m.group("zm")+++def _fused_pass_else(m):+ """TRL's original statement(s), one level deeper, as the ``else`` branch."""+ i = m.group("i")+ return f"{i}else:\n" + textwrap.indent(textwrap.dedent(m.group(0)), i + " ")+++def _fused_pass_reads_ok(text, name, allowed):+ """Every line of ``text`` that reads ``name`` matches one of ``allowed`` (anything else would see hidden states+ or a stand-in where TRL expects logits)."""+ for line in text.splitlines():+ if re.search(name, line) and not any(re.fullmatch(p, line.strip()) for p in allowed):+ return False+ return True+++_KTO_KL_INIT = re.compile(r"^(?P<i>[ \t]*)KL_logps = None\n", re.MULTILINE)+_KTO_KL_FORWARD = re.compile(+ r"^(?P<i>[ \t]*)KL_logits = model\(\*\*KL_model_kwargs\)\.logits\n", re.MULTILINE+)+_KTO_CL_MODE = re.compile(+ r'^(?P<i>[ \t]*)mode = "train" if self\.model\.training else "eval"\n', re.MULTILINE+)+_KTO_CL_FORWARD = re.compile(r"^(?P<i>[ \t]*)outputs = model\(\*\*model_kwargs\)\n", re.MULTILINE)+_KTO_CL_REF_FORWARD = re.compile(+ r"^(?P<i>[ \t]*)ref_outputs = (?P<model>self\.model|self\.ref_model)\(\*\*ref_model_kwargs\)\n",+ re.MULTILINE,+)+_KTO_CL_ENTROPY = re.compile(+ r"^(?P<i>[ \t]*)per_token_entropy = entropy_from_logits\(shift_logits\.detach\(\)\)\n",+ re.MULTILINE,+)+_KTO_CL_SUMS = "outputs.logits.index_select(0, "+++def _kto_rewrite_kl(function):+ if len(_KTO_KL_INIT.findall(function)) != 1 or len(_KTO_KL_FORWARD.findall(function)) != 1:+ return function+ logps = [m for m in _KTO_LOGPS_RE.finditer(function) if m.group("logits") == "shift_KL_logits"]+ if (+ len(logps) != 1+ or not _fused_pass_logps_ok(logps[0])+ or "KL_" not in _fused_pass_mask(logps[0])+ ):+ return function+ if logps[0].group("fn") != "selective_log_softmax" or "KL_" not in logps[0].group("ids"):+ return function+ rest = function[: logps[0].start()] + function[logps[0].end() :]+ if not _fused_pass_reads_ok(+ rest,+ r"\bshift_KL_logits\b",+ [r"shift_KL_logits = KL_logits\[:, :-1, :\](?:\.contiguous\(\))?"],+ ) or not _fused_pass_reads_ok(+ rest,+ r"\bKL_logits\b",+ [+ r"KL_logits = model\(\*\*KL_model_kwargs\)\.logits",+ r"shift_KL_logits = KL_logits\[:, :-1, :\](?:\.contiguous\(\))?",+ # TRL 1.9 - 1.13's liger branch builds real logits; the flag stays False there.+ r"KL_logits = KL_hidden_states @ lm_head\.weight\.t\(\)",+ r"KL_logits = KL_logits \+ lm_head\.bias",+ ],+ ):+ return function+ m = logps[0]+ i = m.group("i")+ new = (+ function[: m.start()]+ + f"{i}if _unsloth_kto_kl_hidden:\n"+ + f"{i} {m.group('out')} = _unsloth_fused_pass_logps(\n"+ + f"{i} self, _unsloth_kto_kl, {m.group('logits')}, {m.group('ids')}, {_fused_pass_mask(m)}\n"+ + f"{i} )\n"+ # TRL 1.6's shape gets the truncation clamp kto_trainer_align_completion_logps would have added.+ + _kto_ref_else(function, m)+ + function[m.end() :]+ )+ new = _KTO_KL_INIT.sub(+ lambda m: m.group(0) + f"{m.group('i')}_unsloth_kto_kl_hidden = False\n", new, count = 1+ )+ return _KTO_KL_FORWARD.sub(+ lambda m: (+ f'{m.group("i")}_unsloth_kto_kl = _unsloth_fused_pass_head(self, model, batch, False, "_compute_kl_logps")\n'+ f"{m.group('i')}KL_logits = _unsloth_dpo_forward(model, KL_model_kwargs, _unsloth_kto_kl is not None).logits\n"+ f"{m.group('i')}_unsloth_kto_kl_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_kto_kl, KL_logits)\n"+ ),+ new,+ count = 1,+ )+++def _kto_rewrite_loss(function):+ for pattern in (_KTO_CL_MODE, _KTO_CL_FORWARD):+ if len(pattern.findall(function)) != 1:+ return function+ ref_forwards = _KTO_CL_REF_FORWARD.findall(function)+ if not 1 <= len(ref_forwards) <= 2 or len({m[1] for m in ref_forwards}) != len(ref_forwards):+ return function+ matches = list(_KTO_LOGPS_RE.finditer(function))+ policy = [m for m in matches if m.group("logits") == "shift_logits"]+ ref = [m for m in matches if m.group("logits") == "ref_shift_logits"]+ if len(policy) != 1 or len(ref) != 1 or len(matches) != 2:+ return function+ policy, ref = policy[0], ref[0]+ if not (_fused_pass_logps_ok(policy) and _fused_pass_logps_ok(ref)) or ref.group("out2"):+ return function+ if any("KL_" in m.group(0) for m in (policy, ref)):+ return function+ # Which family: 1.14 (fused logps + entropy), 1.9 - 1.13 (entropy_from_logits), 1.6 - 1.8 (logits sums).+ fused_entropy = policy.group("out2") is not None+ entropy = len(_KTO_CL_ENTROPY.findall(function))+ sums = function.count(_KTO_CL_SUMS)+ stats = fused_entropy or entropy == 1+ # 1.8 has both: entropy_from_logits and the logits sums.+ if entropy > 1 or (fused_entropy and entropy) or (fused_entropy and sums) or sums not in (0, 2):+ return function+ if not stats and not sums:+ return function+ rest = function[: policy.start()] + function[policy.end() : ref.start()] + function[ref.end() :]+ shift_def = r"shift_logits = outputs\.logits\[:, :-1, :\](?:\.contiguous\(\))?"+ sliced = re.findall(+ r"^[ \t]*(\w+) = shift_logits\.detach\(\)\.index_select\(0, \w+\)\n", rest, re.MULTILINE+ )+ sliced += re.findall(+ r"^[ \t]*(\w+) = outputs\.logits\.index_select\(0, \w+\)\n", rest, re.MULTILINE+ )+ checks = [+ (+ r"(?<!ref_)\bshift_logits\b",+ [+ shift_def,+ r"per_token_entropy = entropy_from_logits\(shift_logits\.detach\(\)\)",+ r"\w+ = shift_logits\.detach\(\)\.index_select\(0, \w+\)",+ ],+ ),+ (+ r"(?<!ref_)\boutputs\.logits\b",+ [+ shift_def,+ r"device = outputs\.logits\.device",+ r"\w+ = outputs\.logits\.index_select\(0, \w+\)",+ ],+ ),+ (+ r"\bref_shift_logits\b",+ [r"ref_shift_logits = ref_outputs\.logits\[:, :-1, :\](?:\.contiguous\(\))?"],+ ),+ (+ r"\bref_outputs\.logits\b",+ [r"ref_shift_logits = ref_outputs\.logits\[:, :-1, :\](?:\.contiguous\(\))?"],+ ),+ ]+ # The sliced stand-ins are only read as TRL's masked row mean (1.9+) or the full sum (1.6 - 1.8).+ for name in sliced:+ checks.append(+ (+ rf"\b{name}\b",+ [+ rf"{name} = (?:shift_logits\.detach\(\)|outputs\.logits)\.index_select\(0, \w+\)",+ rf"\w+ = {name}\[\w+\.bool\(\)\]\.mean\(-1\)\.sum\(\)",+ rf"self\.accelerator\.gather_for_metrics\({name}\.nansum\(\)\)\.nansum\(\)\.item\(\) / \w+",+ ],+ )+ )+ if len(sliced) != 2 or any(not _fused_pass_reads_ok(rest, n, allowed) for n, allowed in checks):+ return function+ i = policy.group("i")+ policy_new = f"{i}if _unsloth_kto_hidden:\n"+ if sums:+ policy_new += f"{i} _unsloth_kto_sums = _unsloth_fused_pass_vocab_sums(self, _unsloth_kto_chunked, outputs.logits)\n"+ if stats:+ entropy_name = policy.group("out2") or "_unsloth_kto_entropy"+ policy_new += (+ f"{i} {policy.group('out')}, {entropy_name}, shift_logits = _unsloth_fused_pass_logps(\n"+ f"{i} self, _unsloth_kto_chunked, shift_logits, {policy.group('ids')}, {_fused_pass_mask(policy)},\n"+ f"{i} stats = True, grad = True,\n"+ f"{i} )\n"+ )+ else:+ policy_new += (+ f"{i} {policy.group('out')} = _unsloth_fused_pass_logps(\n"+ f"{i} self, _unsloth_kto_chunked, shift_logits, {policy.group('ids')}, {_fused_pass_mask(policy)},\n"+ f"{i} grad = True,\n"+ f"{i} )\n"+ )+ j = ref.group("i")+ ref_new = (+ f"{j}if _unsloth_kto_ref_hidden:\n"+ f"{j} {ref.group('out')} = _unsloth_fused_pass_logps(\n"+ f"{j} self, _unsloth_kto_ref, ref_shift_logits, {ref.group('ids')}, {_fused_pass_mask(ref)}\n"+ f"{j} )\n"+ )+ new = (+ function[: policy.start()]+ + policy_new+ + _fused_pass_else(policy)+ + function[policy.end() : ref.start()]+ + ref_new+ + _fused_pass_else(ref)+ + function[ref.end() :]+ )+ new = _KTO_CL_MODE.sub(+ lambda m: m.group(0)+ + f"{m.group('i')}_unsloth_kto_hidden = _unsloth_kto_ref_hidden = False\n",+ new,+ count = 1,+ )+ new = _KTO_CL_FORWARD.sub(+ lambda m: (+ f'{m.group("i")}_unsloth_kto_chunked = _unsloth_fused_pass_head(self, model, inputs, return_outputs, "_compute_loss")\n'+ f"{m.group('i')}outputs = _unsloth_dpo_forward(model, model_kwargs, _unsloth_kto_chunked is not None)\n"+ f"{m.group('i')}_unsloth_kto_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_kto_chunked, outputs.logits)\n"+ ),+ new,+ count = 1,+ )+ new = _KTO_CL_REF_FORWARD.sub(+ lambda m: (+ f'{m.group("i")}_unsloth_kto_ref = _unsloth_fused_pass_head(self, {m.group("model")}, inputs, False, "_compute_loss")\n'+ f"{m.group('i')}ref_outputs = _unsloth_dpo_forward({m.group('model')}, ref_model_kwargs, _unsloth_kto_ref is not None)\n"+ f"{m.group('i')}_unsloth_kto_ref_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_kto_ref, ref_outputs.logits)\n"+ ),+ new,+ )+ if entropy:+ new = _KTO_CL_ENTROPY.sub(+ lambda m: (+ f"{m.group('i')}if _unsloth_kto_hidden:\n"+ f"{m.group('i')} per_token_entropy = _unsloth_kto_entropy\n"+ f"{m.group('i')}else:\n"+ f"{m.group('i')} {m.group(0).lstrip()}"+ ),+ new,+ count = 1,+ )+ if sums:+ new = new.replace(+ _KTO_CL_SUMS,+ "(_unsloth_kto_sums if _unsloth_kto_hidden else outputs.logits).index_select(0, ",+ )+ return new+++def kto_trainer_compute_loss_chunked(function_name, function):+ """Rewrite TRL 1.6 - 1.14's KTO ``_compute_kl_logps`` (the no-grad KL pass, run for the policy and the+ reference) and ``_compute_loss`` (policy pass with entropy / ``logits/*`` metrics, and the inline reference+ pass) to score from hidden states with the fused linear op: same completion masks, same metrics, no+ ``[B, S, V]`` logits. Every anchor must match exactly once and every other reader of the logits must be one the+ rewrite keeps exact, else TRL's source is returned untouched; at run time ``_unsloth_fused_pass_head`` keeps+ TRL's path for the kill switch, ``return_outputs``, liger, aux loss, vision, FSDP / DeepSpeed, a non-dense head+ or a forward that ignored the hidden-states flag."""+ if _unsloth_fused_linear_logprobs is None or "_unsloth_kto_" in function:+ return function+ if function_name == "_compute_kl_logps":+ return _kto_rewrite_kl(function)+ if function_name == "_compute_loss":+ return _kto_rewrite_loss(function)+ return function+++_DPO_REF_FORWARD = re.compile(+ r"^(?P<i>[ \t]*)ref_outputs = (?P<model>self\.model|self\.ref_model|model)\(\*\*model_kwargs\)\n",+ re.MULTILINE,+)+_DPO_REF_SHIFT = r"ref_shift_logits = ref_outputs\.logits\[\.\.\., :-1, :\](?:\.contiguous\(\))?"+++def dpo_trainer_ref_log_probs_chunked(function_name, function):+ """Rewrite TRL 0.29 - 1.14's DPO ``compute_ref_log_probs`` (1.14: ``_compute_ref_log_probs``), the+ ``precompute_ref_log_probs`` pass, to score the reference completions from hidden states. Untouched unless the+ log-prob anchor matches once and the logits have no other reader; each forward picks its own head."""+ if function_name not in ("compute_ref_log_probs", "_compute_ref_log_probs"):+ return function+ if _unsloth_fused_linear_logprobs is None or "_unsloth_dpo_ref" in function:+ return function+ forwards = _DPO_REF_FORWARD.findall(function)+ logps = list(_DPO_REF_LOGPS_RE.finditer(function))+ if not 1 <= len(forwards) <= 3 or len(logps) != 1:+ return function+ m = logps[0]+ if not _fused_pass_logps_ok(m) or m.group("logits") != "ref_shift_logits" or m.group("out2"):+ return function+ rest = function[: m.start()] + function[m.end() :]+ if not _fused_pass_reads_ok(+ rest, r"\bref_shift_logits\b", [_DPO_REF_SHIFT]+ ) or not _fused_pass_reads_ok(rest, r"\bref_outputs\.logits\b", [_DPO_REF_SHIFT]):+ return function+ i = m.group("i")+ new = (+ function[: m.start()]+ + f"{i}if _unsloth_dpo_ref_hidden:\n"+ + f"{i} {m.group('out')} = _unsloth_fused_pass_logps(\n"+ + f"{i} self, _unsloth_dpo_ref, ref_shift_logits, {m.group('ids')}, {_fused_pass_mask(m)}\n"+ + f"{i} )\n"+ + _fused_pass_else(m)+ + function[m.end() :]+ )+ return _DPO_REF_FORWARD.sub(+ lambda f: (+ f'{f.group("i")}_unsloth_dpo_ref = _unsloth_fused_pass_head(self, {f.group("model")}, inputs, False, "{function_name}")\n'+ f"{f.group('i')}ref_outputs = _unsloth_dpo_forward({f.group('model')}, model_kwargs, _unsloth_dpo_ref is not None)\n"+ f"{f.group('i')}_unsloth_dpo_ref_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_dpo_ref, ref_outputs.logits)\n"+ ),+ new,+ )+++def _unsloth_kto_ref_chunked_forward(model, want_hidden_states, *args, **kwargs):+ """``model(*args, **kwargs)``, returning hidden states as ``.logits`` when ``want_hidden_states``."""+ if not want_hidden_states:+ return model(*args, **kwargs)+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ return model(*args, **kwargs)+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+++def _unsloth_kto_ref_batch_logps(self, chunked, hidden_states, labels, label_pad_token_id):+ """TRL < 1.6's ``get_batch_logps(logits, labels, average_log_prob=False)`` (decoder-only) from hidden states."""+ shifted = labels[:, 1:]+ mask = shifted != label_pad_token_id+ return _unsloth_fused_pass_logps(+ self, chunked, hidden_states[:, :-1], shifted.masked_fill(~mask, 0), mask+ ).sum(-1)+++_KTO_REF_NAMES = ("compute_reference_log_probs", "compute_ref_log_probs", "_compute_ref_log_probs")+_KTO_REF_LOGPS_RE = _fused_pass_logps_re(+ r'inputs\["(?:KL_)?(?:completion_)?input_ids"\]\[:, 1:\](?:\.contiguous\(\))?',+ r'inputs\["(?:KL_)?completion_mask"\]\[:, 1:\]',+)+# TRL < 1.6: completion_logps = self.get_batch_logps(completion_logits, padded_batch["completion_labels"], ...)+_KTO_REF_BATCH_LOGPS = re.compile(+ r"^(?P<i>[ \t]*)(?P<out>completion_logps|KL_logps) = self\.get_batch_logps\(\n"+ r"[ \t]+(?P<logits>completion_logits|KL_logits),\n"+ r"[ \t]+(?P<labels>padded_batch\[\"(?:KL_)?completion_labels\"\]),\n"+ r"[ \t]+average_log_prob=False,\n"+ r"(?P<rest>(?:[ \t]+(?:is_encoder_decoder=self\.is_encoder_decoder|label_pad_token_id=self\.label_pad_token_id),\n)*)"+ r"[ \t]+\)\n",+ re.MULTILINE,+)+_KTO_REF_ASSIGN = re.compile(+ r"^(?P<i>[ \t]*)(?P<lhs>completion_logits|KL_logits) = (?P<model>self\.model|self\.ref_model|model)\(",+ re.MULTILINE,+)+# A decoder-only forward: positional ids + keyword args, no nested calls (the encoder-decoder ones have ``.get(``).+_KTO_REF_FORWARD = re.compile(+ r"^(?P<i>[ \t]*)(?P<lhs>completion_logits|KL_logits) = (?P<model>self\.model|self\.ref_model|model)\("+ r"(?P<args>[^()]*)\)\.logits\n",+ re.MULTILINE,+)+_KTO_REF_BODY = re.compile(r"^(?P<def>[ \t]*def [^\n]*:\n)(?P<doc>[ \t]+\"\"\"[^\n]*\"\"\"\n)?")+++def _kto_ref_else(function, m):+ """TRL's statement as the ``else`` branch, in the form ``kto_trainer_align_completion_logps`` gives it today: TRL+ 1.6's ``shift_logits = ...contiguous()`` + statement get the truncation clamp (the shift line stays above the+ ``if``, shared by both branches), every other layout keeps TRL's text."""+ line_start = function.rfind("\n", 0, m.start() - 1) + 1+ pair = function[line_start : m.start()] + m.group(0)+ for regex, repl in ((_KTO_COMPLETION_RE, _kto_completion_repl), (_KTO_KL_RE, _kto_kl_repl)):+ clamped, n = regex.subn(repl, pair)+ if n == 1:+ i = m.group("i")+ body = clamped.split("\n", 1)[1]+ return f"{i}else:\n" + textwrap.indent(textwrap.dedent(body), i + " ")+ return _fused_pass_else(m)+++def kto_trainer_ref_log_probs_chunked(function_name, function):+ """Rewrite TRL 0.22 - 1.14's KTO reference log-prob precompute (``compute_reference_log_probs`` < 1.6,+ ``compute_ref_log_probs`` 1.6 - 1.13, ``_compute_ref_log_probs`` 1.14) to score the completion and KL batches+ from hidden states with the fused linear op instead of ``[B, S, V]`` logits. Every log-prob statement must match+ exactly once, every decoder-only forward must be one the rewrite understands and the logits may have no other+ reader, else TRL's source is returned untouched; each forward picks its own head at run time and keeps TRL's+ path for the kill switch, liger, encoder-decoder, vision, FSDP / DeepSpeed, a hooked or non-dense head or a+ forward that ignored the hidden-states flag. TRL >= 1.15 fuses the head itself (no match)."""+ if function_name not in _KTO_REF_NAMES or _unsloth_fused_linear_logprobs is None:+ return function+ if "_unsloth_kto_ref" in function:+ return function+ body = _KTO_REF_BODY.match(function)+ if body is None:+ return function+ batch_var = "padded_batch" if function_name == "compute_reference_log_probs" else "inputs"+ # Log-prob statements: exactly one for the completions and one for the KL completions.+ old_style = list(_KTO_REF_BATCH_LOGPS.finditer(function))+ new_style = list(_KTO_REF_LOGPS_RE.finditer(function))+ if old_style and new_style:+ return function+ logps = {}+ if old_style:+ if batch_var != "padded_batch":+ return function+ for m in old_style:+ key = "completion" if m.group("logits") == "completion_logits" else "KL"+ if (m.group("out") == "KL_logps") != (key == "KL") or ("KL_" in m.group("labels")) != (+ key == "KL"+ ):+ return function+ logps.setdefault(key, []).append(m)+ else:+ if batch_var != "inputs":+ return function+ for m in new_style:+ if (+ not _fused_pass_logps_ok(m)+ or m.group("out2")+ or m.group("fn") != "selective_log_softmax"+ ):+ return function+ key = {"shift_logits": "completion", "shift_KL_logits": "KL"}.get(m.group("logits"))+ if key is None or ("KL_" in m.group("ids")) != (key == "KL"):+ return function+ if ("KL_" in _fused_pass_mask(m)) != (key == "KL"):+ return function+ logps.setdefault(key, []).append(m)+ if sorted(logps) != ["KL", "completion"] or any(len(v) != 1 for v in logps.values()):+ return function+ # Forwards: every assignment of the logits is a decoder-only forward we rewrite or an encoder-decoder one+ # (refused at run time, so its flag stays False).+ forwards = list(_KTO_REF_FORWARD.finditer(function))+ starts = {m.start() for m in forwards}+ for m in _KTO_REF_ASSIGN.finditer(function):+ if m.start() in starts:+ continue+ call = function[m.end() : function.find(".logits", m.end())]+ if "decoder_input_ids" not in call:+ return function+ for lhs in ("completion_logits", "KL_logits"):+ if not any(f.group("lhs") == lhs for f in forwards):+ return function+ for f in forwards:+ args = f.group("args")+ if f"{batch_var}[" not in args or "**" in args:+ return function+ # The logits (hidden states once rewritten) may only reach the rewritten statements.+ matched = sorted((v[0] for v in logps.values()), key = lambda m: m.start())+ rest = function+ for m in reversed(matched):+ rest = rest[: m.start()] + rest[m.end() :]+ shift = (+ r"shift_(?:KL_)?logits = (?:completion_logits|KL_logits)\[:, :-1, :\](?:\.contiguous\(\))?"+ )+ assign = r"(?:completion_logits|KL_logits) = (?:self\.model|self\.ref_model|model)\(.*"+ if not _fused_pass_reads_ok(rest, r"\b(?:completion_logits|KL_logits)\b", [assign, shift]):+ return function+ if not _fused_pass_reads_ok(rest, r"\bshift_(?:KL_)?logits\b", [shift]):+ return function+ flag = {"completion": "_unsloth_kto_ref_hidden", "KL": "_unsloth_kto_ref_kl_hidden"}+ head = {"completion": "_unsloth_kto_ref", "KL": "_unsloth_kto_ref_kl"}+ new = function+ # Back to front, so earlier offsets stay valid.+ edits = [(m.start(), m.end(), "logps", m) for m in matched]+ edits += [(f.start(), f.end(), "forward", f) for f in forwards]+ for start, end, kind, m in sorted(edits, key = lambda e: e[0], reverse = True):+ i = m.group("i")+ if kind == "forward":+ key = "completion" if m.group("lhs") == "completion_logits" else "KL"+ model = m.group("model")+ args = " ".join(m.group("args").split()).rstrip(",")+ text = (+ f'{i}{head[key]} = _unsloth_fused_pass_head(self, {model}, {batch_var}, False, "{function_name}")\n'+ f"{i}{m.group('lhs')} = _unsloth_kto_ref_chunked_forward(\n"+ f"{i} {model}, {head[key]} is not None, {args}\n"+ f"{i}).logits\n"+ f"{i}{flag[key]} = _unsloth_dpo_returns_hidden_states(self, {head[key]}, {m.group('lhs')})\n"+ )+ elif old_style:+ key = "completion" if m.group("logits") == "completion_logits" else "KL"+ pad = "self.label_pad_token_id" if "label_pad_token_id" in m.group("rest") else "-100"+ text = (+ f"{i}if {flag[key]}:\n"+ f"{i} {m.group('out')} = _unsloth_kto_ref_batch_logps(\n"+ f"{i} self, {head[key]}, {m.group('logits')}, {m.group('labels')}, {pad}\n"+ f"{i} )\n"+ f"{i}else:\n" + textwrap.indent(textwrap.dedent(m.group(0)), i + " ")+ )+ else:+ key = "completion" if m.group("logits") == "shift_logits" else "KL"+ text = (+ f"{i}if {flag[key]}:\n"+ f"{i} {m.group('out')} = _unsloth_fused_pass_logps(\n"+ f"{i} self, {head[key]}, {m.group('logits')}, {m.group('ids')}, {_fused_pass_mask(m)}\n"+ f"{i} )\n" + _kto_ref_else(function, m)+ )+ new = new[:start] + text + new[end:]+ # Flags start False: a forward that is not rewritten (encoder-decoder) keeps TRL's statements.+ first = new[body.end() :].split("\n", 1)[0]+ indent = first[: len(first) - len(first.lstrip())]+ return (+ new[: body.end()]+ + f"{indent}_unsloth_kto_ref_hidden = _unsloth_kto_ref_kl_hidden = False\n"+ + new[body.end() :]+ )+++# Must precede kto_trainer_align_completion_logps, which would reshape TRL 1.6's KL statement first.+RL_FUNCTIONS["kto_trainer"].insert(+ RL_FUNCTIONS["kto_trainer"].index(kto_trainer_align_completion_logps),+ kto_trainer_compute_loss_chunked,+)+RL_FUNCTIONS["kto_trainer"].insert(+ RL_FUNCTIONS["kto_trainer"].index(kto_trainer_align_completion_logps),+ kto_trainer_ref_log_probs_chunked,+)+RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_ref_log_probs_chunked)+RL_PRE_ITEMS["kto_trainer"].append(inspect.getsource(_unsloth_kto_ref_chunked_forward))+RL_PRE_ITEMS["kto_trainer"].append(inspect.getsource(_unsloth_kto_ref_batch_logps))+for _fused_pass_item in (+ _unsloth_dpo_forward,+ _unsloth_fused_pass_head,+ _unsloth_fused_pass_logps,+ _unsloth_fused_pass_vocab_sums,+):+ RL_PRE_ITEMS["kto_trainer"].append(inspect.getsource(_fused_pass_item))+ if _fused_pass_item is not _unsloth_dpo_forward:+ RL_PRE_ITEMS["dpo_trainer"].append(inspect.getsource(_fused_pass_item))+RL_PRE_ITEMS["kto_trainer"].append(+ "try:\n"+ " from unsloth_zoo.fused_losses.fused_linear import (\n"+ " fused_linear_logprobs as _unsloth_fused_linear_logprobs,\n"+ " )\n"+ "except Exception:\n"+ " _unsloth_fused_linear_logprobs = None\n"+)diff --git a/unsloth/models/sentence_transformer.py b/unsloth/models/sentence_transformer.pyindex e3f90edf197..7a9a8e2d7a1 100644--- a/unsloth/models/sentence_transformer.py+++ b/unsloth/models/sentence_transformer.py@@ -2460,6 +2460,9 @@ class FastSentenceTransformer(FastModel):@staticmethoddef _apply_torch_compile(model, mode = "default"):"""Apply torch.compile to a SentenceTransformer model (with an accelerate unwrap_model bug workaround)."""+ if os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") == "1":+ print("Unsloth: UNSLOTH_COMPILE_DISABLE=1, so skipping torch.compile of the encoder.")+ return modelif getattr(model, "_unsloth_unpadding_installed", False):from ._sentence_transformer_unpadding import disable_sentence_transformer_unpaddingdisable_sentence_transformer_unpadding(model)@@ -2664,10 +2667,11 @@ class FastSentenceTransformer(FastModel):if config_kwargs and config is not None:kwargs["config"] = config- # Fast encoder path: native torch.compile for encoder models (6x speedup), bypassing Unsloth's auto-compiler, whose @torch.compiler.disable decorators error for encoders on torch 2.9+. Set UNSLOTH_COMPILE_DISABLE=1 for the old path.+ # Fast encoder path: native torch.compile for encoder models (6x speedup), bypassing Unsloth's auto-compiler, whose @torch.compiler.disable decorators error for encoders on torch 2.9+. UNSLOTH_COMPILE_DISABLE=1 keeps the path and skips only its torch.compile (_apply_torch_compile).is_encoder_model = model_type.lower() in FastSentenceTransformer.ENCODER_MODEL_TYPES- use_fast_encoder = os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") != "1"- if use_fast_encoder and is_encoder_model:+ # Only the fallback loader forwards load_in_8bit; UNSLOTH_COMPILE_DISABLE=1 kept 8-bit encoders there.+ keep_8bit = load_in_8bit and os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") == "1"+ if is_encoder_model and not keep_8bit:# torch.compile mode "default" is safest for PEFT/LoRA training; "reduce-overhead" uses CUDA Graphs, which are incompatible with PEFT.compile_mode = "default"