d1-2B / video_processing_lfm3_vl.py
paulpak58's picture mlabonne's picture Aurelien-Lac's picture
d1-2B
97c5704
Raw History Blame Contribute Delete
18.2 kB
# Vendored from transformers' LFM3 code (not in a release yet) at 69da1b47a11e362fbb15bfe5d5c8da0790c688c5, src/transformers/models/lfm3_vl/video_processing_lfm3_vl.py:
# its relative imports made absolute, nothing else changed.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# This file was automatically generated from src/transformers/models/lfm3_vl/modular_lfm3_vl.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_lfm3_vl.py file directly. One of our CI enforces this.
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
# Copyright 2026 The HuggingFace 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 transformers.image_processing_utils import BatchFeature
from transformers.image_utils import PILImageResampling, SizeDict
from transformers.processing_utils import Unpack, VideosKwargs
from transformers.utils import TensorType, auto_docstring, logging
from transformers.video_processing_utils import BaseVideoProcessor
from transformers.video_utils import (
VideoMetadata,
group_videos_by_shape,
make_batched_metadata,
make_batched_videos,
reorder_videos,
)
logger = logging.get_logger(__name__)
class Lfm3VlVideoProcessorInitKwargs(VideosKwargs, total=False):
r"""
patch_size (`int`, *optional*, defaults to 16):
The spatial patch size of the vision encoder.
temporal_patch_size (`int`, *optional*, defaults to 2):
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 4):
The minimum number of frames to sample from video.
max_frames (`int`, *optional*, defaults to 768):
The maximum number of frames to sample from video.
cap_pixels_per_frame (`bool`, *optional*):
Whether to cap each frame's pixel cost the way the reference implementation (qwen-vl-utils) does:
per-frame pixels are limited to `min(max_video_tokens * factor**2, size["longest_edge"] / num_frames)`
and floored at `1.05 * size["shortest_edge"]`, so token cost scales with clip duration. Without the
cap, videos that sample few frames spend the whole `size["longest_edge"]` budget on those frames and
keep near-native per-frame resolution, so a short clip can cost almost as many tokens as a long
video. If unset, the current uncapped behavior is kept and a warning is emitted: the default will
change to `True` in v5.22, after which the argument will be removed.
max_video_tokens (`int`, *optional*, defaults to 768):
The per-frame token ceiling applied by `cap_pixels_per_frame`, in vision tokens per frame
(qwen-vl-utils' `VIDEO_MAX_TOKEN_NUM`).
"""
patch_size: int
temporal_patch_size: int
merge_size: int
min_frames: int
max_frames: int
cap_pixels_per_frame: bool
max_video_tokens: 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
def _check_video_fps(metadata: VideoMetadata) -> None:
if metadata.fps is not None and not (math.isfinite(metadata.fps) and metadata.fps > 0):
raise ValueError(f"`video_metadata.fps` must be a positive number, got {metadata.fps}")
def _check_video_metadata_count(videos, video_metadata) -> None:
# the shared sampler pairs clips with metadata by `zip`, which drops the clips past the last entry
if video_metadata is None:
return
videos = make_batched_videos(videos)
entries = make_batched_metadata(videos, video_metadata) if video_metadata != [] else []
if len(entries) != len(videos):
raise ValueError(
f"Received {len(videos)} videos but {len(entries)} `video_metadata` entries; pass one entry per video"
)
@auto_docstring
class Lfm3VlVideoProcessor(BaseVideoProcessor):
resample = PILImageResampling.BICUBIC
size = {"shortest_edge": 4_096, "longest_edge": 25_165_824}
image_mean = [0.5, 0.5, 0.5]
image_std = [0.5, 0.5, 0.5]
do_resize = True
do_rescale = True
do_normalize = True
do_convert_rgb = True
patch_size = 16
temporal_patch_size = 2
merge_size = 2
min_frames = 4
max_frames = 768
do_sample_frames = True
cap_pixels_per_frame = False
max_video_tokens = 768
valid_kwargs = Lfm3VlVideoProcessorInitKwargs
model_input_names = ["pixel_values_videos", "video_grid_thw"]
max_image_size = {"longest_edge": 28 * 28 * 2 * 30000}
max_duration = None
num_frames = None
fps = 2.0
def __init__(self, **kwargs: Unpack[Lfm3VlVideoProcessorInitKwargs]):
super().__init__(**kwargs)
def sample_frames(
self, metadata: VideoMetadata, num_frames: int | None = None, fps: int | float | None = None, **kwargs
):
"""Decoded frames whose metadata carries no fps are sampled and timestamped at the 24 fps the shared sampler
assumes (with a warning); pass `video_metadata` with the clip's fps for accurate timestamps."""
_check_video_fps(metadata)
if fps is not None and not (math.isfinite(fps) and fps > 0):
raise ValueError(f"`fps` must be a positive number, got {fps}")
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,
temporal_factor: int,
cap_pixels_per_frame: bool | None = None,
**kwargs,
) -> "torch.Tensor":
"""Resize dynamically based on input video aspect ratio."""
if not size.shortest_edge or not size.longest_edge:
raise ValueError(f"`size` dict must contain 'shortest_edge' and 'longest_edge' keys but got {size}.")
num_frames = videos.shape[1]
max_pixels = size.longest_edge
if cap_pixels_per_frame:
# per-frame pixels are capped at `max_video_tokens` patches or the budget's even share per frame
frame_cap = self.max_video_tokens * factor * factor
pixels_per_frame = max(min(frame_cap, size.longest_edge // num_frames), int(size.shortest_edge * 1.05))
max_pixels = pixels_per_frame * num_frames
height, width = videos.shape[-2:]
resized_height, resized_width = smart_resize(
height=height,
width=width,
num_frames=num_frames,
factor=factor,
temporal_factor=temporal_factor,
min_pixels=size.shortest_edge,
max_pixels=max_pixels,
)
return super().resize(
image=videos,
size=SizeDict(height=resized_height, width=resized_width),
resample=resample,
)
def patchify(
self,
videos: "torch.Tensor",
patch_size: int,
merge_size: int,
temporal_patch_size: int,
) -> tuple["torch.Tensor", int, int]:
"Patchifies each video into flat layout of shape (`seq_len`, `patch_dim`) so we can concat dynamically shaped pixels."
batch_size, num_frames, channel, resized_height, resized_width = videos.shape
# Check that videos have `num_frames` divisible by `temporal_patch_size`
if pad := -num_frames % temporal_patch_size:
repeats = videos[:, -1:].expand(-1, pad, -1, -1, -1)
videos = torch.cat((videos, repeats), 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,
)
patches = patches.permute(0, 1, 4, 7, 5, 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,
patch_size: int | None = None,
temporal_patch_size: int | None = None,
merge_size: int | None = None,
cap_pixels_per_frame: bool | None = None,
return_tensors: str | TensorType | None = None,
**kwargs,
):
if cap_pixels_per_frame is None:
logger.warning_once(
"Lfm3Vl video processing does not apply the per-frame pixel cap the reference "
"implementation (qwen-vl-utils) applies, so some videos cost far more tokens than they "
"would there. In v5.22 the capped behavior will become the default and "
"`cap_pixels_per_frame` will be removed. Pass `cap_pixels_per_frame=True` to adopt the "
"reference behavior now, or `False` to keep the current behavior and silence this "
"warning."
)
cap_pixels_per_frame = False
# Group videos by size for batched resizing
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,
temporal_factor=temporal_patch_size,
cap_pixels_per_frame=cap_pixels_per_frame,
)
resized_videos_grouped[shape] = stacked_videos
resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)
# Group videos by size for further processing
# Needed in case do_resize is False, or resize returns videos with different sizes
grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)
processed_videos_grouped = {}
processed_grids = {}
for shape, stacked_videos in grouped_videos.items():
# Fused rescale and normalize
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)
pixel_values_videos = torch.cat(processed_videos, dim=0)
video_grid_thw = torch.tensor(processed_grids)
return BatchFeature(
data={"pixel_values_videos": pixel_values_videos, "video_grid_thw": video_grid_thw},
tensor_type=return_tensors,
)
def get_num_of_video_patches(self, num_frames: int, height: int, width: int, videos_kwargs=None):
"""
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.
Returns:
`int`: Number of video patches per video.
"""
videos_kwargs = videos_kwargs if videos_kwargs is not None else {}
size = videos_kwargs.get("size", None) or self.size
min_pixels = size["shortest_edge"]
max_pixels = size["longest_edge"]
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
cap_pixels_per_frame = videos_kwargs.get("cap_pixels_per_frame", None) or self.cap_pixels_per_frame
factor = patch_size * merge_size
if cap_pixels_per_frame:
# Keep the count in sync with `resize` when the per-frame cap is active.
frame_cap = self.max_video_tokens * factor * factor
pixels_per_frame = max(min(frame_cap, max_pixels // num_frames), int(min_pixels * 1.05))
max_pixels = pixels_per_frame * num_frames
resized_height, resized_width = smart_resize(
num_frames,
height,
width,
temporal_factor=temporal_patch_size,
factor=factor,
min_pixels=min_pixels,
max_pixels=max_pixels,
)
grid_h, grid_w = resized_height // patch_size, resized_width // patch_size
grid_t = (num_frames + -num_frames % temporal_patch_size) // temporal_patch_size
return grid_t * grid_h * grid_w
def preprocess(self, videos, **kwargs):
_check_video_metadata_count(videos, kwargs.get("video_metadata"))
# the shared `preprocess` fills every unset option from the instance before `sample_frames` runs, so the
# caller's options are told apart from the instance ones here: a caller option beats an instance one, and a
# configured `num_frames` beats the default fps
num_frames, fps = kwargs.get("num_frames"), kwargs.get("fps")
if num_frames is not None and fps is not None:
raise ValueError("`num_frames` and `fps` are mutually exclusive arguments, please use only one!")
if num_frames is not None or (fps is None and self.num_frames is not None):
kwargs["fps"] = None
elif fps is not None:
kwargs["num_frames"] = None
return super().preprocess(videos, **kwargs)
__all__ = ["Lfm3VlVideoProcessor"]