Repository navigation
GRPO: train on video prompts instead of scoring them as text - #13144
Conversation
TRL builds the logprob forward kwargs from image columns only, so a
{"type": "video"} prompt was generated against its video and then scored
without it. Rebuild the video tensors with the processor's chat template
(once per distinct prompt), merge them into forward_kwargs, keep them with
their samples across the shuffle, and strip the None keys Arrow adds to
content parts, which made Qwen2-VL templates render extra video
placeholders and crash with StopIteration.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3097046bf6
ℹ️ 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".
| _unsloth_video_images = images | ||
| except NameError: | ||
| _unsloth_video_images = None | ||
| _unsloth_video_kwargs = _unsloth_grpo_video_inputs(self, prompts, _unsloth_video_images) |
There was a problem hiding this comment.
Preserve video tokens during prompt truncation
When a supported TRL release applies max_prompt_length to a video prompt, its protected-token list contains the image and vision-boundary IDs but not the repeated video-pad ID. A video-heavy prompt longer than the limit therefore loses video tokens while retaining the full decoded video tensors, and this helper later rebuilds the complete tensors from the untruncated prompt; Qwen-style forwards then fail their token/feature-count check. Patch the truncation path to preserve video tokens, or reject video GRPO when truncation would remove them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reachable for video. The protected-token truncation is only emitted for TRL 0.20 to 0.23, where video GRPO raises (it needs 0.24+). On 0.24 and 0.25 Unsloth already strips max_length / truncation from the generation processor call, TRL 1.x has no max_prompt_length, and the vLLM truncate_prompt_tokens path refuses video. In the TRL 0.25.1 and 1.13 runs the video token count matches video_grid_thw in every forward (20 / 20).
| if _target_line in function: | ||
| function = function.replace( | ||
| _target_line, | ||
| _target_line + _metadata_extraction, | ||
| _target_line | ||
| + _metadata_extraction | ||
| + " prompts = _unsloth_grpo_clean_video_prompts(prompts)\n", |
There was a problem hiding this comment.
Clean environment-owned prompts too
The fresh path not covered by the earlier Arrow-key fix is TRL 1.13's environment_factories branch: it assigns prompts with x.get("prompt", ...), while this replacement inserts cleaning only after the alternate exact x["prompt"] assignment and therefore inside that else block. If an environment-backed Arrow dataset supplies video-shaped prompts, its text parts still carry video: None, so Qwen-style template processing can emit spurious video placeholders and fail before training. Apply the cleanup after both prompt-assignment branches.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The inserted lines are at 8 space indentation, after the if / else, not inside the else. In the trainer generated for TRL 1.13 the cleanup sits at function level right after both prompt assignments (and after the chat_template_kwargs extraction), so environment owned prompts go through it too.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cc8c95f75f
ℹ️ 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".
| _target_line | ||
| + _metadata_extraction | ||
| + " prompts = _unsloth_grpo_clean_video_prompts(prompts, self)\n", |
There was a problem hiding this comment.
Validate videos after environment reset
When environment_factories is used and environment.reset() returns a video content block, this cleanup/guard runs before TRL appends that observation to prompts, so the initial text-only placeholder passes the vLLM check. TRL then sends prompt IDs containing video placeholders through vLLM without video data, and _unsloth_grpo_video_inputs rejects the batch only after generation. Fresh evidence beyond the earlier environment-thread concern is the supported reset flow that mutates prompts after this injected line; rerun the cleanup or at least the vLLM video check after environment observations are applied.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar for this PR: an environment whose reset() returns video observations combined with vLLM is not a path video GRPO targets. It still fails loudly (the video rebuild refuses vLLM with the same NotImplementedError right after rollout), nothing trains on the wrong inputs.
| _unsloth_video_images = images | ||
| except NameError: | ||
| _unsloth_video_images = None | ||
| _unsloth_video_kwargs = _unsloth_grpo_video_inputs(self, prompts, _unsloth_video_images) |
There was a problem hiding this comment.
Reject incompatible custom video rollouts
When rollout_func is configured, TRL treats the function's returned prompt_ids as authoritative and allows them to differ from tokenizing the dataset prompt, but this call always rebuilds video tensors from the original prompts. A custom rollout that truncates, reformats, or removes the video placeholder therefore pairs its returned IDs with unrelated video features, causing the model's video token/feature-count check to fail or scoring a different multimodal input than the rollout generated from. Either consume matching multimodal fields from the rollout result or reject video prompts with custom rollouts unless their prompt IDs are verified against the rebuilt template.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar: a custom rollout_func that rewrites the video placeholders of its prompts is outside what this PR supports. A mismatch is not silent either, the Qwen forwards check the video token count against video_grid_thw and raise.
|
Codex Review: Didn't find any major issues. Breezy! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6c4fbe9cc9
ℹ️ 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".
| processed = trainer.processing_class.apply_chat_template( | ||
| conversation = unique_prompts, | ||
| add_generation_prompt = True, | ||
| tokenize = True, | ||
| return_dict = True, |
There was a problem hiding this comment.
Reuse generated frames when scoring stochastic video samples
When video loading uses a stochastic sample_indices_fn, this second apply_chat_template invocation samples the video again after generation, so the old/reference/policy logprobs can be computed from different frames than those that produced the completion. Deduplication also makes every repeated rollout share this newly sampled clip even if generation sampled each copy independently, silently corrupting the GRPO objective. Preserve and reuse the video tensors or sampled indices from the generation processor call instead of decoding the prompts again.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Below the bar: frame sampling for video GRPO is deterministic (the processor's own decoder with fixed fps sampling), and a stochastic sample_indices_fn is not something GRPO passes or documents. With the default loader both calls decode the same frames, which the per forward token count check against video_grid_thw confirms in every run.
GRPO with video prompts (
{"type": "video", "video": path}in the prompt messages) did not train on the video.image/imagesonly. The video was decoded for generation, and then the loss was computed over the video placeholder tokens with nopixel_values_videosbehind them.Dataset, Arrow addsvideo: Noneto every text content part. Qwen2-VL style chat templates test'video' in content, render an extra video placeholder per text part, and the processor dies with a bareStopIteration.This is also how upstream TRL behaves on 1.15: its GRPO is image only.
Needs the zoo half: unslothai/unsloth-zoo#1654. Related: #3357 (the SFT collator part of that issue is unslothai/unsloth-zoo#1653).
Changes (
unsloth/models/rl_replacements.py)_unsloth_grpo_clean_video_prompts: strips the None keys Arrow adds, in every prompt that carries avideokey (including text rows of a column that also holds videos). Prompts without one are passed through untouched. It also refuses vLLM before generation when the batch has video._unsloth_grpo_video_inputs:prompt_idsand the patch rows line up.num_generationscopies (in-memory frames are keyed by identity, never byrepr).GRPOConfig.chat_templatewhen set, as generation does.pixel_values_videos,video_grid_thw,second_per_grid_tsandnum_videos.forward_kwargsright after TRL builds it, before the old and reference logprobs._unsloth_grpo_split_videos_by_sample: keeps each sample's video rows with it across the_prepare_inputsshuffle and slice; the existing unsplit merges them back.mm_token_type_idsis rebuilt when onlyvideo_grid_thwis present.fast_inference = True).video_grid_thw.Text and image GRPO take the same code paths as before: every new branch keys on a video part being present.
Results (tiny checkpoints, 2 GRPO steps, beta 0.04, gradient accumulation 2,
unsloth_grpo_mini_batch = 4)Every generation batch holds an 8 frame and a 16 frame clip, so a video handed to the wrong sample would fail the token count check.
StopIterationStopIterationOn this PR:
video_grid_thwrows divided by 4 (all 4 runs).Tests
tests/test_grpo_video_inputs.pycovers:tests/test_grpo_legacy_trl_vision.pynow hands the new helpers to its exec harness.All unsloth GRPO / RL tests pass with this zoo: