init
This commit is contained in:
0
transformers/tests/models/lfm2_vl/__init__.py
Normal file
0
transformers/tests/models/lfm2_vl/__init__.py
Normal file
289
transformers/tests/models/lfm2_vl/test_image_processing_lfm2_vl.py
Executable file
289
transformers/tests/models/lfm2_vl/test_image_processing_lfm2_vl.py
Executable file
@@ -0,0 +1,289 @@
|
||||
# coding=utf-8
|
||||
# Copyright 2025 HuggingFace Inc.
|
||||
#
|
||||
# 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 unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from transformers.testing_utils import require_torch, require_vision
|
||||
from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
|
||||
|
||||
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
|
||||
|
||||
|
||||
if is_vision_available():
|
||||
from PIL import Image
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
if is_torchvision_available():
|
||||
from transformers import Lfm2VlImageProcessorFast
|
||||
from transformers.models.lfm2_vl.image_processing_lfm2_vl_fast import find_closest_aspect_ratio
|
||||
|
||||
|
||||
class Lfm2VlImageProcessingTester:
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
batch_size=7,
|
||||
num_channels=3,
|
||||
num_images=1,
|
||||
min_resolution=256,
|
||||
max_resolution=1024,
|
||||
downsample_factor=2,
|
||||
do_image_splitting=False,
|
||||
min_tiles=2,
|
||||
max_tiles=10,
|
||||
use_thumbnail=True,
|
||||
min_image_tokens=64,
|
||||
max_image_tokens=256,
|
||||
encoder_patch_size=16,
|
||||
tile_size=512,
|
||||
max_pixels_tolerance=2.0,
|
||||
):
|
||||
self.parent = parent
|
||||
self.batch_size = batch_size
|
||||
self.num_channels = num_channels
|
||||
self.num_images = num_images
|
||||
self.min_resolution = min_resolution
|
||||
self.max_resolution = max_resolution
|
||||
|
||||
self.downsample_factor = downsample_factor
|
||||
self.do_image_splitting = do_image_splitting
|
||||
self.min_tiles = min_tiles
|
||||
self.max_tiles = max_tiles
|
||||
self.use_thumbnail = use_thumbnail
|
||||
self.min_image_tokens = min_image_tokens
|
||||
self.max_image_tokens = max_image_tokens
|
||||
self.encoder_patch_size = encoder_patch_size
|
||||
self.tile_size = tile_size
|
||||
self.max_pixels_tolerance = max_pixels_tolerance
|
||||
|
||||
def prepare_image_processor_dict(self):
|
||||
return {
|
||||
"downsample_factor": self.downsample_factor,
|
||||
"do_image_splitting": self.do_image_splitting,
|
||||
"min_tiles": self.min_tiles,
|
||||
"max_tiles": self.max_tiles,
|
||||
"use_thumbnail": self.use_thumbnail,
|
||||
"min_image_tokens": self.min_image_tokens,
|
||||
"max_image_tokens": self.max_image_tokens,
|
||||
"encoder_patch_size": self.encoder_patch_size,
|
||||
"tile_size": self.tile_size,
|
||||
"max_pixels_tolerance": self.max_pixels_tolerance,
|
||||
}
|
||||
|
||||
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
||||
images = prepare_image_inputs(
|
||||
batch_size=self.batch_size,
|
||||
num_channels=self.num_channels,
|
||||
min_resolution=self.min_resolution,
|
||||
max_resolution=self.max_resolution,
|
||||
equal_resolution=equal_resolution,
|
||||
numpify=numpify,
|
||||
torchify=torchify,
|
||||
)
|
||||
return [[image] for image in images]
|
||||
|
||||
|
||||
@require_torch
|
||||
@require_vision
|
||||
class Lfm2VlImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
|
||||
test_slow_image_processor = False
|
||||
fast_image_processing_class = Lfm2VlImageProcessorFast if is_torchvision_available() else None
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.image_processor_tester = Lfm2VlImageProcessingTester(self)
|
||||
|
||||
@property
|
||||
def image_processor_dict(self):
|
||||
return self.image_processor_tester.prepare_image_processor_dict()
|
||||
|
||||
def test_image_processor_properties(self):
|
||||
for image_processing_class in self.image_processor_list:
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
self.assertTrue(hasattr(image_processing, "downsample_factor"))
|
||||
self.assertTrue(hasattr(image_processing, "min_tiles"))
|
||||
self.assertTrue(hasattr(image_processing, "max_tiles"))
|
||||
self.assertTrue(hasattr(image_processing, "use_thumbnail"))
|
||||
self.assertTrue(hasattr(image_processing, "min_image_tokens"))
|
||||
self.assertTrue(hasattr(image_processing, "max_image_tokens"))
|
||||
self.assertTrue(hasattr(image_processing, "encoder_patch_size"))
|
||||
self.assertTrue(hasattr(image_processing, "tile_size"))
|
||||
self.assertTrue(hasattr(image_processing, "max_pixels_tolerance"))
|
||||
|
||||
@require_vision
|
||||
def test_smart_resize(self):
|
||||
# verify that smart resize output dims are divisible by encoder_patch_size * downsample_factor
|
||||
image_processing = self.fast_image_processing_class(**self.image_processor_dict)
|
||||
width, height = image_processing.smart_resize(
|
||||
height=500,
|
||||
width=300,
|
||||
downsample_factor=image_processing.downsample_factor,
|
||||
min_image_tokens=image_processing.min_image_tokens,
|
||||
max_image_tokens=image_processing.max_image_tokens,
|
||||
encoder_patch_size=image_processing.encoder_patch_size,
|
||||
)
|
||||
mod = image_processing.encoder_patch_size * image_processing.downsample_factor
|
||||
self.assertEqual(width % mod, 0)
|
||||
self.assertEqual(height % mod, 0)
|
||||
|
||||
@require_vision
|
||||
def test_get_grid_layout(self):
|
||||
# splitting a 512×512 image into tiles of size processor.image_processor.tile_size
|
||||
image_processing = self.fast_image_processing_class(**self.image_processor_dict)
|
||||
rows, cols, _, _, num_patches = image_processing._get_grid_layout(
|
||||
height=1024,
|
||||
width=1024,
|
||||
min_tiles=image_processing.min_tiles,
|
||||
max_tiles=image_processing.max_tiles,
|
||||
tile_size=image_processing.tile_size,
|
||||
)
|
||||
self.assertEqual(num_patches, 4)
|
||||
self.assertEqual(num_patches, rows * cols)
|
||||
|
||||
rows, cols, _, _, num_patches = image_processing._get_grid_layout(
|
||||
height=1024,
|
||||
width=1024,
|
||||
min_tiles=8,
|
||||
max_tiles=8,
|
||||
tile_size=image_processing.tile_size,
|
||||
)
|
||||
self.assertEqual(num_patches, 8)
|
||||
self.assertEqual(num_patches, rows * cols)
|
||||
|
||||
def test_find_closest_aspect_ratio(self):
|
||||
# should pick (1,1) over (2,1) for a square image
|
||||
result = find_closest_aspect_ratio(1.0, [(1, 1), (2, 1)], width=100, height=100, image_size=100)
|
||||
self.assertEqual(result, (1, 1))
|
||||
|
||||
result = find_closest_aspect_ratio(0.5, [(1, 1), (1, 2)], width=100, height=200, image_size=200)
|
||||
self.assertEqual(result, (1, 2))
|
||||
|
||||
def test_call_numpy(self):
|
||||
# Initialize image_processing
|
||||
image_processing = self.fast_image_processing_class(**self.image_processor_dict)
|
||||
# create random numpy tensors
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
|
||||
for sample_images in image_inputs:
|
||||
for image in sample_images:
|
||||
self.assertIsInstance(image, np.ndarray)
|
||||
|
||||
# Test not batched input
|
||||
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2),
|
||||
)
|
||||
|
||||
# Test batched
|
||||
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(
|
||||
self.image_processor_tester.batch_size,
|
||||
image_processing.max_num_patches,
|
||||
3 * image_processing.encoder_patch_size**2,
|
||||
),
|
||||
)
|
||||
|
||||
def test_call_numpy_4_channels(self):
|
||||
# Lfm2Vl always processes images as RGB, so it always returns images with 3 channels
|
||||
# Initialize image_processing
|
||||
image_processor_dict = self.image_processor_dict
|
||||
image_processing = self.fast_image_processing_class(**image_processor_dict)
|
||||
# create random numpy tensors
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
|
||||
|
||||
for sample_images in image_inputs:
|
||||
for image in sample_images:
|
||||
self.assertIsInstance(image, np.ndarray)
|
||||
|
||||
# Test not batched input
|
||||
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2),
|
||||
)
|
||||
|
||||
# Test batched
|
||||
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(
|
||||
self.image_processor_tester.batch_size,
|
||||
image_processing.max_num_patches,
|
||||
3 * image_processing.encoder_patch_size**2,
|
||||
),
|
||||
)
|
||||
|
||||
def test_call_pil(self):
|
||||
# Initialize image_processing
|
||||
image_processing = self.fast_image_processing_class(**self.image_processor_dict)
|
||||
# create random PIL images
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
|
||||
for images in image_inputs:
|
||||
for image in images:
|
||||
self.assertIsInstance(image, Image.Image)
|
||||
|
||||
# Test not batched input
|
||||
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2),
|
||||
)
|
||||
|
||||
# Test batched
|
||||
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(
|
||||
self.image_processor_tester.batch_size,
|
||||
image_processing.max_num_patches,
|
||||
3 * image_processing.encoder_patch_size**2,
|
||||
),
|
||||
)
|
||||
|
||||
def test_call_pytorch(self):
|
||||
# Initialize image_processing
|
||||
image_processing = self.fast_image_processing_class(**self.image_processor_dict)
|
||||
# create random PyTorch tensors
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
|
||||
|
||||
for images in image_inputs:
|
||||
for image in images:
|
||||
self.assertIsInstance(image, torch.Tensor)
|
||||
|
||||
# Test not batched input
|
||||
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(1, image_processing.max_num_patches, 3 * image_processing.encoder_patch_size**2),
|
||||
)
|
||||
|
||||
# Test batched
|
||||
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
||||
self.assertEqual(
|
||||
tuple(encoded_images.shape),
|
||||
(
|
||||
self.image_processor_tester.batch_size,
|
||||
image_processing.max_num_patches,
|
||||
3 * image_processing.encoder_patch_size**2,
|
||||
),
|
||||
)
|
||||
296
transformers/tests/models/lfm2_vl/test_modeling_lfm2_vl.py
Normal file
296
transformers/tests/models/lfm2_vl/test_modeling_lfm2_vl.py
Normal file
@@ -0,0 +1,296 @@
|
||||
# Copyright 2025 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.
|
||||
"""Testing suite for the LFM2-VL model."""
|
||||
|
||||
import math
|
||||
import unittest
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from transformers import AutoProcessor, is_torch_available
|
||||
from transformers.models.lfm2_vl.modeling_lfm2_vl import Lfm2VlForConditionalGeneration
|
||||
from transformers.testing_utils import (
|
||||
cleanup,
|
||||
require_read_token,
|
||||
require_torch,
|
||||
require_torch_accelerator,
|
||||
slow,
|
||||
torch_device,
|
||||
)
|
||||
from transformers.utils.import_utils import is_vision_available
|
||||
|
||||
from ...causal_lm_tester import CausalLMModelTester
|
||||
from ...generation.test_utils import GenerationTesterMixin
|
||||
from ...test_configuration_common import ConfigTester
|
||||
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
||||
|
||||
|
||||
if is_vision_available():
|
||||
from PIL import Image
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
from transformers import Lfm2VlConfig, Lfm2VlForConditionalGeneration, Lfm2VlModel
|
||||
|
||||
|
||||
class Lfm2VlModelTester(CausalLMModelTester):
|
||||
if is_torch_available():
|
||||
config_class = Lfm2VlConfig
|
||||
base_model_class = Lfm2VlModel
|
||||
causal_lm_class = Lfm2VlForConditionalGeneration
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
is_training=True,
|
||||
batch_size=2,
|
||||
scale_factor=2,
|
||||
num_images=2,
|
||||
vision_config={
|
||||
"hidden_size": 32,
|
||||
"intermediate_size": 37,
|
||||
"num_hidden_layers": 2,
|
||||
"num_attention_heads": 2,
|
||||
"num_channels": 3,
|
||||
"num_patches": 16,
|
||||
"patch_size": 4,
|
||||
"hidden_act": "gelu_pytorch_tanh",
|
||||
"layer_norm_eps": 1e-6,
|
||||
"attention_dropout": 0.0,
|
||||
},
|
||||
text_config={
|
||||
"vocab_size": 100,
|
||||
"hidden_size": 32,
|
||||
"intermediate_size": 37,
|
||||
"num_hidden_layers": 2,
|
||||
"num_attention_heads": 4,
|
||||
"num_key_value_heads": 2,
|
||||
"max_position_embeddings": 100,
|
||||
"pad_token_id": 0,
|
||||
"bos_token_id": 1,
|
||||
"eos_token_id": 2,
|
||||
"tie_word_embeddings": True,
|
||||
"rope_theta": 1000000.0,
|
||||
"conv_bias": False,
|
||||
"conv_L_cache": 3,
|
||||
"block_multiple_of": 2,
|
||||
"full_attn_idxs": [0],
|
||||
},
|
||||
image_token_id=4,
|
||||
downsample_factor=4,
|
||||
projector_hidden_size=32,
|
||||
):
|
||||
super().__init__(parent)
|
||||
self.vision_config = vision_config
|
||||
self.text_config = text_config
|
||||
self.image_token_id = image_token_id
|
||||
self.is_training = is_training
|
||||
self.batch_size = batch_size
|
||||
self.scale_factor = scale_factor
|
||||
self.num_images = num_images
|
||||
self.downsample_factor = downsample_factor
|
||||
self.projector_hidden_size = projector_hidden_size
|
||||
self.image_seq_length = 4
|
||||
|
||||
def get_config(self):
|
||||
return Lfm2VlConfig(
|
||||
vision_config=self.vision_config,
|
||||
text_config=self.text_config,
|
||||
image_token_id=self.image_token_id,
|
||||
downsample_factor=self.downsample_factor,
|
||||
projector_hidden_size=self.projector_hidden_size,
|
||||
)
|
||||
|
||||
def prepare_config_and_inputs(self):
|
||||
# Create dummy pixel values: [num_images, num_patches, channels * patch_size^2]
|
||||
patch_size = self.vision_config["patch_size"]
|
||||
pixel_values = floats_tensor([self.num_images, 64, 3 * patch_size * patch_size])
|
||||
|
||||
# Spatial shapes: one (height_patches, width_patches) per image
|
||||
patches = int(math.sqrt(64))
|
||||
spatial_shapes = torch.tensor([[patches, patches]] * self.num_images, dtype=torch.long, device=torch_device)
|
||||
|
||||
# Pixel attention mask: mark all patches as valid (no padding)
|
||||
pixel_attention_mask = torch.ones((self.num_images, 64), dtype=torch.long, device=torch_device)
|
||||
config = self.get_config()
|
||||
return config, pixel_values, spatial_shapes, pixel_attention_mask
|
||||
|
||||
def prepare_config_and_inputs_for_common(self):
|
||||
config_and_inputs = self.prepare_config_and_inputs()
|
||||
config, pixel_values, spatial_shapes, pixel_attention_mask = config_and_inputs
|
||||
input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 2) + 1
|
||||
|
||||
# For simplicity just set the last n tokens to the image token
|
||||
input_ids[input_ids == self.image_token_id] = self.text_config["pad_token_id"]
|
||||
input_ids[:, -self.image_seq_length :] = self.image_token_id
|
||||
|
||||
attention_mask = input_ids.ne(1).to(torch_device)
|
||||
inputs_dict = {
|
||||
"pixel_values": pixel_values,
|
||||
"input_ids": input_ids,
|
||||
"attention_mask": attention_mask,
|
||||
"spatial_shapes": spatial_shapes,
|
||||
"pixel_attention_mask": pixel_attention_mask,
|
||||
}
|
||||
return config, inputs_dict
|
||||
|
||||
|
||||
@require_torch
|
||||
class Lfm2VlModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
|
||||
all_model_classes = (Lfm2VlModel, Lfm2VlForConditionalGeneration) if is_torch_available() else ()
|
||||
pipeline_model_mapping = (
|
||||
{
|
||||
"feature-extraction": Lfm2VlModel,
|
||||
"text-generation": Lfm2VlForConditionalGeneration,
|
||||
}
|
||||
if is_torch_available()
|
||||
else {}
|
||||
)
|
||||
test_headmasking = False
|
||||
test_pruning = False
|
||||
fx_compatible = False
|
||||
model_tester_class = Lfm2VlModelTester
|
||||
_is_composite = True
|
||||
|
||||
def setUp(self):
|
||||
self.model_tester = Lfm2VlModelTester(self)
|
||||
common_properties = ["image_token_id", "projector_hidden_size"]
|
||||
self.config_tester = ConfigTester(
|
||||
self, config_class=Lfm2VlConfig, has_text_modality=False, common_properties=common_properties
|
||||
)
|
||||
|
||||
def test_config(self):
|
||||
self.config_tester.run_common_tests()
|
||||
|
||||
@unittest.skip(
|
||||
"Lfm2 backbone alternates between attention and conv layers, so attention are only returned for attention layers"
|
||||
)
|
||||
def test_attention_outputs(self):
|
||||
pass
|
||||
|
||||
@unittest.skip("Lfm2 backbone has a special cache format as it alternates between attention and conv layers")
|
||||
def test_past_key_values_format(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
"Lfm2 backbone has a special cache format which is not compatible with compile as it has static address for conv cache"
|
||||
)
|
||||
@pytest.mark.torch_compile_test
|
||||
def test_sdpa_can_compile_dynamic(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(reason="Backbone Siglip2VisionModel does not support standalone training")
|
||||
def test_training_gradient_checkpointing(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(reason="Backbone Siglip2VisionModel does not support standalone training")
|
||||
def test_training_gradient_checkpointing_use_reentrant(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(reason="Backbone Siglip2VisionModel does not support standalone training")
|
||||
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
reason="Siglip2 backbone has a non-standard initialization scheme, that this test cannot handle easily"
|
||||
)
|
||||
def test_initialization(self):
|
||||
pass
|
||||
|
||||
|
||||
@require_torch_accelerator
|
||||
@require_read_token
|
||||
@slow
|
||||
class Lfm2VlForConditionalGenerationIntegrationTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.processor = AutoProcessor.from_pretrained("LiquidAI/LFM2-VL-1.6B")
|
||||
self.processor.tokenizer.padding_side = "left"
|
||||
self.image = Image.open(
|
||||
requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw
|
||||
)
|
||||
self.image2 = Image.open(
|
||||
BytesIO(
|
||||
requests.get(
|
||||
"https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
|
||||
).content
|
||||
)
|
||||
)
|
||||
|
||||
def tearDown(self):
|
||||
cleanup(torch_device, gc_collect=True)
|
||||
|
||||
def test_integration_test(self):
|
||||
model = Lfm2VlForConditionalGeneration.from_pretrained(
|
||||
"LiquidAI/LFM2-VL-1.6B",
|
||||
dtype=torch.bfloat16,
|
||||
device_map="auto",
|
||||
)
|
||||
|
||||
# Create inputs
|
||||
text = "<image>In this image, we see"
|
||||
images = self.image
|
||||
inputs = self.processor(text=text, images=images, return_tensors="pt")
|
||||
inputs.to(device=torch_device, dtype=torch.bfloat16)
|
||||
|
||||
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
||||
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
|
||||
|
||||
expected_generated_text = "In this image, we see a cat and a dog lying on a pink blanket. They are both sleeping peacefully. They are"
|
||||
self.assertEqual(generated_texts[0], expected_generated_text)
|
||||
|
||||
def test_integration_test_high_resolution(self):
|
||||
model = Lfm2VlForConditionalGeneration.from_pretrained(
|
||||
"LiquidAI/LFM2-VL-1.6B",
|
||||
dtype=torch.bfloat16,
|
||||
device_map="auto",
|
||||
)
|
||||
|
||||
# Create inputs
|
||||
text = "<image>In this image, we see"
|
||||
images = self.image2
|
||||
inputs = self.processor(text=text, images=images, return_tensors="pt")
|
||||
inputs.to(device=torch_device, dtype=torch.bfloat16)
|
||||
|
||||
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
||||
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
|
||||
|
||||
expected_generated_text = (
|
||||
"In this image, we see the Statue of Liberty, standing tall on its pedestal. The statue is made of metal,"
|
||||
)
|
||||
self.assertEqual(generated_texts[0], expected_generated_text)
|
||||
|
||||
def test_integration_test_batched(self):
|
||||
model = Lfm2VlForConditionalGeneration.from_pretrained(
|
||||
"LiquidAI/LFM2-VL-450M",
|
||||
dtype=torch.bfloat16,
|
||||
device_map="auto",
|
||||
)
|
||||
|
||||
# Create inputs
|
||||
text = ["<image>In this image, we see", "<image>In this image, there is a cat on"]
|
||||
images = [[self.image2], [self.image]]
|
||||
inputs = self.processor(text=text, images=images, return_tensors="pt", padding=True)
|
||||
inputs.to(device=torch_device, dtype=torch.bfloat16)
|
||||
|
||||
generated_ids = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
||||
generated_texts = self.processor.batch_decode(generated_ids, skip_special_tokens=True)
|
||||
|
||||
expected_generated_text = [
|
||||
"In this image, we see a panoramic view of the New York City skyline. The iconic Statics and the New York",
|
||||
"In this image, there is a cat on a bed with a cat on a bed with a cat on a bed with a cat on a bed",
|
||||
]
|
||||
self.assertListEqual(generated_texts, expected_generated_text)
|
||||
467
transformers/tests/models/lfm2_vl/test_processing_lfm2_vl.py
Executable file
467
transformers/tests/models/lfm2_vl/test_processing_lfm2_vl.py
Executable file
@@ -0,0 +1,467 @@
|
||||
# Copyright 2025 HuggingFace Inc.
|
||||
#
|
||||
# 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 shutil
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from transformers import AutoTokenizer, Lfm2VlProcessor
|
||||
from transformers.testing_utils import require_torch, require_vision
|
||||
from transformers.utils import is_torchvision_available, is_vision_available
|
||||
|
||||
from ...test_processing_common import ProcessorTesterMixin
|
||||
|
||||
|
||||
if is_vision_available():
|
||||
from PIL import Image
|
||||
|
||||
if is_torchvision_available():
|
||||
from transformers import Lfm2VlImageProcessorFast
|
||||
|
||||
|
||||
@require_torch
|
||||
@require_vision
|
||||
class Lfm2VlProcessorTest(ProcessorTesterMixin, unittest.TestCase):
|
||||
processor_class = Lfm2VlProcessor
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmpdirname = tempfile.mkdtemp()
|
||||
processor_kwargs = cls.prepare_processor_dict()
|
||||
image_processor = Lfm2VlImageProcessorFast(
|
||||
tile_size=14,
|
||||
min_image_tokens=2,
|
||||
max_image_tokens=10,
|
||||
encoder_patch_size=2,
|
||||
do_image_splitting=False,
|
||||
)
|
||||
tokenizer = AutoTokenizer.from_pretrained("LiquidAI/LFM2-VL-1.6B", **processor_kwargs)
|
||||
|
||||
processor = Lfm2VlProcessor(tokenizer=tokenizer, image_processor=image_processor, **processor_kwargs)
|
||||
processor.save_pretrained(cls.tmpdirname)
|
||||
|
||||
# Create images with different sizes
|
||||
cls.small_image = Image.new("RGB", (256, 256))
|
||||
cls.large_image = Image.new("RGB", (512, 1024))
|
||||
cls.high_res_image = Image.new("RGB", (1024, 1024))
|
||||
|
||||
cls.bos_token = processor.tokenizer.bos_token
|
||||
cls.image_token = processor.image_token
|
||||
|
||||
cls.bos_token_id = processor.tokenizer.convert_tokens_to_ids(cls.bos_token)
|
||||
cls.image_token_id = processor.image_token_id
|
||||
cls.image_start_token_id = processor.tokenizer.convert_tokens_to_ids(processor.image_start_token)
|
||||
cls.image_end_token_id = processor.tokenizer.convert_tokens_to_ids(processor.image_end_token)
|
||||
cls.padding_token_id = processor.tokenizer.pad_token_id
|
||||
cls.image_thumbnail_token_id = processor.tokenizer.convert_tokens_to_ids(processor.image_thumbnail_token)
|
||||
|
||||
def get_tokenizer(self, **kwargs):
|
||||
return Lfm2VlProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
|
||||
|
||||
def get_image_processor(self, **kwargs):
|
||||
return Lfm2VlProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
|
||||
|
||||
def get_processor(self, **kwargs):
|
||||
return Lfm2VlProcessor.from_pretrained(self.tmpdirname, **kwargs)
|
||||
|
||||
@staticmethod
|
||||
def prepare_processor_dict():
|
||||
chat_template = (
|
||||
"{{bos_token}}{% for message in messages %}"
|
||||
"{{'<|im_start|>' + message['role'] + '\n'}}"
|
||||
"{% if message['content'] is string %}"
|
||||
"{{ message['content'] }}"
|
||||
"{% else %}"
|
||||
"{% for content in message['content'] %}"
|
||||
"{% if content['type'] == 'image' %}"
|
||||
"{{ '<image>' }}"
|
||||
"{% elif content['type'] == 'text' %}"
|
||||
"{{ content['text'] }}"
|
||||
"{% endif %}"
|
||||
"{% endfor %}"
|
||||
"{% endif %}"
|
||||
"{{'<|im_end|>\n'}}"
|
||||
"{% endfor %}"
|
||||
"{% if add_generation_prompt %}"
|
||||
"{{'<|im_start|>assistant\n' }}"
|
||||
"{% endif %}"
|
||||
)
|
||||
return {"chat_template": chat_template, "use_image_special_tokens": True}
|
||||
|
||||
# Override as Lfm2VL needs images/video to be an explicitly nested batch
|
||||
def prepare_image_inputs(self, batch_size=None):
|
||||
"""This function prepares a list of PIL images for testing"""
|
||||
images = super().prepare_image_inputs(batch_size)
|
||||
if isinstance(images, (list, tuple)):
|
||||
images = [[image] for image in images]
|
||||
return images
|
||||
|
||||
def get_split_image_expected_tokens(self, processor, image_rows, image_cols, add_thumbnail, image_seq_len):
|
||||
text_split_images = [self.image_start_token_id]
|
||||
num_patches_tile = processor.image_processor.tile_size // processor.image_processor.encoder_patch_size
|
||||
tile_seq_len = math.ceil(num_patches_tile / processor.image_processor.downsample_factor) ** 2
|
||||
for n_h in range(image_rows):
|
||||
for n_w in range(image_cols):
|
||||
text_split_images += (
|
||||
processor.tokenizer(f"<|img_row_{n_h + 1}_col_{n_w + 1}|>", add_special_tokens=False)["input_ids"]
|
||||
+ [self.image_token_id] * tile_seq_len
|
||||
)
|
||||
if add_thumbnail:
|
||||
text_split_images += [self.image_thumbnail_token_id] + [self.image_token_id] * image_seq_len
|
||||
text_split_images += [self.image_end_token_id]
|
||||
return text_split_images
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmpdirname, ignore_errors=True)
|
||||
|
||||
def test_process_interleaved_images_prompts_no_image_splitting_single_image(self):
|
||||
processor_components = self.prepare_components()
|
||||
processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left")
|
||||
processor_components["image_processor"] = self.get_component("image_processor", do_image_splitting=False)
|
||||
processor_kwargs = self.prepare_processor_dict()
|
||||
|
||||
processor = self.processor_class(**processor_components, **processor_kwargs)
|
||||
image_str = "<image>"
|
||||
|
||||
# Test that a single image is processed correctly
|
||||
inputs = processor(images=self.small_image, text=image_str)
|
||||
encoder_feature_dims = (
|
||||
3 * processor.image_processor.encoder_patch_size * processor.image_processor.encoder_patch_size
|
||||
)
|
||||
self.assertEqual(
|
||||
np.array(inputs["pixel_values"]).shape,
|
||||
(1, processor.image_processor.max_num_patches, encoder_feature_dims),
|
||||
)
|
||||
self.assertEqual(
|
||||
np.array(inputs["pixel_attention_mask"]).shape, (1, processor.image_processor.max_num_patches)
|
||||
)
|
||||
self.assertListEqual(inputs["spatial_shapes"].tolist(), [[6, 6]])
|
||||
# fmt: on
|
||||
|
||||
def test_process_interleaved_images_prompts_no_image_splitting_single_image_with_text(self):
|
||||
processor_components = self.prepare_components()
|
||||
processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left")
|
||||
processor_components["image_processor"] = self.get_component("image_processor", do_image_splitting=False)
|
||||
processor_kwargs = self.prepare_processor_dict()
|
||||
|
||||
processor = self.processor_class(**processor_components, **processor_kwargs)
|
||||
|
||||
image_str = "<image>"
|
||||
text_str = "In this image, we see"
|
||||
text = image_str + text_str
|
||||
inputs = processor(text=text, images=self.small_image)
|
||||
|
||||
# fmt: off
|
||||
tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False)
|
||||
expected_input_ids = [[self.image_start_token_id] + [self.image_token_id] * 9 + [self.image_end_token_id] + tokenized_sentence["input_ids"]]
|
||||
self.assertEqual(inputs["input_ids"], expected_input_ids)
|
||||
self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids[0])])
|
||||
encoder_feature_dims = 3 * processor.image_processor.encoder_patch_size * processor.image_processor.encoder_patch_size
|
||||
self.assertEqual(np.array(inputs["pixel_values"]).shape, (1, processor.image_processor.max_num_patches, encoder_feature_dims))
|
||||
self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (1, processor.image_processor.max_num_patches))
|
||||
self.assertListEqual(inputs["spatial_shapes"].tolist(), [[6, 6]])
|
||||
# fmt: on
|
||||
|
||||
def test_process_interleaved_images_prompts_no_image_splitting_multiple_images(self):
|
||||
processor_components = self.prepare_components()
|
||||
processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left")
|
||||
processor_components["image_processor"] = self.get_component("image_processor", do_image_splitting=False)
|
||||
processor_kwargs = self.prepare_processor_dict()
|
||||
|
||||
processor = self.processor_class(**processor_components, **processor_kwargs)
|
||||
|
||||
image_str = "<image>"
|
||||
text_str_1 = "In this image, we see"
|
||||
text_str_2 = "In this image, we see"
|
||||
|
||||
text = [
|
||||
image_str + text_str_1,
|
||||
image_str + image_str + text_str_2,
|
||||
]
|
||||
images = [[self.small_image], [self.small_image, self.small_image]]
|
||||
|
||||
inputs = processor(text=text, images=images, padding=True)
|
||||
|
||||
tokenized_sentence_1 = processor.tokenizer(text_str_1, add_special_tokens=False)
|
||||
tokenized_sentence_2 = processor.tokenizer(text_str_2, add_special_tokens=False)
|
||||
image_tokens = [self.image_start_token_id] + [self.image_token_id] * 9 + [self.image_end_token_id]
|
||||
expected_input_ids_1 = image_tokens + tokenized_sentence_1["input_ids"]
|
||||
expected_input_ids_2 = 2 * image_tokens + tokenized_sentence_2["input_ids"]
|
||||
# Pad the first input to match the second input
|
||||
pad_len = len(expected_input_ids_2) - len(expected_input_ids_1)
|
||||
padded_expected_input_ids_1 = [self.padding_token_id] * pad_len + expected_input_ids_1
|
||||
|
||||
self.assertEqual(inputs["input_ids"], [padded_expected_input_ids_1, expected_input_ids_2])
|
||||
self.assertEqual(
|
||||
inputs["attention_mask"],
|
||||
[[0] * pad_len + [1] * len(expected_input_ids_1), [1] * len(expected_input_ids_2)],
|
||||
)
|
||||
encoder_feature_dims = (
|
||||
3 * processor.image_processor.encoder_patch_size * processor.image_processor.encoder_patch_size
|
||||
)
|
||||
self.assertEqual(
|
||||
np.array(inputs["pixel_values"]).shape,
|
||||
(3, processor.image_processor.max_num_patches, encoder_feature_dims),
|
||||
)
|
||||
self.assertEqual(
|
||||
np.array(inputs["pixel_attention_mask"]).shape, (3, processor.image_processor.max_num_patches)
|
||||
)
|
||||
self.assertListEqual(inputs["spatial_shapes"].tolist(), [[6, 6], [6, 6], [6, 6]])
|
||||
|
||||
def test_process_interleaved_images_prompts_image_splitting(self):
|
||||
processor = self.get_processor()
|
||||
|
||||
image_str = "<image>"
|
||||
text_str_1 = "In this image, we see"
|
||||
text_str_2 = "bla, bla"
|
||||
|
||||
text = [image_str + text_str_1, text_str_2 + image_str + image_str]
|
||||
images = [[self.small_image], [self.high_res_image, self.high_res_image]]
|
||||
|
||||
inputs = processor(
|
||||
text=text,
|
||||
images=images,
|
||||
padding=True,
|
||||
padding_side="left",
|
||||
max_pixels_tolerance=2.0,
|
||||
use_thumbnail=True,
|
||||
do_image_splitting=True,
|
||||
)
|
||||
|
||||
tokenized_sentence_1 = processor.tokenizer(text_str_1, add_special_tokens=False)
|
||||
tokenized_sentence_2 = processor.tokenizer(text_str_2, add_special_tokens=False)
|
||||
|
||||
small_image_tokens = self.get_split_image_expected_tokens(processor, 3, 3, True, 9)
|
||||
large_image_tokens = self.get_split_image_expected_tokens(processor, 3, 3, True, 9)
|
||||
high_res_image_tokens = self.get_split_image_expected_tokens(processor, 3, 3, True, 9)
|
||||
|
||||
expected_input_ids_1 = small_image_tokens + tokenized_sentence_1["input_ids"]
|
||||
expected_input_ids_2 = tokenized_sentence_2["input_ids"] + large_image_tokens + high_res_image_tokens
|
||||
# Pad the first input to match the second input
|
||||
pad_len = len(expected_input_ids_2) - len(expected_input_ids_1)
|
||||
padded_expected_input_ids_1 = [self.padding_token_id] * pad_len + expected_input_ids_1
|
||||
|
||||
self.assertEqual(inputs["input_ids"][0], padded_expected_input_ids_1)
|
||||
self.assertEqual(inputs["input_ids"][1], expected_input_ids_2)
|
||||
self.assertEqual(
|
||||
inputs["attention_mask"],
|
||||
[[0] * pad_len + [1] * len(expected_input_ids_1), [1] * len(expected_input_ids_2)],
|
||||
)
|
||||
self.assertEqual(np.array(inputs["pixel_values"]).shape, (30, 49, 12))
|
||||
self.assertEqual(np.array(inputs["pixel_attention_mask"]).shape, (30, 49))
|
||||
self.assertListEqual(inputs["spatial_shapes"].tolist(), ([[7, 7]] * 9 + [[6, 6]]) * 3)
|
||||
|
||||
def test_add_special_tokens_processor_image_splitting(self):
|
||||
processor = self.get_processor()
|
||||
|
||||
image_str = "<image>"
|
||||
text_str = "In this image, we see"
|
||||
text = text_str + image_str
|
||||
|
||||
# fmt: off
|
||||
inputs = processor(text=text, images=self.high_res_image, add_special_tokens=False, do_image_splitting=True)
|
||||
tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False)
|
||||
split_high_res_image_tokens = self.get_split_image_expected_tokens(processor, 3, 3, True, 9)
|
||||
expected_input_ids = [tokenized_sentence["input_ids"] + split_high_res_image_tokens]
|
||||
self.assertEqual(inputs["input_ids"], expected_input_ids)
|
||||
# fmt: on
|
||||
|
||||
def test_add_special_tokens_processor_image_splitting_large_image(self):
|
||||
processor = self.get_processor()
|
||||
|
||||
image_str = "<image>"
|
||||
text_str = "In this image, we see"
|
||||
text = text_str + image_str
|
||||
|
||||
# fmt: off
|
||||
inputs = processor(text=text, images=self.large_image, add_special_tokens=False, max_pixels_tolerance=2.0, do_image_splitting=True)
|
||||
tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False)
|
||||
large_image_tokens = self.get_split_image_expected_tokens(processor, 2, 4, True, 8)
|
||||
expected_input_ids = [tokenized_sentence["input_ids"] + large_image_tokens]
|
||||
self.assertEqual(inputs["input_ids"], expected_input_ids)
|
||||
# fmt: on
|
||||
|
||||
def test_add_special_tokens_processor_image_no_splitting(self):
|
||||
processor = self.get_processor()
|
||||
|
||||
image_str = "<image>"
|
||||
text_str = "In this image, we see"
|
||||
text = image_str + text_str
|
||||
|
||||
# fmt: off
|
||||
inputs = processor(text=text, images=self.high_res_image, add_special_tokens=False, use_image_special_tokens=True, do_image_splitting=False)
|
||||
tokenized_sentence = processor.tokenizer(text_str, add_special_tokens=False)
|
||||
split_high_res_image_tokens = [self.image_start_token_id] + [self.image_token_id] * 9 + [self.image_end_token_id]
|
||||
expected_input_ids = [split_high_res_image_tokens + tokenized_sentence["input_ids"]]
|
||||
self.assertEqual(inputs["input_ids"], expected_input_ids)
|
||||
# fmt: on
|
||||
|
||||
def test_process_interleaved_images_prompts_image_error(self):
|
||||
processor = self.get_processor()
|
||||
|
||||
text = [
|
||||
"This is a test sentence.",
|
||||
"In this other sentence we try some good things",
|
||||
]
|
||||
images = [[self.small_image], [self.large_image]]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
images = [[self.small_image], []]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
text = [
|
||||
"This is a test sentence.<image>",
|
||||
"In this other sentence we try some good things<image>",
|
||||
]
|
||||
images = [[self.small_image], [self.large_image, self.high_res_image]]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
images = [[], [self.large_image]]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
images = [self.small_image, self.large_image, self.high_res_image]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
images = [self.small_image]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
text = [
|
||||
"This is a test sentence.",
|
||||
"In this other sentence we try some good things<image>",
|
||||
]
|
||||
images = [[self.small_image], []]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
images = [[], [self.large_image]]
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
images = [self.small_image, self.large_image]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
images = [self.small_image]
|
||||
with self.assertRaises(ValueError):
|
||||
processor(text=text, images=images, padding=True)
|
||||
|
||||
def test_apply_chat_template(self):
|
||||
# Message contains content which a mix of lists with images and image urls and string
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "text", "text": "What do these images show?"},
|
||||
{"type": "image"},
|
||||
{"type": "image"},
|
||||
],
|
||||
},
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": "The first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.",
|
||||
}
|
||||
],
|
||||
},
|
||||
{"role": "user", "content": [{"type": "text", "text": "And who is that?"}]},
|
||||
]
|
||||
processor = self.get_processor()
|
||||
# Make short sequence length to test that the fake tokens are added correctly
|
||||
rendered = processor.apply_chat_template(messages, add_generation_prompt=True)
|
||||
|
||||
expected_rendered = (
|
||||
"<|startoftext|><|im_start|>user\nWhat do these images show?<image><image><|im_end|>\n"
|
||||
"<|im_start|>assistant\nThe first image shows the statue of Liberty in New York. The second image picture depicts Idefix, the dog of Obelix in Asterix and Obelix.<|im_end|>\n"
|
||||
"<|im_start|>user\nAnd who is that?<|im_end|>\n"
|
||||
"<|im_start|>assistant\n"
|
||||
)
|
||||
self.assertEqual(rendered, expected_rendered)
|
||||
|
||||
def test_text_only_inference(self):
|
||||
"""Test that the processor works correctly with text-only input."""
|
||||
processor_components = self.prepare_components()
|
||||
processor_components["tokenizer"] = self.get_component("tokenizer", padding_side="left")
|
||||
processor_kwargs = self.prepare_processor_dict()
|
||||
|
||||
processor = self.processor_class(**processor_components, **processor_kwargs)
|
||||
|
||||
text = "This is a simple text without images."
|
||||
inputs = processor(text=text)
|
||||
|
||||
tokenized_sentence = processor.tokenizer(text, add_special_tokens=False)
|
||||
expected_input_ids = [tokenized_sentence["input_ids"]]
|
||||
|
||||
self.assertEqual(inputs["input_ids"], expected_input_ids)
|
||||
self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids[0])])
|
||||
self.assertTrue("pixel_values" not in inputs)
|
||||
self.assertTrue("pixel_attention_mask" not in inputs)
|
||||
|
||||
# Test batch of texts without image tokens
|
||||
texts = ["First text.", "Second piece of text."]
|
||||
batch_inputs = processor(text=texts, padding=True)
|
||||
|
||||
tokenized_1 = processor.tokenizer(texts[0], add_special_tokens=False)
|
||||
tokenized_2 = processor.tokenizer(texts[1], add_special_tokens=False)
|
||||
|
||||
expected_1 = tokenized_1["input_ids"]
|
||||
expected_2 = tokenized_2["input_ids"]
|
||||
|
||||
# Pad the shorter sequence
|
||||
pad_len = len(expected_2) - len(expected_1)
|
||||
if pad_len > 0:
|
||||
padded_expected_1 = [self.padding_token_id] * pad_len + expected_1
|
||||
expected_attention_1 = [0] * pad_len + [1] * len(expected_1)
|
||||
self.assertEqual(batch_inputs["input_ids"], [padded_expected_1, expected_2])
|
||||
self.assertEqual(batch_inputs["attention_mask"], [expected_attention_1, [1] * len(expected_2)])
|
||||
else:
|
||||
pad_len = -pad_len
|
||||
padded_expected_2 = [self.padding_token_id] * pad_len + expected_2
|
||||
expected_attention_2 = [0] * pad_len + [1] * len(expected_2)
|
||||
self.assertEqual(batch_inputs["input_ids"], [expected_1, padded_expected_2])
|
||||
self.assertEqual(batch_inputs["attention_mask"], [[1] * len(expected_1), expected_attention_2])
|
||||
|
||||
def test_missing_images_error(self):
|
||||
"""Test that appropriate error is raised when images are referenced but not provided."""
|
||||
processor = self.get_processor()
|
||||
|
||||
# Test single text with image token but no image
|
||||
text = "Let me show you this image: <image> What do you think?"
|
||||
with self.assertRaises(ValueError) as context:
|
||||
processor(text=text)
|
||||
self.assertTrue("We detected 1 tokens in the text but no images were passed" in str(context.exception))
|
||||
|
||||
# Test batch with image tokens but no images
|
||||
texts = [
|
||||
"First text with <image> token.",
|
||||
"Second text <image> with token.",
|
||||
]
|
||||
with self.assertRaises(ValueError) as context:
|
||||
processor(text=texts)
|
||||
self.assertTrue("We detected 2 tokens in the text but no images were passed" in str(context.exception))
|
||||
|
||||
# Test with None as Images
|
||||
with self.assertRaises(ValueError) as context:
|
||||
processor(text=text, images=None)
|
||||
self.assertTrue("We detected 1 tokens in the text but no images were passed" in str(context.exception))
|
||||
|
||||
with self.assertRaises(ValueError) as context:
|
||||
processor(text=texts, images=None)
|
||||
self.assertTrue("We detected 2 tokens in the text but no images were passed" in str(context.exception))
|
||||
Reference in New Issue
Block a user