Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

GRPO: reduce the IS ratio metric per sequence for geometric modes and the env override (#14192)

Daniel Hanb6f21fd28adf
diff --git a/tests/test_grpo_is_metrics_mask.py b/tests/test_grpo_is_metrics_mask.py
index 0a5939d4c25..88313895474 100644
--- a/tests/test_grpo_is_metrics_mask.py
+++ b/tests/test_grpo_is_metrics_mask.py
@@ -83,3 +83,46 @@ def test_shape_mismatch_keeps_the_old_reduction():
delta, flat = _unsloth_inputs(mask, old, sampling, ratio)
got_delta, got_ratio = _helper()(delta, flat, mask[:, :3], False)
assert got_delta.numel() == delta.numel() and got_ratio.numel() == flat.numel()
+
+
+def _sequence_level_helper():
+ tree = ast.parse(RL_REPLACEMENTS.read_text(encoding = "utf-8"))
+ nodes = [
+ n
+ for n in tree.body
+ if isinstance(n, ast.FunctionDef) and n.name == "_unsloth_grpo_is_sequence_level"
+ ]
+ assert len(nodes) == 1, "no _unsloth_grpo_is_sequence_level in rl_replacements.py"
+ ns = {}
+ exec(compile(ast.Module(body = nodes, type_ignores = []), str(RL_REPLACEMENTS), "exec"), ns)
+ return ns["_unsloth_grpo_is_sequence_level"]
+
+
+ "args_mode, env_mode, expected",
+ [
+ (None, "", False),
+ ("token_truncate", "", False),
+ ("token_mask", "", False),
+ ("sequence_mask", "", True),
+ ("sequence_truncate", "", True),
+ # unsloth_zoo geometric_*: one ratio per sequence, like sequence_*.
+ ("geometric_mask", "", True),
+ ("geometric_truncate", "", True),
+ # UNSLOTH_GRPO_VLLM_IS_MODE overrides the config mode in unsloth_zoo's grpo_accumulated_loss.
+ ("token_truncate", "geometric_mask", True),
+ ("sequence_mask", "token_mask", False),
+ ],
+)
+def test_sequence_level_follows_the_applied_mode(monkeypatch, args_mode, env_mode, expected):
+ monkeypatch.setenv("UNSLOTH_GRPO_VLLM_IS_MODE", env_mode)
+ assert _sequence_level_helper()(args_mode) is expected
+
+
+def test_geometric_ratio_metric_is_per_sequence():
+ # Geometric ratio broadcast over a 9-token and a 1-token row: token weighting gives 1.85, TRL-style
+ # per-sequence reduction 1.25.
+ mask = torch.tensor([[1] * 9, [1] + [0] * 8], dtype = torch.float32)
+ ratio = torch.tensor([[2.0], [0.5]]) * mask
+ _, flat = _helper()(torch.zeros(2, 9), ratio, mask, _sequence_level_helper()("geometric_mask"))
+ assert torch.allclose(flat.mean(), torch.tensor(1.25))
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 1709cd1243c..cfa5c9bae97 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -3660,6 +3660,14 @@ def _unsloth_grpo_is_metric_values(delta, flat_is_ratio, mask, sequence_level):
return delta[keep], per_row
+def _unsloth_grpo_is_sequence_level(args_mode):
+ # One IS ratio per sequence: TRL's sequence_* and unsloth_zoo's geometric_* (verl seq_mean_k1),
+ # with the UNSLOTH_GRPO_VLLM_IS_MODE override unsloth_zoo's grpo_accumulated_loss applies.
+ import os as _os
+ mode = _os.environ.get("UNSLOTH_GRPO_VLLM_IS_MODE", "") or args_mode or "token_truncate"
+ return str(mode).startswith(("sequence_", "geometric_"))
+
+
grpo_compute_loss = RL_REPLACEMENTS["grpo_compute_loss"]
grpo_compute_loss_slow = RL_REPLACEMENTS["grpo_compute_loss_slow"]
UnslothEfficientGRPO = RL_REPLACEMENTS["UnslothEfficientGRPO"]
@@ -3680,6 +3688,7 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_get_mm_token_id))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_fix_mm_token_type_ids))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_accumulation_steps))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_is_metric_values))
+RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_is_sequence_level))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_sample_weight_mode))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_trl_masks_unscorable))
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_sample_weight))
@@ -4071,8 +4080,9 @@ def grpo_trainer_compute_loss(function_name, function):
delta,
flat_is_ratio,
completion_mask,
- (getattr(self.args, "vllm_importance_sampling_mode", None) or "token_truncate")
- in ("sequence_mask", "sequence_truncate"),
+ _unsloth_grpo_is_sequence_level(
+ getattr(self.args, "vllm_importance_sampling_mode", None)
+ ),
)
mean_delta = (
torch.mean(delta)