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
GRPO: exclude masked rows from clip_ratio metrics for one-token completions (#13883)
Daniel Han28e8ad8ed8dd
diff --git a/tests/test_grpo_clip_ratio_one_token.py b/tests/test_grpo_clip_ratio_one_token.pynew file mode 100644index 00000000000..3c07347e18c--- /dev/null+++ b/tests/test_grpo_clip_ratio_one_token.py@@ -0,0 +1,52 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""GRPO one-token clip_ratio metrics need masking because width-1 token tensors look sequence-level."""++from __future__ import annotations++import ast+from pathlib import Path++import pytest+import torch+++SOURCE_PATH = Path(__file__).resolve().parents[1] / "unsloth" / "models" / "rl_replacements.py"+++def _load_masked_batch_mean(completion_mask):+ tree = ast.parse(SOURCE_PATH.read_text(encoding = "utf-8"), filename = str(SOURCE_PATH))+ found = [+ node+ for node in ast.walk(tree)+ if isinstance(node, ast.FunctionDef) and node.name == "masked_batch_mean"+ ]+ assert len(found) == 1, f"expected one masked_batch_mean, found {len(found)}"+ namespace = {+ "completion_mask": completion_mask,+ "completion_token_count": completion_mask.sum().clamp(min = 1.0),+ }+ exec(compile(ast.Module(body = found, type_ignores = []), str(SOURCE_PATH), "exec"), namespace)+ return namespace["masked_batch_mean"]+++def test_one_token_completion_excludes_masked_rows():+ completion_mask = torch.tensor([[1.0], [1.0], [0.0], [0.0]])+ clipped = torch.tensor([[1.0], [0.0], [1.0], [1.0]])+ masked_batch_mean = _load_masked_batch_mean(completion_mask)+ assert masked_batch_mean(clipped).item() == pytest.approx(0.5)+++def test_sequence_level_still_plain_mean():+ completion_mask = torch.tensor([[1.0, 1.0, 0.0], [1.0, 0.0, 0.0]])+ per_sequence = torch.tensor([[1.0], [0.0]])+ masked_batch_mean = _load_masked_batch_mean(completion_mask)+ assert masked_batch_mean(per_sequence).item() == pytest.approx(0.5)+++def test_token_level_masked_mean():+ completion_mask = torch.tensor([[1.0, 1.0, 0.0], [1.0, 0.0, 0.0]])+ clipped = torch.tensor([[1.0, 0.0, 1.0], [1.0, 1.0, 1.0]])+ masked_batch_mean = _load_masked_batch_mean(completion_mask)+ assert masked_batch_mean(clipped).item() == pytest.approx(2.0 / 3.0)diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.pyindex a270be3e3a7..3fa36dbfa68 100644--- a/unsloth/models/rl_replacements.py+++ b/unsloth/models/rl_replacements.py@@ -3725,7 +3725,8 @@ def grpo_trainer_compute_loss(function_name, function):completion_token_count = completion_mask.sum().clamp(min = 1.0)def masked_batch_mean(x):- if x.shape[1] == 1: # when importance_sampling_level == "sequence"+ # a width-1 tensor is sequence-level only when the completion mask spans multiple tokens+ if x.shape[1] == 1 and completion_mask.shape[1] != 1:return x.mean()else:return (x * completion_mask).sum() / completion_token_count