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 PPO, RLOO, BCO, Online DPO, XPO, Nash-MD and GKD to the zoo fused linear kernels (#15244)
Daniel Han8fec28219290
diff --git a/tests/python/test_fused_linear_bco.py b/tests/python/test_fused_linear_bco.pynew file mode 100644index 00000000000..5fe0c9857ff--- /dev/null+++ b/tests/python/test_fused_linear_bco.py@@ -0,0 +1,287 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL 0.22 - 1.10 BCO ``forward`` (policy + reference pass) and ``compute_reference_log_probs`` (precompute pass)+scored from hidden states by unsloth_zoo's fused linear op: TRL's own BCOTrainer against one whose two methods went+through Unsloth's RL_FUNCTIONS chain, on a float64 tiny Qwen3 (loss, gradients, every logged metric, precomputed+reference log-probs), plus the kill switches."""++from __future__ import annotations++import ast+import copy+import importlib+import importlib.util+import inspect+import os+import re+import sys+import textwrap++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")++TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM"+_METHODS = ("forward", "compute_reference_log_probs")+_STOCK = {}+++def _bco_module():+ """TRL's real BCO module (0.22 - 0.25: trl.trainer, 0.26 - 1.10: trl.experimental), re-executed from its file:+ importing unsloth replaces the trainer class in TRL's own module with Unsloth's generated one."""+ pytest.importorskip("trl")+ import trl.import_utils as iu++ iu._mergekit_available = False+ for name in ("trl.experimental.bco.bco_trainer", "trl.trainer.bco_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 "class BCOTrainer" in text and "def compute_reference_log_probs" in text:+ if name not in _STOCK:+ importlib.import_module(name)+ fresh_spec = importlib.util.spec_from_file_location(name + "_stock", spec.origin)+ fresh = importlib.util.module_from_spec(fresh_spec)+ fresh.__package__ = name.rsplit(".", 1)[0]+ sys.modules[fresh_spec.name] = fresh+ fresh_spec.loader.exec_module(fresh)+ _STOCK[name] = (fresh, text)+ return _STOCK[name]+ pytest.skip(reason = "TRL >= 1.14 has no BCOTrainer")+++def _sources(text):+ out = {}+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == "BCOTrainer":+ 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 out+++def _patched_class(module, text):+ """BCOTrainer with ``forward`` / ``compute_reference_log_probs`` as unsloth/models/rl.py generates them: every+ RL_FUNCTIONS["bco_trainer"] edit, in a namespace holding RL_PRE_ITEMS["bco_trainer"]."""+ ns = dict(vars(module))+ ns.update(os = os, re = re, torch = torch, inspect = inspect, textwrap = textwrap)+ for item in rl.RL_PRE_ITEMS["bco_trainer"]:+ exec(compile(item, "<bco pre item>", "exec"), ns)+ body = {}+ for name, source in _sources(text).items():+ new = source+ for edit in rl.RL_FUNCTIONS["bco_trainer"]:+ new = edit(name, new)+ assert new != source, f"{name} was not rewritten"+ exec(compile(textwrap.dedent(new), f"<bco {name}>", "exec"), ns)+ body[name] = ns[name]+ return type("PatchedBCOTrainer", (module.BCOTrainer,), body)+++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(4 + i), "completion": text(6 + 3 * i), "label": i % 2 == 0}+ for i in range(4)+ ]+ )+++_MODELS = {}+++def _models(dtype):+ from transformers import AutoModelForCausalLM+ if dtype not in _MODELS:+ torch.manual_seed(0)+ ref = AutoModelForCausalLM.from_pretrained(TINY, torch_dtype = torch.float64)+ policy = copy.deepcopy(ref)+ with (+ torch.no_grad()+ ): # a policy that differs from the reference, so the rewards are not all zero+ for p in policy.parameters():+ p.add_(0.05 * torch.randn_like(p))+ _MODELS[dtype] = (policy.to(dtype), ref.to(dtype))+ return _MODELS[dtype]+++def _run(+ cls,+ module,+ dtype = torch.float64,+ precompute = False,+ honour = True,+):+ from transformers import AutoTokenizer++ policy, ref = (copy.deepcopy(m) for m in _models(dtype))+ for m in (policy, ref):+ if not hasattr(m, "warnings_issued"):+ m.warnings_issued = {}+ if honour:+ _honour_hidden_states(m)+ tok = AutoTokenizer.from_pretrained(TINY)+ cfg = module.BCOConfig(+ output_dir = "/tmp/_unsloth_bco_test",+ per_device_train_batch_size = 4,+ report_to = "none",+ use_cpu = True,+ max_length = 64,+ precompute_ref_log_probs = precompute,+ dataset_num_proc = None,+ bf16 = False,+ fp16 = False,+ )+ cfg.dataset_num_proc = None+ trainer = cls(+ model = policy, ref_model = ref, args = cfg, train_dataset = _dataset(), processing_class = tok+ )+ calls = fused_linear.CALLS["logprobs"]+ batch = next(iter(trainer.get_train_dataloader()))+ precompute_used = fused_linear.CALLS["logprobs"] - calls+ # TRL stores the precomputed log-probs as float32; score one batch directly for the unrounded values.+ direct = None+ if precompute:+ padded = {k: v for k, v in batch.items() if k != "reference_logps"}+ direct = trainer.compute_reference_log_probs(padded).double()+ calls = fused_linear.CALLS["logprobs"]+ loss, metrics = trainer.get_batch_loss_metrics(trainer.model, batch)+ loss.backward()+ used = fused_linear.CALLS["logprobs"] - calls+ grads = {+ n: p.grad.double().clone()+ for n, p in trainer.model.named_parameters()+ if p.grad is not None+ }+ ref_logps = batch.get("reference_logps")+ return dict(+ loss = loss.detach().double(),+ metrics = metrics,+ grads = grads,+ ref_logps = None if ref_logps is None else ref_logps.double(),+ direct = direct,+ used = used,+ precompute_used = precompute_used,+ trainer = trainer,+ )+++def _err(want, got):+ out = {"loss": (got["loss"] - want["loss"]).abs().item()}+ out["grad"] = max(+ ((got["grads"][n] - g).abs().max() / g.abs().max().clamp_min(1e-30)).item()+ for n, g in want["grads"].items()+ )+ out["metrics"] = max(+ abs(got["metrics"][k] - v) / max(abs(v), 1e-6) for k, v in want["metrics"].items()+ )+ if want["ref_logps"] is not None:+ out["ref_logps"] = (got["ref_logps"] - want["ref_logps"]).abs().max().item()+ out["direct_ref_logps"] = (got["direct"] - want["direct"]).abs().max().item()+ return out++[email protected]("precompute", [False, True])+def test_bco_matches_trl_fp64(precompute, monkeypatch):+ module, text = _bco_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ monkeypatch.delenv("UNSLOTH_PREFERENCE_CHUNKED", raising = False)+ want = _run(module.BCOTrainer, module, precompute = precompute)+ got = _run(_patched_class(module, text), module, precompute = precompute)+ # forward: policy + reference (the reference pass is skipped when precomputed); precompute: one per batch.+ assert got["used"] >= (1 if precompute else 2), got["used"]+ assert (got["precompute_used"] >= 1) == precompute, got["precompute_used"]+ assert want["used"] == want["precompute_used"] == 0+ assert getattr(got["trainer"], "_unsloth_dpo_chunked_calls", 0) >= 2+ assert set(got["metrics"]) == set(want["metrics"])+ assert set(got["grads"]) == set(want["grads"])+ err = _err(want, got)+ bf16 = _err(want, _run(module.BCOTrainer, module, dtype = torch.bfloat16, precompute = precompute))+ print(f"\nBCO precompute={precompute} fused fp64 err {err} | stock bf16 err {bf16}")+ assert err["loss"] <= 1e-5 and err["grad"] <= 1e-4 and err["metrics"] <= 1e-4, err+ if precompute:+ assert err["ref_logps"] <= 1e-4 and err["direct_ref_logps"] <= 1e-4, err+ for key in err:+ assert err[key] <= max(bf16[key], 1e-5), (key, err, bf16)++[email protected]("switch", ["UNSLOTH_FUSED_LINEAR", "UNSLOTH_PREFERENCE_CHUNKED"])+def test_bco_kill_switch_keeps_trl_path(switch, monkeypatch):+ module, text = _bco_module()+ monkeypatch.setenv(switch, "0")+ want = _run(module.BCOTrainer, module, precompute = True)+ got = _run(_patched_class(module, text), module, precompute = True)+ assert got["used"] == got["precompute_used"] == 0+ assert getattr(got["trainer"], "_unsloth_dpo_chunked_calls", 0) == 0+ torch.testing.assert_close(got["loss"], want["loss"], atol = 0, rtol = 0)+ torch.testing.assert_close(got["ref_logps"], want["ref_logps"], atol = 0, rtol = 0)+ torch.testing.assert_close(got["direct"], want["direct"], atol = 0, rtol = 0)+++def test_bco_forward_ignoring_the_flag_keeps_trl_math(monkeypatch):+ module, text = _bco_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ want = _run(module.BCOTrainer, module)+ got = _run(_patched_class(module, text), module, honour = False)+ assert got["used"] == 0+ torch.testing.assert_close(got["loss"], want["loss"], atol = 0, rtol = 0)+++def test_bco_rewrite_is_anchored_and_idempotent():+ _, text = _bco_module()+ for name, source in _sources(text).items():+ new = rl.bco_trainer_chunked_logprobs(name, source)+ assert new != source, name+ compile(textwrap.dedent(new), name, "exec")+ assert rl.bco_trainer_chunked_logprobs(name, new) == new, name+ # TRL's statement stays as the fallback branch.+ assert "self.get_batch_logps(" in new, name+ # A forward that reads the logits elsewhere (here: a mean) is left alone.+ forward = _sources(text)["forward"]+ broken = forward.replace(+ "chosen_logits = completion_logits[chosen_idx, ...]",+ "chosen_logits = completion_logits.mean(-1)",+ )+ assert broken != forward+ assert rl.bco_trainer_chunked_logprobs("forward", broken) == broken+ # A precompute pass whose logits get another reader is left alone.+ ref = _sources(text)["compute_reference_log_probs"]+ broken = ref.replace(+ " return completion_logps",+ " return completion_logps, completion_logits.mean()",+ )+ assert broken != ref+ assert rl.bco_trainer_chunked_logprobs("compute_reference_log_probs", broken) == brokendiff --git a/tests/python/test_fused_linear_online_dpo.py b/tests/python/test_fused_linear_online_dpo.pynew file mode 100644index 00000000000..18bd871d6bd--- /dev/null+++ b/tests/python/test_fused_linear_online_dpo.py@@ -0,0 +1,324 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL Online DPO ``_forward`` scored from hidden states by unsloth_zoo's fused linear op: TRL's own ``_forward``+(and Unsloth's right-align rewrite of it) against the full RL_FUNCTIONS["online_dpo_trainer"] chain on a float64+tiny Qwen3 (per-position log-probs, padding positions included, and their gradients), the kill switches, and the+paths that must keep TRL's math (vision inputs, a forward that ignores the flag)."""++from __future__ import annotations++import ast+import copy+import importlib+import importlib.util+import inspect+import os+import re+import textwrap++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")++TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM"+++def _odpo_module():+ """TRL's module defining ``OnlineDPOTrainer._forward`` (<= 0.25: trl.trainer, 0.26+: trl.experimental)."""+ pytest.importorskip("trl")+ import trl.import_utils as iu++ iu._mergekit_available = iu._llm_blender_available = (+ False # broken dist-info fails the trainer import (judges.py)+ )+ for name in (+ "trl.experimental.online_dpo.online_dpo_trainer",+ "trl.trainer.online_dpo_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 "class OnlineDPOTrainer" in text and "def _forward(" in text:+ return importlib.import_module(name), text+ pytest.skip(reason = "TRL has no OnlineDPOTrainer._forward")+++def _source(text):+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == "OnlineDPOTrainer":+ for fn in node.body:+ if isinstance(fn, ast.FunctionDef) and fn.name == "_forward":+ return ast.get_source_segment(text, fn, padded = True)+ raise AssertionError("no _forward")+++def _bind(module, source, edits):+ ns = dict(vars(module))+ ns.update(os = os, re = re, torch = torch, inspect = inspect, textwrap = textwrap)+ for item in rl.RL_PRE_ITEMS["online_dpo_trainer"]:+ exec(compile(item, "<online dpo pre item>", "exec"), ns)+ new = source+ for edit in edits:+ new = edit("_forward", new)+ exec(compile(textwrap.dedent(new), "<online dpo _forward>", "exec"), ns)+ return new, ns["_forward"]+++def _chain(full):+ edits = list(rl.RL_FUNCTIONS["online_dpo_trainer"])+ if not full:+ edits = [e for e in edits if e is not rl.online_dpo_trainer_chunked_logprobs]+ return edits+++class _Accelerator:+ device = torch.device("cpu")++ def unwrap_model(self, model):+ return model+++def _trainer(forward, ref_model = None):+ cls = type("T", (), {"_forward": forward})+ t = cls()+ t.max_length = 64+ t.accelerator = _Accelerator()+ t.ref_model = ref_model+ return t+++def _honour_hidden_states(model):+ 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+++_BASE = {}+++def _model(dtype = torch.float64, honour = True):+ from transformers import AutoModelForCausalLM++ if "m" not in _BASE:+ torch.manual_seed(0)+ _BASE["m"] = AutoModelForCausalLM.from_pretrained(TINY, torch_dtype = torch.float64)+ model = copy.deepcopy(_BASE["m"]).to(dtype)+ return _honour_hidden_states(model) if honour else model+++def _inputs(left_pad = True, vocab = 1000):+ g = torch.Generator().manual_seed(1)+ prompt_ids = torch.randint(5, vocab, (4, 7), generator = g)+ prompt_mask = torch.ones_like(prompt_ids)+ if left_pad:+ prompt_mask[1, :3] = 0+ prompt_mask[3, :1] = 0+ prompt_ids = prompt_ids.masked_fill(prompt_mask == 0, 0)+ completion_ids = torch.randint(5, vocab, (4, 9), generator = g)+ completion_mask = torch.ones_like(completion_ids)+ completion_mask[0, 6:] = 0+ completion_mask[2, 4:] = 0+ completion_ids = completion_ids.masked_fill(completion_mask == 0, 0)+ return prompt_ids, prompt_mask, completion_ids, completion_mask+++def _score(+ forward,+ model,+ inputs,+ grad = True,+):+ trainer = _trainer(forward)+ model.zero_grad(set_to_none = True)+ calls = fused_linear.CALLS["logprobs"]+ with torch.set_grad_enabled(grad):+ logps = forward(trainer, model, *inputs)+ used = fused_linear.CALLS["logprobs"] - calls+ grads = {}+ if grad:+ # A functional of every position, padding included (TRL's objective/kl and objective/entropy read them).+ w = torch.linspace(-1.0, 1.0, logps.numel(), dtype = torch.float64).view_as(logps)+ (logps.double() * w).sum().backward()+ grads = {+ n: p.grad.double().clone() for n, p in model.named_parameters() if p.grad is not None+ }+ return logps.detach().double(), grads, used, trainer+++def _max_err(want, got):+ lp = (got[0] - want[0]).abs().max().item()+ gr = max(+ ((got[1][n] - g).abs().max() / g.abs().max().clamp_min(1e-30)).item()+ for n, g in want[1].items()+ )+ return lp, gr++[email protected]("left_pad", [True, False])+def test_online_dpo_matches_unsloth_base_fp64(left_pad, monkeypatch):+ module, text = _odpo_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ monkeypatch.delenv("UNSLOTH_PREFERENCE_CHUNKED", raising = False)+ source = _source(text)+ _, base = _bind(module, source, _chain(False))+ new, head = _bind(module, source, _chain(True))+ assert "_unsloth_odpo_hidden_logps" in new+ inputs = _inputs(left_pad)+ want = _score(base, _model(), inputs)+ got = _score(head, _model(), inputs)+ assert want[2] == 0 and got[2] == 1+ assert set(got[1]) == set(want[1])+ lp, gr = _max_err(want, got)+ bf16 = _score(base, _model(torch.bfloat16), inputs)+ blp, bgr = _max_err(want, bf16)+ fused_bf16 = _score(head, _model(torch.bfloat16), inputs)+ flp, fgr = _max_err(want, fused_bf16)+ print(+ f"\nOnline DPO left_pad={left_pad}: fused fp64 logp {lp:.2e} grad {gr:.2e} | "+ f"stock bf16 logp {blp:.2e} grad {bgr:.2e} | fused bf16 logp {flp:.2e} grad {fgr:.2e}"+ )+ assert lp <= 1e-5 and gr <= 1e-4+ assert lp <= blp and gr <= bgr+ assert flp <= blp+++def test_online_dpo_matches_pure_trl_without_left_padding(monkeypatch):+ """No left padding: Unsloth's right-align is the identity, so the full chain must equal TRL's own text."""+ module, text = _odpo_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ source = _source(text)+ _, trl_forward = _bind(module, source, [])+ _, head = _bind(module, source, _chain(True))+ inputs = _inputs(left_pad = False)+ want = _score(trl_forward, _model(), inputs)+ got = _score(head, _model(), inputs)+ assert got[2] == 1+ lp, gr = _max_err(want, got)+ assert lp <= 1e-5 and gr <= 1e-4, (lp, gr)+++def test_online_dpo_reference_pass_keeps_no_graph(monkeypatch):+ module, text = _odpo_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ _, base = _bind(module, _source(text), _chain(False))+ _, head = _bind(module, _source(text), _chain(True))+ inputs = _inputs()+ want = _score(base, _model(), inputs, grad = False)+ got = _score(head, _model(), inputs, grad = False)+ assert got[2] == 1+ assert (got[0] - want[0]).abs().max().item() <= 1e-5++[email protected]("switch", ["UNSLOTH_FUSED_LINEAR", "UNSLOTH_PREFERENCE_CHUNKED"])+def test_online_dpo_kill_switch_keeps_unsloth_base(switch, monkeypatch):+ module, text = _odpo_module()+ monkeypatch.setenv(switch, "0")+ _, base = _bind(module, _source(text), _chain(False))+ _, head = _bind(module, _source(text), _chain(True))+ inputs = _inputs()+ want = _score(base, _model(), inputs)+ got = _score(head, _model(), inputs)+ assert got[2] == 0+ assert getattr(got[3], "_unsloth_dpo_chunked_calls", 0) == 0+ torch.testing.assert_close(got[0], want[0], atol = 0, rtol = 0)+++def test_online_dpo_forward_ignoring_the_flag_keeps_trl_math(monkeypatch):+ module, text = _odpo_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ _, base = _bind(module, _source(text), _chain(False))+ _, head = _bind(module, _source(text), _chain(True))+ inputs = _inputs()+ want = _score(base, _model(honour = False), inputs)+ got = _score(head, _model(honour = False), inputs)+ assert got[2] == 0+ assert "forward returned logits, not hidden states" in got[3]._unsloth_dpo_chunked_fallbacks+ torch.testing.assert_close(got[0], want[0], atol = 0, rtol = 0)+++def test_online_dpo_head_declines_vision_inputs(monkeypatch):+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ trainer = _trainer(None)+ model = _model()+ batch = {"attention_mask": torch.ones(1, 2), "pixel_values": torch.zeros(1)}+ assert rl._unsloth_odpo_chunked_head(trainer, model, batch, "_forward") is None+ assert (+ rl._unsloth_odpo_chunked_head(+ trainer, model, {"attention_mask": batch["attention_mask"]}, "_forward"+ )+ is not None+ )+++def test_online_dpo_rewrite_is_anchored_and_idempotent():+ _, text = _odpo_module()+ source = _source(text)+ for chain in ([rl.online_dpo_trainer__forward], []):+ start = source+ for edit in chain:+ start = edit("_forward", start)+ new = rl.online_dpo_trainer_chunked_logprobs("_forward", start)+ assert new != start+ compile(textwrap.dedent(new), "x", "exec")+ assert rl.online_dpo_trainer_chunked_logprobs("_forward", new) == new+ # Another reader of the logits (a temperature divide TRL might add) leaves the source untouched.+ broken = source.replace(+ "logprobs = torch.take_along_dim(logits.log_softmax(dim=-1)",+ "logits = logits / 0.7\n logprobs = torch.take_along_dim(logits.log_softmax(dim=-1)",+ )+ assert broken != source+ assert rl.online_dpo_trainer_chunked_logprobs("_forward", broken) == broken+++# TRL 0.22's ``_forward`` tail (no vision kwargs, ``start_idx:-1``), as the chain sees it.+_TRL_022_FORWARD = """+ def _forward(self, model, prompt_ids, prompt_mask, completion_ids, completion_mask):+ num_tokens_to_truncate = max(prompt_ids.size(1) + completion_ids.size(1) - self.max_length, 0)+ prompt_ids = prompt_ids[:, num_tokens_to_truncate:]+ prompt_mask = prompt_mask[:, num_tokens_to_truncate:]+ prompt_completion_ids = torch.cat((prompt_ids, completion_ids), dim=1)+ prompt_completion_mask = torch.cat((prompt_mask, completion_mask), dim=1)++ # Get the logprobs of the completions from the model+ output = model(prompt_completion_ids, attention_mask=prompt_completion_mask)++ # There is 1 offset, because the model predict the next token+ prompt_len = prompt_ids.size(1)+ start_idx = prompt_len - 1 if prompt_len > 0 else 0+ logits = output.logits[:, start_idx:-1]++ # Take the completion tokens logprob+ logprobs = torch.take_along_dim(logits.log_softmax(dim=-1), completion_ids.unsqueeze(-1), dim=2).squeeze(-1)+ return logprobs+"""+++def test_online_dpo_trl_022_layout(monkeypatch):+ module, _ = _odpo_module()+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ new, head = _bind(module, _TRL_022_FORWARD, _chain(True))+ assert "_unsloth_odpo_hidden_logps" in new and "_unsloth_left_pad" in new+ _, base = _bind(module, _TRL_022_FORWARD, _chain(False))+ inputs = _inputs()+ want = _score(base, _model(), inputs)+ got = _score(head, _model(), inputs)+ assert got[2] == 1+ lp, gr = _max_err(want, got)+ assert lp <= 1e-5 and gr <= 1e-4, (lp, gr)diff --git a/tests/python/test_fused_linear_xpo_nash_md.py b/tests/python/test_fused_linear_xpo_nash_md.pynew file mode 100644index 00000000000..ed606159ff0--- /dev/null+++ b/tests/python/test_fused_linear_xpo_nash_md.py@@ -0,0 +1,172 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""TRL 0.22 - 1.10 XPO / Nash-MD ``_compute_logprobs`` scored from hidden states by unsloth_zoo's fused linear op:+TRL's own method against the rewritten one on a float64 tiny Qwen3 (every returned log-prob tensor and the policy+gradients), plus the kill switch."""++from __future__ import annotations++import ast+import copy+import importlib+import importlib.util+import inspect+import os+import re+import textwrap++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")++TINY = "trl-internal-testing/tiny-Qwen3ForCausalLM"+_TRAINERS = {"xpo": "XPOTrainer", "nash_md": "NashMDTrainer"}+++def _module(kind):+ pytest.importorskip("trl")+ import trl.import_utils as iu++ iu._mergekit_available = iu._llm_blender_available = (+ False # broken dist-info fails the trainer import (judges.py)+ )+ 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()+ if f"class {_TRAINERS[kind]}" in text and "def _compute_logprobs(" in text:+ return importlib.import_module(name), text+ pytest.skip(reason = f"TRL >= 1.14 has no {_TRAINERS[kind]}")+++def _source(kind, text):+ for node in ast.walk(ast.parse(text)):+ if isinstance(node, ast.ClassDef) and node.name == _TRAINERS[kind]:+ for fn in node.body:+ if isinstance(fn, ast.FunctionDef) and fn.name == "_compute_logprobs":+ return ast.get_source_segment(text, fn, padded = True)+ raise AssertionError("no _compute_logprobs")+++def _bind(kind, rewrite):+ module, text = _module(kind)+ source = _source(kind, text)+ ns = dict(vars(module))+ ns.update(os = os, re = re, torch = torch, inspect = inspect, textwrap = textwrap)+ for item in rl.RL_PRE_ITEMS[f"{kind}_trainer"]:+ exec(compile(item, "<pre item>", "exec"), ns)+ new = source+ if rewrite:+ for edit in rl.RL_FUNCTIONS[f"{kind}_trainer"]:+ new = edit("_compute_logprobs", new)+ assert "_unsloth_odpo_hidden_logps" in new+ exec(compile(textwrap.dedent(new), f"<{kind} _compute_logprobs>", "exec"), ns)+ return ns["_compute_logprobs"]+++class _Accelerator:+ device = torch.device("cpu")++ def unwrap_model(self, model):+ return model+++def _honour_hidden_states(model):+ 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+++_BASE = {}+++def _models():+ from transformers import AutoModelForCausalLM+ if "m" not in _BASE:+ torch.manual_seed(0)+ ref = AutoModelForCausalLM.from_pretrained(TINY, torch_dtype = torch.float64)+ policy = copy.deepcopy(ref)+ with torch.no_grad():+ for p in policy.parameters():+ p.add_(0.05 * torch.randn_like(p))+ ref.requires_grad_(False)+ _BASE["m"] = (policy, ref)+ return tuple(_honour_hidden_states(copy.deepcopy(m)) for m in _BASE["m"])+++def _data(seed):+ g = torch.Generator().manual_seed(seed)+ ids = torch.randint(5, 1000, (3, 14), generator = g)+ mask = torch.ones_like(ids)+ mask[0, 11:] = 0 # completion padding+ mask[2, 8:] = 0+ ids = ids.masked_fill(mask == 0, 0)+ return {"input_ids": ids, "attention_mask": mask, "raw": ["p"] * 3}+++def _run(kind, fn):+ policy, ref = _models()+ trainer = type("T", (), {"_compute_logprobs": fn})()+ trainer.accelerator = _Accelerator()+ trainer.ref_model = ref+ args = (_data(1), _data(2)) if kind == "xpo" else (_data(1),)+ calls = fused_linear.CALLS["logprobs"]+ outs = fn(trainer, policy, *args, 6)+ used = fused_linear.CALLS["logprobs"] - calls+ total = sum((o.double() * (i + 1)).sum() for i, o in enumerate(outs) if o.requires_grad)+ total.backward()+ grads = {n: p.grad.clone() for n, p in policy.named_parameters() if p.grad is not None}+ return [o.detach().double() for o in outs], grads, used, [o.requires_grad for o in outs]++[email protected]("kind", ["xpo", "nash_md"])+def test_matches_trl_fp64(kind, monkeypatch):+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ monkeypatch.delenv("UNSLOTH_PREFERENCE_CHUNKED", raising = False)+ want = _run(kind, _bind(kind, False))+ got = _run(kind, _bind(kind, True))+ assert want[2] == 0 and got[2] == (4 if kind == "xpo" else 2)+ assert got[3] == want[3] # policy passes keep a graph, reference passes do not+ for a, b in zip(want[0], got[0]):+ assert (a - b).abs().max().item() <= 1e-5+ assert set(got[1]) == set(want[1])+ for n, g in want[1].items():+ assert ((got[1][n] - g).abs().max() / g.abs().max().clamp_min(1e-30)).item() <= 1e-4, n++[email protected]("kind", ["xpo", "nash_md"])+def test_kill_switch(kind, monkeypatch):+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ want = _run(kind, _bind(kind, False))+ got = _run(kind, _bind(kind, True))+ assert got[2] == 0+ for a, b in zip(want[0], got[0]):+ torch.testing.assert_close(a, b, atol = 0, rtol = 0)++[email protected]("kind", ["xpo", "nash_md"])+def test_rewrite_is_anchored_and_idempotent(kind):+ _, text = _module(kind)+ source = _source(kind, text)+ new = rl.xpo_trainer_chunked_logprobs("_compute_logprobs", source)+ assert new != source+ assert rl.xpo_trainer_chunked_logprobs("_compute_logprobs", new) == new+ broken = source.replace("return token_logprobs", "return token_logprobs, logits")+ assert rl.xpo_trainer_chunked_logprobs("_compute_logprobs", broken) == brokendiff --git a/tests/python/test_gkd_chunked_jsd.py b/tests/python/test_gkd_chunked_jsd.pyindex fa4756dd26c..da36d9731bd 100644--- a/tests/python/test_gkd_chunked_jsd.py+++ b/tests/python/test_gkd_chunked_jsd.py@@ -694,6 +694,8 @@ def test_fp16_grad_scaler_reaches_the_chunked_jsd(enabled, accepts_scaler, monkescaler = None if enabled is None else _Scaler(enabled)trainer.accelerator = types.SimpleNamespace(unwrap_model = lambda m: m, scaler = scaler)calls = []+ # The legacy zoo route (a zoo without fused_linear_jsd); the fused route has its own scaler test.+ monkeypatch.setattr(rl, "_unsloth_fused_linear_jsd", None)monkeypatch.setattr(rl, "distillation_chunked_jsd", _spy_jsd(calls, accepts_scaler))forwards = []student.register_forward_hook(lambda *a: forwards.append(1))diff --git a/tests/python/test_gkd_fused_linear_jsd.py b/tests/python/test_gkd_fused_linear_jsd.pynew file mode 100644index 00000000000..6affaa23445--- /dev/null+++ b/tests/python/test_gkd_fused_linear_jsd.py@@ -0,0 +1,202 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team.+"""GKD compute_loss reaches the zoo's fused two-head JSD op, matches TRL, and UNSLOTH_FUSED_LINEAR=0 restores TRL."""++from __future__ import annotations++import os+import types++import pytest+import torch++os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth.models.rl_replacements as rl++pytest.importorskip("trl")+try:+ from trl.experimental.gkd.gkd_trainer import GKDTrainer+except Exception:+ from trl.trainer.gkd_trainer import GKDTrainer++fl = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")+if not hasattr(fl, "fused_linear_jsd"):+ pytest.skip("installed unsloth_zoo predates fused_linear_jsd", allow_module_level = True)+++class _TinyLM(torch.nn.Module):+ """Honours UNSLOTH_RETURN_HIDDEN_STATES like Unsloth's compiled forwards."""++ __UNSLOTH_SUPPORTS_RETURN_HIDDEN_STATES__ = True++ def __init__(+ self,+ vocab,+ hidden,+ softcap,+ seed,+ bias = False,+ ):+ super().__init__()+ g = torch.Generator().manual_seed(seed)+ self.embed = torch.nn.Parameter(+ torch.randn(vocab, hidden, generator = g, dtype = torch.float64)+ )+ self.mix = torch.nn.Parameter(+ torch.randn(hidden, hidden, generator = g, dtype = torch.float64) / hidden**0.5+ )+ self.lm_head = torch.nn.Linear(hidden, vocab, bias = bias, dtype = torch.float64)+ with torch.no_grad():+ self.lm_head.weight.copy_(torch.randn(vocab, hidden, generator = g, dtype = torch.float64))+ self.config = types.SimpleNamespace(final_logit_softcapping = softcap, model_type = "tiny")++ def get_output_embeddings(self):+ return self.lm_head++ def forward(self, input_ids, attention_mask):+ hidden = torch.tanh(self.embed[input_ids] @ self.mix)+ if os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1":+ return types.SimpleNamespace(logits = hidden)+ logits = self.lm_head(hidden)+ if self.config.final_logit_softcapping:+ cap = self.config.final_logit_softcapping+ logits = cap * torch.tanh(logits / cap)+ return types.SimpleNamespace(logits = logits)+++def _trainer(+ beta,+ student,+ teacher,+ scaler = None,+):+ trainer = GKDTrainer.__new__(GKDTrainer)+ trainer.__dict__.update(+ beta = beta,+ temperature = 0.9,+ use_liger_gkd_loss = False,+ teacher_model = teacher,+ accelerator = types.SimpleNamespace(unwrap_model = lambda m: m, scaler = scaler),+ )+ return trainer+++def _inputs(vocab):+ g = torch.Generator().manual_seed(0)+ input_ids = torch.randint(0, vocab, (3, 21), generator = g)+ labels = input_ids.clone()+ labels[:, :7] = -100+ labels[1, 17:] = -100+ return {+ "input_ids": input_ids,+ "attention_mask": torch.ones_like(input_ids),+ "labels": labels,+ "prompts": input_ids[:, :7],+ }+++def _trl_reference(+ student,+ teacher,+ inputs,+ beta,+ shift,+ num_items = None,+):+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "0"+ try:+ s = student(inputs["input_ids"], inputs["attention_mask"]).logits+ with torch.no_grad():+ t = teacher(inputs["input_ids"], inputs["attention_mask"]).logits+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+ if shift == "prompt":+ s, t, labels = s[:, 6:-1], t[:, 6:-1], inputs["labels"][:, 7:]+ else:+ s, t, labels = s[:, :-1], t[:, :-1], inputs["labels"][:, 1:]+ want = GKDTrainer.generalized_jsd_loss(s, t, labels = labels, beta = beta)+ if num_items is not None:+ want = want * (labels != -100).sum() / num_items+ params = [p for p in student.parameters() if p.requires_grad]+ return want, torch.autograd.grad(want, params)++[email protected]("beta", [0.0, 0.5, 1.0])[email protected]("shift", ["prompt", "shift"])[email protected]("trainable_head", [False, True])+def test_gkd_reaches_fused_op_and_matches_trl(beta, shift, trainable_head, monkeypatch):+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR", raising = False)+ monkeypatch.setenv("UNSLOTH_GKD_CHUNK_SIZE", "8")+ vocab = 97+ student = _TinyLM(vocab, 16, 0.0, 1, bias = trainable_head)+ teacher = _TinyLM(vocab, 24, 5.0, 2)+ student.lm_head.requires_grad_(trainable_head)+ trainer, inputs = _trainer(beta, student, teacher), _inputs(vocab)+ num_items = torch.tensor(29) if shift == "shift" else None+ layout = {"shift": shift, "num_items_in_batch": shift == "shift"}+ want, want_grads = _trl_reference(student, teacher, inputs, beta, shift, num_items)++ before = fl.CALLS["jsd"]+ got = rl._unsloth_gkd_chunked_loss(trainer, student, inputs, num_items, layout)+ assert got is not None+ assert fl.CALLS["jsd"] == before + 1, "GKD did not reach the fused JSD op"+ assert trainer._unsloth_gkd_fused_calls == 1+ params = [p for p in student.parameters() if p.requires_grad]+ got_grads = torch.autograd.grad(got, params)+ torch.testing.assert_close(got.double(), want, rtol = 1e-6, atol = 1e-9)+ for g, w in zip(got_grads, want_grads):+ torch.testing.assert_close(g, w, rtol = 1e-6, atol = 1e-9)+++def test_kill_switch_restores_trl(monkeypatch):+ vocab = 97+ student, teacher = _TinyLM(vocab, 16, 0.0, 1), _TinyLM(vocab, 24, 0.0, 2)+ trainer, inputs = _trainer(0.5, student, teacher), _inputs(vocab)+ layout = {"shift": "shift", "num_items_in_batch": False}+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ before = fl.CALLS["jsd"]+ assert rl._unsloth_gkd_chunked_loss(trainer, student, inputs, None, layout) is None+ assert fl.CALLS["jsd"] == before+ assert trainer._unsloth_gkd_chunked_fallbacks == {"UNSLOTH_FUSED_LINEAR=0": 1}+ assert getattr(trainer, "_unsloth_gkd_fused_calls", 0) == 0++[email protected]("enabled", [True, False])+def test_grad_scaler_scale_reaches_the_op(enabled, monkeypatch):+ class Scaler:+ def is_enabled(self):+ return enabled++ def get_scale(self):+ return 65536.0++ calls = []+ real = rl._unsloth_fused_linear_jsd++ def spy(*args, **kwargs):+ calls.append(kwargs)+ return real(*args, **kwargs)++ monkeypatch.setattr(rl, "_unsloth_fused_linear_jsd", spy)+ vocab = 97+ student, teacher = _TinyLM(vocab, 16, 0.0, 1), _TinyLM(vocab, 24, 0.0, 2)+ trainer, inputs = _trainer(0.5, student, teacher, Scaler()), _inputs(vocab)+ got = rl._unsloth_gkd_chunked_loss(+ trainer, student, inputs, None, {"shift": "prompt", "num_items_in_batch": False}+ )+ assert got is not None and len(calls) == 1+ assert calls[0]["scaling"] == (65536.0 if enabled else None)+ want, want_grads = _trl_reference(student, teacher, inputs, 0.5, "prompt")+ grads = torch.autograd.grad(got, [student.embed, student.mix])+ for g, w in zip(grads, want_grads):+ torch.testing.assert_close(g, w, rtol = 1e-6, atol = 1e-9)+++def test_generated_items_import_the_fused_op():+ pre = "\n".join(rl.RL_PRE_ITEMS["gkd_trainer"])+ assert "fused_linear_jsd as _unsloth_fused_linear_jsd" in pre+ assert rl._unsloth_fused_linear_jsd is not Nonediff --git a/tests/test_ppo_fused_logprobs.py b/tests/test_ppo_fused_logprobs.pynew file mode 100644index 00000000000..14ce4eaafbd--- /dev/null+++ b/tests/test_ppo_fused_logprobs.py@@ -0,0 +1,328 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+"""PPOTrainer's rollout, reference and training log-probs (and entropy metric) scored from hidden states by the zoo+fused linear kernel; the value head keeps reading the critic backbone."""++from __future__ import annotations++import ast+import copy+import importlib+import os+from types import SimpleNamespace++import pytest++torch = pytest.importorskip("torch")+os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth # noqa: F401,E402+import unsloth.models.rl_replacements as rl # noqa: E402+from unsloth.models import _fused_rl_logprobs as frl # noqa: E402++fused_linear = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")+++def _ppo_module():+ for name in ("trl.trainer.ppo_trainer", "trl.experimental.ppo.ppo_trainer"):+ try:+ module = importlib.import_module(name)+ except Exception:+ continue+ if "class PPOTrainer" in open(module.__file__, encoding = "utf-8").read():+ return module+ pytest.skip("this TRL has no PPOTrainer")+++def _trl_train_source(module):+ text = open(module.__file__, encoding = "utf-8").read()+ cls = next(+ n for n in ast.parse(text).body if isinstance(n, ast.ClassDef) and n.name == "PPOTrainer"+ )+ fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == "train")+ return "\n".join(text.split("\n")[fn.lineno - 1 : fn.end_lineno]) + "\n"+++H, V, CL = 16, 40, 4+++class _Policy(torch.nn.Module):+ def __init__(+ self,+ dtype = torch.float64,+ honours_flag = True,+ ):+ super().__init__()+ from transformers import Qwen3Config++ self.config = Qwen3Config(hidden_size = H, vocab_size = V, num_hidden_layers = 1)+ gen = torch.Generator().manual_seed(0)+ self.embed = torch.nn.Embedding(V, H, dtype = dtype)+ self.embed.weight.data = torch.randn(V, H, generator = gen, dtype = dtype)+ self.mix = torch.nn.Linear(H, H, dtype = dtype)+ self.mix.weight.data = torch.randn(H, H, generator = gen, dtype = dtype) / H**0.5+ self.mix.bias.data = torch.zeros(H, dtype = dtype)+ self.lm_head = torch.nn.Linear(H, V, bias = False, dtype = dtype)+ self.lm_head.weight.data = torch.randn(V, H, generator = gen, dtype = dtype)+ self.honours_flag = honours_flag+ self.forwards = []++ def get_output_embeddings(self):+ return self.lm_head++ def forward(+ self,+ input_ids,+ attention_mask = None,+ **kwargs,+ ):+ h = torch.tanh(self.mix(self.embed(input_ids)))+ hidden = self.honours_flag and os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1"+ self.forwards.append("hidden" if hidden else "logits")+ return SimpleNamespace(logits = h if hidden else self.lm_head(h), hidden_states = (h,))++ def generate(+ self,+ input_ids,+ attention_mask,+ generation_config = None,+ return_dict_in_generate = False,+ output_scores = False,+ **kwargs,+ ):+ new = (input_ids[:, -1:] * 7 + torch.arange(1, 6)) % V+ out = SimpleNamespace(sequences = torch.cat([input_ids, new], 1))+ if output_scores:+ out.scores = [+ torch.randn(input_ids.shape[0], V, dtype = torch.float64) for _ in range(new.shape[1])+ ]+ return out+++class _Value(torch.nn.Module):+ base_model_prefix = "backbone"++ def __init__(self):+ super().__init__()+ self.backbone = _Policy()+ self.score = torch.nn.Linear(H, 1, dtype = torch.float64)+++def _wrapper(module, policy):+ value = _Value()++ class _Backbone(torch.nn.Module):+ def __init__(self, inner):+ super().__init__()+ self.inner = inner++ def forward(self, **kwargs):+ out = self.inner(**kwargs)+ return SimpleNamespace(hidden_states = out.hidden_states)++ value.backbone = _Backbone(value.backbone)+ policy.is_gradient_checkpointing = False+ return module.PolicyAndValueWrapper(policy, value)+++def _route(model):+ trainer = SimpleNamespace(+ model = model,+ accelerator = SimpleNamespace(unwrap_model = lambda m, **k: m),+ is_fsdp_enabled = False,+ is_deepspeed_enabled = False,+ )+ return frl.ppo_route(trainer), trainer+++def _query_responses(B = 3, L = 10):+ gen = torch.Generator().manual_seed(2)+ qr = torch.randint(1, V, (B, L), generator = gen)+ qr[0, 0] = 0 # left pad+ return qr+++def test_ppo_train_rewrite_applies_to_installed_trl():+ module = _ppo_module()+ source = _trl_train_source(module)+ new = rl.ppo_trainer_fused_logprobs("train", source)+ assert new != source, "PPO train rewrite did not apply to the installed TRL"+ ast.parse("class A:\n" + new)+ for needle in (+ "_unsloth_ppo_route = _unsloth_ppo_route_of(self)",+ "batch_generation if _unsloth_ppo_route is None else _unsloth_ppo_batch_generation",+ "logprob = _unsloth_ppo_policy_logprobs(",+ "ref_output = _unsloth_ppo_forward(",+ "output, vpred_temp = _unsloth_ppo_forward(",+ "new_logprobs, _unsloth_entropy = _unsloth_scored",+ "entropy = _unsloth_entropy",+ ):+ assert needle in new, needle+ for line in (+ "new_logprobs = selective_log_softmax(logits, mb_responses)",+ "ref_logprob = selective_log_softmax(ref_logits, response)",+ "logprob = selective_log_softmax(logits, response)",+ ):+ assert line in new+ assert rl.ppo_trainer_fused_logprobs("train", new) == new+ assert rl.ppo_trainer_fused_logprobs("generate_completions", source) == source+ drifted = source.replace(+ "new_logprobs = selective_log_softmax(logits, mb_responses)", "new_logprobs = f(logits)"+ )+ assert rl.ppo_trainer_fused_logprobs("train", drifted) == drifted+ assert rl.ppo_trainer_fused_logprobs in rl.RL_FUNCTIONS["ppo_trainer"]+++def _stock_train_logps(module, model, qr, T):+ output, vpred_temp = module.forward(model, qr, 0)+ logits = output.logits[:, CL - 1 : -1]+ logits /= T+ logps = module.selective_log_softmax(logits, qr[:, CL:])+ prob_dist = torch.nn.functional.softmax(logits, dim = -1)+ entropy = torch.logsumexp(logits, dim = -1) - torch.sum(prob_dist * logits, dim = -1)+ return logps, entropy.detach(), vpred_temp+++def _fused_train_logps(module, route, model, qr, T):+ output, vpred_temp = frl.ppo_forward(route, module.forward, model, qr, 0)+ out = frl.ppo_score(route, model, output.logits[:, CL - 1 : -1], qr[:, CL:], T, entropy = True)+ assert out is not None+ return out[0], out[1], vpred_temp+++def test_ppo_training_pass_matches_trl_fp64():+ module = _ppo_module()+ T = 0.7 + 1e-7+ model = _wrapper(module, _Policy())+ route, trainer = _route(model)+ assert route is not None+ qr = _query_responses()+ calls = fused_linear.CALLS["logprobs"]+ results = []+ for fn in (+ lambda: _fused_train_logps(module, route, model, qr, T),+ lambda: _stock_train_logps(module, model, qr, T),+ ):+ model.zero_grad()+ logps, ent, vpred = fn()+ adv = torch.linspace(-1, 1, logps.shape[1], dtype = torch.float64)+ ratio = torch.exp(logps - logps.detach())+ loss = (-adv * ratio).mean() + 0.1 * vpred.square().mean()+ loss.backward()+ grads = [+ p.grad.detach().clone()+ for p in (+ model.policy.mix.weight,+ model.policy.embed.weight,+ model.value_model.score.weight,+ )+ ]+ results.append((logps.detach(), ent, vpred.detach(), loss.detach(), grads))+ assert fused_linear.CALLS["logprobs"] > calls and trainer._unsloth_ppo_fused_calls == 1+ (a, b) = results+ for x, y in zip(a[:4], b[:4]):+ torch.testing.assert_close(x.double(), y.double(), atol = 1e-6, rtol = 1e-6)+ for x, y in zip(a[4], b[4]):+ torch.testing.assert_close(x.double(), y.double(), atol = 1e-6, rtol = 1e-5)+ assert not a[1].requires_grad+++def test_ppo_rollout_and_reference_logprobs_match_trl_fp64():+ module = _ppo_module()+ T = 0.9 + 1e-7+ policy = _Policy()+ model = _wrapper(module, policy)+ route, _ = _route(model)+ qr = _query_responses()+ with torch.no_grad():+ got = frl.ppo_policy_logprobs(+ route, module.forward, module.selective_log_softmax, model, qr, qr[:, CL:], CL, 0, T+ )+ logits = module.forward(policy, qr, 0).logits[:, CL - 1 : -1] / T+ want = module.selective_log_softmax(logits, qr[:, CL:])+ torch.testing.assert_close(got.double(), want.double(), atol = 1e-6, rtol = 1e-6)+ # A reference model whose forward ignores the flag: TRL's lines run on its real logits.+ ref = _Policy(honours_flag = False)+ out = frl.ppo_forward(route, module.forward, ref, qr, 0)+ assert frl.ppo_score(route, ref, out.logits[:, CL - 1 : -1], qr[:, CL:], T) is None+ got = frl.ppo_policy_logprobs(+ route, module.forward, module.selective_log_softmax, ref, qr, qr[:, CL:], CL, 0, T+ )+ want = module.selective_log_softmax(+ module.forward(ref, qr, 0).logits[:, CL - 1 : -1] / T, qr[:, CL:]+ )+ torch.testing.assert_close(got, want)+++def test_ppo_bf16_training_logps_error_not_worse_than_stock():+ module = _ppo_module()+ T = 0.7 + 1e-7+ exact = _wrapper(module, _Policy())+ qr = _query_responses()+ ref, _, _ = _stock_train_logps(module, exact, qr, T)+ low = copy.deepcopy(exact).to(torch.bfloat16)+ route, _ = _route(low)+ fused, _, _ = _fused_train_logps(module, route, low, qr, T)+ stock, _, _ = _stock_train_logps(module, low, qr, T)+ # Mean, not max: one bf16-rounded hidden row dominates a max either way.+ err_fused = (fused.double() - ref.double()).abs().mean()+ err_stock = (stock.double() - ref.double()).abs().mean()+ assert err_fused <= err_stock + 1e-6, (err_fused, err_stock)+++def test_ppo_generation_without_scores_matches_trl():+ module = _ppo_module()+ batch_generation = getattr(module, "batch_generation", None)+ if batch_generation is None:+ from trl.trainer.utils import batch_generation+ policy = _Policy()+ queries = _query_responses(B = 5, L = 4)+ want, logitss = batch_generation(policy, queries, 2, 0, None)+ got, none = frl.ppo_batch_generation(policy, queries, 2, 0, None)+ assert none is None and logitss.shape[-1] == V+ torch.testing.assert_close(got, want)+++def test_ppo_kill_switch_keeps_trl(monkeypatch):+ module = _ppo_module()+ model = _wrapper(module, _Policy())+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ route, trainer = _route(model)+ assert route is None+ assert trainer._unsloth_ppo_fused_fallbacks == {"UNSLOTH_FUSED_LINEAR=0": 1}+ calls = fused_linear.CALLS["logprobs"]+ model.policy.forwards.clear()+ output, _ = frl.ppo_forward(route, module.forward, model, _query_responses(), 0)+ assert output.logits.shape[-1] == V and model.policy.forwards == ["logits"]+ assert frl.ppo_score(route, model, output.logits, _query_responses(), 1.0) is None+ assert fused_linear.CALLS["logprobs"] == calls+++def test_ppo_reference_with_hooked_head_keeps_trl():+ module = _ppo_module()+ T = 0.9 + 1e-7+ route, trainer = _route(_wrapper(module, _Policy()))+ assert route is not None+ ref = _Policy()+ ref.lm_head.register_forward_hook(lambda *a: None)+ qr = _query_responses()+ with torch.no_grad():+ out = frl.ppo_forward(route, module.forward, ref, qr, 0)+ assert ref.forwards == ["logits"] and out.logits.shape[-1] == V+ assert frl.ppo_score(route, ref, out.logits[:, CL - 1 : -1], qr[:, CL:], T) is None+ got = frl.ppo_policy_logprobs(+ route, module.forward, module.selective_log_softmax, ref, qr, qr[:, CL:], CL, 0, T+ )+ want = module.selective_log_softmax(+ module.forward(ref, qr, 0).logits[:, CL - 1 : -1] / T, qr[:, CL:]+ )+ torch.testing.assert_close(got, want)+ assert "output head has hooks or a patched forward" in trainer._unsloth_ppo_fused_fallbacks+++def test_ppo_hooked_head_keeps_trl():+ module = _ppo_module()+ model = _wrapper(module, _Policy())+ model.policy.lm_head.register_forward_hook(lambda *a: None)+ route, trainer = _route(model)+ assert route is None+ assert "output head has hooks or a patched forward" in trainer._unsloth_ppo_fused_fallbacksdiff --git a/tests/test_rloo_fused_logprobs.py b/tests/test_rloo_fused_logprobs.pynew file mode 100644index 00000000000..cb671688c59--- /dev/null+++ b/tests/test_rloo_fused_logprobs.py@@ -0,0 +1,252 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.+"""RLOOTrainer (TRL < 1.15) log-probs and entropies scored from hidden states by the zoo fused linear kernel.++TRL's own ``_get_per_token_logps_and_entropies`` is run on the same fake model as the reference (float64), so the+test pins the rewrite to whatever the installed TRL computes."""++from __future__ import annotations++import copy+import os+import sys+import textwrap+from types import SimpleNamespace++import pytest++torch = pytest.importorskip("torch")+os.environ.setdefault("UNSLOTH_COMPILE_DISABLE", "1")+import unsloth # noqa: F401,E402+import unsloth.models.rl_replacements as rl # noqa: E402++fused_linear = pytest.importorskip("unsloth_zoo.fused_losses.fused_linear")+rloo = pytest.importorskip("trl.trainer.rloo_trainer")++H, V = 16, 40+++class _Model(torch.nn.Module):+ """Unsloth-style CausalLM: ``.logits`` is the last hidden state under UNSLOTH_RETURN_HIDDEN_STATES=1."""++ def __init__(+ self,+ dtype = torch.float64,+ softcap = None,+ ):+ super().__init__()+ from transformers import Qwen3Config++ self.config = Qwen3Config(hidden_size = H, vocab_size = V, num_hidden_layers = 1)+ if softcap:+ self.config.final_logit_softcapping = softcap+ gen = torch.Generator().manual_seed(0)+ self.embed = torch.nn.Embedding(V, H).to(dtype)+ self.embed.weight.data = torch.randn(V, H, generator = gen, dtype = dtype)+ self.mix = torch.nn.Linear(H, H, dtype = dtype)+ self.mix.weight.data = torch.randn(H, H, generator = gen, dtype = dtype) / H**0.5+ self.mix.bias.data = torch.zeros(H, dtype = dtype)+ self.lm_head = torch.nn.Linear(H, V, bias = False, dtype = dtype)+ self.lm_head.weight.data = torch.randn(V, H, generator = gen, dtype = dtype)+ self.softcap = softcap+ self.forwards = []++ def get_output_embeddings(self):+ return self.lm_head++ def forward(+ self,+ input_ids,+ attention_mask = None,+ logits_to_keep = 0,+ use_cache = None,+ **kwargs,+ ):+ h = torch.tanh(self.mix(self.embed(input_ids)))+ if logits_to_keep:+ h = h[:, -logits_to_keep:]+ hidden = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES", "0") == "1"+ self.forwards.append("hidden" if hidden else "logits")+ if hidden:+ return SimpleNamespace(logits = h)+ z = self.lm_head(h)+ if self.softcap:+ z = self.softcap * torch.tanh(z / self.softcap)+ return SimpleNamespace(logits = z)+++class _Accel:+ def unwrap_model(self, model, **kwargs):+ return model+++def _trl_source(name):+ # TRL's own text: importing unsloth swaps trl.trainer.rloo_trainer.RLOOTrainer for the generated class.+ import ast++ text = open(rloo.__file__, encoding = "utf-8").read()+ cls = next(+ n for n in ast.parse(text).body if isinstance(n, ast.ClassDef) and n.name == "RLOOTrainer"+ )+ fn = next(n for n in cls.body if isinstance(n, ast.FunctionDef) and n.name == name)+ return "\n".join(text.split("\n")[fn.lineno - 1 : fn.end_lineno]) + "\n"+++def _methods():+ stock = _trl_source("_get_per_token_logps_and_entropies")+ if "fused_lm_head=True" in stock:+ pytest.skip("TRL >= 1.15 scores through its own fused lm_head (served by the zoo adapter)")+ new = rl.rloo_trainer_fused_logprobs("_get_per_token_logps_and_entropies", stock)+ assert new != stock, "RLOO rewrite did not apply to the installed TRL"+ namespace = dict(vars(rloo))+ exec(compile("class _T:\n" + new, "<rloo>", "exec"), namespace)+ exec(compile("class _S:\n" + stock, "<rloo_stock>", "exec"), namespace)+ return namespace["_T"], namespace["_S"]+++def _trainer(cls, temperature = 0.7):+ t = cls.__new__(cls)+ t.temperature = temperature+ t.model_kwarg_keys = ("input_ids", "attention_mask", "logits_to_keep")+ t.accelerator = _Accel()+ return t+++def _batch(+ B = 3,+ L = 9,+ k = 5,+):+ gen = torch.Generator().manual_seed(1)+ ids = torch.randint(0, V, (B, L), generator = gen)+ mask = torch.ones(B, L, dtype = torch.long)+ mask[0, :2] = 0+ mask[1, -2:] = 0 # padded completion+ return ids, mask, k+++def _call(t, model, entropy):+ ids, mask, k = _batch()+ out = t._get_per_token_logps_and_entropies(+ model, ids, mask, k, batch_size = 2, compute_entropy = entropy+ )+ return out[0], out[1], out++[email protected]("softcap", [None, 3.0])+def test_rloo_fused_matches_trl_fp64(softcap):+ T, S = _methods()+ model = _Model(softcap = softcap)+ calls = fused_linear.CALLS["logprobs"]+ logps, ent, out = _call(_trainer(T), model, True)+ assert fused_linear.CALLS["logprobs"] > calls+ assert "hidden" in model.forwards and "logits" not in model.forwards+ ref_logps, ref_ent, ref_out = _call(_trainer(S), model, True)+ assert len(out) == len(ref_out)+ assert logps.dtype == torch.float32 or logps.dtype == ref_logps.dtype+ torch.testing.assert_close(logps.double(), ref_logps.double(), atol = 1e-5, rtol = 1e-5)+ torch.testing.assert_close(ent.double(), ref_ent.double(), atol = 1e-5, rtol = 1e-5)+ assert not ent.requires_grad+++def test_rloo_fused_gradients_match_trl_fp64():+ T, S = _methods()+ model = _Model()+ ids, mask, k = _batch()+ grads = []+ for cls in (T, S):+ model.zero_grad()+ out = _trainer(cls)._get_per_token_logps_and_entropies(+ model, ids, mask, k, compute_entropy = True+ )+ cm = mask[:, -k:].double()+ loss = -((out[0].double() * torch.linspace(-1, 1, k)).mul(cm).sum() / cm.sum())+ loss.backward()+ grads.append(+ (+ loss.detach(),+ [p.grad.detach().clone() for p in (model.mix.weight, model.embed.weight)],+ )+ )+ torch.testing.assert_close(grads[0][0], grads[1][0], atol = 1e-6, rtol = 1e-6)+ for a, b in zip(grads[0][1], grads[1][1]):+ torch.testing.assert_close(a.double(), b.double(), atol = 1e-6, rtol = 1e-5)+++def test_rloo_fused_bf16_error_not_worse_than_stock():+ T, S = _methods()+ exact = _Model(torch.float64)+ ref, _, _ = _call(_trainer(S), exact, False)+ low = copy.deepcopy(exact).to(torch.bfloat16)+ fused, _, _ = _call(_trainer(T), low, False)+ stock, _, _ = _call(_trainer(S), low, False)+ keep = _batch()[1][:, -_batch()[2] :].bool()+ # Mean, not max: one bf16-rounded hidden row dominates a max either way.+ err_fused = (fused.double() - ref)[keep].abs().mean()+ err_stock = (stock.double() - ref)[keep].abs().mean()+ assert err_fused <= err_stock + 1e-6, (err_fused, err_stock)+++def test_rloo_kill_switch_and_fallbacks(monkeypatch):+ T, S = _methods()+ model = _Model()+ monkeypatch.setenv("UNSLOTH_FUSED_LINEAR", "0")+ calls = fused_linear.CALLS["logprobs"]+ t = _trainer(T)+ logps, ent, _ = _call(t, model, True)+ assert fused_linear.CALLS["logprobs"] == calls+ assert model.forwards == ["logits", "logits"]+ assert "UNSLOTH_FUSED_LINEAR=0" in t._unsloth_rloo_fused_fallbacks+ monkeypatch.delenv("UNSLOTH_FUSED_LINEAR")+ # Vision inputs keep TRL's body.+ if "pixel_values" in _trl_source("_get_per_token_logps_and_entropies").split(")", 1)[0]:+ t = _trainer(T)+ ids, mask, k = _batch()+ t._get_per_token_logps_and_entropies(model, ids, mask, k, pixel_values = torch.zeros(3, 1))+ assert t._unsloth_rloo_fused_fallbacks == {"vision inputs": 1}+++def test_rloo_forward_ignoring_the_flag_hands_back_to_trl():+ T, S = _methods()++ class _Plain(_Model):+ def forward(self, *a, **kw):+ old = os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ try:+ return super().forward(*a, **kw)+ finally:+ if old is not None:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = old++ model = _Plain()+ t = _trainer(T)+ logps, _, _ = _call(t, model, False)+ ref, _, _ = _call(_trainer(S), model, False)+ torch.testing.assert_close(logps, ref)+ assert t._unsloth_rloo_fused_off is True+++def test_rloo_rewrite_idempotent_and_scoped():+ stock = _trl_source("_get_per_token_logps_and_entropies")+ if "fused_lm_head=True" in stock:+ pytest.skip("TRL >= 1.15")+ new = rl.rloo_trainer_fused_logprobs("_get_per_token_logps_and_entropies", stock)+ assert rl.rloo_trainer_fused_logprobs("_get_per_token_logps_and_entropies", new) == new+ assert rl.rloo_trainer_fused_logprobs("_compute_loss", stock) == stock+ assert rl.rloo_trainer_fused_logprobs in rl.RL_FUNCTIONS["rloo_trainer"]+++def test_rloo_fused_scorer_compiles_without_graph_breaks():+ from unsloth.models._fused_rl_logprobs import score_hidden_states++ model = _Model(torch.float32)+ head_info = (model.lm_head, (0.0, 0.0, 0.0), None)+ ids, mask, k = _batch()+ hidden = torch.randn(3, k, H)++ def fn(h):+ return score_hidden_states(model, h, ids[:, -k:], 0.7, entropy = True, head_info = head_info)++ torch._dynamo.reset()+ explain = torch._dynamo.explain(fn)(hidden)+ assert explain.graph_break_count == 0, explain.break_reasonsdiff --git a/unsloth/models/_fused_rl_logprobs.py b/unsloth/models/_fused_rl_logprobs.pynew file mode 100644index 00000000000..2ce8b6b310b--- /dev/null+++ b/unsloth/models/_fused_rl_logprobs.py@@ -0,0 +1,389 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2023-present Daniel Han-Chen & the Unsloth team. All rights reserved.++"""PPO / RLOO log-probs scored from hidden states by unsloth_zoo's fused linear kernel.++The model forward is the stock one, run with ``UNSLOTH_RETURN_HIDDEN_STATES=1`` so ``.logits`` carries the final+hidden states; the kernel then computes ``log_softmax(transform(h @ W.T + b) / T)[target]`` (and the entropy)+without a tokens x vocab tensor. Anything the kernel cannot reproduce keeps TRL's own path."""++import contextlib+import os++import torch++__all__ = [+ "fused_head",+ "hidden_states_forward",+ "score_hidden_states",+ "ppo_route",+ "ppo_batch_generation",+ "ppo_forward",+ "ppo_score",+ "rloo_fused_logps",+ "rloo_stock_traits",+ "ppo_policy_logprobs",+]+++def _kernel():+ try:+ from unsloth_zoo.fused_losses.fused_linear import fused_linear_logprobs+ except Exception:+ return None+ return fused_linear_logprobs+++def _note(owner, key, reason):+ try:+ fallbacks = owner.__dict__.setdefault(key, {})+ fallbacks[reason] = fallbacks.get(reason, 0) + 1+ except Exception:+ pass+++def _unwrap(model):+ seen = 0+ while seen < 4 and isinstance(+ model, (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)+ ):+ model = model.module+ seen += 1+ return model+++def fused_head(model):+ """``(head, (multiply, divide, softcap), reason)``; ``head`` is None (with a reason) when the kernel cannot read+ the output head directly, or the model changes the hidden states before it."""+ from .rl_replacements import (+ _unsloth_get_model_config,+ _unsloth_gkd_dense_head,+ _unsloth_pref_logit_transforms,+ _unsloth_text_configs,+ )++ if os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ return None, None, "UNSLOTH_FUSED_LINEAR=0"+ if _kernel() is None:+ return None, None, "unsloth_zoo has no fused_linear_logprobs"+ model = _unwrap(model)+ head = _unsloth_gkd_dense_head(model)+ if head is None:+ return None, None, "output head is not a dense nn.Linear"+ # The kernel reads weight / bias directly: a hooked head is not F.linear(h, W, b).+ 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, None, "output head has hooks or a patched forward"+ if hasattr(head.weight, "ds_id"):+ return None, None, "DeepSpeed ZeRO-3 head"+ for config in _unsloth_text_configs(_unsloth_get_model_config(model)):+ if getattr(config, "model_type", None) == "minicpm3":+ return None, None, "minicpm3 scales hidden states before the head"+ return head, _unsloth_pref_logit_transforms(model), None+++def hidden_states_forward(enabled = True):+ """Unsloth's CausalLM forwards return the final hidden states as ``.logits`` while this is active."""+ if not enabled:+ yield+ return+ prior = os.environ.get("UNSLOTH_RETURN_HIDDEN_STATES")+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = "1"+ try:+ yield+ finally:+ if prior is None:+ os.environ.pop("UNSLOTH_RETURN_HIDDEN_STATES", None)+ else:+ os.environ["UNSLOTH_RETURN_HIDDEN_STATES"] = prior+++def score_hidden_states(+ model,+ tensor,+ targets,+ temperature,+ mask = None,+ entropy = False,+ head_info = None,+):+ """``(logps, entropy | None)`` from ``tensor`` when it is the final hidden states of ``model``, else None (the+ forward ignored the flag and ``tensor`` is real logits). Entropy is detached, as every caller logs it under+ ``no_grad``; rows outside ``mask`` are 0."""+ from .rl_replacements import _unsloth_pref_returns_hidden_states++ head, transforms, _ = head_info if head_info is not None else fused_head(model)+ if head is None:+ return None+ if not _unsloth_pref_returns_hidden_states(_unwrap(model), tensor, head.weight):+ return None+ multiply, divide, softcap = transforms+ out = _kernel()(+ tensor.to(head.weight.device),+ head.weight,+ targets,+ bias = head.bias,+ mask = mask,+ temperature = float(temperature),+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ return_entropy = bool(entropy),+ entropy_requires_grad = False,+ )+ if entropy:+ logps, ent = out+ return logps.to(targets.device), ent.detach().to(targets.device)+ return out.to(targets.device), None+++class _PPORoute:+ __slots__ = ("trainer",)++ def __init__(self, trainer):+ self.trainer = trainer+++def ppo_route(trainer):+ """A route object when PPOTrainer.train can score from hidden states, else None (TRL's logits path runs).+ The policy head is checked here; the reference model is checked per call."""+ reason = None+ if getattr(trainer, "is_fsdp_enabled", False) or getattr(+ trainer, "is_deepspeed_enabled", False+ ):+ reason = "FSDP / DeepSpeed"+ if reason is None:+ try:+ wrapper = trainer.accelerator.unwrap_model(trainer.model)+ policy = wrapper.policy+ except Exception:+ policy = None+ reason = "no PolicyAndValueWrapper.policy"+ if reason is None:+ head, _, reason = fused_head(policy)+ if reason is None and getattr(trainer.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:+ _note(trainer, "_unsloth_ppo_fused_fallbacks", reason)+ return None+ return _PPORoute(trainer)+++def _right_pad_cat(tensors, value):+ width = max(t.shape[1] for t in tensors)+ return torch.cat(+ [torch.nn.functional.pad(t, (0, width - t.shape[1]), value = value) for t in tensors], dim = 0+ )++[email protected]_grad()+def ppo_batch_generation(+ model, queries, local_rollout_forward_batch_size, pad_token_id, generation_config+):+ """TRL's ``batch_generation`` without ``output_scores``: the rollout log-probs are scored from hidden states, so+ the stacked float32 [batch, response, vocab] scores are never built. Returns ``(query_responses, None)``."""+ query_responses = []+ for i in range(0, queries.shape[0], local_rollout_forward_batch_size):+ query = queries[i : i + local_rollout_forward_batch_size]+ context_length = query.shape[1]+ attention_mask = query != pad_token_id+ input_ids = torch.masked_fill(query, ~attention_mask, 0)+ output = model.generate(+ input_ids = input_ids,+ attention_mask = attention_mask,+ generation_config = generation_config,+ return_dict_in_generate = True,+ )+ query_responses.append(torch.cat((query, output.sequences[:, context_length:]), dim = 1))+ return _right_pad_cat(query_responses, pad_token_id), None+++def ppo_forward(route, forward, model, query_responses, pad_token_id):+ """TRL's ``forward(model, query_responses, pad_token_id)``, with Unsloth's forwards returning hidden states+ only when ``ppo_score`` will score this model's head (a reference model is not checked by ``ppo_route``)."""+ enabled = route is not None and fused_head(_ppo_policy(route, model))[0] is not None+ with hidden_states_forward(enabled):+ return forward(model, query_responses, pad_token_id)+++def _ppo_policy(route, model):+ try:+ model = route.trainer.accelerator.unwrap_model(model)+ except Exception:+ model = _unwrap(model)+ return getattr(model, "policy", model)+++def ppo_score(+ route,+ model,+ tensor,+ responses,+ temperature,+ entropy = False,+):+ """``(logps, entropy | None)`` for PPO from ``tensor = output.logits[:, context_length - 1 : -1]``, or None when+ the route is off or the forward returned real logits (TRL's lines then run on them unchanged). ``model`` is the+ PolicyAndValueWrapper (its policy head scores) or a standalone reference policy."""+ if route is None:+ return None+ model = _ppo_policy(route, model)+ head_info = fused_head(model)+ if head_info[0] is None:+ _note(route.trainer, "_unsloth_ppo_fused_fallbacks", head_info[2])+ return None+ out = score_hidden_states(+ model, tensor, responses, temperature, entropy = entropy, head_info = head_info+ )+ if out is None:+ _note(+ route.trainer,+ "_unsloth_ppo_fused_fallbacks",+ "forward returned logits, not hidden states",+ )+ return None+ route.trainer.__dict__["_unsloth_ppo_fused_calls"] = (+ route.trainer.__dict__.get("_unsloth_ppo_fused_calls", 0) + 1+ )+ return out++[email protected]_grad()+def ppo_policy_logprobs(+ route,+ forward,+ selective_log_softmax,+ model,+ query_responses,+ responses,+ context_length,+ pad_token_id,+ temperature,+):+ """Rollout log-probs of the current policy, recomputed by the same forward and scorer as the training pass+ (the stock path reads them off the generation scores, which ``ppo_batch_generation`` no longer keeps). A forward+ that returned real logits is scored with TRL's formula on them."""+ policy = _ppo_policy(route, model)+ output = ppo_forward(route, forward, policy, query_responses, pad_token_id)+ tensor = output.logits[:, context_length - 1 : -1]+ out = ppo_score(route, policy, tensor, responses, temperature)+ if out is not None:+ return out[0]+ return selective_log_softmax(tensor / temperature, responses)+++_RLOO_VISION_KEYS = (+ "pixel_values",+ "image_grid_thw",+ "num_images",+ "pixel_attention_mask",+ "spatial_shapes",+ "num_tiles",+ "image_sizes",+ "token_type_ids",+ "mm_token_type_ids",+ "image_position_ids",+)+++def rloo_stock_traits(source):+ """What the generated dispatcher bakes in from TRL's body: whether it returns the MoE aux loss (a third value)+ and whether it zeroes the log-probs / entropies of padded completion tokens (TRL 1.14's ``row_mask``)."""+ return {+ "aux": "compute_aux_loss" in source.split(")", 1)[0],+ "row_mask": "row_mask=" in source.replace(" ", ""),+ }+++def rloo_fused_logps(+ self,+ traits,+ model,+ input_ids,+ attention_mask,+ logits_to_keep,+ batch_size,+ compute_entropy,+ args,+ kwargs,+):+ """RLOOTrainer._get_per_token_logps_and_entropies (TRL < 1.15, which reads ``model(**inputs).logits``) from+ hidden states. None -> the caller runs TRL's body. Text only; vision and MoE aux loss keep TRL's path."""+ reason = None+ if self.__dict__.get("_unsloth_rloo_fused_off"):+ return None+ if args:+ reason = "positional extras"+ elif any(kwargs.get(k) is not None for k in _RLOO_VISION_KEYS):+ reason = "vision inputs"+ elif kwargs.get("compute_aux_loss", False):+ reason = "router aux loss needs the stock forward"+ elif set(kwargs) - set(_RLOO_VISION_KEYS) - {"compute_aux_loss"}:+ reason = "unknown keyword arguments"+ elif getattr(self, "is_fsdp_enabled", False) or getattr(self, "is_deepspeed_enabled", False):+ reason = "FSDP / DeepSpeed"+ head_info = None+ if reason is None:+ try:+ unwrapped = self.accelerator.unwrap_model(model)+ except Exception:+ unwrapped = _unwrap(model)+ head_info = fused_head(unwrapped)+ reason = head_info[2]+ if reason is None and getattr(model, "find_unused_parameters", False):+ head = head_info[0]+ 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:+ _note(self, "_unsloth_rloo_fused_fallbacks", reason)+ return None++ batch_size = batch_size or input_ids.size(0)+ all_logps, all_entropies = [], []+ for start in range(0, input_ids.size(0), batch_size):+ input_ids_batch = input_ids[start : start + batch_size]+ attention_mask_batch = attention_mask[start : start + batch_size]+ model_inputs = {"input_ids": input_ids_batch, "attention_mask": attention_mask_batch}+ if "logits_to_keep" in getattr(self, "model_kwarg_keys", ()):+ model_inputs["logits_to_keep"] = logits_to_keep + 1+ model_inputs["use_cache"] = False+ with hidden_states_forward():+ hidden = model(**model_inputs).logits+ hidden = hidden[:, :-1, :][:, -logits_to_keep:, :]+ completion_ids = input_ids_batch[:, -logits_to_keep:]+ mask = attention_mask_batch[:, -logits_to_keep:] if traits["row_mask"] else None+ out = score_hidden_states(+ unwrapped,+ hidden,+ completion_ids,+ self.temperature,+ mask = mask,+ entropy = compute_entropy,+ head_info = head_info,+ )+ if out is None:+ # The forward ignored the flag: hand this model to TRL from now on (one wasted forward).+ self.__dict__["_unsloth_rloo_fused_off"] = True+ _note(+ self, "_unsloth_rloo_fused_fallbacks", "forward returned logits, not hidden states"+ )+ return None+ all_logps.append(out[0])+ if compute_entropy:+ all_entropies.append(out[1])+ self.__dict__["_unsloth_rloo_fused_calls"] = (+ self.__dict__.get("_unsloth_rloo_fused_calls", 0) + 1+ )+ logps = torch.cat(all_logps, dim = 0)+ entropies = torch.cat(all_entropies, dim = 0) if compute_entropy else None+ if traits["aux"]:+ return logps, entropies, None+ return logps, entropiesdiff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex 3d5f41e41d0..8c841558222 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -193,6 +193,223 @@ def ppo_trainer_free_rollout_logits(function_name, function):RL_FUNCTIONS["ppo_trainer"].append(ppo_trainer_free_rollout_logits)+def _unsloth_replace_block(function, old_lines, new_lines):+ """Replace the one run of consecutive lines whose stripped text is ``old_lines`` with ``new_lines`` (written+ relative to the first old line's indent). None unless the run occurs exactly once."""+ lines = function.split("\n")+ stripped = [line.strip() for line in lines]+ n = len(old_lines)+ hits = [i for i in range(len(lines) - n + 1) if stripped[i : i + n] == list(old_lines)]+ if len(hits) != 1:+ return None+ i = hits[0]+ indent = lines[i][: len(lines[i]) - len(lines[i].lstrip())]+ return "\n".join(+ lines[:i] + [indent + line if line else line for line in new_lines] + lines[i + n :]+ )+++_PPO_FUSED_IMPORT = (+ "from unsloth.models._fused_rl_logprobs import (",+ " ppo_route as _unsloth_ppo_route_of,",+ " ppo_batch_generation as _unsloth_ppo_batch_generation,",+ " ppo_forward as _unsloth_ppo_forward,",+ " ppo_score as _unsloth_ppo_score,",+ " ppo_policy_logprobs as _unsloth_ppo_policy_logprobs,",+ ")",+ "_unsloth_ppo_route = _unsloth_ppo_route_of(self)",+)+_PPO_FUSED_BLOCKS = (+ # The route is decided once per train() before the first rollout.+ (+ ("for update in range(1, args.num_total_batches + 1):",),+ _PPO_FUSED_IMPORT + ("for update in range(1, args.num_total_batches + 1):",),+ ),+ # Rollouts without the stacked float32 generation scores.+ (+ ("query_responses, logitss = batch_generation(",),+ (+ "query_responses, logitss = (",+ " batch_generation if _unsloth_ppo_route is None else _unsloth_ppo_batch_generation",+ ")(",+ ),+ ),+ # Rollout (old) log-probs: the policy forward + fused scorer the training pass uses.+ (+ (+ "logits = logitss[i : i + args.local_rollout_forward_batch_size]",+ "logprob = selective_log_softmax(logits, response)",+ "del logits",+ ),+ (+ "if _unsloth_ppo_route is not None:",+ " logprob = _unsloth_ppo_policy_logprobs(",+ " _unsloth_ppo_route, forward, selective_log_softmax, model, query_response, response,",+ " context_length, processing_class.pad_token_id, args.temperature + 1e-7,",+ " )",+ "else:",+ " logits = logitss[i : i + args.local_rollout_forward_batch_size]",+ " logprob = selective_log_softmax(logits, response)",+ " del logits",+ ),+ ),+ (+ ("ref_output = forward(model.policy, query_response, processing_class.pad_token_id)",),+ (+ "ref_output = _unsloth_ppo_forward(",+ " _unsloth_ppo_route, forward, model.policy, query_response, processing_class.pad_token_id",+ ")",+ ),+ ),+ (+ ("ref_output = forward(ref_policy, query_response, processing_class.pad_token_id)",),+ (+ "ref_output = _unsloth_ppo_forward(",+ " _unsloth_ppo_route, forward, ref_policy, query_response, processing_class.pad_token_id",+ ")",+ ),+ ),+ (+ (+ "ref_logits = ref_output.logits[:, context_length - 1 : -1]",+ "ref_logits /= args.temperature + 1e-7",+ "ref_logprob = selective_log_softmax(ref_logits, response)",+ "del ref_output, ref_logits",+ ),+ (+ "_unsloth_scored = _unsloth_ppo_score(",+ " _unsloth_ppo_route, model if ref_policy is None else ref_policy,",+ " ref_output.logits[:, context_length - 1 : -1], response, args.temperature + 1e-7,",+ ")",+ "if _unsloth_scored is None:",+ " ref_logits = ref_output.logits[:, context_length - 1 : -1]",+ " ref_logits /= args.temperature + 1e-7",+ " ref_logprob = selective_log_softmax(ref_logits, response)",+ " del ref_output, ref_logits",+ "else:",+ " ref_logprob = _unsloth_scored[0]",+ " del ref_output, _unsloth_scored",+ ),+ ),+ # Training pass: the value head still reads the critic backbone; only the policy head is fused.+ (+ ("output, vpred_temp = forward(model, mb_query_responses, processing_class.pad_token_id)",),+ (+ "output, vpred_temp = _unsloth_ppo_forward(",+ " _unsloth_ppo_route, forward, model, mb_query_responses, processing_class.pad_token_id",+ ")",+ ),+ ),+ (+ (+ "logits = output.logits[:, context_length - 1 : -1]",+ "logits /= args.temperature + 1e-7",+ "new_logprobs = selective_log_softmax(logits, mb_responses)",+ ),+ (+ "_unsloth_scored = _unsloth_ppo_score(",+ " _unsloth_ppo_route, model, output.logits[:, context_length - 1 : -1], mb_responses,",+ " args.temperature + 1e-7, entropy = True,",+ ")",+ "if _unsloth_scored is None:",+ " logits = output.logits[:, context_length - 1 : -1]",+ " logits /= args.temperature + 1e-7",+ " new_logprobs = selective_log_softmax(logits, mb_responses)",+ "else:",+ " logits = None",+ " new_logprobs, _unsloth_entropy = _unsloth_scored",+ " del _unsloth_scored",+ ),+ ),+ # The entropy metric comes out of the same kernel pass (detached, temperature-scaled like TRL's).+ (+ (+ "prob_dist = torch.nn.functional.softmax(logits, dim=-1)",+ "entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1)",+ ),+ (+ "if logits is None:",+ " prob_dist = None",+ " entropy = _unsloth_entropy",+ "else:",+ " prob_dist = torch.nn.functional.softmax(logits, dim=-1)",+ " entropy = torch.logsumexp(logits, dim=-1) - torch.sum(prob_dist * logits, dim=-1)",+ ),+ ),+)+++def ppo_trainer_fused_logprobs(function_name, function):+ """Score PPO's rollout, reference and training log-probs (and the entropy metric) from hidden states with the+ fused linear kernel. Every anchor must match exactly once, else TRL's source is returned untouched; at run time+ ``ppo_route`` / ``ppo_score`` keep TRL's lines for any head or forward the kernel cannot serve."""+ if function_name != "train" or "_unsloth_ppo_route" in function:+ return function+ new = function+ for old_lines, new_lines in _PPO_FUSED_BLOCKS:+ new = _unsloth_replace_block(new, old_lines, new_lines)+ if new is None:+ return function+ return new+++RL_FUNCTIONS["ppo_trainer"].append(ppo_trainer_fused_logprobs)+++_RLOO_LOGPS_DEF = re.compile(+ r"^(?P<indent>[ \t]*)def _get_per_token_logps_and_entropies\(", re.MULTILINE+)+++def rloo_trainer_fused_logprobs(function_name, function):+ """RLOOTrainer (TRL < 1.15) reads ``model(**inputs).logits``: keep its body as+ ``_unsloth_stock_get_per_token_logps_and_entropies`` and put a dispatcher in front that scores text-only batches+ from hidden states. TRL >= 1.15 calls its own fused lm_head, already served by the zoo kernel."""+ if function_name != "_get_per_token_logps_and_entropies":+ return function+ if "fused_lm_head=True" in function or "_unsloth_rloo" in function:+ return function+ match = list(_RLOO_LOGPS_DEF.finditer(function))+ if len(match) != 1 or ".logits" not in function or "self.temperature" not in function:+ return function+ indent = match[0].group("indent")+ try:+ from unsloth.models._fused_rl_logprobs import rloo_stock_traits+ except Exception:+ return function+ traits = rloo_stock_traits(function)+ stock = _RLOO_LOGPS_DEF.sub(+ lambda m: m.group("indent") + "def _unsloth_stock_get_per_token_logps_and_entropies(",+ function,+ count = 1,+ )+ body = [+ "def _get_per_token_logps_and_entropies(",+ " self, model, input_ids, attention_mask, logits_to_keep, batch_size=None, compute_entropy=False,",+ " *args, **kwargs,",+ "):",+ " try:",+ " from unsloth.models._fused_rl_logprobs import rloo_fused_logps as _unsloth_rloo_fused_logps",+ " except Exception:",+ " _unsloth_rloo_fused_logps = None",+ " if _unsloth_rloo_fused_logps is not None:",+ " _out = _unsloth_rloo_fused_logps(",+ f" self, {traits!r}, model, input_ids, attention_mask, logits_to_keep, batch_size,",+ " compute_entropy, args, kwargs,",+ " )",+ " if _out is not None:",+ " return _out",+ " return self._unsloth_stock_get_per_token_logps_and_entropies(",+ " model, input_ids, attention_mask, logits_to_keep, batch_size, compute_entropy, *args, **kwargs",+ " )",+ ]+ dispatcher = "\n".join(indent + line for line in body) + "\n\n"+ return dispatcher + stock+++RL_FUNCTIONS["rloo_trainer"].append(rloo_trainer_fused_logprobs)++def dpo_trainer_fix_columns(call_args, extra_args):if "model" in call_args and "train_dataset" in call_args:fix_dpo = (@@ -5386,6 +5603,10 @@ try:from unsloth_zoo.rl_replacements import distillation_chunked_jsdexcept Exception:distillation_chunked_jsd = None+try:+ from unsloth_zoo.fused_losses.fused_linear import fused_linear_jsd as _unsloth_fused_linear_jsd+except Exception:+ _unsloth_fused_linear_jsd = Nonedef _unsloth_gkd_canonical(source):@@ -5646,17 +5867,21 @@ def _unsloth_gkd_chunked_loss(self, model, inputs, num_items_in_batch, layout):"""TRL's GKD loss without either full logits tensor, or ``None`` to run TRL's own ``compute_loss``."""if layout is None:return None- if distillation_chunked_jsd is None:+ if distillation_chunked_jsd is None and _unsloth_fused_linear_jsd is None:return _unsloth_gkd_note_fallback(self, "unsloth_zoo has no distillation_chunked_jsd")if os.environ.get("UNSLOTH_GKD_CHUNKED", "1").lower() in ("0", "false", "no", "off"):return _unsloth_gkd_note_fallback(self, "UNSLOTH_GKD_CHUNKED=0")+ # Read per call like the other fused lm_head routes: UNSLOTH_FUSED_LINEAR=0 restores TRL's dense loss.+ if os.environ.get("UNSLOTH_FUSED_LINEAR", "1") == "0":+ return _unsloth_gkd_note_fallback(self, "UNSLOTH_FUSED_LINEAR=0")+ use_fused = _unsloth_fused_linear_jsd is not Noneif getattr(self, "use_liger_gkd_loss", False):return _unsloth_gkd_note_fallback(self, "use_liger_gkd_loss")if getattr(self, "is_fsdp_enabled", False) or getattr(self, "is_deepspeed_enabled", False):return _unsloth_gkd_note_fallback(self, "FSDP / DeepSpeed")jsd_kwargs = {}scaler = getattr(self.accelerator, "scaler", None)- if scaler is not None and scaler.is_enabled():+ if scaler is not None and scaler.is_enabled() and not use_fused:if "scaler" not in inspect.signature(distillation_chunked_jsd).parameters:return _unsloth_gkd_note_fallback(self, "unsloth_zoo JSD has no GradScaler support")jsd_kwargs["scaler"] = scaler@@ -5766,6 +5991,34 @@ def _unsloth_gkd_chunked_loss(self, model, inputs, num_items_in_batch, layout):# A dispatched model can return hidden states off its head's device; the zoo's accumulators follow the states.student_states = student_states.to(student_head.weight.device)teacher_states = teacher_states.to(teacher_head.weight.device)+ if use_fused:+ # Both heads one row chunk at a time, student gradient taken in forward (zoo fused_linear).+ rows = os.environ.get("UNSLOTH_GKD_CHUNK_SIZE", "")+ loss = _unsloth_fused_linear_jsd(+ student_states,+ student_head.weight,+ teacher_states.detach(),+ teacher_head.weight.detach(),+ labels = shifted_labels,+ beta = float(self.beta),+ # No TRL release passes a temperature to generalized_jsd_loss (GKDConfig.temperature is for sampling).+ temperature = 1.0,+ student_bias = student_head.bias,+ teacher_bias = None if teacher_head.bias is None else teacher_head.bias.detach(),+ student_logit_scale = student_scale,+ student_logit_softcapping = student_softcap,+ teacher_logit_scale = teacher_scale,+ teacher_logit_softcapping = teacher_softcap,+ num_items_in_batch = items,+ scaling = scaler.get_scale() if scaler is not None and scaler.is_enabled() else None,+ rows_per_chunk = int(rows) if rows.strip().isdigit() else None,+ )+ try:+ self._unsloth_gkd_chunked_calls = getattr(self, "_unsloth_gkd_chunked_calls", 0) + 1+ self._unsloth_gkd_fused_calls = getattr(self, "_unsloth_gkd_fused_calls", 0) + 1+ except Exception:+ pass+ return lossloss, _entropy_sum, _n_valid = distillation_chunked_jsd(student_states,teacher_states.detach(),@@ -5797,7 +6050,7 @@ def gkd_trainer_compute_loss(function_name, function):if function_name != "compute_loss" or "_unsloth_trl_compute_loss" in function:return functionlayout = _unsloth_gkd_layout(function)- if layout is None or distillation_chunked_jsd is None:+ if layout is None or (distillation_chunked_jsd is None and _unsloth_fused_linear_jsd is None):return functionrenamed, n = re.subn(r"\bdef compute_loss\(", "def _unsloth_trl_compute_loss(", function, count = 1@@ -5855,6 +6108,10 @@ RL_PRE_ITEMS["gkd_trainer"].append(" from unsloth_zoo.rl_replacements import distillation_chunked_jsd\n""except Exception:\n"" distillation_chunked_jsd = None\n"+ "try:\n"+ " from unsloth_zoo.fused_losses.fused_linear import fused_linear_jsd as _unsloth_fused_linear_jsd\n"+ "except Exception:\n"+ " _unsloth_fused_linear_jsd = None\n")@@ -7425,7 +7682,11 @@ def _kto_ref_else(function, m):return _fused_pass_else(m)-def kto_trainer_ref_log_probs_chunked(function_name, function):+def kto_trainer_ref_log_probs_chunked(+ function_name,+ function,+ keys = ("KL", "completion"),+):"""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 batchesfrom hidden states with the fused linear op instead of ``[B, S, V]`` logits. Every log-prob statement must match@@ -7473,7 +7734,8 @@ def kto_trainer_ref_log_probs_chunked(function_name, function):if ("KL_" in _fused_pass_mask(m)) != (key == "KL"):return functionlogps.setdefault(key, []).append(m)- if sorted(logps) != ["KL", "completion"] or any(len(v) != 1 for v in logps.values()):+ # KTO scores a completion and a KL batch; BCO only the completions.+ if sorted(logps) != sorted(keys) 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).@@ -7485,9 +7747,9 @@ def kto_trainer_ref_log_probs_chunked(function_name, function):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+ wanted = {"completion_logits"} | ({"KL_logits"} if "KL" in keys else set())+ if {f.group("lhs") for f in forwards} != wanted:+ return functionfor f in forwards:args = f.group("args")if f"{batch_var}[" not in args or "**" in args:@@ -7582,3 +7844,288 @@ RL_PRE_ITEMS["kto_trainer"].append("except Exception:\n"" _unsloth_fused_linear_logprobs = None\n")+++# BCO (TRL 0.22 - 1.10): the policy / reference ``forward`` and the precompute pass are KTO's (TRL < 1.6) layout.+def _unsloth_preference_chunked_off():+ return os.environ.get("UNSLOTH_PREFERENCE_CHUNKED", "1").lower() in ("0", "false", "no", "off")+++def _unsloth_bco_chunked_head(self, model, batch, method):+ """``_unsloth_dpo_chunked_head`` that also honours ``UNSLOTH_PREFERENCE_CHUNKED=0``."""+ if _unsloth_preference_chunked_off():+ return None+ return _unsloth_dpo_chunked_head(self, model, batch, method)+++def _unsloth_bco_fused_pass_head(self, model, batch, return_outputs, method):+ if _unsloth_preference_chunked_off():+ return None+ return _unsloth_fused_pass_head(self, model, batch, return_outputs, method)+++def bco_trainer_chunked_logprobs(function_name, function):+ """BCO's ``forward`` is KTO's TRL < 1.6 ``forward`` (``completion_logits`` is read only by row selection for the+ ``logits/*_sum`` metrics, which the vocab-sum stand-in keeps exact); its ``compute_reference_log_probs`` is KTO's+ precompute without the KL batch. The UDM classifier reads prompt embeddings, never the logits."""+ if function_name == "forward":+ new = kto_trainer_chunked_logprobs(function_name, function)+ old = '_unsloth_dpo_chunked_head(self, model, batch, "forward")'+ if new == function or new.count(old) != 1:+ return function+ return new.replace(old, '_unsloth_bco_chunked_head(self, model, batch, "forward")')+ if function_name == "compute_reference_log_probs":+ new = kto_trainer_ref_log_probs_chunked(function_name, function, keys = ("completion",))+ if new == function:+ return function+ return new.replace(+ "= _unsloth_fused_pass_head(self, ", "= _unsloth_bco_fused_pass_head(self, "+ )+ return function+++RL_FUNCTIONS["bco_trainer"].append(bco_trainer_chunked_logprobs)+++# Online DPO (TRL 0.22 - 1.x ``_forward``), XPO / Nash-MD (TRL 0.22 - 1.10 ``_compute_logprobs``): score the+# completions from hidden states instead of [B, C, V] logits.+def _unsloth_odpo_chunked_head(self, model, batch, method):+ """``(unwrapped, head, transforms)`` when this pass can score from hidden states, else ``None``."""+ 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 _unsloth_preference_chunked_off():+ reason = "UNSLOTH_PREFERENCE_CHUNKED=0"+ elif any(k != "attention_mask" and k != "input_ids" for k in batch):+ # Vision rows (pixel_values, image_grid_thw, ...) keep TRL's layout.+ reason = "extra model inputs"+ 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, batch, method)+++def _unsloth_odpo_hidden_logps(+ self,+ chunked,+ hidden_states,+ completion_ids,+ mask = None,+):+ """TRL's ``log_softmax(head(hidden_states))[completion_ids]`` per position (float32). Rows outside ``mask`` are 0+ (the caller zeroes them anyway). A shape TRL would reject or broadcast gets real logits and TRL's own math."""+ _, head, (multiply, divide, softcap) = chunked+ if hidden_states.dim() != 3 or hidden_states.shape[:2] != completion_ids.shape:+ logits = torch.nn.functional.linear(+ hidden_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 torch.take_along_dim(+ logits.log_softmax(dim = -1), completion_ids.unsqueeze(-1), dim = 2+ ).squeeze(-1)+ logps = _unsloth_fused_linear_logprobs(+ hidden_states,+ head.weight,+ completion_ids,+ bias = head.bias,+ mask = None if mask is None else mask.bool(),+ logit_scale_multiply = multiply,+ logit_scale_divide = divide,+ logit_softcapping = softcap,+ )+ try:+ self._unsloth_dpo_chunked_calls = getattr(self, "_unsloth_dpo_chunked_calls", 0) + 1+ except Exception:+ pass+ return logps.to(completion_ids.device)+++_ODPO_CALL = re.compile(+ r"^(?P<i>[ \t]*)output = model\(prompt_completion_ids, "+ r"(?P<kwargs>attention_mask=prompt_completion_mask|\*\*model_kwargs)\)[ \t]*\n",+ re.MULTILINE,+)+_ODPO_LOGPS = re.compile(+ r"^(?P<i>[ \t]*)logprobs = torch\.take_along_dim\(logits\.log_softmax\(dim=-1\), "+ r"completion_ids\.unsqueeze\(-1\), dim=2\)\.squeeze\(-1\)[ \t]*\n",+ re.MULTILINE,+)+# Between the forward and the log-probs, ``output.logits`` / ``logits`` may only be sliced or row-gathered (the same+# code then slices hidden states): TRL's slice, and online_dpo_trainer__forward's right-align gather.+_ODPO_READS = (+ r"logits = output\.logits\[:, (?:start_idx|prompt_ids\.size\(1\) - 1) ?: ?(?:end_idx|-1)\]",+ r"_unsloth_index = _unsloth_index\.clamp\(0, output\.logits\.size\(1\) - 1\)",+ r"_unsloth_rows, _unsloth_len = output\.logits\.shape\[:2\]",+ r"logits = output\.logits\.reshape\(_unsloth_rows \* _unsloth_len, -1\)\.index_select\(",+ r"\).view\(_unsloth_rows, -1, output\.logits\.size\(-1\)\)",+)+++def online_dpo_trainer_chunked_logprobs(function_name, function):+ """Rewrite Online DPO's ``_forward``: the forward returns hidden states, TRL's slice (or Unsloth's right-align+ gather) picks the completion positions, and the fused op scores every one of them (``objective/kl`` and+ ``objective/entropy`` read the padding positions too). No temperature: TRL scores raw logits. Untouched unless+ both anchors match once and nothing else reads the logits."""+ if function_name != "_forward" or _unsloth_fused_linear_logprobs is None:+ return function+ if "_unsloth_odpo" in function:+ return function+ calls = list(_ODPO_CALL.finditer(function))+ logps = list(_ODPO_LOGPS.finditer(function))+ if len(calls) != 1 or len(logps) != 1 or calls[0].end() > logps[0].start():+ return function+ between = function[calls[0].end() : logps[0].start()]+ code = "\n".join(line for line in between.splitlines() if not line.lstrip().startswith("#"))+ if not _fused_pass_reads_ok(code, r"\blogits\b", _ODPO_READS):+ return function+ if (+ re.search(r"\blogits\b", function[logps[0].end() :])+ or "output.logits" in function[: calls[0].start()]+ ):+ return function+ c, m = calls[0], logps[0]+ i = c.group("i")+ kwargs = (+ "model_kwargs"+ if c.group("kwargs") == "**model_kwargs"+ else "dict(attention_mask=prompt_completion_mask)"+ )+ forward = (+ f"{i}_unsloth_odpo_kwargs = {kwargs}\n"+ f'{i}_unsloth_odpo = _unsloth_odpo_chunked_head(self, model, _unsloth_odpo_kwargs, "_forward")\n'+ f"{i}output = _unsloth_dpo_model_forward(\n"+ f"{i} model, prompt_completion_ids, _unsloth_odpo_kwargs, _unsloth_odpo is not None\n"+ f"{i})\n"+ f"{i}_unsloth_odpo_hidden = _unsloth_dpo_returns_hidden_states(self, _unsloth_odpo, output.logits)\n"+ )+ j = m.group("i")+ score = (+ f"{j}if _unsloth_odpo_hidden:\n"+ f"{j} logprobs = _unsloth_odpo_hidden_logps(self, _unsloth_odpo, logits, completion_ids)\n"+ f"{j}else:\n" + textwrap.indent(textwrap.dedent(m.group(0)), j + " ")+ )+ return function[: c.start()] + forward + between + score + function[m.end() :]+++_XPO_LOGPS = re.compile(+ r"^(?P<i>[ \t]*)output = m\(data\[\"input_ids\"\], attention_mask=data\[\"attention_mask\"\]\)\n"+ r"(?P=i)logits = output\.logits\[:, context_length - 1 : -1\]\n"+ r"(?P=i)token_logprobs = selective_log_softmax\(logits, data\[\"input_ids\"\]\[:, context_length:\]\)\n"+ r"(?P=i)return token_logprobs\n",+ re.MULTILINE,+)+++def xpo_trainer_chunked_logprobs(function_name, function):+ """XPO / Nash-MD ``_compute_logprobs``: each ``compute_logprobs_for_data`` pass scores the completion tokens from+ hidden states. Padding rows come back 0, which is what TRL's ``masked_fill(padding_mask, 0.0)`` makes them."""+ if function_name != "_compute_logprobs" or _unsloth_fused_linear_logprobs is None:+ return function+ if "_unsloth_odpo" in function:+ return function+ found = list(_XPO_LOGPS.finditer(function))+ if len(found) != 1 or len(re.findall(r"\blogits\b", function)) != 3:+ return function+ if (+ len(+ re.findall(+ r"model_padding_mask = model_data\[\"attention_mask\"\]\[:, context_length:\] == 0",+ function,+ )+ )+ != 1+ ):+ return function+ i = found[0].group("i")+ new = (+ f'{i}_unsloth_odpo_kwargs = dict(attention_mask=data["attention_mask"])\n'+ f'{i}_unsloth_odpo = _unsloth_odpo_chunked_head(self, m, _unsloth_odpo_kwargs, "_compute_logprobs")\n'+ f"{i}output = _unsloth_dpo_model_forward(\n"+ f'{i} m, data["input_ids"], _unsloth_odpo_kwargs, _unsloth_odpo is not None\n'+ f"{i})\n"+ f"{i}logits = output.logits[:, context_length - 1 : -1]\n"+ f"{i}if _unsloth_dpo_returns_hidden_states(self, _unsloth_odpo, output.logits):\n"+ f"{i} return _unsloth_odpo_hidden_logps(\n"+ f'{i} self, _unsloth_odpo, logits, data["input_ids"][:, context_length:],\n'+ f'{i} data["attention_mask"][:, context_length:] != 0,\n'+ f"{i} )\n"+ f'{i}token_logprobs = selective_log_softmax(logits, data["input_ids"][:, context_length:])\n'+ f"{i}return token_logprobs\n"+ )+ return function[: found[0].start()] + new + function[found[0].end() :]+++# After online_dpo_trainer__forward, whose right-align gather the rewrite reuses on hidden states.+RL_FUNCTIONS["online_dpo_trainer"].append(online_dpo_trainer_chunked_logprobs)+RL_FUNCTIONS["xpo_trainer"].append(xpo_trainer_chunked_logprobs)+RL_FUNCTIONS["nash_md_trainer"].append(xpo_trainer_chunked_logprobs)+for _odpo_trainer in ("bco_trainer", "online_dpo_trainer", "xpo_trainer", "nash_md_trainer"):+ for _odpo_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_preference_chunked_off,+ ):+ RL_PRE_ITEMS[_odpo_trainer].append(inspect.getsource(_odpo_item))+ if _odpo_trainer == "bco_trainer":+ for _odpo_item in (+ _unsloth_kto_hidden_logps,+ _unsloth_bco_chunked_head,+ _unsloth_kto_ref_chunked_forward,+ _unsloth_kto_ref_batch_logps,+ _unsloth_fused_pass_head,+ _unsloth_bco_fused_pass_head,+ _unsloth_fused_pass_logps,+ ):+ RL_PRE_ITEMS[_odpo_trainer].append(inspect.getsource(_odpo_item))+ else:+ for _odpo_item in (_unsloth_odpo_chunked_head, _unsloth_odpo_hidden_logps):+ RL_PRE_ITEMS[_odpo_trainer].append(inspect.getsource(_odpo_item))+ RL_PRE_ITEMS[_odpo_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"+ "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"+ )