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: keep masking completions cut by the vLLM context limit (#16057)

Daniel Han0f289fde012e
diff --git a/tests/test_grpo_stop_string_truncation.py b/tests/test_grpo_stop_string_truncation.py
index d6e3465f4ee..bc6256aa81d 100644
--- a/tests/test_grpo_stop_string_truncation.py
+++ b/tests/test_grpo_stop_string_truncation.py
@@ -1,11 +1,13 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""A stop-string completion below max_completion_length has no EOS but is not truncated (#15382)."""
+"""A stop-string completion below max_completion_length has no EOS but is not truncated (#15382),
+while one cut by the vLLM context (prompt + completion reaching max_model_len) still is."""
import ast
import importlib.util
import re
+import types
import pytest
@@ -24,25 +26,65 @@ def _trl_method_source(name):
pytest.skip(f"this trl has no GRPOTrainer.{name}")
-def _is_truncated(name, transform, completions, max_completion_length):
- source = transform(name, _trl_method_source(name))
+def _transform(name):
+ from unsloth.models import rl_replacements
+ return {
+ "_generate": rl_replacements.grpo_trainer__generate,
+ "_generate_and_score_completions": rl_replacements.grpo_trainer__generate_and_score_completions,
+ }[name]
+
+
+def _trainer(
+ max_completion_length,
+ max_model_len = None,
+ via_vllm_generation = False,
+):
+ trainer = types.SimpleNamespace(max_completion_length = max_completion_length, use_vllm = False)
+ if max_model_len is not None:
+ model_config = types.SimpleNamespace(max_model_len = max_model_len)
+ llm = types.SimpleNamespace(llm_engine = types.SimpleNamespace(model_config = model_config))
+ trainer.use_vllm = True
+ if via_vllm_generation: # TRL 0.28+ keeps the engine on VLLMGeneration
+ trainer.vllm_generation = types.SimpleNamespace(llm = llm)
+ else:
+ trainer.llm = llm
+ return trainer
+
+
+def _is_truncated(
+ name,
+ completions,
+ trainer,
+ prompts = None,
+):
+ from unsloth.models import rl_replacements
+
+ source = _transform(name)(name, _trl_method_source(name))
if "eos_and_pad" not in source:
pytest.skip("this trl does not detect truncation from the last token")
- match = re.search(r"is_truncated = torch\.tensor\((\[[^\n]*for ids in (\w+)\])", source)
+ match = re.search(r"is_truncated = torch\.tensor\(([^\n]*), device=device\)", source)
assert match is not None
- trainer = type("Trainer", (), {"max_completion_length": max_completion_length})()
- namespace = {"self": trainer, "eos_and_pad": [EOS, PAD], match.group(2): completions}
- return eval(match.group(1), namespace)
+ if prompts is None:
+ prompts = [[7] * 4 for _ in completions]
+ namespace = {
+ "self": trainer,
+ "eos_and_pad": [EOS, PAD],
+ "completion_ids": completions,
+ "completion_ids_list": completions,
+ "prompt_ids": prompts,
+ "prompt_ids_list": prompts,
+ }
+ helper = getattr(rl_replacements, "_unsloth_grpo_is_truncated", None)
+ if helper is not None:
+ namespace["_unsloth_grpo_is_truncated"] = helper
+ return list(eval(match.group(1), namespace))
[email protected]("name", ["_generate", "_generate_and_score_completions"])
-def test_only_length_exhausted_completions_without_eos_are_truncated(name):
- from unsloth.models import rl_replacements
+NAMES = ["_generate", "_generate_and_score_completions"]
- transform = {
- "_generate": rl_replacements.grpo_trainer__generate,
- "_generate_and_score_completions": rl_replacements.grpo_trainer__generate_and_score_completions,
- }[name]
+
[email protected]("name", NAMES)
+def test_only_length_exhausted_completions_without_eos_are_truncated(name):
completions = [
[5] * 85, # stopped on a stop string well below the limit
[5] * 128,
@@ -50,5 +92,29 @@ def test_only_length_exhausted_completions_without_eos_are_truncated(name):
[5] * 127 + [PAD],
[5] * 40 + [EOS],
]
- assert _is_truncated(name, transform, completions, 128) == [False, True, False, False, False]
- assert _is_truncated(name, transform, completions, None) == [True, True, False, False, False]
+ assert _is_truncated(name, completions, _trainer(128)) == [False, True, False, False, False]
+ assert _is_truncated(name, completions, _trainer(None)) == [True, True, False, False, False]
+
+
[email protected]("via_vllm_generation", [False, True])
[email protected]("name", NAMES)
+def test_completion_cut_by_vllm_context_is_truncated(name, via_vllm_generation):
+ # max_model_len 512 (= max_seq_length of the fast_inference engine), max_completion_length 128.
+ completions = [
+ [5] * 32, # 480-token prompt: vLLM stops at 512 total tokens, FINISHED_LENGTH_CAPPED
+ [5] * 10, # 480-token prompt, stop string after 10 tokens: 490 < 512, not truncated
+ [5] * 10, # short prompt, stop string
+ [5] * 31 + [EOS], # EOS exactly at the context limit is a normal stop
+ [5] * 128, # completion budget exhausted
+ ]
+ prompts = [[7] * 480, [7] * 480, [7] * 20, [7] * 480, [7] * 20]
+ trainer = _trainer(128, max_model_len = 512, via_vllm_generation = via_vllm_generation)
+ assert _is_truncated(name, completions, trainer, prompts) == [True, False, False, False, True]
+ # Without a local engine (HF generate, vLLM server mode) only the completion budget is known.
+ assert _is_truncated(name, completions, _trainer(128), prompts) == [
+ False,
+ False,
+ False,
+ False,
+ True,
+ ]
diff --git a/unsloth/models/rl_replacements.py b/unsloth/models/rl_replacements.py
index 7da7f3a2b7c..8dacccab47d 100644
--- a/unsloth/models/rl_replacements.py
+++ b/unsloth/models/rl_replacements.py
@@ -2310,15 +2310,64 @@ def grpo_trainer__generate_single_turn(function_name, function):
RL_FUNCTIONS["grpo_trainer"].append(grpo_trainer__generate_single_turn)
+def _unsloth_grpo_is_truncated(trainer, completion_ids, prompt_ids, eos_and_pad):
+ """Completions cut by a length limit, not ended by EOS or a stop string (no EOS either).
+ vLLM also caps prompt + completion at max_model_len (= max_seq_length), so that counts too."""
+ limit = getattr(trainer, "max_completion_length", None)
+ max_model_len = None
+ if getattr(trainer, "use_vllm", False):
+ llm = getattr(trainer, "llm", None)
+ if llm is None:
+ llm = getattr(getattr(trainer, "vllm_generation", None), "llm", None)
+ engine = getattr(llm, "llm_engine", None)
+ model_config = getattr(engine, "model_config", None)
+ if model_config is None:
+ model_config = getattr(getattr(engine, "vllm_config", None), "model_config", None)
+ max_model_len = getattr(model_config, "max_model_len", None)
+ if not isinstance(max_model_len, int):
+ max_model_len = None
+ if (
+ max_model_len is not None
+ and isinstance(prompt_ids, (list, tuple))
+ and len(prompt_ids) == len(completion_ids)
+ ):
+ prompt_lengths = [len(ids) for ids in prompt_ids]
+ else:
+ prompt_lengths = None
+ is_truncated = []
+ for i, ids in enumerate(completion_ids):
+ if ids[-1] in eos_and_pad:
+ is_truncated.append(False)
+ elif limit is None or len(ids) >= limit:
+ is_truncated.append(True)
+ else:
+ is_truncated.append(
+ prompt_lengths is not None and prompt_lengths[i] + len(ids) >= max_model_len
+ )
+ return is_truncated
+
+
+def _unsloth_patch_grpo_truncation_check(function):
+ # TRL 0.24+ marks any non-EOS / pad ending as truncated. `_generate` has `prompt_ids`,
+ # `_generate_and_score_completions` has `prompt_ids_list` (0.24.0 to 1.17).
+ def _replace(match):
+ completions = match.group(1)
+ prompts = "prompt_ids_list" if completions.endswith("_list") else "prompt_ids"
+ return f"_unsloth_grpo_is_truncated(self, {completions}, {prompts}, eos_and_pad)"
+
+ return re.sub(
+ r"\[ids\[-1\] not in eos_and_pad for ids in (completion_ids(?:_list)?)\]",
+ _replace,
+ function,
+ )
+
+
def grpo_trainer__generate(function_name, function):
if function_name != "_generate":
return function
# A stop string can terminate a completion before the limit without an EOS token.
- function = function.replace(
- "ids[-1] not in eos_and_pad",
- "(self.max_completion_length is None or len(ids) >= self.max_completion_length) and ids[-1] not in eos_and_pad",
- )
+ function = _unsloth_patch_grpo_truncation_check(function)
return _guard_vllm_sync_reload_for_shared_weights(function)
@@ -2330,10 +2379,7 @@ def grpo_trainer__generate_and_score_completions(function_name, function):
if function_name != "_generate_and_score_completions":
return function
- function = function.replace(
- "ids[-1] not in eos_and_pad",
- "(self.max_completion_length is None or len(ids) >= self.max_completion_length) and ids[-1] not in eos_and_pad",
- )
+ function = _unsloth_patch_grpo_truncation_check(function)
function = function.replace(
"prompt_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False",
"prompt_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False",
@@ -4915,6 +4961,7 @@ RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_returns_hidd
RL_PRE_ITEMS["grpo_trainer"].append(inspect.getsource(_unsloth_grpo_hidden_states_signal))
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_is_truncated))
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))