Skip to content

Keep TRL's own RL config defaults and clamp preference max_length - #12069

Merged
danielhanchen merged 5 commits into
mainfrom
rl-config-defaults-match-trl
Sep 27, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
rl-config-defaults-match-trl

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Follow up to #11951. An audit of every RL trainer config Unsloth rewrites, against TRL 0.18.2 through 1.14.0, found defaults that silently drifted away from TRL's own, plus one crash. Everything here is config-side; the loss math matched TRL.

Fixes

# What was wrong Who hits it Fix
1 top_k was forced to None in every RL config. TRL 0.27 made 0 the "off" value (trl#4695). On transformers 5, None falls back to the model's generation_config.top_k (or 50), so rollouts were sampled from a truncated distribution while log-probs use the full softmax. GRPO without vLLM, RLOO, Online DPO on TRL >= 0.27 Drop the override, keep TRL's default
2 The default rewrite regex had no word boundary, so the seed default also rewrote data_seed = None to 3407. Data order then ignored the user's seed. Every trainer, every TRL \b anchor
3 loss_type="dapo" overwrote explicit epsilon_high and mask_truncated_completions. DAPO users who set them Fill the DAPO paper values only when unset (mask_truncated_completions now defaults to a None sentinel, resolved to False for other loss types)
4 GRPO on TRL 0.18.x / 0.19.x crashed on the first step with NameError: has_images (then images, importance_sampling_level, missing reference logps). GRPO on TRL < 0.20 Clear ImportError asking for trl >= 0.20.0
5 DPO / KTO / ORPO / CPO crashed with Size does not match at dimension 1 when a row was longer than the model's max_seq_length: the fast forward truncates input_ids, but TRL builds labels at args.max_length (default 1024). The KTO-only regex guard stopped matching at TRL 1.7. Preference trainers with max_seq_length < max_length Clamp args.max_length (and max_prompt_length) to the model limit

Two comments were also corrected: bnpo is TRL's pre-0.22 default, not the GRPO paper objective (that is grpo), and router_aux_loss_coef > 0 is rejected, not an opt in.

Evidence

Top-k on TRL 1.14.0, tiny Qwen3 whose generation config has top_k=20, GRPO non-vLLM generation config:

main: config top_k None -> effective top_k 20 | warpers ['TopKLogitsWarper']
this: config top_k 0    -> effective top_k 0  | warpers []

Preference trainers, max_seq_length=48, Qwen2.5-0.5B, rows of about 67 tokens:

DPO TRL 0.25.1  main: RuntimeError Size does not match at dimension 1 expected index [8, 68, 1] ... self [8, 48, 151936]
                this: max_length reduced to 48, loss 0.6931
KTO TRL 1.14.0  main: RuntimeError Size does not match at dimension 1 expected index [4, 66, 1] ... self [4, 47, 151936]
                this: max_length reduced to 48, loss 0.5

GRPO on old TRL: 0.18.2 and 0.19.1 now raise Unsloth: GRPO needs trl >= 0.20.0; SFT / DPO configs there are unchanged, and 0.22.2 is unaffected.

Tests

New deterministic CPU tests, so the next TRL default change fails a test instead of a training run:

  • tests/version_compat/test_trl_config_defaults_contract.py: every generated config (SFT, DPO, GRPO, RLOO, KTO, ORPO, CPO, Reward, GKD, Online DPO) may only differ from TRL's own defaults on an explicit allowlist of intended overrides; top_k and data_seed must equal TRL's; DAPO fills only unset values; and the TRL defaults the loss-type overrides key on (scale_rewards, epsilon_high, mask_truncated_completions) are pinned so a new spelling is caught.
  • tests/version_compat/test_pref_max_length_clamp.py: the clamp logic, and that the patched DPO / KTO trainers carry it.

Base vs head (merge base c0b27d245): 19 tests fail on main and pass here, 7 unchanged, 0 new failures. Run against TRL 0.22.2, 0.25.1 and 1.14.0; the top_k cases only discriminate on TRL >= 0.27, as expected.

A companion unsloth-zoo PR warns when TRL 1.8's entropy_coef / use_adaptive_entropy is set, since the optimized GRPO loss does not apply the entropy bonus.

- Stop forcing top_k=None. TRL 0.27 made 0 the off value (trl#4695); None lets
  transformers 5 fall back to the model's top_k, so RLOO and non-vLLM GRPO
  rollouts were sampled with top-k 20 or 50.
- Anchor the default rewrites on a word boundary so the seed default no longer
  rewrites data_seed.
- DAPO: fill epsilon_high and mask_truncated_completions only when unset.
- GRPO on TRL < 0.20 now raises a clear upgrade error instead of NameError.
- Contract test: generated configs may only move the defaults Unsloth means to.
The fast forward cuts input_ids to model.max_seq_length, but these trainers build
labels and completion ids at args.max_length (default 1024), so a longer row
crashed the log-prob gather. The KTO-only regex guard stopped matching at TRL 1.7
and DPO / ORPO / CPO never had one.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-27T04:23:30.029801Z f077fd8 Manual request
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8dd74984b2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread unsloth/models/rl.py Outdated
Comment on lines +2582 to +2583
" if getattr(args, 'max_prompt_length', None) is not None and args.max_prompt_length >= args.max_length:\n"
" args.max_prompt_length = args.max_length // 2\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Resolve a None prompt cap before clamping

When max_prompt_length=None is passed with a model limit of 128 tokens or fewer, this condition leaves it unset while reducing max_length to the model limit. The inspected CPO/ORPO/KTO trainer initializers subsequently resolve None to 128; CPO then raises because the prompt limit is not strictly below max_length, while ORPO/KTO can compute a negative completion budget. This can now fail even for datasets whose rows already fit the model limit, so the clamp should assign a safe prompt limit for the None case as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1f828d2: when max_length is clamped to 128 or less, an unset max_prompt_length now gets half of it, so the None -> 128 resolution in ORPO / CPO / KTO stays below max_length. Covered by a new test.

Comment thread unsloth/models/rl.py
Comment on lines +2786 to +2787
# None = unset, so the dapo check below can tell it from an explicit False.
"mask_truncated_completions": None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the unset sentinel in dataclass-based parsers

Changing only the generated __init__ signature to default this argument to None does not change the inherited dataclass field, whose default remains False. HfArgumentParser/TRL's TrlParser derive defaults from dataclasses.fields() and pass every parsed field into the constructor, so a CLI run that selects loss_type=dapo without mentioning this option supplies False and bypasses the new None-based DAPO defaulting. Such runs silently retain mask_truncated_completions=False instead of receiving the intended DAPO value; the sentinel must also be represented to dataclass-backed configuration loaders.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this: nothing in unsloth or studio builds these configs through HfArgumentParser / TrlParser, and a parser-supplied False is TRL's own default, so such runs get plain TRL behaviour rather than a wrong value.

Comment thread unsloth/models/rl.py Outdated
Comment on lines +2582 to +2583
" if getattr(args, 'max_prompt_length', None) is not None and args.max_prompt_length >= args.max_length:\n"
" args.max_prompt_length = args.max_length // 2\n"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Only rewrite the prompt limit when the sequence cap changed

This prompt-limit rewrite runs even when args.max_length was already below the model limit and therefore was not clamped. For example, DPO with max_length=1024, max_prompt_length=1024, and a model limit of 2048 is silently changed to a 512-token prompt cap; DPO's preprocessing applies that prompt cap independently, so otherwise valid examples with a long prompt and a short completion lose prompt tokens despite having fit the requested full-sequence limit. Track whether the outer branch actually reduced max_length and restrict this fallback to that case instead of altering explicit, unrelated settings.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 1f828d2: the prompt limit is only touched when max_length was actually clamped, with a regression test for max_length=1024, max_prompt_length=1024 on a 2048 model.

Leave an explicit max_prompt_length alone when max_length already fits the model,
and give an unset one half the clamped length when that is 128 or less, since
ORPO / CPO / KTO resolve None to 128.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 27, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: 1f828d2771

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: f077fd857f

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@danielhanchen
danielhanchen merged commit ec9cc2c into main Sep 27, 2026
27 checks passed
@danielhanchen
danielhanchen deleted the rl-config-defaults-match-trl branch September 27, 2026 05:15
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…slothai#12069)

* Keep TRL's own config defaults: top_k, data_seed, explicit DAPO settings

- Stop forcing top_k=None. TRL 0.27 made 0 the off value (trl#4695); None lets
  transformers 5 fall back to the model's top_k, so RLOO and non-vLLM GRPO
  rollouts were sampled with top-k 20 or 50.
- Anchor the default rewrites on a word boundary so the seed default no longer
  rewrites data_seed.
- DAPO: fill epsilon_high and mask_truncated_completions only when unset.
- GRPO on TRL < 0.20 now raises a clear upgrade error instead of NameError.
- Contract test: generated configs may only move the defaults Unsloth means to.

* Clamp DPO / KTO / ORPO / CPO max_length to the model max_seq_length

The fast forward cuts input_ids to model.max_seq_length, but these trainers build
labels and completion ids at args.max_length (default 1024), so a longer row
crashed the log-prob gather. The KTO-only regex guard stopped matching at TRL 1.7
and DPO / ORPO / CPO never had one.

* Trim new comments

* Only move the prompt limit when max_length was clamped

Leave an explicit max_prompt_length alone when max_length already fits the model,
and give an unset one half the clamped length when that is 128 or less, since
ORPO / CPO / KTO resolve None to 128.

* Run the new config and max_length contract tests in version-compat CI
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Oct 5, 2026
…rch (unslothai#12274)

* tests: skip two version_compat suites where the daily sweep has no torch

daily-fresh-fetch in version-compat-ci.yml runs all of tests/version_compat/
after installing nothing but pytest. The other suites there that need torch
skip in that job, eight of them on a module-scope find_spec("torch") guard, and
two of those say why: "daily-fresh-fetch collects this directory with only
pytest installed." test_trl_config_defaults_contract.py (unslothai#12069, unslothai#12088) and
test_pref_max_length_clamp.py (unslothai#12069) have no guard. They pass in
grpo-fake-run, which installs torch, and in the sweep every `import unsloth`
stops at unsloth/_gpu_init.py's `import numpy`.

The sweep passed daily up to 2026-09-26 and has failed daily since unslothai#12069
merged: 43 failed on 09-28 and 09-29, all 43 in these two files on that
ModuleNotFoundError. The 09-27 run exited 1 and its log has expired.

The defaults contract imports unsloth in every test, so it takes its
neighbours' guard at module scope. In the clamp file seven tests read rl.py as
text and still run in the sweep, so only test_patched_trainer_carries_the_clamp,
which imports unsloth and trl, is guarded.

test_the_daily_sweep_skips_what_it_cannot_import runs every suite the sweep
collects outside the pip-free bundle in a subprocess with torch, numpy,
transformers, trl, peft, accelerate and unsloth_zoo hidden, and fails on any
test that fails rather than skips. workflow-trigger-lint runs that file on
every pull request with no torch installed, so a suite added without the guard
now fails its own pull request instead of the next morning's cron. It fails on
main with the sweep's 43 tests and passes here.

One consequence worth naming: the new test adds about 2 s to
workflow-trigger-lint on every pull request, measured in that job's environment.

* Tighten comments in the version-compat sweep guard

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant