Skip to content

GRPO: train on video prompts instead of scoring them as text - #13144

Merged
danielhanchen merged 7 commits into
mainfrom
grpo-video
Oct 9, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
grpo-video

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 9, 2026 •

Copy link
Copy Markdown
Member

GRPO with video prompts ({"type": "video", "video": path} in the prompt messages) did not train on the video.

  • TRL builds the old, reference and policy logprob forward kwargs from image / images only. The video was decoded for generation, and then the loss was computed over the video placeholder tokens with no pixel_values_videos behind them.
  • With a normal HF Dataset, Arrow adds video: None to 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 bare StopIteration.

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 a video key (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:
    • Rebuilds the video tensors with the processor's own chat template, the same call generation makes, so the video tokens in prompt_ids and the patch rows line up.
    • Each distinct prompt is decoded once and expanded for its num_generations copies (in-memory frames are keyed by identity, never by repr).
    • Uses GRPOConfig.chat_template when set, as generation does.
    • Returns pixel_values_videos, video_grid_thw, second_per_grid_ts and num_videos.
    • Merged into forward_kwargs right 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_inputs shuffle and slice; the existing unsplit merges them back.
  • Both logprob passes treat a video batch as a vision batch:
    • No left packing or sequence packing (they move M-RoPE video positions).
    • mm_token_type_ids is rebuilt when only video_grid_thw is present.
  • Clear errors instead of silent text training for:
    • vLLM (fast_inference = True).
    • Image and video in the same batch (columns or inline image parts).
    • Processors without video_grid_thw.
    • TRL < 0.24.
    • An unsloth_zoo without the video keys.

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.

Model / TRL main, Arrow dataset main, Json dataset this PR, Arrow dataset
Qwen2.5-VL / 0.25.1 StopIteration trains, 0 of 5 logprob forwards get video tensors trains, 20 of 20 get video tensors
Qwen2.5-VL / 1.13.0 StopIteration trains, 0 of 5 logprob forwards get video tensors trains, 20 of 20 get video tensors
Qwen3-VL / 0.25.1 not run not run trains, 20 of 20 get video tensors
Qwen3-VL / 1.13.0 not run not run trains, 20 of 20 get video tensors

On this PR:

  • In every forward, the video token count equals the video_grid_thw rows divided by 4 (all 4 runs).
  • KL at step 1 is 0 on both TRL versions, so the reference pass and the policy pass see the same video inputs.
  • Max absolute logprob difference with real vs blanked video tensors:
TRL Qwen2.5-VL Qwen3-VL
0.25.1 0.0235 0.0812
1.13.0 0.0337 0.1140

Tests

tests/test_grpo_video_inputs.py covers:

  • None-key cleaning.
  • Per distinct prompt decoding and expansion order.
  • Batches without video cost nothing (no processor call).
  • The vLLM / mixed refusals.
  • Video rows surviving TRL's shuffle and slice.
  • The merge landing before the old / reference logprob calls in the real TRL source.

tests/test_grpo_legacy_trl_vision.py now hands the new helpers to its exec harness.

All unsloth GRPO / RL tests pass with this zoo:

  • TRL 0.25.1: 322 passed (315 on main).
  • TRL 1.13.0: 323 passed (316 on main).

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 9, 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-10-09T17:17:32.725733Z 6c4fbe9 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 Oct 9, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 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".

Comment thread unsloth/models/rl_replacements.py Outdated
_unsloth_video_images = images
except NameError:
_unsloth_video_images = None
_unsloth_video_kwargs = _unsloth_grpo_video_inputs(self, prompts, _unsloth_video_images)

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 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 👍 / 👎.

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 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).

Comment thread unsloth/models/rl_replacements.py Outdated
Comment on lines +1867 to +1872
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",

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 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 👍 / 👎.

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.

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.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@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: 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".

Comment on lines +1884 to +1886
_target_line
+ _metadata_extraction
+ " prompts = _unsloth_grpo_clean_video_prompts(prompts, self)\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 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 👍 / 👎.

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.

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.

Comment thread unsloth/models/rl_replacements.py Outdated
_unsloth_video_images = images
except NameError:
_unsloth_video_images = None
_unsloth_video_kwargs = _unsloth_grpo_video_inputs(self, prompts, _unsloth_video_images)

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 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 👍 / 👎.

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.

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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Breezy!

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

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 9, 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 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: 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".

Comment on lines +1368 to +1372
processed = trainer.processing_class.apply_chat_template(
conversation = unique_prompts,
add_generation_prompt = True,
tokenize = True,
return_dict = True,

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 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 👍 / 👎.

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.

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.

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.

1 participant