first commit
Some checks failed
Self-hosted runner (nightly-past-ci-caller) / Get number (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.11 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.10 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.9 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.8 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.7 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.6 (push) Has been cancelled
Self-hosted runner (nightly-past-ci-caller) / TensorFlow 2.5 (push) Has been cancelled
Self-hosted runner (benchmark) / Benchmark (aws-g5-4xlarge-cache) (push) Has been cancelled
Build documentation / build (push) Has been cancelled
Build documentation / build_other_lang (push) Has been cancelled
CodeQL Security Analysis / CodeQL Analysis (push) Has been cancelled
New model PR merged notification / Notify new model (push) Has been cancelled
PR CI / pr-ci (push) Has been cancelled
Slow tests on important models (on Push - A10) / Get all modified files (push) Has been cancelled
Secret Leaks / trufflehog (push) Has been cancelled
Update Transformers metadata / build_and_package (push) Has been cancelled
Slow tests on important models (on Push - A10) / Model CI (push) Has been cancelled
Check Tiny Models / Check tiny models (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Model CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Pipeline CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Example CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / DeepSpeed CI (push) Has been cancelled
Self-hosted runner (Intel Gaudi3 scheduled CI caller) / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI - Flash Attn / Setup (push) Has been cancelled
Nvidia CI - Flash Attn / Model CI (push) Has been cancelled
Nvidia CI / Setup (push) Has been cancelled
Nvidia CI / Model CI (push) Has been cancelled
Nvidia CI / Torch pipeline CI (push) Has been cancelled
Nvidia CI / Example CI (push) Has been cancelled
Nvidia CI / Trainer/FSDP CI (push) Has been cancelled
Nvidia CI / DeepSpeed CI (push) Has been cancelled
Nvidia CI / Quantization CI (push) Has been cancelled
Nvidia CI / Kernels CI (push) Has been cancelled
Doctests / Setup (push) Has been cancelled
Doctests / Call doctest jobs (push) Has been cancelled
Doctests / Send results to webhook (push) Has been cancelled
Extras Smoke Test / Get supported Python versions (push) Has been cancelled
Extras Smoke Test / Test extras on Python ${{ matrix.python-version }} (push) Has been cancelled
Extras Smoke Test / Check Slack token availability (push) Has been cancelled
Extras Smoke Test / Notify failures to Slack (push) Has been cancelled
Self-hosted runner (AMD scheduled CI caller) / Trigger Scheduled AMD CI (push) Has been cancelled
Stale Bot / Close Stale Issues (push) Has been cancelled

This commit is contained in:
陈赣
2026-06-05 16:53:03 +08:00
commit 06f1fd69a6
6047 changed files with 1895387 additions and 0 deletions

View File

View File

@@ -0,0 +1,903 @@
# 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_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
from transformers.models.lfm2_vl.image_processing_lfm2_vl import (
find_closest_aspect_ratio,
round_by_factor,
)
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):
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_processing_classes.values():
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.image_processing_classes["torchvision"](**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.image_processing_classes["torchvision"](**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.image_processing_classes["torchvision"](**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.image_processing_classes["torchvision"](**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.image_processing_classes["torchvision"](**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.image_processing_classes["torchvision"](**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,
),
)
def test_small_image_no_tiling_no_thumbnail(self):
"""Small image with tiling disabled should use smart resize, no thumbnail."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=False,
use_thumbnail=True, # even if enabled, should not be used for small/non-tiled images
)
# Create a small image (256x256)
small_image = Image.new("RGB", (256, 256), color="red")
result = image_processing([[small_image]], return_tensors="pt", return_row_col_info=True)
# With tiling disabled, should be 1 tile (no thumbnail)
self.assertEqual(result.image_rows[0].item(), 1)
self.assertEqual(result.image_cols[0].item(), 1)
# Should have exactly 1 image in batch (no thumbnail)
self.assertEqual(result.pixel_values.shape[0], 1)
def test_small_image_tiling_enabled_no_thumbnail(self):
"""Small image with tiling enabled should not be tiled (too small), no thumbnail."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
)
# Create a small image that won't exceed the max_image_tokens threshold
small_image = Image.new("RGB", (256, 256), color="blue")
result = image_processing([[small_image]], return_tensors="pt", return_row_col_info=True)
# Small image should not be tiled (1x1 grid), no thumbnail added
self.assertEqual(result.image_rows[0].item(), 1)
self.assertEqual(result.image_cols[0].item(), 1)
# Should have exactly 1 image in batch (no thumbnail)
self.assertEqual(result.pixel_values.shape[0], 1)
def test_large_image_no_tiling_smart_resize(self):
"""Large image with tiling disabled should use smart resize, no thumbnail."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=False,
use_thumbnail=True, # even if enabled, should not be used
)
# Create a large image (2048x2048)
large_image = Image.new("RGB", (2048, 2048), color="green")
result = image_processing([[large_image]], return_tensors="pt", return_row_col_info=True)
# With tiling disabled, should be 1 tile even for large images
self.assertEqual(result.image_rows[0].item(), 1)
self.assertEqual(result.image_cols[0].item(), 1)
# Should have exactly 1 image in batch (no thumbnail, smart resize only)
self.assertEqual(result.pixel_values.shape[0], 1)
def test_large_image_tiling_enabled_thumbnail_disabled(self):
"""Large image with tiling enabled but thumbnail disabled should tile without thumbnail."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=False,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create a large image that will require tiling
large_image = Image.new("RGB", (2048, 2048), color="yellow")
result = image_processing([[large_image]], return_tensors="pt", return_row_col_info=True)
# Large image should be tiled into multiple tiles
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
num_tiles = num_rows * num_cols
self.assertGreater(num_tiles, 1, "Large image should be tiled into multiple tiles")
# Count actual patches - with thumbnail disabled, should equal number of tiles
num_images_in_batch = result.pixel_values.shape[0]
self.assertEqual(
num_images_in_batch, num_tiles, "Number of patches should equal number of tiles (no thumbnail)"
)
def test_large_image_tiling_enabled_thumbnail_enabled(self):
"""Large image with tiling and thumbnail enabled should tile AND add thumbnail."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create a large image that will require tiling
large_image = Image.new("RGB", (2048, 2048), color="purple")
result = image_processing([[large_image]], return_tensors="pt", return_row_col_info=True)
# Large image should be tiled into multiple tiles
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
num_tiles = num_rows * num_cols
self.assertGreater(num_tiles, 1, "Large image should be tiled into multiple tiles")
# With thumbnail enabled, we should have tiles + 1 thumbnail
num_images_in_batch = result.pixel_values.shape[0]
self.assertEqual(num_images_in_batch, num_tiles + 1, "Number of patches should equal tiles + 1 (thumbnail)")
# ==================== Non-Square Aspect Ratio Tests ====================
def test_landscape_image_aspect_ratio(self):
"""Test that landscape images (wider than tall) are processed correctly."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create a landscape image (1920x1080, ~16:9 aspect ratio)
landscape_image = Image.new("RGB", (1920, 1080), color="blue")
result = image_processing([[landscape_image]], return_tensors="pt", return_row_col_info=True)
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
# Landscape image should have more columns than rows
self.assertGreaterEqual(num_cols, num_rows, "Landscape image should have cols >= rows")
def test_extreme_aspect_ratio_wide(self):
"""Test extremely wide image (panorama-like)."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create an extremely wide image (3000x500)
wide_image = Image.new("RGB", (3000, 500), color="red")
result = image_processing([[wide_image]], return_tensors="pt", return_row_col_info=True)
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
# Very wide image should have significantly more cols than rows
self.assertGreater(num_cols, num_rows, "Very wide image should have cols > rows")
def test_extreme_aspect_ratio_tall(self):
"""Test extremely tall image."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=10,
tile_size=512,
)
# Create an extremely tall image (500x3000)
tall_image = Image.new("RGB", (500, 3000), color="yellow")
result = image_processing([[tall_image]], return_tensors="pt", return_row_col_info=True)
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
# Very tall image should have significantly more rows than cols
self.assertGreater(num_rows, num_cols, "Very tall image should have rows > cols")
# ==================== Output Validation Tests ====================
def test_image_sizes_returned_with_row_col_info(self):
"""Test that image_sizes is returned when return_row_col_info=True."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
image = Image.new("RGB", (512, 256), color="green")
result = image_processing([[image]], return_tensors="pt", return_row_col_info=True)
# Check all row/col info is returned
self.assertIn("image_rows", result)
self.assertIn("image_cols", result)
self.assertIn("image_sizes", result)
# image_sizes should contain [height, width] for the resized image
image_sizes = result.image_sizes
self.assertIsInstance(image_sizes, torch.Tensor)
self.assertEqual(image_sizes.shape[0], 1) # one sample
self.assertEqual(image_sizes.shape[1], 2) # [height, width]
def test_output_consistency_across_formats(self):
"""Test that outputs are consistent regardless of input format (PIL, numpy, torch)."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Create same image in different formats
pil_image = Image.new("RGB", (256, 256), color="white")
np_image = np.array(pil_image)
torch_image = torch.from_numpy(np_image).permute(2, 0, 1)
result_pil = image_processing([[pil_image]], return_tensors="pt")
result_np = image_processing([[np_image]], return_tensors="pt")
result_torch = image_processing([[torch_image]], return_tensors="pt")
# All should produce same shapes
self.assertEqual(result_pil.pixel_values.shape, result_np.pixel_values.shape)
self.assertEqual(result_pil.pixel_values.shape, result_torch.pixel_values.shape)
self.assertEqual(result_pil.spatial_shapes.tolist(), result_np.spatial_shapes.tolist())
self.assertEqual(result_pil.spatial_shapes.tolist(), result_torch.spatial_shapes.tolist())
# ==================== Multiple Images Per Sample Tests ====================
def test_multiple_images_per_sample(self):
"""Test processing multiple images in a single sample: [[img1, img2, img3]]."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
img1 = Image.new("RGB", (256, 256), color="red")
img2 = Image.new("RGB", (256, 256), color="green")
img3 = Image.new("RGB", (256, 256), color="blue")
result = image_processing([[img1, img2, img3]], return_tensors="pt")
# Should have 3 images processed
self.assertEqual(result.pixel_values.shape[0], 3)
self.assertEqual(result.spatial_shapes.shape[0], 3)
self.assertEqual(result.pixel_attention_mask.shape[0], 3)
def test_mixed_image_counts_across_batch(self):
"""Test batch with different number of images per sample: [[img1], [img2, img3]]."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
img1 = Image.new("RGB", (256, 256), color="red")
img2 = Image.new("RGB", (256, 256), color="green")
img3 = Image.new("RGB", (256, 256), color="blue")
# First sample has 1 image, second sample has 2 images
result = image_processing([[img1], [img2, img3]], return_tensors="pt")
# Total should be 3 images (1 + 2)
self.assertEqual(result.pixel_values.shape[0], 3)
self.assertEqual(result.spatial_shapes.shape[0], 3)
def test_multiple_images_different_sizes(self):
"""Test multiple images per sample with different sizes."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
img_small = Image.new("RGB", (256, 256), color="red")
img_medium = Image.new("RGB", (512, 512), color="green")
img_large = Image.new("RGB", (768, 768), color="blue")
result = image_processing([[img_small, img_medium, img_large]], return_tensors="pt")
# Should have 3 images processed
self.assertEqual(result.pixel_values.shape[0], 3)
# All should have same max_num_patches due to padding
self.assertEqual(result.pixel_values.shape[1], image_processing.max_num_patches)
# ==================== Parameter Variations Tests ====================
def test_forced_grid_config_min_equals_max(self):
"""Test forcing a specific grid configuration with min_tiles == max_tiles."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
min_tiles=4,
max_tiles=4, # Force exactly 4 tiles
tile_size=512,
use_thumbnail=False,
)
# Large image that would normally get more tiles
wide_image = Image.new("RGB", (3000, 500), color="red")
result = image_processing([[wide_image]], return_tensors="pt", return_row_col_info=True)
num_rows = result.image_rows[0].item()
num_cols = result.image_cols[0].item()
num_tiles = num_rows * num_cols
# Should be exactly 4 tiles
self.assertEqual(num_tiles, 4, "Should have exactly 4 tiles when min_tiles == max_tiles == 4")
# ==================== Input Validation Tests ====================
def test_min_tiles_greater_than_max_tiles_raises_error(self):
"""Test that min_tiles > max_tiles raises ValueError."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
min_tiles=10,
max_tiles=2, # Invalid: min > max
)
image = Image.new("RGB", (1024, 1024), color="red")
with self.assertRaises(ValueError) as context:
image_processing([[image]], return_tensors="pt")
self.assertIn("min_tiles", str(context.exception).lower())
# ==================== Edge Case Images Tests ====================
def test_very_small_image(self):
"""Test image smaller than encoder_patch_size."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=False,
encoder_patch_size=16,
)
# Image smaller than patch size
tiny_image = Image.new("RGB", (8, 8), color="red")
result = image_processing([[tiny_image]], return_tensors="pt")
# Should still process without error
self.assertIn("pixel_values", result)
self.assertEqual(result.pixel_values.dim(), 3)
def test_grayscale_image(self):
"""Test that grayscale (1-channel) images are converted to RGB."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Create grayscale image
grayscale_image = Image.new("L", (256, 256), color=128)
result = image_processing([[grayscale_image]], return_tensors="pt")
# Should process and output 3 channels (converted to RGB)
self.assertIn("pixel_values", result)
# pixel_values shape is (batch, num_patches, patch_size^2 * 3)
expected_patch_dim = 3 * image_processing.encoder_patch_size**2
self.assertEqual(result.pixel_values.shape[2], expected_patch_dim)
def test_rgba_4_channel_image(self):
"""Test that RGBA (4-channel) images are converted to RGB."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Create RGBA image with alpha channel
rgba_image = Image.new("RGBA", (256, 256), color=(255, 0, 0, 128))
result = image_processing([[rgba_image]], return_tensors="pt", do_convert_rgb=True)
# Should process and output 3 channels (alpha dropped)
self.assertIn("pixel_values", result)
expected_patch_dim = 3 * image_processing.encoder_patch_size**2
self.assertEqual(result.pixel_values.shape[2], expected_patch_dim)
def test_numpy_4_channel_rgba(self):
"""Test actual 4-channel numpy array input - convert to PIL for RGB conversion."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Create 4-channel numpy array (RGBA) and convert to PIL Image for RGB conversion
rgba_np = np.random.randint(0, 255, (256, 256, 4), dtype=np.uint8)
rgba_pil = Image.fromarray(rgba_np, mode="RGBA")
result = image_processing([[rgba_pil]], return_tensors="pt", do_convert_rgb=True)
# Should convert to 3 channels
self.assertIn("pixel_values", result)
expected_patch_dim = 3 * image_processing.encoder_patch_size**2
self.assertEqual(result.pixel_values.shape[2], expected_patch_dim)
def test_single_pixel_image(self):
"""Test 1x1 pixel image (extreme edge case)."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
single_pixel = Image.new("RGB", (1, 1), color="blue")
result = image_processing([[single_pixel]], return_tensors="pt")
# Should process without error
self.assertIn("pixel_values", result)
# ==================== Helper Function Unit Tests ====================
def test_round_by_factor(self):
"""Test round_by_factor function."""
# Exact multiples should return themselves
self.assertEqual(round_by_factor(32, 16), 32)
self.assertEqual(round_by_factor(64, 16), 64)
# Values should round to nearest multiple
self.assertEqual(round_by_factor(30, 16), 32) # 30 -> 32 (closer to 32 than 16)
self.assertEqual(round_by_factor(20, 16), 16) # 20 -> 16 (closer to 16 than 32)
self.assertEqual(round_by_factor(24, 16), 32) # 24 -> 32 (equidistant, rounds up)
# Test with different factors
self.assertEqual(round_by_factor(100, 32), 96) # 100 -> 96
self.assertEqual(round_by_factor(50, 32), 64) # 50 -> 64
# Test with factor of 1
self.assertEqual(round_by_factor(17, 1), 17)
def test_is_image_too_large_small_image(self):
"""Test _is_image_too_large with small image."""
image_processing = self.image_processing_classes["torchvision"](
max_image_tokens=256,
encoder_patch_size=16,
downsample_factor=2,
max_pixels_tolerance=2.0,
)
is_large = image_processing._is_image_too_large(
height=512,
width=512,
max_image_tokens=256,
encoder_patch_size=16,
downsample_factor=2,
max_pixels_tolerance=2.0,
)
self.assertFalse(is_large)
def test_is_image_too_large_large_image(self):
"""Test _is_image_too_large with large image."""
image_processing = self.image_processing_classes["torchvision"](
max_image_tokens=256,
encoder_patch_size=16,
downsample_factor=2,
max_pixels_tolerance=1.0,
)
is_large = image_processing._is_image_too_large(
height=565,
width=565,
max_image_tokens=256,
encoder_patch_size=16,
downsample_factor=2,
max_pixels_tolerance=1.0,
)
self.assertTrue(is_large)
# ==================== Batch Processing Tests ====================
def test_batch_mixed_image_sizes(self):
"""Test batch processing with different image sizes requiring different processing paths."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Create images with significantly different sizes
small_image = Image.new("RGB", (256, 256), color="red")
medium_image = Image.new("RGB", (512, 512), color="green")
large_image = Image.new("RGB", (1024, 1024), color="blue")
# Process as batch
result = image_processing([[small_image], [medium_image], [large_image]], return_tensors="pt")
# All should be processed and padded to same size
self.assertEqual(result.pixel_values.shape[0], 3)
# All should have same max_num_patches
self.assertEqual(result.pixel_values.shape[1], image_processing.max_num_patches)
# Patch dimension should be patch_size^2 * 3 channels
expected_patch_dim = 3 * image_processing.encoder_patch_size**2
self.assertEqual(result.pixel_values.shape[2], expected_patch_dim)
# Spatial shapes should all be square (equal height and width)
shapes = result.spatial_shapes.tolist()
for shape in shapes:
self.assertEqual(shape[0], shape[1], "Square images should have equal height and width")
# pixel_attention_mask should have correct shape
self.assertEqual(result.pixel_attention_mask.shape[0], 3)
self.assertEqual(result.pixel_attention_mask.shape[1], image_processing.max_num_patches)
def test_batch_mixed_aspect_ratios(self):
"""Test batch with mixed aspect ratios."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
square = Image.new("RGB", (512, 512), color="red")
landscape = Image.new("RGB", (1024, 512), color="green")
portrait = Image.new("RGB", (512, 1024), color="blue")
result = image_processing([[square], [landscape], [portrait]], return_tensors="pt")
# All should be processed
self.assertEqual(result.pixel_values.shape[0], 3)
self.assertEqual(result.spatial_shapes.shape[0], 3)
# Spatial shapes should reflect aspect ratios: [height, width]
shapes = result.spatial_shapes.tolist()
square_shape, landscape_shape, portrait_shape = shapes
# Square: height == width
self.assertEqual(square_shape[0], square_shape[1], "Square image should have equal spatial dimensions")
# Landscape: width > height
self.assertGreater(landscape_shape[1], landscape_shape[0], "Landscape image should have width > height")
# Portrait: height > width
self.assertGreater(portrait_shape[0], portrait_shape[1], "Portrait image should have height > width")
# pixel_attention_mask should match batch size and max_num_patches
self.assertEqual(result.pixel_attention_mask.shape[0], 3)
self.assertEqual(result.pixel_attention_mask.shape[1], image_processing.max_num_patches)
def test_disable_grouping_single_image(self):
"""Test disable_grouping parameter with single image."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
image = Image.new("RGB", (512, 512), color="purple")
# Process with and without disable_grouping
result_grouped = image_processing([[image]], return_tensors="pt", disable_grouping=False)
result_ungrouped = image_processing([[image]], return_tensors="pt", disable_grouping=True)
# Both should produce all expected output keys
for result in [result_grouped, result_ungrouped]:
self.assertIn("pixel_values", result)
self.assertIn("spatial_shapes", result)
self.assertIn("pixel_attention_mask", result)
# Both should have same output shapes for single image
self.assertEqual(result_grouped.pixel_values.shape, result_ungrouped.pixel_values.shape)
self.assertEqual(result_grouped.spatial_shapes.shape, result_ungrouped.spatial_shapes.shape)
self.assertEqual(result_grouped.pixel_attention_mask.shape, result_ungrouped.pixel_attention_mask.shape)
# Verify specific shapes
self.assertEqual(result_ungrouped.pixel_values.shape[0], 1)
self.assertEqual(result_ungrouped.pixel_values.shape[1], image_processing.max_num_patches)
expected_patch_dim = 3 * image_processing.encoder_patch_size**2
self.assertEqual(result_ungrouped.pixel_values.shape[2], expected_patch_dim)
def test_disable_grouping_batch(self):
"""Test disable_grouping parameter with batch of images."""
image_processing = self.image_processing_classes["torchvision"](do_image_splitting=False)
# Images of same size - normally would be grouped
img1 = Image.new("RGB", (256, 256), color="red")
img2 = Image.new("RGB", (256, 256), color="green")
img3 = Image.new("RGB", (256, 256), color="blue")
# Process with disable_grouping=True
result = image_processing([[img1], [img2], [img3]], return_tensors="pt", disable_grouping=True)
# Should produce valid output for all images
self.assertEqual(result.pixel_values.shape[0], 3)
def test_batch_with_tiling(self):
"""Test batch processing when some images need tiling."""
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=True,
min_tiles=2,
max_tiles=4,
tile_size=512,
)
# Small image (no tiling needed) and large image (will be tiled)
small = Image.new("RGB", (256, 256), color="red")
large = Image.new("RGB", (1024, 1024), color="blue") # 2x2 tiles at 512
result = image_processing([[small], [large]], return_tensors="pt", return_row_col_info=True)
# Calculate tiles for each image
small_tiles = result.image_rows[0].item() * result.image_cols[0].item()
large_tiles = result.image_rows[1].item() * result.image_cols[1].item()
# Small image: single tile (no splitting needed)
self.assertEqual(small_tiles, 1, "Small 256x256 image should have 1 tile (no splitting)")
# Large image: 2x2 = 4 tiles for 1024x1024 with tile_size=512
self.assertEqual(large_tiles, 4, "Large 1536x1536 image should have 4 tiles (2x2)")
# Total images: small (1) + large tiles (4) + thumbnail for large (1) = 6
# Thumbnail is only added when there's more than 1 tile
expected_total = 1 + 4 + 1 # small + large_tiles + large_thumbnail
self.assertEqual(result.pixel_values.shape[0], expected_total)
self.assertEqual(result.spatial_shapes.shape[0], expected_total)
self.assertEqual(result.pixel_attention_mask.shape[0], expected_total)
def test_batch_tiling(self):
"""Test that patches from different images don't get mixed when batch processing with tiling.
This test verifies that when processing a batch of images with tiling enabled,
patches from image 0 don't end up in image 1's output and vice versa.
This was a bug caused by incorrect permute/reshape operations in crop_image_to_patches.
"""
for use_thumbnail in [False, True]:
with self.subTest(use_thumbnail=use_thumbnail):
image_processing = self.image_processing_classes["torchvision"](
do_image_splitting=True,
use_thumbnail=use_thumbnail,
min_tiles=2,
max_tiles=4,
tile_size=512,
)
# Create two large images with completely different solid colors
# Red image: RGB = (255, 0, 0)
# Blue image: RGB = (0, 0, 255)
red_image = Image.new("RGB", (1024, 1024), color=(255, 0, 0))
blue_image = Image.new("RGB", (1024, 1024), color=(0, 0, 255))
result = image_processing(
[[red_image], [blue_image]],
return_tensors="pt",
return_row_col_info=True,
do_rescale=False, # Keep original pixel values for easier verification
do_normalize=False,
)
# Each 1024x1024 image should be split into 2x2 = 4 tiles
red_tiles = result.image_rows[0].item() * result.image_cols[0].item()
blue_tiles = result.image_rows[1].item() * result.image_cols[1].item()
self.assertEqual(red_tiles, 4)
self.assertEqual(blue_tiles, 4)
# Calculate expected total patches
# Without thumbnail: 4 + 4 = 8
# With thumbnail: (4 + 1) + (4 + 1) = 10
thumb_count = 1 if use_thumbnail else 0
expected_total = (red_tiles + thumb_count) + (blue_tiles + thumb_count)
self.assertEqual(result.pixel_values.shape[0], expected_total)
pixel_values = result.pixel_values
patch_size = image_processing.encoder_patch_size
patches_per_image = red_tiles + thumb_count
# Check red image patches (and thumbnail if enabled)
# All should have high red, zero blue
for i in range(patches_per_image):
first_patch = pixel_values[i][0].view(3, patch_size, patch_size)
red_mean = first_patch[0].float().mean().item()
blue_mean = first_patch[2].float().mean().item()
patch_type = "thumbnail" if use_thumbnail and i == red_tiles else f"patch {i}"
self.assertGreater(
red_mean,
blue_mean,
f"Red image {patch_type} has more blue than red - patches may be interleaved",
)
# Check blue image patches (and thumbnail if enabled)
# All should have high blue, zero red
for i in range(patches_per_image, 2 * patches_per_image):
first_patch = pixel_values[i][0].view(3, patch_size, patch_size)
red_mean = first_patch[0].float().mean().item()
blue_mean = first_patch[2].float().mean().item()
local_idx = i - patches_per_image
patch_type = "thumbnail" if use_thumbnail and local_idx == blue_tiles else f"patch {local_idx}"
self.assertGreater(
blue_mean,
red_mean,
f"Blue image {patch_type} has more red than blue - patches may be interleaved",
)

View File

@@ -0,0 +1,385 @@
# 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 (
Expectations,
cleanup,
require_deterministic_for_xpu,
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 {}
)
model_tester_class = Lfm2VlModelTester
_is_composite = True
test_torch_exportable = False
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 _get_conv_state_shape(self, batch_size: int, config):
return (batch_size, config.hidden_size, config.conv_L_cache)
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 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
@pytest.mark.xfail(reason="This architecture seems to not compute gradients for some layer.")
def test_training_gradient_checkpointing(self):
super().test_training_gradient_checkpointing()
@pytest.mark.xfail(reason="This architecture seems to not compute gradients for some layer.")
def test_training_gradient_checkpointing_use_reentrant_false(self):
super().test_training_gradient_checkpointing_use_reentrant_false()
@pytest.mark.xfail(reason="This architecture seems to not compute gradients for some layer.")
def test_training_gradient_checkpointing_use_reentrant_true(self):
super().test_training_gradient_checkpointing_use_reentrant_true()
@require_torch_accelerator
@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)
@require_deterministic_for_xpu
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 two cats sleeping on a pink blanket. There are also two remote controls on the blanket.\n\n\n\n"
self.assertEqual(generated_texts[0], expected_generated_text)
@require_deterministic_for_xpu
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)
@require_deterministic_for_xpu
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, we see a cat"]
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, we see a cat that is lying on its side on a cat bed.",
]
self.assertListEqual(generated_texts, expected_generated_text)
@require_torch_accelerator
@slow
class Lfm2_5VlForConditionalGenerationIntegrationTest(unittest.TestCase):
def setUp(self):
self.processor = AutoProcessor.from_pretrained("LiquidAI/LFM2.5-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)
@require_deterministic_for_xpu
def test_integration_test(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2.5-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 two cats lying on a pink blanket. One cat is a tabby, and the other is a"
)
self.assertEqual(generated_texts[0], expected_generated_text)
@require_deterministic_for_xpu
def test_integration_test_high_resolution(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2.5-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, an iconic symbol of freedom and democracy. It stands on Liberty Island in"
self.assertEqual(generated_texts[0], expected_generated_text)
@require_deterministic_for_xpu
def test_integration_test_batched(self):
model = Lfm2VlForConditionalGeneration.from_pretrained(
"LiquidAI/LFM2.5-VL-1.6B",
dtype=torch.bfloat16,
device_map="auto",
)
# Create inputs
text = ["<image>In this image, we see", "<image>In this image, we see"]
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 = Expectations(
{
(None, None): [
"In this image, we see the Statue of Liberty, an iconic symbol of freedom and democracy. It stands on Liberty Island in",
"In this image, we see two cats lying on a pink blanket. One cat is a tabby, and the other is a",
],
("xpu", 5): [
"In this image, we see the Statue of Liberty, an iconic symbol of freedom and democracy. It stands tall on a small",
"In this image, we see two cats lying on a pink blanket. One cat is a tabby, and the other is a",
],
}
).get_expectation()
self.assertListEqual(generated_texts, expected_generated_text)

View File

@@ -0,0 +1,599 @@
# 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 unittest
import numpy as np
from transformers import 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():
pass
@require_torch
@require_vision
class Lfm2VlProcessorTest(ProcessorTesterMixin, unittest.TestCase):
processor_class = Lfm2VlProcessor
@classmethod
def _setup_image_processor(cls):
image_processor_class = cls._get_component_class_from_processor("image_processor")
return image_processor_class(
tile_size=14,
min_image_tokens=2,
max_image_tokens=10,
encoder_patch_size=2,
do_image_splitting=False,
)
@classmethod
def _setup_tokenizer(cls):
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
processor_kwargs = cls.prepare_processor_dict()
return tokenizer_class.from_pretrained("LiquidAI/LFM2-VL-1.6B", **processor_kwargs)
@classmethod
def _setup_test_attributes(cls, processor):
# 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)
@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}
@unittest.skip("Lfm2VlProcessor adds special tokens to the text")
def test_tokenizer_defaults(self):
pass
# 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
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, 4, 2, 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))
def test_single_tile_image_with_thumbnail_disabled(self):
"""Test that single-tile images work correctly when use_thumbnail=False."""
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 = "Describe this image."
text = image_str + text_str
# Test with use_thumbnail=False - this should still generate correct tokens
inputs = processor(text=text, images=self.small_image, use_thumbnail=False)
# Count image tokens in input_ids
num_image_tokens = sum(1 for token_id in inputs["input_ids"][0] if token_id == self.image_token_id)
# Verify we have image tokens (the bug caused 0 tokens)
self.assertGreater(num_image_tokens, 0, "Single-tile image with use_thumbnail=False should have image tokens")
# Verify the number of image tokens matches expected based on spatial_shapes
spatial_shape = inputs["spatial_shapes"][0].tolist()
expected_tokens = math.ceil(spatial_shape[0] / processor.image_processor.downsample_factor) * math.ceil(
spatial_shape[1] / processor.image_processor.downsample_factor
)
self.assertEqual(
num_image_tokens,
expected_tokens,
f"Image tokens ({num_image_tokens}) should match expected ({expected_tokens}) based on spatial shapes",
)
# Verify pixel_values shape is correct
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),
)
def test_multi_image(self):
"""Test that text is correctly processed when multiple images are present."""
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)
# Text with multiple images and text segments between them
text_1 = "First: "
text_2 = " Middle: "
text_3 = " End."
text = text_1 + "<image>" + text_2 + "<image>" + text_3
images = [[self.small_image, self.small_image]]
inputs = processor(text=text, images=images)
# Construct expected input_ids
tokenized_1 = processor.tokenizer(text_1, add_special_tokens=False)["input_ids"]
tokenized_2 = processor.tokenizer(text_2, add_special_tokens=False)["input_ids"]
tokenized_3 = processor.tokenizer(text_3, add_special_tokens=False)["input_ids"]
image_tokens = [self.image_start_token_id] + [self.image_token_id] * 9 + [self.image_end_token_id]
expected_input_ids = tokenized_1 + image_tokens + tokenized_2 + image_tokens + tokenized_3
self.assertEqual(inputs["input_ids"], [expected_input_ids])
self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids)])
def test_multi_turn_multi_image(self):
"""Test that text is correctly processed when multiple images are present in a multi-turn conversation."""
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)
# Simulate a multi-turn conversation with images
messages = [
{
"role": "user",
"content": [
{"type": "text", "text": "What is in image A?"},
{"type": "image"},
{"type": "text", "text": "And image B?"},
{"type": "image"},
],
},
{
"role": "assistant",
"content": [{"type": "text", "text": "Image A shows X. Image B shows Y."}],
},
{
"role": "user",
"content": [{"type": "text", "text": "Tell me more about image A."}],
},
]
text = processor.apply_chat_template(messages, add_generation_prompt=True)
images = [[self.small_image, self.small_image]]
inputs = processor(text=text, images=images, do_image_splitting=False)
# Construct expected input_ids based on the chat template structure
image_tokens = [self.image_start_token_id] + [self.image_token_id] * 9 + [self.image_end_token_id]
# Build expected sequence from chat template parts
bos = processor.tokenizer(self.bos_token, add_special_tokens=False)["input_ids"]
user_start = processor.tokenizer("<|im_start|>user\n", add_special_tokens=False)["input_ids"]
assistant_start = processor.tokenizer("<|im_start|>assistant\n", add_special_tokens=False)["input_ids"]
im_end = processor.tokenizer("<|im_end|>\n", add_special_tokens=False)["input_ids"]
text_a = processor.tokenizer("What is in image A?", add_special_tokens=False)["input_ids"]
text_b = processor.tokenizer("And image B?", add_special_tokens=False)["input_ids"]
assistant_response = processor.tokenizer("Image A shows X. Image B shows Y.", add_special_tokens=False)[
"input_ids"
]
followup = processor.tokenizer("Tell me more about image A.", add_special_tokens=False)["input_ids"]
expected_input_ids = (
bos
+ user_start
+ text_a
+ image_tokens
+ text_b
+ image_tokens
+ im_end
+ assistant_start
+ assistant_response
+ im_end
+ user_start
+ followup
+ im_end
+ assistant_start
)
self.assertEqual(inputs["input_ids"], [expected_input_ids])
self.assertEqual(inputs["attention_mask"], [[1] * len(expected_input_ids)])