[BUG] RuntimeError: position_ids dimension mismatch when mixing video samples with different durations in same batch
System Info
- verl version: 0.7.0.dev
- PyTorch: 2.6+
- Model: Qwen3-VL / Qwen2.5-VL
- Task: Video RLHF training with different frame counts
Problem Description
When training video data with different durations (frame counts) in the same batch, a dimension mismatch error occurs:
RuntimeError: The size of tensor a (3) must match the size of tensor b (8) at non-singleton dimension 0
This happens specifically when video samples with different frame counts (e.g., 60, 180, 300 frames) are mixed in the same training batch.
Root Cause
Video samples with different durations have different position_ids tensor shapes. When mixed in the same batch, the tensors cannot be properly stacked, leading to dimension mismatches during the forward pass.
Example:
Batch: [60-frame video, 60-frame video, 180-frame video, 180-frame video]
position_ids: [tensor(60), tensor(60), tensor(180), tensor(180)]
→ Dimension mismatch during stacking!
Reproduction
- Prepare a dataset with video samples of different durations (e.g., 60, 180, 300 frames)
- Run GRPO/PPO training with standard DataLoader settings
- Error occurs when different-duration samples are batched together
Expected Behavior
Training should proceed without position_ids dimension errors, either by:
- Ensuring same-duration samples in each batch
- Providing proper padding/handling for mixed-duration batches
- Supporting duration-grouped batching strategy
Current Workaround
Using a custom BatchSampler that groups samples by duration and skips incomplete batches.
Information
- [ ] The official example scripts
- [x] My own modified scripts
Tasks
- [ ] An officially supported task in the
examplesfolder - [x] My own task or dataset (video RLHF with multiple durations)
Update: Root Cause Identified and Fixed
After deeper investigation, the original root cause analysis in this issue was incorrect. The problem is not caused by mixing different-duration samples in the same batch. Here is the corrected analysis and fix.
True Root Cause
The error occurs when all samples in a micro_batch have identical sequence lengths (e.g., all VLM samples producing the same token count after hitting the max_token limit).
The bug is in torch.nested.as_nested_tensor(tensors, layout=torch.jagged) — when called on 3D tensors (VLM position_ids with shape (channels, seq_len) per sample), it auto-detects the jagged dimension. When all samples have identical sequence lengths:
- Expected:
(batch, channels=3, j_seq)withjagged_dim=2(sequence is variable) - Actual:
(batch, j_channels, seq_len)withjagged_dim=1(channels becomes "variable")
This corrupts the position_ids layout. When passed to RoPE embedding, inv_freq_expanded has dim 0 = 3 (channels) but position_ids_expanded has dim 0 = 8 (2 samples × 4 channels treated as batch), causing the 3 vs 8 RuntimeError.
Evidence
# Correct (different seq lengths, auto-detect works):
as_nested_tensor shape: torch.Size([2, 3, j]) # jagged on dim 2 ✅
# Buggy (identical seq lengths, auto-detect fails):
as_nested_tensor shape: torch.Size([2, j, 33470]) # jagged on dim 1 ❌
Fix
Added _reconstruct_nested_tensor() in verl/utils/tensordict_utils.py that explicitly uses nested_tensor_from_jagged(jagged_dim=2) for 3D NestedTensors, replacing the unreliable as_nested_tensor auto-detection.
Modified 3 call sites:
verl/utils/tensordict_utils.py→index_select_tensor_dict()(micro_batch splitting)verl/utils/tensordict_utils.py→chunk_tensordict()(alternative splitting path)verl/utils/seqlen_balancing.py→restore_dynamic_batch()(dynamic batch restoration)
Additional Note: OOM After Fix
After fixing the dimension bug, a secondary OOM issue may be revealed (previously masked by the dimension error crashing first). When all samples have identical lengths, dynamic batching can pack too many samples into one micro_batch, exceeding GPU memory. This can be resolved by lowering ppo_max_token_len_per_gpu to reduce the number of samples per micro_batch.
Summary
| Issue | Root Cause | Fix |
|---|---|---|
RuntimeError: 3 vs 8 dimension mismatch |
as_nested_tensor auto-detects wrong jagged dim when all samples have identical seq lengths |
Use explicit jagged_dim=2 via nested_tensor_from_jagged |
| Potential OOM after fix | micro_batch packs too many same-length samples | Lower ppo_max_token_len_per_gpu appropriately |
Great root cause analysis and fix! The as_nested_tensor auto-detection issue when all samples have identical sequence lengths is a subtle bug.
Your fix using explicit jagged_dim=2 via nested_tensor_from_jagged is correct. A few additional notes:
-
Edge case: This can also happen with non-video VLM tasks when all samples happen to have the same token count (e.g., all hitting
max_tokenlimit). -
Performance consideration: The
_reconstruct_nested_tensorfunction adds overhead. Consider memoizing or caching when possible. -
Test coverage: This edge case (all samples with identical seq lengths) should be added to the CI tests to prevent regression.
-
OOM mitigation: The secondary OOM issue you mentioned can be handled by:
actor_rollout_ref.actor.ppo_max_token_len_per_gpu=32768 # Adjust based on GPU memory
Would be valuable to upstream this fix to PyTorch's as_nested_tensor documentation as a known limitation.