Skip to content

Do not inject the GRPO prompt-trim block into a TRL that cannot host it - #11169

Merged
danielhanchen merged 7 commits into
mainfrom
pr/grpo-protected-tokens-guard
Sep 17, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
pr/grpo-protected-tokens-guard

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Summary

GRPO training with max_prompt_length set dies inside generated code on the bottom of the
TRL range we publish. unsloth/models/rl_replacements.py substitutes a prompt-trim block
into TRL's _generate_and_score_completions, and what it substitutes is a TRL 0.20.0+
block
:

protected = [self.image_token_id, self.vision_start_token_id, self.vision_end_token_id]
protected = [token for token in protected if token is not None]
prompt_ids, prompt_mask = truncate_with_protected_tokens(
    prompt_ids, prompt_mask, self.max_prompt_length, protected
)
prompts_text = [re.sub(rf"^({re.escape(self.pad_token)})+", "", text) for text in prompts_text]

None of truncate_with_protected_tokens, self.pad_token, self.image_token or the three
vision token ids exists on TRL 0.18.2 or 0.19.1, which the declared window
trl>=0.18.2,!=0.19.0,<=0.24.0 still admits. The regex that selects the block matches them
anyway, so on those two releases Unsloth replaced TRL's own working slicing with code whose
names do not resolve:

unsloth_compiled_cache/UnslothGRPOTrainer.py: in _generate_and_score_completions
    protected = [self.image_token_id, self.vision_start_token_id, self.vision_end_token_id]
AttributeError: 'UnslothGRPOTrainer' object has no attribute 'image_token_id'

and, past that line, NameError: name 'truncate_with_protected_tokens' is not defined.

Which versions, measured

Driving the real substitution (grpo_trainer__generate_and_score_completions) against each
release's actual trl/trainer/grpo_trainer.py:

trl block matched helper + pad_token + image_token + ids present before after
0.18.2 (declared floor) yes no AttributeError, then NameError not injected, TRL's slicing kept
0.19.1 yes no AttributeError, then NameError not injected, TRL's slicing kept
0.20.0 yes yes fine injected, unchanged
0.21.0 yes yes fine injected, unchanged
0.22.0 yes yes fine injected, unchanged
0.22.2 yes yes fine injected, unchanged
0.23.0 yes yes fine injected, unchanged
0.23.1 yes yes fine injected, unchanged
0.24.0 (declared ceiling) no, the regex no longer matches no fine unchanged
0.25.1 no no fine unchanged
1.13.0 no no fine unchanged

So this is the bottom of the declared window, not the ceiling. Within that window the
affected releases are 0.18.2 and 0.19.1, and 0.18.2 is what a user gets by pinning the floor
we publish.

Fix

Two changes, both in the one substitution:

  1. Gate the substitution on TRL's own call to truncate_with_protected_tokens inside the
    block it is about to replace.
    That call is the exact discriminator between the two
    groups above: present on 0.20.0 through 0.23.1, absent on 0.18.2 and 0.19.1, and 0.24.0
    and later never matched the regex. Where it is absent, TRL's native
    prompt_ids = prompt_ids[:, -self.max_prompt_length :] is left in place, which is what a
    plain TRL run of those versions does.
  2. getattr(self, "...", None) for the three vision token ids. Belt and braces rather
    than the fix for the above, and it costs nothing: the emitted line immediately after
    already drops None, so an id a fork or a subclass does not set means "no vision token to
    protect" instead of an AttributeError from inside a generated trainer.

The rationale lives in comments outside the emitted f-string, so it explains the choice to a
reader of this file without being pasted into every user's generated trainer.

Tests

tests/version_compat/test_grpo_protected_tokens_guard.py reads the substitution's output
and executes the statements it emits, so it needs neither the affected TRL nor a GPU. It
holds both block shapes as fixtures, so both groups are covered on a runner that has neither:

  • the pre-0.20 shape is not substituted: TRL's slicing survives and none of
    truncate_with_protected_tokens, self.pad_token, self.image_token or protected is
    injected,
  • a vacuity guard that the substitution still fires on the 0.20+ shape, since everything
    below would pass silently if the guard stopped matching it,
  • on the 0.20+ shape, a trainer with none of the three ids: no exception, nothing
    protected,
  • a trainer with all three: all three still reach truncate_with_protected_tokens,
  • a trainer with one: the other two do not discard it,
  • a negative control proving the pre-fix spelling really does raise AttributeError there.

Mutation-checked both ways: dropping the new guard reds the first test, and reverting
getattr to bare attribute access reds three of the others.

The suite is wired into the GRPO fake-run job of .github/workflows/version-compat-ci.yml,
on both the TRL latest and the TRL main invocations, so it runs on pull requests rather than
only on demand. That job is the one in this file that installs CPU torch and TRL, which this
module needs: it drives the real rewriter, so it imports unsloth.models.rl_replacements.
For the dependency-free jobs in the same file (daily-fresh-fetch collects the whole
directory with only pytest installed) the module carries the same pytest.skip guard its
siblings use, so it skips there instead of failing collection for the directory.

How this was found

The transformers floor lane in #11016 could not import at all
(transformers>=4.51.3 with peft>=0.18.0), which hid a dtype kwarg that these training
tests could not survive at the floor, which in turn hid this. With both of those fixed the
tests execute at the declared floor for the first time and this was the one remaining
failure. #11016 stacks on this branch so its floor lane can be green without either carrying
a known red or narrowing what it runs.

rl_replacements.py substitutes an 'if self.max_prompt_length is not None:'
block into TRL's _generate_and_score_completions, and that block read
self.image_token_id, self.vision_start_token_id and self.vision_end_token_id
directly. GRPOTrainer sets those three only on part of the TRL range, while the
substitution fires on any TRL whose source the regex matches, which is wider, so
GRPO training with max_prompt_length set raised AttributeError from inside
generated code.

Measured by driving the real substitution at every release in the declared
window: injected with the attributes ABSENT at 0.18.2 and 0.19.1, injected with
them present from 0.20.0 to 0.23.1, and not injected at all at 0.24.0 or 1.13.0
because the regex no longer matches. The break is the bottom of the window, not
the shipped ceiling.

getattr(..., None) for all three, which is identical wherever they exist because
the next emitted line already drops None.

tests/version_compat/test_grpo_protected_tokens_guard.py executes the emitted
statements against a trainer with none of the three ids, one of them, and all
three, plus a vacuity check that the substitution still fires and a negative
control that the old spelling really did raise.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 17, 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-17T14:15:07.011319Z 819f7d4 Manual request
🔒 Security Review ✅ Completed 2026-09-17T13:19:34.564869Z 7b92ec9 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.

@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: d8f9fed34f

ℹ️ 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".

sys.path.insert(0, str(_SPOOF_DIR))
import _zoo_aggressive_cuda_spoof as _spoof # noqa: E402

_spoof.apply()

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 Guard the torch-dependent spoof in the dependency-free sweep

The daily-fresh-fetch job in .github/workflows/version-compat-ci.yml installs only pytest and then collects the entire tests/version_compat/ directory, but this unconditional call imports torch through _zoo_aggressive_cuda_spoof.apply(). On that job, collection therefore fails with ModuleNotFoundError: No module named 'torch' before any compatibility tests run; this is reproducible locally with pytest -q tests/version_compat/test_grpo_protected_tokens_guard.py. Skip the module when torch is absent or load the rewriter without the torch-dependent spoof.

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.

Confirmed and fixed in 7b92ec9. Reproduced with a pytest-only venv: PYTHONPATH=. python -m pytest -q tests/version_compat/test_grpo_protected_tokens_guard.py errored at collection with ModuleNotFoundError: No module named 'torch' from _zoo_aggressive_cuda_spoof.apply(), which took the whole directory's collection down in daily-fresh-fetch. Added the same module-level guard the siblings already use (test_trl_grpo_fake_run.py, test_trl_loss_normalization_contract.py): if importlib.util.find_spec("torch") is None: pytest.skip(..., allow_module_level = True). With torch absent the directory now collects 1718 tests and this module reports 1 skipped; with torch present the 5 tests still pass.

pre-commit-ci Bot and others added 3 commits September 17, 2026 02:16
tests/studio/test_version_compat_bundle.py asserts that every version_compat suite is named
by a pull_request job, so adding a suite without wiring it up fails that check rather than
silently leaving a compat surface uncovered. That is what happened here.

The suite needs no network and no affected TRL installed: it reads the substitution's own
output and executes the protected lines it emits against an object with none of the three
attributes. It runs in 0.05 s, so the pinned-symbol matrix is the right home for it.
daily-fresh-fetch collects tests/version_compat/ with only pytest installed, and
this module applies the CUDA spoof at import, which imports torch. Collection of
the whole directory failed there. Guard the module the way its siblings already
do.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 7b92ec983f

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

@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: 7b92ec983f

ℹ️ 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 .github/workflows/version-compat-ci.yml Outdated
PYTHONPATH=. python -m pytest \
tests/vllm_compat/test_vllm_pinned_symbols.py \
tests/version_compat/test_trl_grpo_pinned_symbols.py \
tests/version_compat/test_grpo_protected_tokens_guard.py \

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 Run the guard in a torch-enabled lane

In the inspected pinned-symbol-matrix job, only pytest/xdist/packaging are installed, while this test now module-skips whenever torch is absent; the daily directory sweep has the same dependency-free setup, and no other workflow names this test. Consequently all five new regression tests are skipped in CI, so reverting the production fix would remain green. Add this file to one of the existing CPU-torch GRPO invocations (or make the test genuinely torch-independent) instead of listing it here.

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.

Correct, and already fixed in eefa7cd: the pinned-symbol matrix installs pytest, pytest-xdist and packaging only, so with the torch skip guard in place the five tests would have skipped on every pull request and a revert of the rewriter change would still have been green. The file now sits on the GRPO fake-run job instead, on both the TRL latest invocation (which runs on pull requests) and the TRL main invocation (schedule and dispatch), which is the lane in this workflow that installs CPU torch and TRL. It is out of the pinned-symbol line entirely, so the dependency-free jobs only meet it through daily-fresh-fetch's directory sweep, where the guard skips it cleanly. tests/studio/test_version_compat_bundle.py still passes after the move.

The pinned-symbol matrix installs pytest and packaging only, so the suite wired
into it would have skipped on every pull request instead of running. Move it to
the GRPO fake-run job, which installs CPU torch and TRL, and put it on both the
TRL latest and the TRL main invocations.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex 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: eefa7cd7f1

ℹ️ 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 on lines +1112 to +1114
getattr(self, "image_token_id", None),
getattr(self, "vision_start_token_id", None),
getattr(self, "vision_end_token_id", 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.

P1 Badge Add a pre-0.22 prompt-truncation fallback

On the TRL 0.18.2/0.19.1 path this change targets, the guarded accesses now proceed directly to truncate_with_protected_tokens, but the repository's compatibility test documents that this helper only shipped in TRL 0.22.2–0.23.1 (tests/version_compat/test_trl_grpo_pinned_symbols.py:478-485), and there is no Unsloth definition or import supplying it. Therefore training with max_prompt_length on those declared-supported releases still fails, now with NameError instead of AttributeError; the new test misses this because _protected_lines executes only the two assignment statements. Preserve the old slicing behavior or inject an equivalent helper when the TRL module lacks this symbol.

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.

Confirmed and fixed in 819f7d4. Checked against each release's real trl/trainer/grpo_trainer.py: truncate_with_protected_tokens does not exist anywhere in 0.18.2 or 0.19.1 (it arrives in 0.20.0 inside grpo_trainer.py and moves to trainer/utils.py in 0.22.0), and the same two releases also have no self.pad_token and no self.image_token, which the replacement reads as well. So the getattr guard on its own moved the failure from AttributeError to NameError rather than clearing it, exactly as you describe.

The whole replacement is a 0.20.0+ block, so the fix is to stop substituting where it cannot run rather than to backfill a helper. TRL's own call to truncate_with_protected_tokens inside the block that is about to be replaced is the exact discriminator: present on 0.20.0 through 0.23.1, absent on 0.18.2 and 0.19.1, and on 0.24.0 and later the selecting regex stops matching anyway. Driving the real substitution against 0.18.2, 0.19.1, 0.20.0, 0.21.0, 0.22.0, 0.22.2, 0.23.0, 0.23.1, 0.24.0, 0.25.1 and 1.13.0: the two affected releases now keep prompt_ids = prompt_ids[:, -self.max_prompt_length :] untouched and get nothing injected, and 0.20.0 through 0.23.1 are unchanged.

The test file now covers both shapes. test_the_pre_0_20_block_is_left_alone asserts the native slicing survives and that none of truncate_with_protected_tokens, self.pad_token, self.image_token or protected is injected; the getattr tests moved onto a 0.20+ shaped block. Mutation-checked both ways: dropping the new guard reds the first test, reverting getattr to bare attribute access reds three others.

The replacement is a TRL 0.20.0+ block: it calls truncate_with_protected_tokens
and reads self.pad_token and self.image_token. None of the four exist on 0.18.2
or 0.19.1, which the declared window trl>=0.18.2,!=0.19.0,<=0.24.0 still admits,
and the selecting regex matches them anyway. Substituting there replaced working
native slicing with code that raised inside generated trainers the first time
max_prompt_length was set, so the getattr guard alone moved the failure from
AttributeError to NameError rather than clearing it.

Gate the substitution on TRL's own call to truncate_with_protected_tokens inside
the block it is about to lose. Driven against each release's real source, that is
present on 0.20.0 through 0.23.1 and absent on 0.18.2 and 0.19.1, where TRL's
slicing is now left in place; 0.24.0 and later never matched the regex.
@danielhanchen danielhanchen changed the title Do not require TRL's vision token ids in the injected GRPO prompt trim Do not inject the GRPO prompt-trim block into a TRL that cannot host it Sep 17, 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. 🚀

Reviewed commit: 819f7d4dc4

ℹ️ 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 abc3056 into main Sep 17, 2026
3 of 27 checks passed
@danielhanchen
danielhanchen deleted the pr/grpo-protected-tokens-guard branch September 17, 2026 14:43
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…it (unslothai#11169)

* Do not require TRL's vision token ids in the injected GRPO prompt trim

rl_replacements.py substitutes an 'if self.max_prompt_length is not None:'
block into TRL's _generate_and_score_completions, and that block read
self.image_token_id, self.vision_start_token_id and self.vision_end_token_id
directly. GRPOTrainer sets those three only on part of the TRL range, while the
substitution fires on any TRL whose source the regex matches, which is wider, so
GRPO training with max_prompt_length set raised AttributeError from inside
generated code.

Measured by driving the real substitution at every release in the declared
window: injected with the attributes ABSENT at 0.18.2 and 0.19.1, injected with
them present from 0.20.0 to 0.23.1, and not injected at all at 0.24.0 or 1.13.0
because the regex no longer matches. The break is the bottom of the window, not
the shipped ceiling.

getattr(..., None) for all three, which is identical wherever they exist because
the next emitted line already drops None.

tests/version_compat/test_grpo_protected_tokens_guard.py executes the emitted
statements against a trainer with none of the three ids, one of them, and all
three, plus a vacuity check that the substitution still fires and a negative
control that the old spelling really did raise.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Run the new protected-tokens suite on pull requests

tests/studio/test_version_compat_bundle.py asserts that every version_compat suite is named
by a pull_request job, so adding a suite without wiring it up fails that check rather than
silently leaving a compat surface uncovered. That is what happened here.

The suite needs no network and no affected TRL installed: it reads the substitution's own
output and executes the protected lines it emits against an object with none of the three
attributes. It runs in 0.05 s, so the pinned-symbol matrix is the right home for it.

* Skip the protected-tokens guard when torch is absent

daily-fresh-fetch collects tests/version_compat/ with only pytest installed, and
this module applies the CUDA spoof at import, which imports torch. Collection of
the whole directory failed there. Guard the module the way its siblings already
do.

* Run the protected-tokens suite where torch is installed

The pinned-symbol matrix installs pytest and packaging only, so the suite wired
into it would have skipped on every pull request instead of running. Move it to
the GRPO fake-run job, which installs CPU torch and TRL, and put it on both the
TRL latest and the TRL main invocations.

* Do not inject the prompt-trim block into a TRL that cannot host it

The replacement is a TRL 0.20.0+ block: it calls truncate_with_protected_tokens
and reads self.pad_token and self.image_token. None of the four exist on 0.18.2
or 0.19.1, which the declared window trl>=0.18.2,!=0.19.0,<=0.24.0 still admits,
and the selecting regex matches them anyway. Substituting there replaced working
native slicing with code that raised inside generated trainers the first time
max_prompt_length was set, so the getattr guard alone moved the failure from
AttributeError to NameError rather than clearing it.

Gate the substitution on TRL's own call to truncate_with_protected_tokens inside
the block it is about to lose. Driven against each release's real source, that is
present on 0.20.0 through 0.23.1 and absent on 0.18.2 and 0.19.1, where TRL's
slicing is now left in place; 0.24.0 and later never matched the regex.

* Tighten the comments on the prompt-trim guard

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
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.

2 participants