Skip to content

Fix RLHF _template_context clears template.max_length by default causing truncation to be skipped in GRPO/GKD training - #10192

Merged
tastelikefeet merged 1 commit into
modelscope:mainfrom
burm95:rl-max-length-bug-fix
Sep 20, 2026
Merged

tastelikefeet merged 1 commit into
modelscope:mainfrom
burm95:rl-max-length-bug-fix

Conversation

@burm95

@burm95 burm95 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Background
In GRPO/GKD training, users expect max_length + truncation_strategy=left to truncate long samples before model forward, preventing OOM.

However, entering the _template_context default path (i.e. with self._template_context(template):) unconditionally sets template.max_length = None via the default argument. Because Template._encode_truncated only performs truncation when self.max_length is not None, the truncation step is effectively skipped for the re-encoded training batch.

This leads to the user-visible symptom: even with a very small max_length and truncation_strategy=left, samples that exceed the configured length still cause OOM during policy/ref forward.

Fix
Use a sentinel object (_TEMPLATE_CONTEXT_USE_ORIGINAL) to distinguish between:

Not passed (default): preserve the original template.max_length so truncation keeps working.
Explicitly passed: use the caller-provided value, including None, to temporarily un-set the length limit.
This preserves the existing helper semantics (max_length=None can still explicitly disable length override) while fixing the regression where the default context entry silently disables truncation.

Files changed
swift/rlhf_trainers/rollout_mixin.py
Add _TEMPLATE_CONTEXT_USE_ORIGINAL sentinel.
Update _template_context signature and logic to only override max_length when the caller explicitly passes it.
Verification
Manually validated the call sites in GRPOTrainer/GKDTrainer that enter _template_context without an explicit max_length: they no longer clear template.max_length, so Template._encode_truncated correctly applies the configured max_length + truncation_strategy=left.
Local runs with long prompt samples previously causing OOM now correctly truncate and fit into memory under the same max_length setting.
Notes
This is a minimal, behavior-preserving fix for the default code path. It does not change the call signature contract for code that explicitly passes max_length=None.

@hjh0119

hjh0119 commented Sep 18, 2026

Copy link
Copy Markdown
Collaborator

max_length in GRPO/GKD bounds the prompt (already enforced on the rollout side), so re-encoding prompt+completion here must not truncate again.

@tastelikefeet
tastelikefeet merged commit 2d04646 into modelscope:main Sep 20, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants