Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions src/transformers/models/aya_vision/processing_aya_vision.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,7 @@ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
]

token_per_patch = (self.img_size // self.patch_size) ** 2
num_image_tokens = [
token_per_patch + 3 + sum(token_per_patch + 1 for _ in range(1, num_patches))
for num_patches in num_image_patches
] # Add +3 and +1 for BOI/EOI and image tile tokens
num_image_tokens = [token_per_patch * num_patches for num_patches in num_image_patches]
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
Comment thread
hmellor marked this conversation as resolved.
Resolved

return MultiModalData(**vision_data)
Expand Down
23 changes: 22 additions & 1 deletion src/transformers/models/blip_2/processing_blip_2.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput
from ...processing_utils import ProcessingKwargs, ProcessorMixin, Unpack
from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin, Unpack
from ...tokenization_utils_base import AddedToken, BatchEncoding, PreTokenizedInput, TextInput
from ...utils import auto_docstring, logging
from ...utils.deprecation import deprecate_attr
Expand Down Expand Up @@ -98,6 +98,27 @@ def __call__(
encoding = BatchFeature(encoding, tensor_type=return_tensors)
return encoding

def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""

vision_data = {}
if image_sizes is not None:
num_image_tokens = [self.num_query_tokens] * len(image_sizes)
num_image_patches = [1] * len(image_sizes)
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})

return MultiModalData(**vision_data)


__getattr__ = deprecate_attr(__name__, rename={"Blip2ProcessorKwargs": (ProcessingKwargs, "5.29.0")})

Expand Down
3 changes: 1 addition & 2 deletions src/transformers/models/chameleon/processing_chameleon.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):

vision_data = {}
if image_sizes is not None:
# add 2 for BOI and EOI tokens
num_image_tokens = [self.image_seq_length + 2] * len(image_sizes)
num_image_tokens = [self.image_seq_length] * len(image_sizes)
num_image_patches = [1] * len(image_sizes)

vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 19 additions & 0 deletions src/transformers/models/deepseek_ocr2/modular_deepseek_ocr2.py
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,25 @@ def _preprocess(

return BatchFeature(data=data, tensor_type=return_tensors)

def get_number_of_image_patches(self, height: int, width: int, images_kwargs: dict | None = None) -> int:
"""
Returns the number of image patches for a given image size (1 global + local patches).
"""
images_kwargs = images_kwargs or {}
min_patches = images_kwargs.get("min_patches", self.min_patches)
max_patches = images_kwargs.get("max_patches", self.max_patches)
tile_size = images_kwargs.get("tile_size", self.tile_size)
crop_to_patches = images_kwargs.get("crop_to_patches", self.crop_to_patches)

num_patches = 1 # global view
if crop_to_patches and max(height, width) > tile_size:
num_columns, num_rows = get_optimal_tiled_canvas(
(height, width), (tile_size, tile_size), min_patches, max_patches
)
num_patches += num_columns * num_rows

return num_patches


@auto_docstring(checkpoint="deepseek-community/DeepSeek-OCR-2")
@strict
Expand Down
40 changes: 34 additions & 6 deletions src/transformers/models/deepseek_ocr2/processing_deepseek_ocr2.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import math

from ...image_utils import make_flat_list_of_images
from ...processing_utils import ProcessingKwargs, ProcessorMixin
from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin
from ...tokenization_utils_base import TextInput
from ...utils import auto_docstring, logging
from ...utils.deprecation import deprecate_attr
Expand Down Expand Up @@ -70,18 +70,46 @@ def validate_inputs(self, images=None, text=None, videos=None, audio=None, **kwa
raise ValueError("You have to specify text.")

def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> TextInput:
size = kwargs.get("size") or self.image_processor.size
tile_size = kwargs.get("tile_size") or self.image_processor.tile_size
num_tokens = self._get_num_image_tokens(image_inputs["num_local_patches"][image_idx], **kwargs)
return self.image_token * num_tokens

def _get_num_image_tokens(self, num_crops: int, size=None, tile_size=None, **kwargs) -> int:
size = size or self.image_processor.size
tile_size = tile_size or self.image_processor.tile_size

num_queries_global = math.ceil(size["height"] / self.patch_size / self.downsample_ratio)
global_tokens = num_queries_global * num_queries_global

num_queries_local = math.ceil(tile_size / self.patch_size / self.downsample_ratio)
local_tokens = num_queries_local * num_queries_local

num_crops = image_inputs["num_local_patches"][image_idx]
num_tokens = global_tokens + local_tokens * num_crops + 1
return self.image_token * num_tokens
return global_tokens + local_tokens * num_crops + 1

def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""
vision_data = {}
if image_sizes is not None:
images_kwargs = self._merge_kwargs(**kwargs)["images_kwargs"]

num_image_tokens = []
for image_size in image_sizes:
# `get_number_of_image_patches` also counts the global view, but `_get_num_image_tokens` takes the
# number of local crops only
num_crops = self.image_processor.get_number_of_image_patches(*image_size, images_kwargs) - 1
num_image_tokens.append(self._get_num_image_tokens(num_crops, **images_kwargs))
num_image_patches = [1] * len(image_sizes)
Comment thread
hmellor marked this conversation as resolved.
Resolved
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
return MultiModalData(**vision_data)


__getattr__ = deprecate_attr(__name__, rename={"DeepseekOcr2ProcessorKwargs": (ProcessingKwargs, "5.29.0")})
Expand Down
21 changes: 20 additions & 1 deletion src/transformers/models/deepseek_vl/modular_deepseek_vl.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from huggingface_hub.dataclasses import strict

from ...configuration_utils import PreTrainedConfig, SubConfigSpec
from ...processing_utils import ProcessingKwargs, ProcessorMixin
from ...processing_utils import MultiModalData, ProcessingKwargs, ProcessorMixin
from ...utils import (
auto_docstring,
logging,
Expand Down Expand Up @@ -171,6 +171,25 @@ def __init__(
def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> str:
return self.image_token * self.num_image_tokens

def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""
vision_data = {}
if image_sizes is not None:
num_image_tokens = [self.num_image_tokens] * len(image_sizes)
num_image_patches = [1] * len(image_sizes)
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
return MultiModalData(**vision_data)


__getattr__ = deprecate_attr(__name__, rename={"DeepseekVLProcessorKwargs": (ProcessingKwargs, "5.29.0")})

Expand Down
21 changes: 20 additions & 1 deletion src/transformers/models/deepseek_vl/processing_deepseek_vl.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 28 additions & 1 deletion src/transformers/models/got_ocr2/processing_got_ocr2.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from ...image_processing_utils import BatchFeature
from ...image_utils import ImageInput, get_image_size, is_valid_image
from ...processing_utils import ImagesKwargs, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
from ...processing_utils import ImagesKwargs, MultiModalData, ProcessingKwargs, ProcessorMixin, TextKwargs, Unpack
from ...tokenization_utils_base import PreTokenizedInput, TextInput
from ...utils import auto_docstring, logging
from ...utils.deprecation import deprecate_attr
Expand Down Expand Up @@ -353,6 +353,33 @@ def replace_image_token(self, image_inputs: dict, image_idx: int, **kwargs) -> s
num_patches = sum(image_inputs["num_patches"][current_patch_index : current_patch_index + num_pages])
return self.image_token * num_image_tokens * num_patches

def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.

Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.

Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""
vision_data = {}
if image_sizes is not None:
merged_kwargs = self._merge_kwargs(**kwargs)
images_kwargs = merged_kwargs["images_kwargs"]
# `images_kwargs` has priority for backwards compatibility, as in `__call__`. Remove in v5.29.0.
num_image_tokens = images_kwargs.get("num_image_tokens", merged_kwargs["num_image_tokens"])
Comment thread
hmellor marked this conversation as resolved.
Resolved

num_image_patches = [
self.image_processor.get_number_of_image_patches(*image_size, images_kwargs)
for image_size in image_sizes
]
num_image_tokens = [num_image_tokens * num_patches for num_patches in num_image_patches]
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})
return MultiModalData(**vision_data)

@property
def unused_input_names(self) -> list[str]:
"Input names returned always by subprocessors but not used in model's `forward`"
Expand Down
27 changes: 27 additions & 0 deletions src/transformers/models/idefics2/processing_idefics2.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from ...feature_extraction_utils import BatchFeature
from ...image_utils import ImageInput, is_valid_image, load_image
from ...processing_utils import (
MultiModalData,
ProcessingKwargs,
ProcessorMixin,
Unpack,
Expand Down Expand Up @@ -176,6 +177,32 @@ def __call__(

return BatchFeature(inputs, tensor_type=return_tensors)

def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs):
"""
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes.
Args:
image_sizes (`list[list[int]]`, *optional*):
The input sizes formatted as (height, width) per each image.
Returns:
`MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided
input modalities, along with other useful data.
"""

vision_data = {}
if image_sizes is not None:
images_kwargs = self._merge_kwargs(**kwargs)["images_kwargs"]
do_image_splitting = images_kwargs.get("do_image_splitting", self.image_processor.do_image_splitting)

# Image splitting yields 4 crops + the original image
num_patches = 5 if do_image_splitting else 1
num_image_tokens = [self.image_seq_len * num_patches] * len(image_sizes)
num_image_patches = [num_patches] * len(image_sizes)
vision_data.update({"num_image_tokens": num_image_tokens, "num_image_patches": num_image_patches})

return MultiModalData(**vision_data)


__getattr__ = deprecate_attr(__name__, rename={"Idefics2ProcessorKwargs": (ProcessingKwargs, "5.29.0")})

Expand Down
Loading
Loading