# processing_rynn_value_lang.py import torch from typing import Union, Optional, List from einops import rearrange from PIL.Image import Image from transformers.feature_extraction_utils import BatchFeature from transformers.image_utils import ImageInput from transformers.models.qwen3_vl.processing_qwen3_vl import ( Qwen3VLProcessor, Qwen3VLProcessorKwargs, ) from transformers.processing_utils import Unpack from transformers.tokenization_utils_base import PreTokenizedInput, TextInput from .conversations import ( ConversationBuilder, InterleavedHistoryConversationBuilder, InterleavedLangConversationBuilder, build_conversation_builder, ) DEFAULT_CONVERSATION_STYLE = InterleavedHistoryConversationBuilder.name class RynnValueLangProcessor(Qwen3VLProcessor): attributes = ["image_processor", "tokenizer"] image_processor_class = "AutoImageProcessor" tokenizer_class = ("Qwen2Tokenizer", "Qwen2TokenizerFast") def __init__( self, image_processor=None, tokenizer=None, video_processor=None, chat_template=None, use_meta=False, conversation_style: str = DEFAULT_CONVERSATION_STYLE, value_token_repeat: int = 1, relative_value_token_repeat: int = 1, **kwargs, ): super().__init__(image_processor=image_processor, tokenizer=tokenizer, video_processor=video_processor, chat_template=chat_template, **kwargs) # Whether to inject robot type / camera position meta info into prompts. # Decided at processor construction and persisted in processor_config.json; # not threaded through individual build_conversation/process_* calls. self.use_meta = use_meta # Selects the ConversationBuilder that owns the prompt layout. Persisted # in processor_config.json so train and inference build identical prompts # without the caller having to re-specify. self.conversation_style = conversation_style # Number of consecutive tokens emitted per prediction slot. # Persisted so the model can pool the R tokens back to one prediction. if value_token_repeat < 1: raise ValueError( f"value_token_repeat must be >= 1, got {value_token_repeat}" ) self.value_token_repeat = int(value_token_repeat) # Same for : R copies per slot, pooled by the model. if relative_value_token_repeat < 1: raise ValueError( f"relative_value_token_repeat must be >= 1, got {relative_value_token_repeat}" ) self.relative_value_token_repeat = int(relative_value_token_repeat) # Whether the relative-value pathway is active. Set by # add_special_tokens_and_resize from the model config (a relative head # present, or a layout that structurally requires the token). Defaults to # True so standalone / inference use keeps the legacy behaviour until the # setup routine refines it. Gates whether the builder emits # tokens and whether process_* pack relative targets. self.use_relative = True # Build eagerly so callers can rely on `self.conversation_builder` from # __init__ onwards. After mutating tokens or toggling use_meta / # conversation_style, callers must invoke # ``refresh_conversation_builder()`` to pick up the change — see # ``add_special_tokens_and_resize``. self.conversation_builder: ConversationBuilder = self._build_conversation_builder() @classmethod def from_qwen3vl(cls, pretrained_model_name_or_path: str, **kwargs): """ Build a RynnValueLangProcessor from a Qwen3VL checkpoint. """ return cls.from_pretrained(pretrained_model_name_or_path, **kwargs) @property def value_token(self): return "" @property def value_token_id(self): return self.tokenizer.convert_tokens_to_ids(self.value_token) @property def relative_value_token(self): return "" if "" in self.tokenizer.get_vocab() else None @property def relative_value_token_id(self): token = self.relative_value_token return None if token is None else self.tokenizer.convert_tokens_to_ids(token) def __call__( self, images: ImageInput, text: Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None, **kwargs: Unpack[Qwen3VLProcessorKwargs], ) -> BatchFeature: return super().__call__( images=images, text=text, **kwargs, **{ "return_tensors": "pt", }, ) def _build_conversation_builder(self) -> ConversationBuilder: """Snapshot the processor's current state into a ConversationBuilder.""" return build_conversation_builder( self.conversation_style, value_token=self.value_token, relative_value_token=self.relative_value_token if self.use_relative else None, use_meta=self.use_meta, value_token_repeat=self.value_token_repeat, relative_value_token_repeat=self.relative_value_token_repeat, ) def refresh_conversation_builder(self) -> ConversationBuilder: """Rebuild ``self.conversation_builder`` from the current processor state. Callers should invoke this whenever they mutate any input the builder depends on (e.g. ``use_meta``, ``conversation_style``, or any of the special tokens on the tokenizer). """ self.conversation_builder = self._build_conversation_builder() return self.conversation_builder def build_conversation( self, instruction: str, num_frames: int = 1, conversation_type: str = "progress", target_image: Optional[Image] = None, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ): """Build a conversation for value prediction. The actual prompt layout is owned by ``self.conversation_builder`` (see ``conversations.py``). The processor only forwards the request and stays agnostic to the chosen style — different builders may emit a single trailing ```` (video-prefix layout) or one per frame (legacy interleaved layout). ``robot_description`` and ``camera_description`` are pre-resolved natural-language descriptions (computed by the strategy layer) for the embodiment and camera viewpoint; they are only consumed when the processor was constructed with ``use_meta=True``. In relative mode the step ```` is NOT predicted — each frame carries only a ```` token (time-to-target), trained by the separate relative head. The target image is required and is part of the leading prompt; the caller must pass it as the first image to ``__call__`` so placeholders line up with the supplied images. """ if num_frames < 1: raise ValueError(f"num_frames must be >= 1, got {num_frames}") conversation_type = conversation_type.lower() builder = self.conversation_builder if conversation_type == "progress": content = builder.build_progress( instruction=instruction, num_frames=num_frames, robot_description=robot_description, camera_description=camera_description, ) elif conversation_type == "relative": content = builder.build_relative( instruction=instruction, num_frames=num_frames, target_image=target_image, robot_description=robot_description, camera_description=camera_description, ) elif conversation_type == "progress_relative": content = builder.build_progress_relative( instruction=instruction, num_frames=num_frames, target_image=target_image, robot_description=robot_description, camera_description=camera_description, ) else: raise ValueError( f"Unsupported conversation_type: {conversation_type}. " "Expected one of ['progress', 'relative', 'progress_relative']." ) return [{"role": "user", "content": content}] @staticmethod def _frame_target_values( goal_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, ) -> torch.Tensor: """Return per-frame targets as [1, N].""" ts = frame_timestamps.to(device).reshape(-1) goal_ts = goal_timestamp.to(device).reshape(1) return (goal_ts - ts).float().unsqueeze(0) @staticmethod def _anchor_target_value( goal_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, ) -> torch.Tensor: """Return the single anchor (last-frame) target as [1, 1].""" ts = frame_timestamps.to(device).reshape(-1) goal_ts = goal_timestamp.to(device).reshape(1) return (goal_ts - ts[-1:]).float().unsqueeze(0) def _progress_targets( self, goal_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, value_count: int, ) -> torch.Tensor: """Targets aligned with the builder's token count. ``value_count == 1`` -> anchor (last-frame) remaining time, [1, 1]. Otherwise per-frame remaining times, [1, value_count]; ``value_count`` must equal the number of input frames so the targets align with the interleaved tokens. Frames past the goal saturate at 0 — the progress head represents non-negative time-to-done. """ if value_count == 1: target = self._anchor_target_value(goal_timestamp, frame_timestamps, device) else: target = self._frame_target_values(goal_timestamp, frame_timestamps, device) if target.shape[1] != value_count: raise ValueError( f"Conversation builder expects {value_count} targets but " f"received {target.shape[1]} frame timestamps." ) return target.clamp_min(0) @staticmethod def _normalized_denominator( goal_timestamp: torch.Tensor, start_timestamp: torch.Tensor, device: torch.device, ) -> torch.Tensor: """Episode duration ``goal - start`` used to normalize progress. Clamped away from zero so degenerate (single-frame / zero-length) episodes don't produce NaNs; the numerator is ~0 there anyway. """ goal_ts = goal_timestamp.to(device).reshape(1).float() start_ts = start_timestamp.to(device).reshape(1).float() return (goal_ts - start_ts).clamp_min(1e-6) @staticmethod def _normalized_frame_targets( goal_timestamp: torch.Tensor, start_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, ) -> torch.Tensor: """Per-frame normalized progress ``(t - start) / (goal - start)`` as [1, N].""" ts = frame_timestamps.to(device).reshape(-1).float() start_ts = start_timestamp.to(device).reshape(1).float() denom = RynnValueLangProcessor._normalized_denominator(goal_timestamp, start_timestamp, device) return ((ts - start_ts) / denom).unsqueeze(0) @staticmethod def _normalized_anchor_target( goal_timestamp: torch.Tensor, start_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, ) -> torch.Tensor: """Single anchor (last-frame) normalized progress as [1, 1].""" ts = frame_timestamps.to(device).reshape(-1).float() start_ts = start_timestamp.to(device).reshape(1).float() denom = RynnValueLangProcessor._normalized_denominator(goal_timestamp, start_timestamp, device) return ((ts[-1:] - start_ts) / denom).unsqueeze(0) def _normalized_progress_targets( self, goal_timestamp: torch.Tensor, start_timestamp: torch.Tensor, frame_timestamps: torch.Tensor, device: torch.device, value_count: int, ) -> torch.Tensor: """Normalized [0, 1] progress targets aligned with the tokens. Mirrors :meth:`_progress_targets` but returns a unitless completion fraction instead of remaining seconds: 0 at ``start_frame`` and 1 at ``cutoff_frame``. Frames past the goal saturate at 1. """ if value_count == 1: target = self._normalized_anchor_target( goal_timestamp, start_timestamp, frame_timestamps, device ) else: target = self._normalized_frame_targets( goal_timestamp, start_timestamp, frame_timestamps, device ) if target.shape[1] != value_count: raise ValueError( f"Conversation builder expects {value_count} targets but " f"received {target.shape[1]} frame timestamps." ) return target.clamp(0.0, 1.0) def process_step( self, instruction: str, images: List[Image], frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process a single step/progress sample. The number and placement of ```` tokens is decided by the active ConversationBuilder. Targets are aligned accordingly: a single-token builder yields an anchor (last-frame) target, while a per-frame builder yields one target per frame. """ builder = self.conversation_builder value_count = builder.progress_value_count(len(images)) conversation = self.build_conversation( instruction, num_frames=len(images), conversation_type="progress", robot_description=robot_description, camera_description=camera_description, ) text = self.apply_chat_template(conversation) mini_outputs = self.__call__(text=text, images=images) input_ids = mini_outputs["input_ids"] target_values = self._progress_targets( goal_timestamp, frame_timestamps, device=input_ids.device, value_count=value_count, ) mini_outputs["value"] = target_values return mini_outputs def process_sequence( self, instruction: str, images: List[Image], frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process a sequence sample (multi-frame value prediction). Delegates to :meth:`process_step` — exists as a distinct entry point so the SequenceStrategy pipeline has its own call signature. """ return self.process_step( instruction=instruction, images=images, frame_timestamps=frame_timestamps, goal_timestamp=goal_timestamp, robot_description=robot_description, camera_description=camera_description, ) def process_sequence_lang( self, instructions: List[str], images: List[Image], frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, relative_distances: torch.Tensor, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process a sequence sample for joint value + language prediction. Args: instructions: Per-frame instruction targets (len == len(images)). Each element is the instruction text to predict for that frame. images: List of PIL Images for the sampled frames. frame_timestamps: Timestamps of the sampled frames. goal_timestamp: Timestamp of task completion. relative_distances: Signed time delta between consecutive frames (positive = progress, negative = regress). Shape [num_frames]. robot_description: Optional robot embodiment description. camera_description: Optional camera viewpoint description. Uses the ``interleaved_lang`` conversation layout where each frame is followed by ``{instruction_i} ``. The instruction tokens are supervised with causal LM loss (next-token prediction), while ```` tokens are supervised by the value head. ``relative_distances`` serves as additional per-frame supervision target. """ if len(instructions) != len(images): raise ValueError( f"instructions length ({len(instructions)}) must equal " f"images length ({len(images)})." ) builder = self.conversation_builder num_frames = len(images) value_count = builder.progress_value_count(num_frames) content = builder.build_progress( instructions=instructions, num_frames=num_frames, robot_description=robot_description, camera_description=camera_description, ) conversation = [{"role": "user", "content": content}] text = self.apply_chat_template(conversation) mini_outputs = self.__call__(text=text, images=images) input_ids = mini_outputs["input_ids"] target_values = self._progress_targets( goal_timestamp, frame_timestamps, device=input_ids.device, value_count=value_count, ) mini_outputs["value"] = target_values # Relative value: tokens predict per-frame relative distances if self.relative_value_token_id is not None and self.relative_value_token_id >= 0: mini_outputs["relative_value"] = relative_distances.to(input_ids.device).float().unsqueeze(0) # Build causal LM labels for each frame's instruction tokens labels = self._build_lang_labels_multi(input_ids, instructions) mini_outputs["labels"] = labels return mini_outputs def process_history( self, instruction: str, description: Optional[str], images: List[Image], frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, success: Optional[bool] = None, fusion: Optional[bool] = None, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process a history sample. Layout (``interleaved_history``): top-level instruction, frames with ```` between them, optional description sentence (input only, no LM supervision), and per-frame ```` tokens. Relative-value targets are derived from ``frame_timestamps`` as signed consecutive deltas of length ``num_frames - 1``. Token positions for the prediction heads are inferred inside the model from ``input_ids`` + registered token IDs, so no ``*_logits_to_keep`` tensors are emitted here. """ builder = self.conversation_builder num_frames = len(images) value_count = builder.progress_value_count(num_frames) fusion_flag = 0 if fusion is None else int(bool(fusion)) match_answer = "No" if fusion_flag else "Yes" if success is None: success_answer = None else: success_answer = "Yes" if success else "No" content = builder.build_progress( instruction=instruction, description=description, num_frames=num_frames, robot_description=robot_description, camera_description=camera_description, match_answer=match_answer, success_answer=success_answer, ) conversation = [{"role": "user", "content": content}] text = self.apply_chat_template(conversation) mini_outputs = self.__call__(text=text, images=images) input_ids = mini_outputs["input_ids"] target_values = self._progress_targets( goal_timestamp, frame_timestamps, device=input_ids.device, value_count=value_count, ) mini_outputs["value"] = target_values mini_outputs["value_fusion_mask"] = torch.full_like( target_values, fill_value=fusion_flag, dtype=torch.long ) ts = frame_timestamps.reshape(-1).to(input_ids.device).float() if builder.relative_value_token is not None: mini_outputs["relative_value"] = (ts[1:] - ts[:-1]).unsqueeze(0) # Language loss labels: supervise the "Analysis:" span with causal LM # loss. Always emitted (all -100 if marker not found) so batches with # mixed samples concat cleanly. mini_outputs["labels"] = self._build_history_labels(input_ids) return mini_outputs def process_history_normalized( self, instruction: str, description: Optional[str], images: List[Image], frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, start_timestamp: torch.Tensor, success: Optional[bool] = None, fusion: Optional[bool] = None, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """History sample with [0, 1] normalized progress targets. Identical prompt layout to :meth:`process_history` (driven by the active ConversationBuilder), but the ```` targets are the normalized completion fraction ``(t - start) / (goal - start)`` and the ```` targets are the per-frame deltas divided by the same episode duration, so both heads live in a unitless space. The remaining- time path (:meth:`process_history`) is left untouched. """ builder = self.conversation_builder num_frames = len(images) value_count = builder.progress_value_count(num_frames) fusion_flag = 0 if fusion is None else int(bool(fusion)) match_answer = "No" if fusion_flag else "Yes" if success is None: success_answer = None else: success_answer = "Yes" if success else "No" content = builder.build_progress( instruction=instruction, description=description, num_frames=num_frames, robot_description=robot_description, camera_description=camera_description, match_answer=match_answer, success_answer=success_answer, ) conversation = [{"role": "user", "content": content}] text = self.apply_chat_template(conversation) mini_outputs = self.__call__(text=text, images=images) input_ids = mini_outputs["input_ids"] target_values = self._normalized_progress_targets( goal_timestamp, start_timestamp, frame_timestamps, device=input_ids.device, value_count=value_count, ) mini_outputs["value"] = target_values mini_outputs["value_fusion_mask"] = torch.full_like( target_values, fill_value=fusion_flag, dtype=torch.long ) ts = frame_timestamps.reshape(-1).to(input_ids.device).float() if builder.relative_value_token is not None: denom = self._normalized_denominator(goal_timestamp, start_timestamp, input_ids.device) # Normalized frame-to-frame deltas: fraction of total episode duration. # The relative ValueTokenizer clamps these to its bin-center support # [bin_values[0], bin_values[-1]] — under support_transform=quantile # that follows the knots, not min_value/max_value. mini_outputs["relative_value"] = ((ts[1:] - ts[:-1]) / denom).unsqueeze(0) mini_outputs["labels"] = self._build_history_labels(input_ids) return mini_outputs def _build_lang_labels_multi( self, input_ids: torch.Tensor, instructions: List[str], ) -> torch.Tensor: """Create causal LM labels for per-frame instruction spans. Locates instruction tokens using the "Task:" prefix as start marker and the token as end boundary. Labels are set to input_ids at instruction positions, -100 elsewhere. The loss function (ForCausalLMLoss) handles the internal shift for next-token prediction. """ B, L = input_ids.shape labels = torch.full_like(input_ids, -100) rel_id = self.relative_value_token_id if rel_id is None: raise ValueError( "_build_lang_labels_multi requires a registered token." ) prefix_ids = self.tokenizer.encode("Task:", add_special_tokens=False) prefix_t = torch.tensor(prefix_ids, device=input_ids.device) prefix_len = len(prefix_ids) for b in range(B): seq = input_ids[b] search_start = 0 for _ in instructions: # Find "Task:" prefix instr_start = None for i in range(search_start, L - prefix_len + 1): if torch.equal(seq[i:i + prefix_len], prefix_t): instr_start = i break if instr_start is None: break # Instruction content starts after "Task:" prefix content_start = instr_start + prefix_len # Find token as end boundary instr_end = None for i in range(content_start, L): if seq[i].item() == rel_id: instr_end = i break if instr_end is None: break # Set labels = input_ids at instruction content positions # (ForCausalLMLoss internally shifts for next-token prediction) if instr_end > content_start: labels[b, content_start:instr_end] = seq[content_start:instr_end] search_start = instr_end + 1 return labels def _build_history_labels( self, input_ids: torch.Tensor, ) -> torch.Tensor: """Create causal LM labels for the "Analysis:" span in the history layout. Everything after "Analysis:" is supervised with causal LM loss. Since "Analysis:" is emitted as a standalone text block, its token sequence is deterministic — we match it directly in input_ids. Raises ValueError if the marker isn't found (indicates a builder bug). """ B, L = input_ids.shape marker_ids = self.tokenizer.encode("Analysis: \n", add_special_tokens=False) marker_len = len(marker_ids) marker_t = torch.tensor(marker_ids, device=input_ids.device) labels = torch.full_like(input_ids, -100) for b in range(B): seq = input_ids[b] found = False for i in range(L - marker_len, -1, -1): if torch.equal(seq[i:i + marker_len], marker_t): content_start = i + marker_len if content_start < L: labels[b, content_start:] = seq[content_start:] found = True break if not found: raise ValueError( f"'Analysis:' marker not found in sample {b}. " "The conversation builder must emit an 'Analysis:' block." ) return labels def process_relative( self, instruction: str, images: List[Image], target_image: Image, frame_timestamps: torch.Tensor, target_timestamp: torch.Tensor, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: if target_image is None: raise ValueError("`target_image` must be provided for relative processing.") conversation = self.build_conversation( instruction, num_frames=len(images), conversation_type="relative", target_image=target_image, robot_description=robot_description, camera_description=camera_description, ) text = self.apply_chat_template(conversation) # Target image is the leading prompt image (first image); it carries no # value token, so frame_timestamps covers only the N prediction frames. mini_outputs = self.__call__(text=text, images=[target_image] + images) input_ids = mini_outputs["input_ids"] target_values = self._frame_target_values( target_timestamp, frame_timestamps, device=input_ids.device, ) if input_ids.eq(self.value_token_id).any(): raise ValueError("Relative conversations must not contain tokens.") if self.relative_value_token_id is None or self.relative_value_token_id < 0: raise ValueError("relative processing requires a registered token.") mini_outputs["relative_value"] = target_values return mini_outputs def process_progress_relative( self, instruction: str, images: List[Image], target_image: Image, frame_timestamps: torch.Tensor, goal_timestamp: torch.Tensor, target_timestamp: torch.Tensor, robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process a progress sample with a trailing relative prediction. Same supervision as :meth:`process_step` (progress ```` aligned with the conversation builder) plus a single trailing ```` token supervised against the time-to-target. The target image is appended after the regular frames so the chat template's image placeholders line up with ``images + [target_image]``. """ if target_image is None: raise ValueError("`target_image` must be provided for progress_relative processing.") builder = self.conversation_builder value_count = builder.progress_value_count(len(images)) conversation = self.build_conversation( instruction, num_frames=len(images), conversation_type="progress_relative", target_image=target_image, robot_description=robot_description, camera_description=camera_description, ) text = self.apply_chat_template(conversation) # Trailing target image is the last placeholder in the conversation, # so append it after the prediction frames. mini_outputs = self.__call__(text=text, images=list(images) + [target_image]) input_ids = mini_outputs["input_ids"] target_values = self._progress_targets( goal_timestamp, frame_timestamps, device=input_ids.device, value_count=value_count, ) mini_outputs["value"] = target_values if self.relative_value_token_id is None or self.relative_value_token_id < 0: raise ValueError( "progress_relative processing requires a registered token." ) mini_outputs["relative_value"] = self._anchor_target_value( target_timestamp, frame_timestamps, device=input_ids.device, ) return mini_outputs def process_episode( self, instruction: str, images: List[Image], robot_description: Optional[str] = None, camera_description: Optional[str] = None, ) -> BatchFeature: """Process one episode in progress mode (inference). All images passed in are used directly as prediction frames. The output is shaped as a single sample: ``input_ids``/``attention_mask`` are ``(1, L)`` and ``pixel_values``/``image_grid_thw`` are ``(1, k, D)`` with ``k`` equal to the number of input images. For interleaved_lang builder, the same instruction is repeated for each frame. """ if len(images) == 0: raise ValueError("process_episode requires at least one prediction image.") k = len(images) builder = self.conversation_builder if isinstance(builder, InterleavedLangConversationBuilder): content = builder.build_progress( instructions=[instruction] * k, num_frames=k, robot_description=robot_description, camera_description=camera_description, ) elif isinstance(builder, InterleavedHistoryConversationBuilder): # Also covers InterleavedHistoryNormalizedConversationBuilder (subclass): # identical layout / build_progress signature, only the question # wording differs, so it must take this branch too. content = builder.build_progress( instruction=instruction, description=None, num_frames=k, robot_description=robot_description, camera_description=camera_description, is_inference=True, ) else: # interleaved / video_prefix and any future single-instruction layout. content = builder.build_progress( instruction=instruction, num_frames=k, robot_description=robot_description, camera_description=camera_description, ) conv = [{"role": "user", "content": content}] text = self.apply_chat_template(conv) merged = self.__call__(text=text, images=images) eos_token_id = self.tokenizer.convert_tokens_to_ids("<|im_end|>") input_ids = merged["input_ids"] eos_positions = (input_ids[0] == eos_token_id).nonzero(as_tuple=True)[0] if len(eos_positions) > 0: input_ids = input_ids[:, :eos_positions[-1]] merged["input_ids"] = input_ids merged["attention_mask"] = merged["attention_mask"][:, :input_ids.shape[-1]] merged["pixel_values"] = rearrange(merged["pixel_values"], "(b t) d -> b t d", b=1) merged["image_grid_thw"] = rearrange(merged["image_grid_thw"], "(b t) d -> b t d", b=1) return merged