hy4-flash-vision-encoder / native_source /video_processing_hy_v4_flash.py
gatilin's picture
Add files using upload-large-folder tool
48e1b03 verified
Raw History Blame Contribute Delete
17 kB
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# This file was automatically generated from src/transformers/models/hy_v4_flash/modular_hy_v4_flash.py.
# Do NOT edit this file manually as any edits will be overwritten by the generation of
# the file from the modular. If any change should be done, please apply the change to the
# modular_hy_v4_flash.py file directly. One of our CI enforces this.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 Tencent HunYuan Team and The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import numpy as np
import torch
from torchvision.transforms.v2 import functional as tvF
from ...image_processing_utils import BatchFeature
from ...image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD, PILImageResampling, SizeDict
from ...processing_utils import Unpack, VideosKwargs
from ...utils import TensorType, auto_docstring, logging
from ...video_processing_utils import BaseVideoProcessor
from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos
logger = logging.get_logger(__name__)
class HYV4FlashVideoProcessorInitKwargs(VideosKwargs, total=False):
r"""
size (`dict[str, int]`, *optional*):
Total clip pixel budget, given by the required `longest_edge` key. A `shortest_edge` entry, which existing
configs carry, is accepted but not used: frames are never upscaled.
patch_size (`int`, *optional*, defaults to 16):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 1):
The temporal patch size of the vision encoder.
merge_size (`int`, *optional*, defaults to 2):
The merge size of the vision encoder to llm encoder.
min_frames (`int`, *optional*, defaults to 2):
The minimum number of frames to sample from a video.
max_frames (`int`, *optional*, defaults to 1024):
The maximum number of frames to sample from a video.
max_image_size (`dict[str, int]`, *optional*):
Per-frame pixel-area limit, specified by the `longest_edge` key.
"""
patch_size: int
temporal_patch_size: int
merge_size: int
min_frames: int
max_frames: int
max_image_size: dict[str, int]
def smart_resize(
num_frames: int,
height: int,
width: int,
temporal_factor: int = 2,
factor: int = 28,
min_pixels: int = 112 * 112,
max_pixels: int = 14 * 14 * 2 * 2 * 2 * 6144,
):
if num_frames < temporal_factor:
raise ValueError(f"t:{num_frames} must be larger than temporal_factor:{temporal_factor}")
if height < factor or width < factor:
scale = max(factor / height, factor / width)
height = int(height * scale)
width = int(width * scale)
if max(height, width) / min(height, width) > 200:
raise ValueError(
f"absolute aspect ratio must be smaller than 200, got {max(height, width) / min(height, width)}"
)
h_bar = round(height / factor) * factor
w_bar = round(width / factor) * factor
t_bar = round(num_frames / temporal_factor) * temporal_factor
if t_bar * h_bar * w_bar > max_pixels:
beta = math.sqrt((num_frames * height * width) / max_pixels)
h_bar = max(factor, math.floor(height / beta / factor) * factor)
w_bar = max(factor, math.floor(width / beta / factor) * factor)
elif t_bar * h_bar * w_bar < min_pixels:
beta = math.sqrt(min_pixels / (num_frames * height * width))
h_bar = math.ceil(height * beta / factor) * factor
w_bar = math.ceil(width * beta / factor) * factor
return h_bar, w_bar
@auto_docstring
class HYV4FlashVideoProcessor(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
size = {"shortest_edge": 4096, "longest_edge": 33554432}
image_mean = IMAGENET_STANDARD_MEAN
image_std = IMAGENET_STANDARD_STD
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = True
patch_size = 16
temporal_patch_size = 1
merge_size = 2
min_frames = 2
max_frames = 1024
do_sample_frames = False
valid_kwargs = HYV4FlashVideoProcessorInitKwargs
model_input_names = ["pixel_values_videos", "video_grid_thw"]
max_image_size = {"longest_edge": 1024 * 1024}
max_duration = None
num_frames = None
fps = 2
def __init__(self, **kwargs: Unpack[HYV4FlashVideoProcessorInitKwargs]):
super().__init__(**kwargs)
def sample_frames(
self,
metadata: VideoMetadata,
num_frames: int | None = None,
fps: int | float | None = None,
**kwargs,
):
"""
Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames.
If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames`
and `fps` are mutually exclusive.
Args:
video (`torch.Tensor`):
Video that need to be sampled.
metadata (`VideoMetadata`):
Metadata of the video containing information about total duration, fps and total number of frames.
num_frames (`int`, *optional*):
Maximum number of frames to sample. Defaults to `self.num_frames`.
fps (`int` or `float`, *optional*):
Target frames to sample per second. Defaults to `self.fps`.
Returns:
np.ndarray: Sampled video frames.
"""
if fps is not None and num_frames is not None:
raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
total_num_frames = metadata.total_num_frames
fps = fps if fps is not None else self.fps
# If num_frames is not given but fps is, calculate num_frames from fps
if num_frames is None and fps is not None:
if metadata.fps is None:
metadata.fps = 24
logger.warning_once(
"Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. "
"Defaulting to `fps=24`. Please provide `video_metadata` for more accurate results."
)
num_frames = int(total_num_frames / metadata.fps * fps)
num_frames = min(max(num_frames, self.min_frames), self.max_frames, total_num_frames)
if num_frames is None:
num_frames = min(max(total_num_frames, self.min_frames), self.max_frames)
indices = np.linspace(0, total_num_frames - 1, num_frames).round().astype(int)
return indices
def resize(
self,
videos: "torch.Tensor",
size: SizeDict,
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
factor: int,
max_image_size: dict[str, int],
**kwargs,
) -> "torch.Tensor":
"""Resize dynamically based on input video aspect ratio."""
# Only the clip budget is needed: `shortest_edge` is not a lower bound, frames are never upscaled.
if not size.longest_edge:
raise ValueError(f"`size` dict must contain a 'longest_edge' key but got {size}.")
height, width = self.smart_resize(
frame_height=videos.shape[-2],
frame_width=videos.shape[-1],
num_frames=videos.shape[1],
factor=factor,
max_pixels=size.longest_edge,
max_image_size=max_image_size["longest_edge"],
)
return super().resize(
image=videos,
size=SizeDict(height=height, width=width),
resample=resample,
)
def patchify(
self,
videos: "torch.Tensor",
patch_size: int,
merge_size: int,
temporal_patch_size: int,
) -> tuple["torch.Tensor", int, int, int]:
batch_size, num_frames, channel, resized_height, resized_width = videos.shape
if pad := -num_frames % temporal_patch_size:
videos = torch.cat((videos, videos[:, -1:].expand(-1, pad, -1, -1, -1)), dim=1)
num_frames += pad
grid_t = num_frames // temporal_patch_size
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
patches = videos.view(
batch_size,
grid_t,
temporal_patch_size,
channel,
grid_h // merge_size,
merge_size,
patch_size,
grid_w // merge_size,
merge_size,
patch_size,
)
# Key difference: row-major order within each merged block, as in the image processor
patches = patches.permute(0, 1, 4, 5, 7, 8, 3, 2, 6, 9)
flatten_patches = patches.reshape(
batch_size,
grid_t * grid_h * grid_w,
channel * temporal_patch_size * patch_size * patch_size,
)
return flatten_patches, grid_t, grid_h, grid_w
def _preprocess(
self,
videos: list["torch.Tensor"],
do_resize: bool,
size: SizeDict,
resample: "PILImageResampling | tvF.InterpolationMode | int | None",
do_rescale: bool,
rescale_factor: float,
do_normalize: bool,
image_mean: float | list[float] | None,
image_std: float | list[float] | None,
max_image_size: dict[str, int],
patch_size: int | None = None,
temporal_patch_size: int | None = None,
merge_size: int | None = None,
return_tensors: str | TensorType | None = None,
**kwargs,
):
grouped_videos, grouped_videos_index = group_videos_by_shape(videos)
resized_videos_grouped = {}
for shape, stacked_videos in grouped_videos.items():
if do_resize:
stacked_videos = self.resize(
videos=stacked_videos,
size=size,
resample=resample,
factor=patch_size * merge_size,
max_image_size=max_image_size,
)
resized_videos_grouped[shape] = stacked_videos
resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
processed_videos_grouped = {}
processed_grids = {}
for shape, stacked_videos in grouped_videos.items():
stacked_videos = self.rescale_and_normalize(
stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std
)
patches, grid_t, grid_h, grid_w = self.patchify(
stacked_videos,
patch_size=patch_size,
merge_size=merge_size,
temporal_patch_size=temporal_patch_size,
)
processed_videos_grouped[shape] = patches
processed_grids[shape] = [[grid_t, grid_h, grid_w]] * len(stacked_videos)
processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)
processed_grids = reorder_videos(processed_grids, grouped_videos_index)
return BatchFeature(
data={
"pixel_values_videos": torch.cat(processed_videos, dim=0),
"video_grid_thw": torch.tensor(processed_grids),
},
tensor_type=return_tensors,
)
def get_num_of_video_patches(
self, num_frames: int, height: int, width: int, videos_kwargs=None, *, return_grid: bool = False
) -> int | tuple[int, int, int, int]:
"""
A utility that returns number of video patches a given video size.
Args:
num_frames (`int`):
Number of frames in the input video.
height (`int`):
Height of the input video.
width (`int`):
Width of the input video.
videos_kwargs (`dict`, *optional*)
Any kwargs to override defaults of the video processor.
return_grid (`bool`, *optional*, defaults to `False`):
Whether to also return the temporal, height and width grid of the patches.
Returns:
`int`: Number of video patches per video, or `tuple[int, int, int, int]` with the number of patches and
the `(grid_t, grid_h, grid_w)` grid if `return_grid=True`.
"""
videos_kwargs = videos_kwargs if videos_kwargs is not None else {}
do_resize = videos_kwargs.get("do_resize", None)
do_resize = do_resize if do_resize is not None else self.do_resize
size = videos_kwargs.get("size", None) or self.size
max_pixels = size["longest_edge"]
max_image_size = videos_kwargs.get("max_image_size", None) or self.max_image_size
patch_size = videos_kwargs.get("patch_size", None) or self.patch_size
merge_size = videos_kwargs.get("merge_size", None) or self.merge_size
temporal_patch_size = videos_kwargs.get("temporal_patch_size", None) or self.temporal_patch_size
factor = patch_size * merge_size
if do_resize:
height, width = self.smart_resize(
frame_height=height,
frame_width=width,
num_frames=num_frames,
factor=factor,
max_pixels=max_pixels,
max_image_size=max_image_size["longest_edge"],
)
grid_t = (num_frames + -num_frames % temporal_patch_size) // temporal_patch_size
grid_h, grid_w = height // patch_size, width // patch_size
num_patches = grid_t * grid_h * grid_w
return (num_patches, grid_t, grid_h, grid_w) if return_grid else num_patches
@staticmethod
def smart_resize(
frame_height: int,
frame_width: int,
num_frames: int,
*,
factor: int,
max_pixels: int = 33554432,
max_image_size: int = 1024 * 1024,
) -> tuple[int, int]:
"""Return the largest aligned ``(height, width)`` for a frame that fits every budget.
``factor`` is the merged patch edge in pixels (``patch_size * merge_size``). A frame of ``rows x cols``
merged patches costs ``rows * (cols + 1)`` tokens, one newline token per row, which is the same accounting the
processor uses. The result never upscales, keeps each frame within ``max_image_size`` pixels, and keeps
``num_frames * rows * (cols + 1)`` inside the visual token budget of ``max_pixels``. Calling it again on its
own output returns the same size, so a frame that was already resized is left untouched.
"""
if min(num_frames, frame_height, frame_width, factor, max_pixels, max_image_size) <= 0:
raise ValueError("Video dimensions, resize factor, and pixel budgets must be positive.")
if max(frame_height, frame_width) / min(frame_height, frame_width) > 200:
raise ValueError(
f"absolute aspect ratio must be smaller than 200, got {max(frame_height, frame_width) / min(frame_height, frame_width)}"
)
max_rows = max(1, frame_height // factor)
max_cols = max(1, frame_width // factor)
visual_budget = max_pixels // (factor * factor)
for rows in range(max_rows, 0, -1):
# On the ray scale * (height, width), rows == k spans cols floor(W*k/H) .. ceil(W*(k+1)/H) - 1;
# rows clamp at 1, so the last step admits any narrower width.
low_cols = 1 if rows == 1 else max(1, frame_width * rows // frame_height)
high_cols = min(max_cols, max(1, -(-frame_width * (rows + 1) // frame_height) - 1))
budget_cols = visual_budget // (num_frames * rows) - 1 if visual_budget > 0 else 0
cap_cols = max_image_size // (factor * factor * rows)
cols = min(high_cols, budget_cols, cap_cols)
if cols >= low_cols:
return rows * factor, cols * factor
return factor, factor
__all__ = ["HYV4FlashVideoProcessor"]