|
| 1 | +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 |
| 2 | +# This file was automatically generated from src/transformers/models/deepseek_vl/modular_deepseek_vl.py. |
| 3 | +# Do NOT edit this file manually as any edits will be overwritten by the generation of |
| 4 | +# the file from the modular. If any change should be done, please apply the change to the |
| 5 | +# modular_deepseek_vl.py file directly. One of our CI enforces this. |
| 6 | +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 |
| 7 | +# Copyright 2025 Deepseek AI and The HuggingFace Team. All rights reserved. |
| 8 | +# |
| 9 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 10 | +# you may not use this file except in compliance with the License. |
| 11 | +# You may obtain a copy of the License at |
| 12 | +# |
| 13 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 14 | +# |
| 15 | +# Unless required by applicable law or agreed to in writing, software |
| 16 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 17 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 18 | +# See the License for the specific language governing permissions and |
| 19 | +# limitations under the License. |
| 20 | + |
| 21 | +from typing import Optional, Union |
| 22 | + |
| 23 | +import torch.nn.functional as F |
| 24 | + |
| 25 | +from ...image_processing_utils import BatchFeature |
| 26 | +from ...image_processing_utils_fast import ( |
| 27 | + BaseImageProcessorFast, |
| 28 | + DefaultFastImageProcessorKwargs, |
| 29 | + group_images_by_shape, |
| 30 | + reorder_images, |
| 31 | +) |
| 32 | +from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling, SizeDict |
| 33 | +from ...processing_utils import Unpack |
| 34 | +from ...utils import ( |
| 35 | + TensorType, |
| 36 | + auto_docstring, |
| 37 | + is_torch_available, |
| 38 | +) |
| 39 | + |
| 40 | + |
| 41 | +if is_torch_available(): |
| 42 | + import torch |
| 43 | + |
| 44 | + |
| 45 | +class DeepseekVLFastImageProcessorKwargs(DefaultFastImageProcessorKwargs): |
| 46 | + r""" |
| 47 | + min_size (`int`, *optional*, defaults to 14): |
| 48 | + The minimum allowed size for the resized image. Ensures that neither the height nor width |
| 49 | + falls below this value after resizing. |
| 50 | + """ |
| 51 | + |
| 52 | + min_size: int |
| 53 | + |
| 54 | + |
| 55 | +@auto_docstring |
| 56 | +class DeepseekVLImageProcessorFast(BaseImageProcessorFast): |
| 57 | + resample = PILImageResampling.BICUBIC |
| 58 | + image_mean = OPENAI_CLIP_MEAN |
| 59 | + image_std = OPENAI_CLIP_STD |
| 60 | + size = {"height": 384, "width": 384} |
| 61 | + min_size = 14 |
| 62 | + do_resize = True |
| 63 | + do_rescale = True |
| 64 | + do_normalize = True |
| 65 | + valid_kwargs = DeepseekVLFastImageProcessorKwargs |
| 66 | + |
| 67 | + def __init__(self, **kwargs: Unpack[DeepseekVLFastImageProcessorKwargs]): |
| 68 | + super().__init__(**kwargs) |
| 69 | + if kwargs.get("image_mean", None) is None: |
| 70 | + background_color = (127, 127, 127) |
| 71 | + else: |
| 72 | + background_color = tuple([int(x * 255) for x in kwargs.get("image_mean")]) |
| 73 | + self.background_color = tuple(background_color) |
| 74 | + |
| 75 | + def resize( |
| 76 | + self, |
| 77 | + image: "torch.Tensor", |
| 78 | + size: SizeDict, |
| 79 | + min_size: int, |
| 80 | + interpolation: "F.InterpolationMode" = None, |
| 81 | + antialias: bool = True, |
| 82 | + **kwargs, |
| 83 | + ) -> "torch.Tensor": |
| 84 | + if size.height is None or size.width is None or size.height != size.width: |
| 85 | + raise ValueError( |
| 86 | + f"Output height and width must be the same. Got height={size['height']} and width={size['width']}" |
| 87 | + ) |
| 88 | + size = size.height |
| 89 | + |
| 90 | + height, width = image.shape[-2:] |
| 91 | + max_size = max(height, width) |
| 92 | + |
| 93 | + delta = size / max_size |
| 94 | + # Largest side becomes `size` and the other side is scaled according to the aspect ratio. |
| 95 | + output_size_nonpadded = SizeDict( |
| 96 | + height=max(int(height * delta), min_size), |
| 97 | + width=max(int(width * delta), min_size), |
| 98 | + ) |
| 99 | + |
| 100 | + return super().resize(image, size=output_size_nonpadded, interpolation=interpolation, antialias=antialias) |
| 101 | + |
| 102 | + def pad_to_square( |
| 103 | + self, |
| 104 | + images: "torch.Tensor", |
| 105 | + background_color: Union[int, tuple[int, int, int]] = 0, |
| 106 | + ) -> "torch.Tensor": |
| 107 | + """ |
| 108 | + Pads an image to a square based on the longest edge. |
| 109 | +
|
| 110 | + Args: |
| 111 | + images (`torch.Tensor`): |
| 112 | + The images to pad. |
| 113 | + background_color (`int` or `tuple[int, int, int]`, *optional*, defaults to 0): |
| 114 | + The color to use for the padding. Can be an integer for single channel or a |
| 115 | + tuple of integers representing for multi-channel images. If passed as integer |
| 116 | + in mutli-channel mode, it will default to `0` in subsequent channels. |
| 117 | +
|
| 118 | + Returns: |
| 119 | + `torch.Tensor`: The padded images. |
| 120 | + """ |
| 121 | + height, width = images.shape[-2:] |
| 122 | + num_channels = images.shape[1] |
| 123 | + batch_size = images.shape[0] |
| 124 | + |
| 125 | + if height == width: |
| 126 | + return images |
| 127 | + |
| 128 | + max_dim = max(height, width) |
| 129 | + |
| 130 | + # Ensure background_color is the correct shape |
| 131 | + if isinstance(background_color, int): |
| 132 | + background_color = [background_color] |
| 133 | + elif len(background_color) != num_channels: |
| 134 | + raise ValueError( |
| 135 | + f"background_color must have no more than {num_channels} elements to match the number of channels" |
| 136 | + ) |
| 137 | + |
| 138 | + padded_images = torch.zeros( |
| 139 | + (batch_size, num_channels, max_dim, max_dim), dtype=images.dtype, device=images.device |
| 140 | + ) |
| 141 | + for i, color in enumerate(background_color): |
| 142 | + padded_images[:, i, :, :] = color |
| 143 | + if width > height: |
| 144 | + start = (max_dim - height) // 2 |
| 145 | + padded_images[:, :, start : start + height, :] = images |
| 146 | + else: |
| 147 | + start = (max_dim - width) // 2 |
| 148 | + padded_images[:, :, :, start : start + width] = images |
| 149 | + |
| 150 | + return padded_images |
| 151 | + |
| 152 | + def _preprocess( |
| 153 | + self, |
| 154 | + images: list["torch.Tensor"], |
| 155 | + do_resize: bool, |
| 156 | + size: SizeDict, |
| 157 | + min_size: int, |
| 158 | + interpolation: Optional["F.InterpolationMode"], |
| 159 | + do_rescale: bool, |
| 160 | + rescale_factor: float, |
| 161 | + do_normalize: bool, |
| 162 | + image_mean: Optional[Union[float, list[float]]], |
| 163 | + image_std: Optional[Union[float, list[float]]], |
| 164 | + disable_grouping: Optional[bool], |
| 165 | + return_tensors: Optional[Union[str, TensorType]], |
| 166 | + do_pad: bool = True, |
| 167 | + **kwargs, |
| 168 | + ) -> BatchFeature: |
| 169 | + # Group images by size for batched resizing |
| 170 | + grouped_images, grouped_images_index = group_images_by_shape(images, disable_grouping=disable_grouping) |
| 171 | + resized_images_grouped = {} |
| 172 | + for shape, stacked_images in grouped_images.items(): |
| 173 | + if do_resize: |
| 174 | + stacked_images = self.resize( |
| 175 | + image=stacked_images, size=size, min_size=min_size, interpolation=interpolation |
| 176 | + ) |
| 177 | + resized_images_grouped[shape] = stacked_images |
| 178 | + resized_images = reorder_images(resized_images_grouped, grouped_images_index) |
| 179 | + |
| 180 | + # Group images by size for further processing |
| 181 | + # Needed in case do_resize is False, or resize returns images with different sizes |
| 182 | + grouped_images, grouped_images_index = group_images_by_shape(resized_images, disable_grouping=disable_grouping) |
| 183 | + processed_images_grouped = {} |
| 184 | + for shape, stacked_images in grouped_images.items(): |
| 185 | + if do_pad: |
| 186 | + stacked_images = self.pad_to_square(stacked_images, background_color=self.background_color) |
| 187 | + # Fused rescale and normalize |
| 188 | + stacked_images = self.rescale_and_normalize( |
| 189 | + stacked_images, do_rescale, rescale_factor, do_normalize, image_mean, image_std |
| 190 | + ) |
| 191 | + processed_images_grouped[shape] = stacked_images |
| 192 | + |
| 193 | + processed_images = reorder_images(processed_images_grouped, grouped_images_index) |
| 194 | + processed_images = torch.stack(processed_images, dim=0) if return_tensors else processed_images |
| 195 | + |
| 196 | + return BatchFeature(data={"pixel_values": processed_images}, tensor_type=return_tensors) |
| 197 | + |
| 198 | + |
| 199 | +__all__ = ["DeepseekVLImageProcessorFast"] |
0 commit comments