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
DPO, ORPO, CPO: opt-in fused preference loss (UNSLOTH_FUSED_PREFERENCE_LOSS=1) (#13870)
Daniel Han85d7482933ae
diff --git a/tests/test_fused_preference_loss.py b/tests/test_fused_preference_loss.pynew file mode 100644index 00000000000..8a06e716b09--- /dev/null+++ b/tests/test_fused_preference_loss.py@@ -0,0 +1,710 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""UNSLOTH_FUSED_PREFERENCE_LOSS=1 must reproduce TRL's DPO / ORPO / CPO exactly.++The fused path scores completions from the final hidden states through the output head in+row chunks (unsloth_zoo.fused_losses.preference_loss) instead of building batch x seq x vocab+logits. Each case runs TRL's own get_batch_loss_metrics twice on a tiny float64 Llama, once+through TRL's concatenated_forward and once through Unsloth's, and compares the loss, every+logged metric and the parameter gradients. TRL >= 0.29 DPO has no concatenated_forward, so+the DPO cases need TRL 0.22-0.28; ORPO / CPO keep theirs through the 1.x experimental copies.+"""++from __future__ import annotations++import contextlib+import importlib.util+import os+import pathlib+import sys+import types++import pytest+import torch++transformers = pytest.importorskip("transformers")+trl = pytest.importorskip("trl")++from transformers import LlamaConfig, LlamaForCausalLM+from transformers.modeling_outputs import CausalLMOutputWithPast++ROOT = pathlib.Path(__file__).resolve().parents[1]+++def _load(name, path):+ spec = importlib.util.spec_from_file_location(name, path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def _zoo_preference_loss():+ spec = importlib.util.find_spec("unsloth_zoo")+ if spec is None or not spec.submodule_search_locations:+ pytest.skip("unsloth_zoo not installed")+ path = (+ pathlib.Path(list(spec.submodule_search_locations)[0])+ / "fused_losses"+ / "preference_loss.py"+ )+ if not path.exists():+ pytest.skip("unsloth_zoo without fused_losses/preference_loss.py")+ return _load("_zoo_preference_loss_under_test", path)+++def dpo_module(monkeypatch):+ zoo = _zoo_preference_loss()+ module = _load("_unsloth_dpo_under_test", ROOT / "unsloth" / "models" / "dpo.py")+ monkeypatch.setattr(+ module, "_zoo_kernels", lambda: (zoo.fused_linear_token_logps, zoo.linear_mean_logits)+ )+ monkeypatch.setenv("UNSLOTH_FUSED_PREFERENCE_LOSS", "1")+ return module+++VOCAB, HIDDEN = 61, 16+++class HiddenStatesLlama(LlamaForCausalLM):+ """Honours UNSLOTH_RETURN_HIDDEN_STATES the way Unsloth's forwards do."""++ softcap = 0.0+ calls = 0+ hidden_calls = 0++ def forward(+ self,+ input_ids = None,+ attention_mask = None,+ position_ids = None,+ logits_to_keep = 0,+ use_cache = None,+ **kwargs,+ ):+ type(self).calls += 1+ hidden = self.model(+ input_ids = input_ids,+ attention_mask = attention_mask,+ position_ids = position_ids,+ use_cache = False,+ ).last_hidden_state+ if logits_to_keep:+ hidden = hidden[:, -logits_to_keep:]+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":+ type(self).hidden_calls += 1+ return CausalLMOutputWithPast(logits = hidden)+ logits = self.lm_head(hidden)+ if self.softcap:+ logits = self.softcap * torch.tanh(logits / self.softcap)+ return CausalLMOutputWithPast(logits = logits)+++def _model(+ seed,+ softcap = 0.0,+ bias = False,+ vocab = VOCAB,+ hidden = HIDDEN,+):+ torch.manual_seed(seed)+ config = LlamaConfig(+ vocab_size = vocab,+ hidden_size = hidden,+ intermediate_size = 32,+ num_hidden_layers = 2,+ num_attention_heads = 2,+ num_key_value_heads = 2,+ max_position_embeddings = 64,+ tie_word_embeddings = False,+ )+ model = HiddenStatesLlama(config).double()+ if bias:+ model.lm_head.bias = torch.nn.Parameter(torch.randn(vocab, dtype = torch.float64))+ with torch.no_grad():+ model.lm_head.weight.mul_(8.0)+ model.softcap = softcap+ return model+++class _Accelerator:+ device = torch.device("cpu")++ def unwrap_model(self, model):+ return model++ def gather_for_metrics(self, x):+ return x++ def gather(self, x):+ return x+++def _rows(gen, n, lo, hi, pad, left):+ lengths = torch.randint(lo, hi + 1, (n,), generator = gen)+ width = int(lengths.max())+ ids = torch.full((n, width), pad, dtype = torch.long)+ mask = torch.zeros((n, width), dtype = torch.long)+ for i, length in enumerate(lengths.tolist()):+ tokens = torch.randint(1, VOCAB, (length,), generator = gen)+ if left:+ ids[i, width - length :] = tokens+ mask[i, width - length :] = 1+ else:+ ids[i, :length] = tokens+ mask[i, :length] = 1+ return ids, mask+++PAD = 0+++def _dpo_batch(seed, n = 3):+ gen = torch.Generator().manual_seed(seed)+ prompt_ids, prompt_mask = _rows(gen, n, 2, 6, PAD, left = True)+ chosen_ids, chosen_mask = _rows(gen, n, 1, 7, PAD, left = False)+ rejected_ids, rejected_mask = _rows(gen, n, 1, 5, PAD, left = False)+ return {+ "prompt_input_ids": prompt_ids,+ "prompt_attention_mask": prompt_mask,+ "chosen_input_ids": chosen_ids,+ "chosen_attention_mask": chosen_mask,+ "rejected_input_ids": rejected_ids,+ "rejected_attention_mask": rejected_mask,+ }+++def _dpo_trainer(module, model, ref_model, fused, **overrides):+ from trl import DPOTrainer++ if not hasattr(DPOTrainer, "concatenated_forward"):+ pytest.skip("TRL >= 0.29 DPOTrainer has no concatenated_forward")++ class Stub:+ concatenated_inputs = staticmethod(DPOTrainer.concatenated_inputs)+ dpo_loss = DPOTrainer.dpo_loss+ get_batch_loss_metrics = DPOTrainer.get_batch_loss_metrics+ compute_ref_log_probs = DPOTrainer.compute_ref_log_probs+ null_ref_context = DPOTrainer.null_ref_context++ def concatenated_forward(+ self,+ model,+ batch,+ is_ref_model = False,+ ):+ if fused:+ out = module.unsloth_fused_dpo_concatenated_forward(+ self, model, batch, is_ref_model+ )+ assert out is not None, "fused path declined a supported case"+ return out+ return DPOTrainer.concatenated_forward(self, model, batch, is_ref_model = is_ref_model)++ trainer = Stub()+ loss_type = overrides.pop("loss_type", "sigmoid")+ if loss_type == "aot_pair" and "aot_unpaired" in __import__("inspect").getsource(+ DPOTrainer.dpo_loss+ ):+ loss_type = "aot_unpaired"+ trainer.__dict__.update(+ accelerator = _Accelerator(),+ model = model,+ ref_model = ref_model,+ is_encoder_decoder = False,+ aux_loss_enabled = False,+ is_peft_model = False,+ ref_adapter_name = None,+ _peft_has_been_casted_to_bf16 = False,+ padding_value = PAD,+ pad_token_id = PAD,+ label_pad_token_id = -100,+ max_length = None,+ truncation_mode = "keep_end",+ use_logits_to_keep = False,+ padding_free = False,+ loss_type = loss_type if isinstance(loss_type, list) else [loss_type],+ loss_weights = None,+ beta = 0.1,+ label_smoothing = 0.0,+ reference_free = False,+ f_divergence_type = "reverse_kl",+ f_divergence_params = {},+ use_weighting = False,+ )+ args = dict(+ use_liger_loss = False,+ use_liger_kernel = False,+ rpo_alpha = None,+ ld_alpha = None,+ discopop_tau = 0.05,+ )+ for key in list(overrides):+ if key in args:+ args[key] = overrides.pop(key)+ trainer.args = types.SimpleNamespace(**args)+ trainer.__dict__.update(overrides)+ return trainer+++def _run(trainer, model, batch):+ model.zero_grad(set_to_none = True)+ loss, metrics = trainer.get_batch_loss_metrics(model, dict(batch))+ loss.backward()+ grads = {n: p.grad.clone() for n, p in model.named_parameters() if p.grad is not None}+ return loss.detach(), metrics, grads+++def _assert_same(+ base,+ head,+ tol = 1e-9,+):+ (loss_b, metrics_b, grads_b), (loss_h, metrics_h, grads_h) = base, head+ assert torch.isfinite(loss_b)+ torch.testing.assert_close(loss_h, loss_b, rtol = tol, atol = tol)+ assert set(metrics_b) == set(metrics_h)+ for key in metrics_b:+ assert metrics_h[key] == pytest.approx(metrics_b[key], rel = tol, abs = tol), key+ assert set(grads_b) == set(grads_h)+ assert any(g.abs().sum() > 0 for g in grads_b.values())+ for name in grads_b:+ torch.testing.assert_close(grads_h[name], grads_b[name], rtol = tol, atol = tol, msg = name)+++DPO_CASES = [+ dict(),+ dict(loss_type = "ipo"),+ dict(loss_type = "hinge"),+ dict(loss_type = "sigmoid", label_smoothing = 0.1),+ dict(loss_type = "robust", label_smoothing = 0.1),+ dict(loss_type = "exo_pair", label_smoothing = 0.1),+ dict(loss_type = "nca_pair"),+ dict(loss_type = "sppo_hard"),+ dict(loss_type = "apo_zero"),+ dict(loss_type = "apo_down"),+ dict(loss_type = "aot"),+ dict(loss_type = "aot_pair"), # renamed aot_unpaired in TRL 0.28+ dict(loss_type = "discopop"),+ dict(loss_type = ["sigmoid", "sft"], loss_weights = [0.7, 0.3]),+ dict(rpo_alpha = 0.5),+ dict(ld_alpha = 0.5),+ dict(use_weighting = True),+ dict(beta = 2.0),+ dict(reference_free = True),+ dict(max_length = 7, truncation_mode = "keep_end"),+ dict(max_length = 7, truncation_mode = "keep_start"),+ dict(use_logits_to_keep = True),+ dict(padding_free = True),+ dict(softcap = 3.0),+ dict(bias = True),+]+++ "case", DPO_CASES, ids = lambda c: "-".join(f"{k}={v}" for k, v in c.items()) or "default"+)[email protected]("reference", ["ref_model", "precomputed"])+def test_dpo_matches_trl(dpo_module, monkeypatch, case, reference):+ case = dict(case)+ softcap = case.pop("softcap", 0.0)+ bias = case.pop("bias", False)+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, softcap))+ batch = _dpo_batch(seed = 3)+ results = []+ for fused in (False, True):+ model = _model(0, softcap, bias)+ ref_model = _model(1, softcap, bias)+ trainer = _dpo_trainer(dpo_module, model, ref_model, fused, **dict(case))+ run_batch = dict(batch)+ if reference == "precomputed":+ # TRL precompute_ref_log_probs stores these per row; reuse the reference pass of this arm.+ with torch.no_grad():+ ref_chosen, ref_rejected = trainer.compute_ref_log_probs(run_batch)+ run_batch["ref_chosen_logps"], run_batch["ref_rejected_logps"] = (+ ref_chosen,+ ref_rejected,+ )+ HiddenStatesLlama.hidden_calls = 0+ results.append(_run(trainer, model, run_batch))+ if fused:+ assert HiddenStatesLlama.hidden_calls >= 1, "fused path never ran"+ else:+ assert HiddenStatesLlama.hidden_calls == 0+ _assert_same(*results)+++def test_dpo_policy_equals_reference_gives_log2(dpo_module, monkeypatch):+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))+ model = _model(0)+ trainer = _dpo_trainer(dpo_module, model, _model(0), fused = True)+ loss, metrics = trainer.get_batch_loss_metrics(model, _dpo_batch(seed = 5))+ assert loss.item() == pytest.approx(+ torch.log(torch.tensor(2.0, dtype = torch.float64)).item(), abs = 1e-12+ )+ assert metrics["rewards/margins"] == pytest.approx(0.0, abs = 1e-12)+++def test_dpo_declines_vision_and_flag_off(dpo_module, monkeypatch):+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))+ model = _model(0)+ trainer = _dpo_trainer(dpo_module, model, _model(1), fused = True)+ batch = _dpo_batch(seed = 3)+ batch["pixel_values"] = torch.zeros(3, 1)+ assert dpo_module.unsloth_fused_dpo_concatenated_forward(trainer, model, batch) is None+ monkeypatch.setenv("UNSLOTH_FUSED_PREFERENCE_LOSS", "0")+ assert (+ dpo_module.unsloth_fused_dpo_concatenated_forward(trainer, model, _dpo_batch(seed = 3))+ is None+ )+++def test_dpo_falls_back_to_logits_when_forward_ignores_flag(dpo_module, monkeypatch):+ """A forward that ignores UNSLOTH_RETURN_HIDDEN_STATES still gets TRL's numbers."""+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))+ monkeypatch.setattr(+ HiddenStatesLlama,+ "forward",+ lambda self, *a, **k: LlamaForCausalLM.forward(+ self, *a, **{x: y for x, y in k.items() if x != "use_cache"}+ ),+ )+ batch = _dpo_batch(seed = 3)+ results = []+ for fused in (False, True):+ model = _model(0)+ trainer = _dpo_trainer(dpo_module, model, _model(1), fused)+ results.append(_run(trainer, model, batch))+ _assert_same(*results)+++def _orpo_batch(seed, n = 3):+ gen = torch.Generator().manual_seed(seed)+ batch = {}+ prompt_lengths = torch.randint(1, 5, (n,), generator = gen).tolist()+ prompts = [torch.randint(1, VOCAB, (p,), generator = gen) for p in prompt_lengths]+ for side, hi in (("chosen", 7), ("rejected", 5)):+ answers = [+ torch.randint(+ 1, VOCAB, (int(torch.randint(1, hi + 1, (1,), generator = gen)),), generator = gen+ )+ for _ in range(n)+ ]+ width = max(len(p) + len(a) for p, a in zip(prompts, answers))+ ids = torch.full((n, width), PAD, dtype = torch.long)+ mask = torch.zeros((n, width), dtype = torch.long)+ labels = torch.full((n, width), -100, dtype = torch.long)+ for i, (p, a) in enumerate(zip(prompts, answers)):+ row = torch.cat([p, a])+ ids[i, : len(row)] = row+ mask[i, : len(row)] = 1+ labels[i, len(p) : len(row)] = a+ batch[f"{side}_input_ids"], batch[f"{side}_attention_mask"], batch[f"{side}_labels"] = (+ ids,+ mask,+ labels,+ )+ return batch+++def _orpo_trainer(module, model, method, fused, **overrides):+ if method == "orpo":+ try:+ from trl import ORPOTrainer as Trainer+ except ImportError:+ from trl.experimental.orpo import ORPOTrainer as Trainer+ else:+ try:+ from trl import CPOTrainer as Trainer+ except ImportError:+ from trl.experimental.cpo import CPOTrainer as Trainer++ class Stub:+ concatenated_inputs = staticmethod(Trainer.concatenated_inputs)+ get_batch_logps = staticmethod(Trainer.get_batch_logps)+ get_batch_loss_metrics = Trainer.get_batch_loss_metrics++ def concatenated_forward(self, model, batch):+ if fused:+ out = module.unsloth_fused_orpo_concatenated_forward(+ self, model, batch, method = method+ )+ if out is not None:+ return out+ assert fused == "auto", "fused path declined a supported case"+ return Trainer.concatenated_forward(self, model, batch)++ if method == "orpo":+ Stub.odds_ratio_loss = Trainer.odds_ratio_loss+ else:+ Stub.cpo_loss = Trainer.cpo_loss+ trainer = Stub()+ trainer.__dict__.update(+ accelerator = _Accelerator(),+ is_encoder_decoder = False,+ aux_loss_enabled = False,+ padding_value = PAD,+ pad_token_id = PAD,+ label_pad_token_id = -100,+ beta = 0.1,+ loss_type = "sigmoid",+ cpo_alpha = 1.0,+ simpo_gamma = 0.5,+ label_smoothing = 0.0,+ alpha = 0.0,+ )+ trainer.__dict__.update(overrides)+ return trainer+++ORPO_CASES = [+ ("orpo", dict()),+ ("orpo", dict(beta = 1.0)),+ ("orpo", dict(softcap = 3.0)),+ ("cpo", dict()),+ ("cpo", dict(loss_type = "hinge")),+ ("cpo", dict(loss_type = "ipo")),+ ("cpo", dict(loss_type = "simpo", cpo_alpha = 0.0)),+ ("cpo", dict(loss_type = "simpo", cpo_alpha = 0.5, label_smoothing = 0.1)),+ ("cpo", dict(alpha = 0.3)),+ ("cpo", dict(bias = True)),+]++[email protected]("method, case", ORPO_CASES, ids = lambda c: str(c))+def test_orpo_cpo_match_trl(dpo_module, monkeypatch, method, case):+ case = dict(case)+ softcap = case.pop("softcap", 0.0)+ bias = case.pop("bias", False)+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, softcap))+ batch = _orpo_batch(seed = 4)+ results = []+ for fused in (False, True):+ model = _model(0, softcap, bias)+ trainer = _orpo_trainer(dpo_module, model, method, fused, **case)+ if method == "cpo" and case.get("alpha", 0.0) and not hasattr(type(trainer), "cpo_loss"):+ pytest.skip("CPO alpha needs TRL with AlphaPO")+ HiddenStatesLlama.hidden_calls = 0+ results.append(_run(trainer, model, batch))+ assert (HiddenStatesLlama.hidden_calls >= 1) == fused+ _assert_same(*results)+++def test_orpo_under_ddp_find_unused_falls_back(dpo_module, monkeypatch, tmp_path):+ """DDP(find_unused_parameters = True) would mark the trainable head ready twice."""+ import torch.distributed as dist+ from torch.nn.parallel import DistributedDataParallel++ if dist.is_initialized():+ pytest.skip("a process group is already initialised")+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))++ class Unwrapping(_Accelerator):+ def unwrap_model(self, model):+ return getattr(model, "module", model)++ batch = _orpo_batch(seed = 4)+ reference = _run(_orpo_trainer(dpo_module, _model(0), "orpo", False), _model(0), batch)+ dist.init_process_group(+ "gloo", init_method = f"file://{tmp_path / 'store'}", rank = 0, world_size = 1+ )+ try:+ for find_unused in (True, False):+ model = _model(0)+ ddp = DistributedDataParallel(model, find_unused_parameters = find_unused)+ trainer = _orpo_trainer(dpo_module, model, "orpo", "auto", accelerator = Unwrapping())+ HiddenStatesLlama.hidden_calls = 0+ model.zero_grad(set_to_none = True)+ loss, metrics, _ = _run(trainer, ddp, batch)+ grads = {n: p.grad.clone() for n, p in model.named_parameters() if p.grad is not None}+ assert (HiddenStatesLlama.hidden_calls >= 1) == (not find_unused)+ _assert_same(reference, (loss, metrics, grads))+ finally:+ dist.destroy_process_group()+++def test_orpo_under_compiled_ddp_find_unused_falls_back(dpo_module, monkeypatch, tmp_path):+ """Accelerate's dynamo integration wraps DDP in torch.compile, leaving it on _orig_mod."""+ import torch.distributed as dist+ from torch.nn.parallel import DistributedDataParallel++ if dist.is_initialized():+ pytest.skip("a process group is already initialised")+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))++ class Compiled(torch.nn.Module):+ def __init__(self, inner):+ super().__init__()+ self._orig_mod = inner++ def forward(self, *args, **kwargs):+ return self._orig_mod(*args, **kwargs)++ class Unwrapping(_Accelerator):+ def unwrap_model(self, model):+ return getattr(model, "_orig_mod", model).module++ batch = _orpo_batch(seed = 4)+ reference = _run(_orpo_trainer(dpo_module, _model(0), "orpo", False), _model(0), batch)+ dist.init_process_group(+ "gloo", init_method = f"file://{tmp_path / 'store'}", rank = 0, world_size = 1+ )+ try:+ for find_unused in (True, False):+ model = _model(0)+ compiled = Compiled(DistributedDataParallel(model, find_unused_parameters = find_unused))+ trainer = _orpo_trainer(dpo_module, model, "orpo", "auto", accelerator = Unwrapping())+ HiddenStatesLlama.hidden_calls = 0+ model.zero_grad(set_to_none = True)+ loss, metrics, _ = _run(trainer, compiled, batch)+ grads = {n: p.grad.clone() for n, p in model.named_parameters() if p.grad is not None}+ assert (HiddenStatesLlama.hidden_calls >= 1) == (not find_unused)+ _assert_same(reference, (loss, metrics, grads))+ finally:+ dist.destroy_process_group()+++def test_orpo_under_fsdp1_falls_back(dpo_module, monkeypatch, tmp_path):+ """FSDP1 reshards the head's parameter view after its forward, so the fused path must not read it."""+ import torch.distributed as dist++ if dist.is_initialized():+ pytest.skip("a process group is already initialised")+ try:+ from torch.distributed.fsdp import FullyShardedDataParallel+ except Exception:+ pytest.skip("no FSDP1")+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))++ class Unwrapping(_Accelerator):+ def unwrap_model(self, model):+ return getattr(model, "module", model)++ batch = _orpo_batch(seed = 4)+ dist.init_process_group(+ "gloo", init_method = f"file://{tmp_path / 'store'}", rank = 0, world_size = 1+ )+ try:+ model = _model(0)+ wrapped = FullyShardedDataParallel(+ model, device_id = torch.device("cpu"), use_orig_params = True+ )+ trainer = _orpo_trainer(dpo_module, model, "orpo", "auto", accelerator = Unwrapping())+ assert dpo_module._output_head(trainer, wrapped) == (None, None)+ HiddenStatesLlama.hidden_calls = 0+ loss = _run(trainer, wrapped, batch)[0]+ assert torch.isfinite(loss) and HiddenStatesLlama.hidden_calls == 0+ assert dpo_module._output_head(trainer, model)[1] is not None+ finally:+ dist.destroy_process_group()+++def _real_hidden_states_helpers():+ text = (ROOT / "unsloth" / "models" / "rl_replacements.py").read_text(encoding = "utf-8")+ start = text.index("def _unsloth_grpo_returns_hidden_states(")+ end = text.index("_GRPO_HIDDEN_STATES_WIDTH_DISPATCH = ")+ package = types.ModuleType("_fake_unsloth_models")+ package.__path__ = []+ helpers = types.ModuleType("_fake_unsloth_models.rl_replacements")+ exec(text[start:end], helpers.__dict__)+ return package, helpers++[email protected]("honours_flag", [False, True])+def test_square_head_needs_explicit_hidden_states_signal(dpo_module, monkeypatch, honours_flag):+ """vocab_size == hidden_size: logits look like hidden states, so only a marked forward is fused."""+ package, helpers = _real_hidden_states_helpers()+ monkeypatch.setitem(sys.modules, package.__name__, package)+ monkeypatch.setitem(sys.modules, helpers.__name__, helpers)+ monkeypatch.setattr(dpo_module, "__package__", package.__name__)+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))+ if honours_flag:+ monkeypatch.setattr(+ HiddenStatesLlama, "__UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__", True, raising = False+ )+ else:+ monkeypatch.setattr(+ HiddenStatesLlama,+ "forward",+ lambda self, *a, **k: LlamaForCausalLM.forward(+ self, *a, **{x: y for x, y in k.items() if x != "use_cache"}+ ),+ )+ batch = _orpo_batch(seed = 4)+ results = []+ for fused in (False, "auto"):+ model = _model(0, vocab = 64, hidden = 64)+ trainer = _orpo_trainer(dpo_module, model, "orpo", fused)+ HiddenStatesLlama.hidden_calls = 0+ results.append(_run(trainer, model, batch))+ assert (HiddenStatesLlama.hidden_calls >= 1) == (honours_flag and bool(fused))+ _assert_same(*results)+++def test_rl_replacement_injects_dispatch_only_when_enabled(monkeypatch):+ """The generated trainer is untouched unless the flag is set at patch time."""+ source = (+ " def concatenated_forward(\n"+ " self, model, batch, is_ref_model: bool = False\n"+ " ) -> dict:\n"+ ' """Doc."""\n'+ " num_examples = batch['prompt_input_ids'].shape[0]\n"+ " return num_examples\n"+ )+ rl_path = ROOT / "unsloth" / "models" / "rl_replacements.py"+ text = rl_path.read_text(encoding = "utf-8")+ start = text.index("def _insert_after_docstring(")+ end = text.index('RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_fused_preference_forward)')+ namespace = {"os": os, "re": __import__("re"), "textwrap": __import__("textwrap")}+ exec(text[start:end], namespace)+ monkeypatch.setenv("UNSLOTH_FUSED_PREFERENCE_LOSS", "0")+ assert (+ namespace["dpo_trainer_fused_preference_forward"]("concatenated_forward", source) == source+ )+ monkeypatch.setenv("UNSLOTH_FUSED_PREFERENCE_LOSS", "1")+ patched = namespace["dpo_trainer_fused_preference_forward"]("concatenated_forward", source)+ assert patched != source+ compile(__import__("textwrap").dedent(patched), "<patched>", "exec")+ lines = patched.split("\n")+ doc = lines.index(' """Doc."""')+ assert (+ lines[doc + 1]+ .strip()+ .startswith("from unsloth.models.dpo import unsloth_fused_dpo_concatenated_forward")+ )+ assert (+ namespace["dpo_trainer_fused_preference_forward"]("concatenated_inputs", source) == source+ )++[email protected]("kind", ["forward_hook", "pre_hook", "hf_hook", "subclass"])+def test_hooked_or_custom_head_falls_back(dpo_module, monkeypatch, kind):+ """The kernel reads the head's weight directly, so a head whose forward does more is left to TRL."""+ monkeypatch.setattr(dpo_module, "_logit_transforms", lambda unwrapped: (0.0, 0.0, 0.0))+ batch = _orpo_batch(seed = 4)+ model = _model(0)+ head = model.get_output_embeddings()+ if kind == "forward_hook":+ head.register_forward_hook(lambda m, i, o: o * 2)+ elif kind == "pre_hook":+ head.register_forward_pre_hook(lambda m, i: (i[0] * 2,))+ elif kind == "hf_hook":+ head._hf_hook = object()+ else:++ class Scaled(torch.nn.Linear):+ def forward(self, x):+ return super().forward(x) * 2++ head.__class__ = Scaled+ trainer = _orpo_trainer(dpo_module, model, "orpo", "auto")+ assert dpo_module._output_head(trainer, model) == (None, None)+ if kind == "hf_hook":+ return+ reference = _run(_orpo_trainer(dpo_module, model, "orpo", False), model, batch)+ model.zero_grad(set_to_none = True)+ HiddenStatesLlama.hidden_calls = 0+ loss, metrics, _ = _run(trainer, model, batch)+ assert HiddenStatesLlama.hidden_calls == 0+ torch.testing.assert_close(loss, reference[0])diff --git a/unsloth/models/dpo.py b/unsloth/models/dpo.pyindex d65a32ff5ee..37c8e825fc5 100644--- a/unsloth/models/dpo.py+++ b/unsloth/models/dpo.py@@ -12,8 +12,17 @@__all__ = ["PatchDPOTrainer","PatchKTOTrainer",+ "fused_preference_loss_enabled",+ "unsloth_fused_dpo_concatenated_forward",+ "unsloth_fused_orpo_concatenated_forward",]+import inspect+import os+import weakref++import torch+def PatchDPOTrainer():return@@ -21,3 +30,471 @@ def PatchDPOTrainer():def PatchKTOTrainer():return+++# Opt-in: UNSLOTH_FUSED_PREFERENCE_LOSS=1 scores DPO / ORPO / CPO completions from the+# final hidden states in row chunks (unsloth_zoo.fused_losses.preference_loss) instead of+# materialising batch x seq_len x vocab logits. Every helper below returns None when it+# cannot reproduce TRL's concatenated_forward semantics, and the caller then runs TRL's own.+_TEXT_ONLY_KEYS = frozenset(+ (+ "prompt_input_ids",+ "prompt_attention_mask",+ "completion_input_ids",+ "completion_attention_mask",+ )+)+_FLOAT_HEAD_DTYPES = (torch.float16, torch.bfloat16, torch.float32, torch.float64)+++def fused_preference_loss_enabled():+ return os.environ.get("UNSLOTH_FUSED_PREFERENCE_LOSS", "0") == "1"+++def _zoo_kernels():+ try:+ from unsloth_zoo.fused_losses.preference_loss import (+ fused_linear_token_logps,+ linear_mean_logits,+ )+ except Exception:+ return None+ return fused_linear_token_logps, linear_mean_logits+++def _wrappers(model):+ seen = 0+ while model is not None and seen < 4:+ yield model+ model = getattr(model, "_orig_mod", None)+ seen += 1+++def _uses_fsdp1(trainer, model):+ try:+ from torch.distributed.fsdp import FullyShardedDataParallel+ except Exception:+ return False+ cache = vars(trainer).setdefault("_unsloth_fsdp1_models", weakref.WeakKeyDictionary())+ if model not in cache:+ cache[model] = any(isinstance(m, FullyShardedDataParallel) for m in model.modules())+ return cache[model]+++def _output_head(trainer, model):+ # FSDP1 frees or reshards the unwrapped head's parameter view outside its own forward.+ if isinstance(model, torch.nn.Module) and _uses_fsdp1(trainer, model):+ return None, None+ try:+ unwrapped = trainer.accelerator.unwrap_model(model)+ except Exception:+ unwrapped = model+ get_head = getattr(unwrapped, "get_output_embeddings", None)+ if get_head is None:+ return None, None+ try:+ head = get_head()+ except Exception:+ return None, None+ # A LoRA / modules_to_save head computes more than weight @ h; leave it to its own forward.+ if head is None or hasattr(head, "base_layer") or hasattr(head, "modules_to_save"):+ return None, None+ # The kernel reads weight / bias directly: only a plain, unhooked nn.Linear is exactly F.linear(h, W, b).+ if (+ type(head) is not torch.nn.Linear+ or hasattr(head, "_hf_hook")+ or "forward" in vars(head)+ or head._forward_hooks+ or head._forward_pre_hooks+ ):+ return None, None+ weight = getattr(head, "weight", None)+ if not isinstance(weight, torch.Tensor) or weight.dim() != 2:+ return None, None+ if weight.dtype not in _FLOAT_HEAD_DTYPES or hasattr(weight, "quant_state"):+ return None, None+ if type(weight).__name__ == "DTensor":+ return None, None+ bias = getattr(head, "bias", None)+ bias = bias if isinstance(bias, torch.Tensor) else None+ # DDP(find_unused_parameters = True) marks a trainable head unused once model(...) returns,+ # so applying it afterwards makes backward mark it ready a second time and raise.+ # Accelerate's dynamo integration puts DDP under torch.compile's _orig_mod.+ ddp = next(+ (m for m in _wrappers(model) if isinstance(m, torch.nn.parallel.DistributedDataParallel)),+ None,+ )+ if ddp is not None and getattr(ddp, "find_unused_parameters", False):+ if any(p is not None and p.requires_grad for p in (weight, bias)):+ return None, None+ # vocab_size == hidden_size: the output width cannot tell hidden states from logits, so+ # only a forward that explicitly honours UNSLOTH_RETURN_HIDDEN_STATES is trusted.+ if weight.shape[0] == weight.shape[1]:+ try:+ from .rl_replacements import _unsloth_grpo_hidden_states_signal+ trusted = any(_unsloth_grpo_hidden_states_signal(m) is True for m in (model, unwrapped))+ except Exception:+ trusted = False+ if not trusted:+ return None, None+ return unwrapped, (weight, bias)+++def _logit_transforms(unwrapped):+ config = getattr(unwrapped, "config", None)+ try:+ from unsloth_zoo.device_map_planner import detect_logit_transforms+ found = detect_logit_transforms(config)+ return (+ float(found["logit_scale_multiply"] or 0.0),+ float(found["logit_scale_divide"] or 0.0),+ float(found["logit_softcapping"] or 0.0),+ )+ except Exception:+ pass+ try:+ from .rl_replacements import (+ _unsloth_get_final_logit_softcapping,+ _unsloth_resolve_logit_scales,+ )+ multiply, divide = _unsloth_resolve_logit_scales(config)+ softcap = _unsloth_get_final_logit_softcapping(unwrapped)+ except Exception:+ # Unknown transforms would score the wrong logits: let TRL's forward run instead.+ return None+ return float(multiply or 0.0), float(divide or 0.0), float(softcap or 0.0)+++def _forward_hidden_states(model, unwrapped, head_weight, args, kwargs):+ """Run the model with UNSLOTH_RETURN_HIDDEN_STATES=1; returns ``(tensor, is_hidden)``."""+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ outputs = model(*args, **kwargs)+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+ tensor = outputs.logits+ try:+ from .rl_replacements import _unsloth_grpo_returns_hidden_states+ is_hidden = _unsloth_grpo_returns_hidden_states(unwrapped, tensor, head_weight)+ except Exception:+ is_hidden = tensor.shape[-1] == head_weight.shape[1] != head_weight.shape[0]+ return tensor, bool(is_hidden)+++def _pad_value(trainer):+ # TRL <= 0.23 names it padding_value, later releases pad_token_id.+ if "pad_token_id" in vars(trainer):+ return trainer.pad_token_id+ return getattr(trainer, "padding_value", None)+++def _token_logps(+ hidden_or_logits,+ is_hidden,+ head,+ transforms,+ labels,+ mask,+ want_lssp = False,+):+ """Per-token logps (0 off ``mask``) plus the no-grad vocab-mean of the logits at each position."""+ fused_linear_token_logps, _ = _zoo_kernels()+ if is_hidden:+ out = fused_linear_token_logps(+ hidden_or_logits,+ head[0],+ head[1],+ labels,+ mask,+ logit_scale_multiply = transforms[0],+ logit_scale_divide = transforms[1],+ logit_softcapping = transforms[2],+ return_mean_logits = True,+ return_log_sum_sq_probs = want_lssp,+ )+ return out["per_token_logps"], out["mean_logits"], out.get("log_sum_sq_probs")+ # The forward ignored the flag and returned real logits: score them the way TRL does.+ from trl.trainer.utils import selective_log_softmax++ logits = hidden_or_logits+ per_token_logps = selective_log_softmax(logits, labels.masked_fill(~mask, 0))+ per_token_logps = per_token_logps.masked_fill(~mask, 0)+ with torch.no_grad():+ mean_logits = logits.mean(-1).masked_fill(~mask, 0)+ lssp = None+ if want_lssp:+ lssp = torch.logsumexp(2 * torch.log_softmax(logits, dim = -1), dim = -1)+ return per_token_logps, mean_logits, lssp+++def unsloth_fused_dpo_concatenated_forward(+ trainer,+ model,+ batch,+ is_ref_model = False,+):+ """TRL 0.22-0.28 ``DPOTrainer.concatenated_forward`` for text-only decoder models, scored+ from hidden states. Returns ``None`` (run TRL's own) whenever the inputs leave that case."""+ if not fused_preference_loss_enabled() or _zoo_kernels() is None:+ return None+ if getattr(trainer, "is_encoder_decoder", False) or getattr(trainer, "aux_loss_enabled", False):+ return None+ unwrapped, head = _output_head(trainer, model)+ if head is None:+ return None+ transforms = _logit_transforms(unwrapped)+ if transforms is None:+ return None+ from trl.trainer.utils import flush_left, flush_right++ num_examples = batch["prompt_input_ids"].shape[0]+ concatenated_batch = trainer.concatenated_inputs(batch, padding_value = _pad_value(trainer))+ if not set(concatenated_batch).issubset(_TEXT_ONLY_KEYS):+ return None++ model_kwargs = {"use_cache": False}+ prompt_input_ids = concatenated_batch["prompt_input_ids"]+ prompt_attention_mask = concatenated_batch["prompt_attention_mask"]+ completion_input_ids = concatenated_batch["completion_input_ids"]+ completion_attention_mask = concatenated_batch["completion_attention_mask"]+ input_ids = torch.cat((prompt_input_ids, completion_input_ids), dim = 1)+ attention_mask = torch.cat((prompt_attention_mask, completion_attention_mask), dim = 1)+ loss_mask = torch.cat(+ (torch.zeros_like(prompt_attention_mask), completion_attention_mask), dim = 1+ )++ max_length = trainer.max_length+ if max_length is not None and max_length < attention_mask.size(1):+ if trainer.truncation_mode == "keep_start":+ attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)+ attention_mask = attention_mask[:, :max_length]+ input_ids = input_ids[:, :max_length]+ loss_mask = loss_mask[:, :max_length]+ elif trainer.truncation_mode == "keep_end":+ attention_mask, input_ids, loss_mask = flush_right(attention_mask, input_ids, loss_mask)+ input_ids = input_ids[:, -max_length:]+ attention_mask = attention_mask[:, -max_length:]+ loss_mask = loss_mask[:, -max_length:]+ attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)+ else:+ return None+ else:+ attention_mask, input_ids, loss_mask = flush_left(attention_mask, input_ids, loss_mask)++ use_logits_to_keep = getattr(trainer, "use_logits_to_keep", False)+ if use_logits_to_keep:+ first_compute_index = loss_mask.nonzero(as_tuple = True)[1].min()+ logits_to_keep = (loss_mask.shape[1] - first_compute_index).item() + 1+ model_kwargs["logits_to_keep"] = logits_to_keep++ padding_free = getattr(trainer, "padding_free", False)+ if padding_free:+ input_ids = input_ids[attention_mask.bool()].unsqueeze(0)+ loss_mask = loss_mask[attention_mask.bool()].unsqueeze(0)+ position_ids = attention_mask.cumsum(1)[attention_mask.bool()].unsqueeze(0) - 1+ model_kwargs["position_ids"] = position_ids+ else:+ model_kwargs["attention_mask"] = attention_mask++ hidden, is_hidden = _forward_hidden_states(+ model, unwrapped, head[0], (input_ids,), model_kwargs+ )++ labels = torch.roll(input_ids, shifts = -1, dims = 1)+ loss_mask = torch.roll(loss_mask, shifts = -1, dims = 1).bool()+ if use_logits_to_keep:+ labels = labels[:, -logits_to_keep:]+ loss_mask = loss_mask[:, -logits_to_keep:]+ if hidden.shape[:2] != labels.shape[:2]:+ hidden = hidden[:, -labels.shape[1] :]++ labels[~loss_mask] = 0+ use_weighting = getattr(trainer, "use_weighting", False)+ per_token_logps, mean_logits, log_sum_sq_probs = _token_logps(+ hidden,+ is_hidden,+ head,+ transforms,+ labels,+ loss_mask,+ want_lssp = use_weighting,+ )+ del hidden+ unrolled_logps = per_token_logps+ per_token_logps = torch.roll(per_token_logps, shifts = 1, dims = 1)++ if padding_free:+ batch_size, seq_len = attention_mask.shape+ per_token_logps_ = per_token_logps.new_zeros(batch_size, seq_len)+ per_token_logps_[attention_mask.bool()] = per_token_logps+ per_token_logps = per_token_logps_++ all_logps = per_token_logps[:, 1:].sum(-1)+ output = {}+ args = trainer.args+ loss_type = trainer.loss_type++ if use_weighting:+ with torch.no_grad():+ per_token_logps_adjusted = per_token_logps - log_sum_sq_probs+ all_weights = (per_token_logps_adjusted * loss_mask).sum(-1) / loss_mask.sum(-1)+ chosen_weights = all_weights[:num_examples]+ rejected_weights = all_weights[num_examples:]+ output["policy_weights"] = torch.clamp(+ torch.exp(chosen_weights + rejected_weights), max = 1+ )++ if getattr(args, "rpo_alpha", None) is not None or "sft" in loss_type:+ # F.cross_entropy(chosen logits[:, :-1], labels[:, :-1], ignore_index = 0), mean over kept tokens.+ chosen_labels = labels[:num_examples, :-1]+ keep = chosen_labels != 0+ output["nll_loss"] = -(unrolled_logps[:num_examples, :-1] * keep).sum() / keep.sum()++ if "ipo" in loss_type:+ all_logps = all_logps / loss_mask.sum(-1)++ ld_alpha = getattr(args, "ld_alpha", None)+ if ld_alpha is not None and not is_ref_model:+ completion_lengths = loss_mask.sum(dim = 1)+ chosen_lengths = completion_lengths[:num_examples]+ rejected_lengths = completion_lengths[num_examples:]+ public_lengths = torch.min(chosen_lengths, rejected_lengths)+ public_lengths = torch.cat([public_lengths, public_lengths], dim = 0)+ seq_len = per_token_logps.size(1)+ position_ids = torch.arange(seq_len, device = per_token_logps.device).expand_as(+ per_token_logps+ )+ ld_mask = position_ids < public_lengths.unsqueeze(1)+ mask = position_ids < completion_lengths.unsqueeze(1)+ front_mask = (ld_mask & mask).float()+ rear_mask = (~ld_mask & mask).float()+ front_logps = (per_token_logps * front_mask).sum(dim = 1)+ rear_logps = (per_token_logps * rear_mask).sum(dim = 1)+ all_logps = front_logps + ld_alpha * rear_logps++ output["chosen_logps"] = all_logps[:num_examples]+ output["rejected_logps"] = all_logps[num_examples:]++ # logits[rows][loss_mask[rows]].mean() is the mean of the per-position vocab means.+ if padding_free:+ split_idx = (position_ids == 0).nonzero(as_tuple = True)[1][num_examples]+ chosen_sel = loss_mask[0, :split_idx]+ rejected_sel = loss_mask[0, split_idx:]+ mean_chosen_logits = mean_logits[0, :split_idx][chosen_sel].mean()+ mean_rejected_logits = mean_logits[0, split_idx:][rejected_sel].mean()+ else:+ mean_chosen_logits = mean_logits[:num_examples][loss_mask[:num_examples]].mean()+ mean_rejected_logits = mean_logits[num_examples:][loss_mask[num_examples:]].mean()+ output["mean_chosen_logits"] = mean_chosen_logits+ output["mean_rejected_logits"] = mean_rejected_logits+ return output+++def unsloth_fused_orpo_concatenated_forward(+ trainer,+ model,+ batch,+ method = "orpo",+):+ """TRL ``ORPOTrainer`` / ``CPOTrainer.concatenated_forward`` (0.22 through the 1.x+ experimental copies) for decoder-only models, scored from hidden states. ``None`` means+ run TRL's own."""+ if not fused_preference_loss_enabled() or _zoo_kernels() is None:+ return None+ if getattr(trainer, "is_encoder_decoder", False) or getattr(trainer, "aux_loss_enabled", False):+ return None+ label_pad_token_id = getattr(trainer, "label_pad_token_id", -100)+ # TRL's NLL is nn.CrossEntropyLoss(), which only ignores -100.+ if label_pad_token_id != -100:+ return None+ unwrapped, head = _output_head(trainer, model)+ if head is None:+ return None+ transforms = _logit_transforms(unwrapped)+ if transforms is None:+ return None++ params = inspect.signature(trainer.concatenated_inputs).parameters+ call_kwargs = {"is_encoder_decoder": False, "padding_value": _pad_value(trainer)}+ if "label_pad_token_id" in params:+ call_kwargs["label_pad_token_id"] = label_pad_token_id+ if "device" in params:+ call_kwargs["device"] = trainer.accelerator.device+ concatenated_batch = trainer.concatenated_inputs(batch, **call_kwargs)+ if set(concatenated_batch) - {+ "concatenated_input_ids",+ "concatenated_attention_mask",+ "concatenated_labels",+ }:+ return None+ len_chosen = batch["chosen_labels"].shape[0]+ input_ids = concatenated_batch["concatenated_input_ids"]+ attention_mask = concatenated_batch["concatenated_attention_mask"]+ concatenated_labels = concatenated_batch["concatenated_labels"]++ # Position t scores token t + 1. The NLL and the preference logps both read input_ids there.+ target_ids = input_ids[:, 1:]+ logps_mask = concatenated_labels[:, 1:] != label_pad_token_id+ if bool((concatenated_labels[:, 1:][logps_mask] != target_ids[logps_mask]).any()):+ return None+ if method == "orpo":+ nll_labels = torch.where(attention_mask == 1, input_ids, -100)[:, 1:]+ average_log_prob = True+ else:+ nll_labels = concatenated_labels[:, 1:]+ average_log_prob = trainer.loss_type in ["ipo", "simpo"]+ nll_mask = nll_labels != -100+ nll_mask[len_chosen:] = False+ need_nll = method == "orpo" or trainer.cpo_alpha != 0++ hidden, is_hidden = _forward_hidden_states(+ model,+ unwrapped,+ head[0],+ (input_ids,),+ {"attention_mask": attention_mask, "use_cache": False},+ )+ score_mask = logps_mask | nll_mask if need_nll else logps_mask+ per_token_logps, _, _ = _token_logps(+ hidden[:, :-1],+ is_hidden,+ head,+ transforms,+ target_ids,+ score_mask,+ )++ if need_nll:+ chosen_nll = nll_mask[:len_chosen]+ nll_loss = -(per_token_logps[:len_chosen] * chosen_nll).sum() / chosen_nll.sum()+ else:+ nll_loss = torch.tensor(0.0).to(trainer.accelerator.device)++ logps = (per_token_logps * logps_mask).sum(-1)+ if average_log_prob:+ logps = logps / logps_mask.sum(-1)+ chosen_logps = logps[:len_chosen]+ rejected_logps = logps[len_chosen:]++ # The trainers only log logits.detach().mean(); per-position vocab means average to the same value.+ if is_hidden:+ _, linear_mean_logits = _zoo_kernels()+ mean_logits = linear_mean_logits(+ hidden.detach(),+ head[0],+ head[1],+ logit_scale_multiply = transforms[0],+ logit_scale_divide = transforms[1],+ logit_softcapping = transforms[2],+ )+ else:+ mean_logits = hidden.detach().mean(-1)+ if method == "orpo":+ mean_logits = mean_logits[:, :-1]+ chosen_logits = mean_logits[:len_chosen]+ rejected_logits = mean_logits[len_chosen:]+ return (chosen_logps, rejected_logps, chosen_logits, rejected_logits, nll_loss)diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 3fa36dbfa68..569fbaa6aa2 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -470,6 +470,80 @@ RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_compute_loss_liger)RL_EXTRA_ARGS["dpo_trainer"].append(dpo_trainer_data_collator_vision_keys)+def _insert_after_docstring(function, lines):+ """Put ``lines`` (body-relative) first in the method body, after any docstring."""+ import ast++ try:+ node = ast.parse(textwrap.dedent(function)).body[0]+ except SyntaxError:+ return function+ if not isinstance(node, ast.FunctionDef) or not node.body:+ return function+ first = node.body[0]+ has_docstring = (+ isinstance(first, ast.Expr)+ and isinstance(getattr(first, "value", None), ast.Constant)+ and isinstance(first.value.value, str)+ )+ source_lines = function.split("\n")+ anchor = node.body[1] if has_docstring and len(node.body) > 1 else first+ indent = re.match(r"[ \t]*", source_lines[anchor.lineno - 1]).group(0)+ insert_at = first.end_lineno if has_docstring else first.lineno - 1+ block = [indent + line for line in lines]+ return "\n".join(source_lines[:insert_at] + block + source_lines[insert_at:])+++def _fused_preference_dispatch(function_name, function, call, signature):+ if function_name != "concatenated_forward" or signature not in function:+ return function+ if os.environ.get("UNSLOTH_FUSED_PREFERENCE_LOSS", "0") != "1":+ return function+ if "_unsloth_fused_output" in function:+ return function+ return _insert_after_docstring(+ function,+ [+ "from unsloth.models.dpo import " + call.split("(")[0],+ "_unsloth_fused_output = " + call,+ "if _unsloth_fused_output is not None:",+ " return _unsloth_fused_output",+ ],+ )+++def dpo_trainer_fused_preference_forward(function_name, function):+ return _fused_preference_dispatch(+ function_name,+ function,+ "unsloth_fused_dpo_concatenated_forward(self, model, batch, is_ref_model)",+ "is_ref_model",+ )+++def orpo_trainer_fused_preference_forward(function_name, function):+ return _fused_preference_dispatch(+ function_name,+ function,+ 'unsloth_fused_orpo_concatenated_forward(self, model, batch, method = "orpo")',+ "batch",+ )+++def cpo_trainer_fused_preference_forward(function_name, function):+ return _fused_preference_dispatch(+ function_name,+ function,+ 'unsloth_fused_orpo_concatenated_forward(self, model, batch, method = "cpo")',+ "batch",+ )+++RL_FUNCTIONS["dpo_trainer"].append(dpo_trainer_fused_preference_forward)+RL_FUNCTIONS["orpo_trainer"].append(orpo_trainer_fused_preference_forward)+RL_FUNCTIONS["cpo_trainer"].append(cpo_trainer_fused_preference_forward)++# Unsloth's training forward drops the 2D mask, so right-align Online DPO rows (GRPO's left_pack_padding) before scoring._ONLINE_DPO_MODEL_CALL = re.compile(r"^(?P<indent>[ \t]*)output = model\(prompt_completion_ids, "