"""Padding-aligned GRPO trainer for the pinned TRL 1.9.1 + Qwen3.5-VL stack. TRL 1.9.1's ``GRPOTrainer._generate_and_score_completions`` builds the multimodal forward inputs for a VLM batch from *two* separate processor calls that pad on opposite sides: * ``prompt_ids`` come from ``_tokenize_prompts`` and are later left-padded (``padding_side="left"``) so the causal model can decode from the right edge. * ``mm_token_type_ids`` and ``image_grid_thw`` come from a second call ``processing_class(images=..., text=..., padding=True)`` whose Qwen processor pads on the **right**. For a batch whose prompts have unequal token lengths the two tensors no longer describe the same columns: the image markers in ``mm_token_type_ids`` sit at different positions than the real image-pad tokens in the left-padded ``prompt_completion_ids``. ``Qwen3_5VLForConditionalGeneration.get_rope_index`` then groups the (misaligned) ``mm_token_type_ids``, consumes a full ``image_grid_thw`` entry for a *partial* image-marker run, and produces an ``llm_positions`` tensor whose column count exceeds the non-padded token count of the row — raising:: RuntimeError: shape mismatch: value tensor of shape [3, 929] cannot be broadcast to indexing result of shape [3, 613] The crash is data- and batch-composition-dependent: equal-length batches pad trivially and run; a heterogeneous batch (different image patch counts / prompt lengths) misaligns and crashes. The same misalignment can also fail *silently*, dropping an image's vision positions entirely (text-only fallback) without raising. The fix recomputes ``mm_token_type_ids`` from the actual ``input_ids`` that reach the model: every image-pad token marks a vision position, every other token marks a text position. This is exactly the construction TRL already uses for the tool-image path (``grpo_trainer.py`` ~line 2524), ported to the non-tool path. Because ``input_ids`` is the left-padded ``prompt_completion_ids`` itself, the rebuilt marker tensor is aligned to it by construction, regardless of how the second processor call padded. Only the per-token marker tensor is rewritten; ``pixel_values``, ``image_grid_thw``, ``num_images``, prompts, completions, masks, and the rollout are untouched, so vLLM generation (which uses its own path) and all sampling are unchanged — this is a correctness fix to the training forward, not a hyperparameter. The override lives on a single shared base so every controlled RL arm (``grpo``, ``papo_controlled``, ``evi_po``) inherits it. """ from __future__ import annotations import logging import os from typing import Any, cast import torch from trl import GRPOTrainer from .vllm_runtime import ( CUDAGRAPH_ENV_VAR, cudagraphs_enabled, patched_rollout_engine, rollout_engine_kwargs, ) logger = logging.getLogger(__name__) def install_reload_weights_skip(vllm_generation: Any) -> bool: """No-op vLLM's per-step ``reload_weights`` disk-reload on CUDA colocate. TRL 1.9.1's colocate + sleep_mode generate path calls ``self.llm.collective_rpc("reload_weights")`` every step as a workaround for vLLM issue #29341 (weights going stale after ``sleep``/``wake_up``). On CUDA + vLLM 0.25.1 this disk reload leaks file/mmap handles: the per-step "Loading safetensors checkpoint shards" duration grows exponentially (~0.7s -> ~12s over ~30 steps around step 2900) and hard-hangs after ~2900 sleep/wake cycles, which is fatal for the 5750-step main/ablation runs (the stall is deterministic -- every retry replays the same batch and re-trips the leak). The reload is redundant here. ``sync_weights`` already pushes the merged LoRA weights into vLLM every step via ``load_weights`` (``_push_param_to_vllm``), and ``wake_up(tags=["weights"])`` restores the weight-memory mapping. That push+wake path is exactly what TRL falls back to on backends that do not implement ``reload_weights`` (the ``except NotImplementedError`` branch in ``generate``), so skipping the disk reload on CUDA is equivalent to that already-supported fallback and keeps the rolled-out weights correct every step. ``collective_rpc`` is invoked exactly once in TRL's vLLM generation module -- with ``"reload_weights"`` -- so narrowing the no-op to that method name leaves every other engine RPC untouched. Returns whether the patch was applied (the LLM object is absent in non-vLLM / server-mode arms). """ llm = getattr(vllm_generation, "llm", None) if llm is None or not callable(getattr(llm, "collective_rpc", None)): return False original = llm.collective_rpc def collective_rpc(method: str, *args: Any, **kwargs: Any) -> Any: if method == "reload_weights": return None return original(method, *args, **kwargs) try: llm.collective_rpc = collective_rpc # type: ignore[method-assign] except AttributeError: logger.warning( "vLLM LLM object rejects instance-level collective_rpc override " "(__slots__); per-step reload_weights leak NOT patched." ) return False logger.info( "Patched vLLM collective_rpc to skip per-step reload_weights " "(vLLM #29341 workaround leaks on CUDA; sync_weights push suffices)." ) return True def realign_mm_token_type_ids( input_ids: torch.Tensor, mm_token_type_ids: torch.Tensor | None, image_pad_token_id: int | None, ) -> torch.Tensor | None: """Rebuild ``mm_token_type_ids`` aligned to ``input_ids``. Returns ``None`` when there is nothing to realign (no multimodal markers, or the image-pad token id is unknown). Otherwise returns a new ``long`` tensor the same shape as ``input_ids`` with ``1`` at every image-pad token position and ``0`` elsewhere — aligned to the (left-padded) ``input_ids`` the model sees, instead of the right-padded markers TRL's second processor call emits. """ if mm_token_type_ids is None or image_pad_token_id is None: return mm_token_type_ids realigned = torch.zeros_like(input_ids, dtype=torch.long) realigned[input_ids == image_pad_token_id] = 1 return realigned class AlignedGRPOTrainer(GRPOTrainer): # type: ignore[misc] """``GRPOTrainer`` with Qwen3.5-VL ``mm_token_type_ids`` realigned to ``input_ids``.""" def __init__(self, *args: Any, **kwargs: Any) -> None: # Build the vLLM rollout engine with cuda-graphs off. vLLM V1 cuda-graph # execution of the Qwen3.5-VL Gated-DeltaNet decode wedges mid-step # (GPU 100%, CPU idle, SIGTERM ignored) about once per 600-900 steps, # which forces the stall watchdog to SIGKILL and resume. The override # must wrap super().__init__ because that is where TRL constructs the # engine; see vllm_runtime for why cudagraph_mode beats enforce_eager # and why this deliberately stays out of the frozen vllm_config. engine_kwargs = rollout_engine_kwargs(os.environ) with patched_rollout_engine(engine_kwargs) as patched: if patched: logger.info( "vLLM rollout engine: cuda-graphs disabled " "(compilation_config=%s) to avoid the V1 cuda-graph " "generation deadlock; set %s=1 to restore upstream behaviour.", engine_kwargs.get("compilation_config"), CUDAGRAPH_ENV_VAR, ) elif cudagraphs_enabled(os.environ): logger.info( "vLLM rollout engine: cuda-graphs left ENABLED by %s; " "the V1 cuda-graph generation deadlock can recur " "(~1 per 600-900 steps).", CUDAGRAPH_ENV_VAR, ) super().__init__(*args, **kwargs) # Neutralize the per-step vLLM reload_weights disk-reload, which leaks # on CUDA and hard-hangs long RL runs after ~2900 sleep/wake cycles. # Applied after super().__init__ so ``self.vllm_generation`` exists; it # is a per-rank instance, so every DDP worker patches its own vLLM. vllm_generation = getattr(self, "vllm_generation", None) if vllm_generation is not None: install_reload_weights_skip(vllm_generation) def _get_per_token_logps_and_entropies( self, model: Any, input_ids: torch.Tensor, attention_mask: torch.Tensor, logits_to_keep: int, batch_size: int | None = None, compute_entropy: bool = False, compute_aux_loss: bool = False, pixel_values: torch.Tensor | None = None, image_grid_thw: torch.Tensor | None = None, num_images: list[int] | None = None, pixel_attention_mask: torch.Tensor | None = None, spatial_shapes: torch.Tensor | None = None, num_tiles: list[int] | None = None, image_sizes: torch.Tensor | None = None, token_type_ids: torch.Tensor | None = None, mm_token_type_ids: torch.Tensor | None = None, image_position_ids: torch.Tensor | None = None, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor | None]: # Realign the multimodal token-type markers to the (left-padded) # input_ids the model is about to see. TRL's non-tool VLM path builds # mm_token_type_ids from a second, right-padded processor call, which # misaligns from input_ids in heterogeneous-length batches and crashes # Qwen3.5-VL's 3D-RoPE index construction. Rebuilding from the image-pad # token positions in input_ids restores per-column alignment. mm_token_type_ids = realign_mm_token_type_ids( input_ids, mm_token_type_ids, getattr(self, "_image_pad_token_id", None) ) return cast( tuple[torch.Tensor, torch.Tensor, torch.Tensor | None], super()._get_per_token_logps_and_entropies( model, input_ids, attention_mask, logits_to_keep, batch_size=batch_size, compute_entropy=compute_entropy, compute_aux_loss=compute_aux_loss, pixel_values=pixel_values, image_grid_thw=image_grid_thw, num_images=num_images, pixel_attention_mask=pixel_attention_mask, spatial_shapes=spatial_shapes, num_tiles=num_tiles, image_sizes=image_sizes, token_type_ids=token_type_ids, mm_token_type_ids=mm_token_type_ids, image_position_ids=image_position_ids, ), )