yanziang/InternVideo3-8B-Instruct
101.5k
1# coding=utf-82# Copyright 2025 The InternVideo Team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Video processor class for InternVideo3."""16 17import math18from typing import Optional, Union19 20import numpy as np21import torch22 23from transformers.feature_extraction_utils import BatchFeature24from transformers.image_utils import ChannelDimension, PILImageResampling, SizeDict, get_image_size25from transformers.processing_utils import Unpack, VideosKwargs26from transformers.utils import TensorType, logging27from transformers.video_processing_utils import BaseVideoProcessor28from transformers.video_utils import VideoMetadata, group_videos_by_shape, reorder_videos29 30 31logger = logging.get_logger(__name__)32 33 34def smart_resize(35 num_frames: int,36 height: int,37 width: int,38 temporal_factor: int = 2,39 factor: int = 32,40 min_pixels: int = 128 * 128,41 max_pixels: int = 16 * 16 * 2 * 2 * 2 * 6144,42):43 if num_frames < temporal_factor:44 raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")45 if height < factor or width < factor:46 raise ValueError(f"height:{height} or width:{width} must be larger than factor:{factor}")47 elif max(height, width) / min(height, width) > 200:48 raise ValueError(49 f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"50 )51 h_bar = round(height / factor) * factor52 w_bar = round(width / factor) * factor53 t_bar = round(num_frames / temporal_factor) * temporal_factor54 55 if t_bar * h_bar * w_bar > max_pixels:56 beta = math.sqrt((num_frames * height * width) / max_pixels)57 h_bar = max(factor, math.floor(height / beta / factor) * factor)58 w_bar = max(factor, math.floor(width / beta / factor) * factor)59 elif t_bar * h_bar * w_bar < min_pixels:60 beta = math.sqrt(min_pixels / (num_frames * height * width))61 h_bar = math.ceil(height * beta / factor) * factor62 w_bar = math.ceil(width * beta / factor) * factor63 64 return h_bar, w_bar65 66 67class InternVideo3VideoProcessorInitKwargs(VideosKwargs):68 patch_size: Optional[int]69 temporal_patch_size: Optional[int]70 merge_size: Optional[int]71 min_frames: Optional[int]72 max_frames: Optional[int]73 74 75class InternVideo3VideoProcessor(BaseVideoProcessor):76 resample = PILImageResampling.BICUBIC77 size = {"shortest_edge": 128 * 32 * 32, "longest_edge": 32 * 32 * 768}78 image_mean = [0.5, 0.5, 0.5]79 image_std = [0.5, 0.5, 0.5]80 do_resize = True81 do_rescale = True82 do_normalize = True83 do_convert_rgb = True84 patch_size = 1685 temporal_patch_size = 286 merge_size = 287 fps = 288 min_frames = 489 max_frames = 76890 do_sample_frames = True91 valid_kwargs = InternVideo3VideoProcessorInitKwargs92 model_input_names = ["pixel_values_videos", "video_grid_thw"]93 94 def __init__(self, **kwargs: Unpack[InternVideo3VideoProcessorInitKwargs]):95 super().__init__(**kwargs)96 if self.size is not None and (97 self.size.get("shortest_edge", None) is None or self.size.get("longest_edge", None) is None98 ):99 raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")100 101 def _further_process_kwargs(102 self,103 size: Optional[SizeDict] = None,104 **kwargs,105 ) -> dict:106 if size is not None and ("shortest_edge" not in size or "longest_edge" not in size):107 raise ValueError("size must contain 'shortest_edge' and 'longest_edge' keys.")108 return super()._further_process_kwargs(size=size, **kwargs)109 110 def sample_frames(111 self,112 metadata: VideoMetadata,113 num_frames: Optional[int] = None,114 fps: Optional[Union[int, float]] = None,115 **kwargs,116 ):117 if fps is not None and num_frames is not None:118 raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")119 120 total_num_frames = metadata.total_num_frames121 fps = fps if fps is not None else self.fps122 123 if num_frames is None and fps is not None:124 if metadata.fps is None:125 metadata.fps = 24126 logger.warning_once(127 "Asked to sample `fps` frames per second but no video metadata was provided. "128 "Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."129 )130 num_frames = int(total_num_frames / metadata.fps * fps)131 num_frames = min(min(max(num_frames, self.min_frames), self.max_frames), total_num_frames)132 133 if num_frames is None:134 num_frames = min(max(total_num_frames, self.min_frames), self.max_frames)135 136 indices = np.linspace(0, total_num_frames - 1, num_frames).round().astype(int)137 return indices138 139 def _preprocess(140 self,141 videos: list[torch.Tensor],142 do_convert_rgb: bool = True,143 do_resize: bool = True,144 size: Optional[SizeDict] = None,145 interpolation: PILImageResampling = PILImageResampling.BICUBIC,146 do_rescale: bool = True,147 rescale_factor: float = 1 / 255.0,148 do_normalize: bool = True,149 image_mean: Optional[Union[float, list[float]]] = None,150 image_std: Optional[Union[float, list[float]]] = None,151 patch_size: Optional[int] = None,152 temporal_patch_size: Optional[int] = None,153 merge_size: Optional[int] = None,154 return_tensors: Optional[Union[str, TensorType]] = None,155 **kwargs,156 ):157 grouped_videos, grouped_videos_index = group_videos_by_shape(videos)158 resized_videos_grouped = {}159 160 for shape, stacked_videos in grouped_videos.items():161 B, T, C, H, W = stacked_videos.shape162 num_frames, height, width = T, H, W163 if do_resize:164 resized_height, resized_width = smart_resize(165 num_frames=num_frames,166 height=height,167 width=width,168 temporal_factor=temporal_patch_size,169 factor=patch_size * merge_size,170 min_pixels=size.shortest_edge,171 max_pixels=size.longest_edge,172 )173 stacked_videos = stacked_videos.view(B * T, C, H, W)174 stacked_videos = self.resize(175 stacked_videos,176 size=SizeDict(height=resized_height, width=resized_width),177 interpolation=interpolation,178 )179 stacked_videos = stacked_videos.view(B, T, C, resized_height, resized_width)180 resized_videos_grouped[shape] = stacked_videos181 resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)182 183 grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)184 processed_videos_grouped = {}185 processed_grids = {}186 for shape, stacked_videos in grouped_videos.items():187 resized_height, resized_width = get_image_size(stacked_videos[0], channel_dim=ChannelDimension.FIRST)188 189 stacked_videos = self.rescale_and_normalize(190 stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std191 )192 patches = stacked_videos193 194 if patches.shape[1] % temporal_patch_size != 0:195 repeats = patches[:, -1:].repeat(1, temporal_patch_size - 1, 1, 1, 1)196 patches = torch.cat([patches, repeats], dim=1)197 batch_size, grid_t, channel = patches.shape[:3]198 grid_t = grid_t // temporal_patch_size199 grid_h, grid_w = resized_height // patch_size, resized_width // patch_size200 201 patches = patches.view(202 batch_size,203 grid_t,204 temporal_patch_size,205 channel,206 grid_h // merge_size,207 merge_size,208 patch_size,209 grid_w // merge_size,210 merge_size,211 patch_size,212 )213 patches = patches.permute(0, 1, 4, 7, 5, 8, 3, 2, 6, 9)214 flatten_patches = patches.reshape(215 batch_size,216 grid_t * grid_h * grid_w,217 channel * temporal_patch_size * patch_size * patch_size,218 )219 220 processed_videos_grouped[shape] = flatten_patches221 processed_grids[shape] = [[grid_t, grid_h, grid_w]] * batch_size222 223 processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)224 processed_grids = reorder_videos(processed_grids, grouped_videos_index)225 pixel_values_videos = torch.cat(processed_videos, dim=0)226 video_grid_thw = torch.tensor(processed_grids)227 data = {228 "pixel_values_videos": pixel_values_videos,229 "video_grid_thw": video_grid_thw,230 }231 232 return BatchFeature(data=data, tensor_type=return_tensors)233 234 235__all__ = ["InternVideo3VideoProcessor"]236 