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
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:
0
tests/models/paddleocr_vl/__init__.py
Normal file
0
tests/models/paddleocr_vl/__init__.py
Normal file
363
tests/models/paddleocr_vl/test_image_processing_paddleocr_vl.py
Normal file
363
tests/models/paddleocr_vl/test_image_processing_paddleocr_vl.py
Normal file
@@ -0,0 +1,363 @@
|
||||
# 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 itertools
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from transformers.image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD
|
||||
from transformers.models.paddleocr_vl.image_processing_paddleocr_vl import smart_resize
|
||||
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_torch_available():
|
||||
import torch
|
||||
|
||||
if is_vision_available():
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class PaddleOCRVLImageProcessingTester:
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
batch_size=7,
|
||||
num_channels=3,
|
||||
min_resolution=56,
|
||||
max_resolution=80,
|
||||
do_resize=True,
|
||||
size=None,
|
||||
do_normalize=True,
|
||||
image_mean=OPENAI_CLIP_MEAN,
|
||||
image_std=OPENAI_CLIP_STD,
|
||||
temporal_patch_size=1,
|
||||
patch_size=14,
|
||||
merge_size=2,
|
||||
do_convert_rgb=True,
|
||||
):
|
||||
# Use small pixel bounds so tests run quickly with small images
|
||||
size = size if size is not None else {"shortest_edge": 56 * 56, "longest_edge": 28 * 28 * 1280}
|
||||
self.parent = parent
|
||||
self.batch_size = batch_size
|
||||
self.num_channels = num_channels
|
||||
self.min_resolution = min_resolution
|
||||
self.max_resolution = max_resolution
|
||||
self.do_resize = do_resize
|
||||
self.size = size
|
||||
self.do_normalize = do_normalize
|
||||
self.image_mean = image_mean
|
||||
self.image_std = image_std
|
||||
self.temporal_patch_size = temporal_patch_size
|
||||
self.patch_size = patch_size
|
||||
self.merge_size = merge_size
|
||||
self.do_convert_rgb = do_convert_rgb
|
||||
|
||||
def prepare_image_processor_dict(self):
|
||||
return {
|
||||
"do_resize": self.do_resize,
|
||||
"image_mean": self.image_mean,
|
||||
"image_std": self.image_std,
|
||||
"do_normalize": self.do_normalize,
|
||||
"min_pixels": self.size["shortest_edge"],
|
||||
"max_pixels": self.size["longest_edge"],
|
||||
"patch_size": self.patch_size,
|
||||
"temporal_patch_size": self.temporal_patch_size,
|
||||
"merge_size": self.merge_size,
|
||||
"do_convert_rgb": self.do_convert_rgb,
|
||||
}
|
||||
|
||||
def expected_output_image_shape(self, images):
|
||||
"""
|
||||
Returns the expected pixel_values shape for a batch of images.
|
||||
PaddleOCRVL outputs patches of shape (N_patches_total, C, patch_size, patch_size).
|
||||
"""
|
||||
seq_len = 0
|
||||
for image in images:
|
||||
if isinstance(image, Image.Image):
|
||||
width, height = image.size
|
||||
elif isinstance(image, np.ndarray):
|
||||
if image.ndim == 3 and image.shape[2] <= 4:
|
||||
# channels-last: (H, W, C)
|
||||
height, width = image.shape[:2]
|
||||
else:
|
||||
# channels-first: (C, H, W)
|
||||
height, width = image.shape[-2:]
|
||||
elif is_torch_available() and isinstance(image, torch.Tensor):
|
||||
height, width = image.shape[-2:]
|
||||
else:
|
||||
height, width = self.min_resolution, self.min_resolution
|
||||
|
||||
resized_height, resized_width = smart_resize(
|
||||
height,
|
||||
width,
|
||||
factor=self.patch_size * self.merge_size,
|
||||
min_pixels=self.size["shortest_edge"],
|
||||
max_pixels=self.size["longest_edge"],
|
||||
)
|
||||
grid_h = resized_height // self.patch_size
|
||||
grid_w = resized_width // self.patch_size
|
||||
seq_len += grid_h * grid_w # temporal_patch_size=1, so grid_t=1
|
||||
|
||||
return (seq_len, self.num_channels, self.patch_size, self.patch_size)
|
||||
|
||||
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
||||
return 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,
|
||||
)
|
||||
|
||||
|
||||
@require_torch
|
||||
@require_vision
|
||||
class PaddleOCRVLImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
self.image_processor_tester = PaddleOCRVLImageProcessingTester(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, "do_normalize"))
|
||||
self.assertTrue(hasattr(image_processing, "image_mean"))
|
||||
self.assertTrue(hasattr(image_processing, "image_std"))
|
||||
self.assertTrue(hasattr(image_processing, "do_resize"))
|
||||
self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
|
||||
self.assertTrue(hasattr(image_processing, "patch_size"))
|
||||
self.assertTrue(hasattr(image_processing, "temporal_patch_size"))
|
||||
self.assertTrue(hasattr(image_processing, "merge_size"))
|
||||
|
||||
def test_image_processor_to_json_string(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processor = image_processing_class(**self.image_processor_dict)
|
||||
obj = json.loads(image_processor.to_json_string())
|
||||
for key, value in self.image_processor_dict.items():
|
||||
# min_pixels/max_pixels are stored as size in the config
|
||||
if key not in ["min_pixels", "max_pixels"]:
|
||||
self.assertEqual(obj[key], value)
|
||||
|
||||
def test_image_processor_from_dict_with_kwargs(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processor = image_processing_class.from_dict(self.image_processor_dict)
|
||||
self.assertEqual(
|
||||
image_processor.size,
|
||||
{
|
||||
"shortest_edge": self.image_processor_dict["min_pixels"],
|
||||
"longest_edge": self.image_processor_dict["max_pixels"],
|
||||
},
|
||||
)
|
||||
|
||||
image_processor = image_processing_class.from_dict(
|
||||
self.image_processor_dict, min_pixels=28 * 28, max_pixels=56 * 56
|
||||
)
|
||||
self.assertEqual(image_processor.size, {"shortest_edge": 28 * 28, "longest_edge": 56 * 56})
|
||||
|
||||
def test_select_best_resolution(self):
|
||||
best_resolution = smart_resize(561, 278, factor=28)
|
||||
self.assertEqual(best_resolution, (560, 280))
|
||||
|
||||
def test_call_pil(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
|
||||
for image in image_inputs:
|
||||
self.assertIsInstance(image, Image.Image)
|
||||
|
||||
# Single image
|
||||
encoded = image_processing(image_inputs[0], return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (1, 3))
|
||||
|
||||
# Batched
|
||||
encoded = image_processing(image_inputs, return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (self.image_processor_tester.batch_size, 3))
|
||||
|
||||
def test_call_numpy(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
|
||||
for image in image_inputs:
|
||||
self.assertIsInstance(image, np.ndarray)
|
||||
|
||||
# Single image
|
||||
encoded = image_processing(image_inputs[0], return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (1, 3))
|
||||
|
||||
# Batched
|
||||
encoded = image_processing(image_inputs, return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (self.image_processor_tester.batch_size, 3))
|
||||
|
||||
def test_call_pytorch(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
|
||||
for image in image_inputs:
|
||||
self.assertIsInstance(image, torch.Tensor)
|
||||
|
||||
# Single image
|
||||
encoded = image_processing(image_inputs[0], return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]])
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (1, 3))
|
||||
|
||||
# Batched
|
||||
encoded = image_processing(image_inputs, return_tensors="pt")
|
||||
expected_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
|
||||
self.assertEqual(tuple(encoded.pixel_values.shape), expected_shape)
|
||||
self.assertEqual(encoded.image_grid_thw.shape, (self.image_processor_tester.batch_size, 3))
|
||||
|
||||
def test_call_equal_resolution(self):
|
||||
"""With equal-resolution images, the batched output shapes are fully deterministic."""
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
# equal_resolution=True → all images are max_resolution × max_resolution = 80×80
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
|
||||
|
||||
# smart_resize(80, 80, factor=28, min_pixels=56*56, max_pixels=28*28*1280) → (84, 84)
|
||||
# grid_h = grid_w = 84 / 14 = 6, N_per_image = 36
|
||||
expected_n_patches_per_image = 6 * 6
|
||||
batch_size = self.image_processor_tester.batch_size
|
||||
|
||||
process_out = image_processing(image_inputs, return_tensors="pt")
|
||||
self.assertEqual(
|
||||
tuple(process_out.pixel_values.shape),
|
||||
(batch_size * expected_n_patches_per_image, 3, 14, 14),
|
||||
)
|
||||
expected_grid = torch.tensor([[1, 6, 6]] * batch_size)
|
||||
self.assertTrue((process_out.image_grid_thw == expected_grid).all())
|
||||
|
||||
@unittest.skip(reason="PaddleOCRVLImageProcessor converts to RGB, 4-channel images not consistently supported")
|
||||
def test_call_numpy_4_channels(self):
|
||||
pass
|
||||
|
||||
def test_custom_image_size(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
with tempfile.TemporaryDirectory() as tmpdirname:
|
||||
image_processing.save_pretrained(tmpdirname)
|
||||
image_processor_loaded = image_processing_class.from_pretrained(
|
||||
tmpdirname, max_pixels=56 * 56, min_pixels=28 * 28
|
||||
)
|
||||
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
|
||||
# equal_resolution=True → all images are max_resolution × max_resolution = 80×80
|
||||
# smart_resize(80, 80, factor=28, min_pixels=28*28=784, max_pixels=56*56=3136):
|
||||
# h_bar=84, 84*84=7056 > 3136, so reduce:
|
||||
# beta = sqrt(80*80/3136) = sqrt(2.041) = 1.429
|
||||
# h_bar = floor(80/1.429/28)*28 = floor(2.0)*28 = 2*28 = 56
|
||||
# grid_h=4, grid_w=4 → N=16 per image
|
||||
process_out = image_processor_loaded(image_inputs, return_tensors="pt")
|
||||
expected_n = 16 # 4*4 grid (56/14 = 4)
|
||||
self.assertEqual(process_out.pixel_values.shape[0], self.image_processor_tester.batch_size * expected_n)
|
||||
self.assertEqual(process_out.pixel_values.shape[1:], (3, 14, 14))
|
||||
|
||||
def test_custom_pixels(self):
|
||||
# Use pixel values >= 784 (28*28) to avoid smart_resize producing 0-size outputs
|
||||
# for images in the 56x80 px range used in the tester (factor=28 requires output >= 28px)
|
||||
pixel_choices = frozenset(itertools.product((1000, 5000, 50000), (1000, 5000, 50000)))
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processor_dict = self.image_processor_dict.copy()
|
||||
for a_pixels, b_pixels in pixel_choices:
|
||||
image_processor_dict["min_pixels"] = min(a_pixels, b_pixels)
|
||||
image_processor_dict["max_pixels"] = max(a_pixels, b_pixels)
|
||||
image_processor = image_processing_class(**image_processor_dict)
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs()
|
||||
# Just verify no error is raised
|
||||
image_processor(image_inputs, return_tensors="pt")
|
||||
|
||||
@require_vision
|
||||
@require_torch
|
||||
def test_backends_equivalence(self):
|
||||
if len(self.image_processing_classes) < 2:
|
||||
self.skipTest(reason="Skipping backends equivalence test as there are less than 2 backends")
|
||||
|
||||
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)
|
||||
|
||||
encodings = {}
|
||||
for backend_name, image_processing_class in self.image_processing_classes.items():
|
||||
image_processor = image_processing_class(**self.image_processor_dict)
|
||||
encodings[backend_name] = image_processor(image_inputs, return_tensors="pt")
|
||||
|
||||
backend_names = list(encodings.keys())
|
||||
reference_backend = backend_names[0]
|
||||
reference_encoding = encodings[reference_backend]
|
||||
for backend_name in backend_names[1:]:
|
||||
self._assert_tensors_equivalence(reference_encoding.pixel_values, encodings[backend_name].pixel_values)
|
||||
self.assertEqual(reference_encoding.image_grid_thw.dtype, encodings[backend_name].image_grid_thw.dtype)
|
||||
self._assert_tensors_equivalence(
|
||||
reference_encoding.image_grid_thw.float(), encodings[backend_name].image_grid_thw.float()
|
||||
)
|
||||
|
||||
@require_vision
|
||||
@require_torch
|
||||
def test_backends_equivalence_batched(self):
|
||||
if len(self.image_processing_classes) < 2:
|
||||
self.skipTest(reason="Skipping backends equivalence test as there are less than 2 backends")
|
||||
|
||||
dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
|
||||
|
||||
encodings = {}
|
||||
for backend_name, image_processing_class in self.image_processing_classes.items():
|
||||
image_processor = image_processing_class(**self.image_processor_dict)
|
||||
encodings[backend_name] = image_processor(dummy_images, return_tensors="pt")
|
||||
|
||||
backend_names = list(encodings.keys())
|
||||
reference_backend = backend_names[0]
|
||||
reference_encoding = encodings[reference_backend]
|
||||
for backend_name in backend_names[1:]:
|
||||
self._assert_tensors_equivalence(reference_encoding.pixel_values, encodings[backend_name].pixel_values)
|
||||
self._assert_tensors_equivalence(
|
||||
reference_encoding.image_grid_thw.float(), encodings[backend_name].image_grid_thw.float()
|
||||
)
|
||||
|
||||
def test_get_num_patches_without_images(self):
|
||||
for image_processing_class in self.image_processing_classes.values():
|
||||
image_processing = image_processing_class(**self.image_processor_dict)
|
||||
# 100×100 → smart_resize(100, 100, factor=28, min_pixels=56*56, max_pixels=28*28*1280)
|
||||
# h_bar=112, w_bar=112, grid_h=8, grid_w=8 → 64 patches
|
||||
num_patches = image_processing.get_number_of_image_patches(height=100, width=100, images_kwargs={})
|
||||
self.assertEqual(num_patches, 64)
|
||||
|
||||
# 200×50 → h_bar=196, w_bar=56, grid_h=14, grid_w=4 → 56 patches
|
||||
num_patches = image_processing.get_number_of_image_patches(height=200, width=50, images_kwargs={})
|
||||
self.assertEqual(num_patches, 56)
|
||||
|
||||
# With custom patch_size=28 → factor=28*2=56
|
||||
# 100×100 → smart_resize(100, 100, factor=56, min_pixels=56*56, max_pixels=28*28*1280)
|
||||
# h_bar=round(100/56)*56=2*56=112, grid_h=112/28=4, grid_w=4 → 16 patches
|
||||
num_patches = image_processing.get_number_of_image_patches(
|
||||
height=100, width=100, images_kwargs={"patch_size": 28}
|
||||
)
|
||||
self.assertEqual(num_patches, 16)
|
||||
543
tests/models/paddleocr_vl/test_modeling_paddleocr_vl.py
Normal file
543
tests/models/paddleocr_vl/test_modeling_paddleocr_vl.py
Normal file
@@ -0,0 +1,543 @@
|
||||
# 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 PaddleOCRVL model."""
|
||||
|
||||
import copy
|
||||
import gc
|
||||
import unittest
|
||||
|
||||
import pytest
|
||||
from parameterized import parameterized
|
||||
|
||||
from transformers import (
|
||||
AutoProcessor,
|
||||
PaddleOCRVLConfig,
|
||||
PaddleOCRVLForConditionalGeneration,
|
||||
is_torch_available,
|
||||
)
|
||||
from transformers.testing_utils import (
|
||||
backend_empty_cache,
|
||||
require_flash_attn,
|
||||
require_torch,
|
||||
require_torch_accelerator,
|
||||
slow,
|
||||
torch_device,
|
||||
)
|
||||
|
||||
from ...generation.test_utils import GenerationTesterMixin
|
||||
from ...test_configuration_common import ConfigTester
|
||||
from ...test_modeling_common import (
|
||||
ModelTesterMixin,
|
||||
floats_tensor,
|
||||
ids_tensor,
|
||||
)
|
||||
from ...test_pipeline_mixin import PipelineTesterMixin
|
||||
from ...test_processing_common import url_to_local_path
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
|
||||
class PaddleOCRVLVisionText2TextModelTester:
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
batch_size=7,
|
||||
seq_length=13,
|
||||
num_channels=3,
|
||||
image_height=28,
|
||||
image_width=28,
|
||||
text_config={
|
||||
"pad_token_id": 0,
|
||||
"bos_token_id": 1,
|
||||
"eos_token_id": 2,
|
||||
"vocab_size": 103424,
|
||||
"head_dim": 128,
|
||||
"hidden_act": "silu",
|
||||
"hidden_dropout_prob": 0.0,
|
||||
"hidden_size": 32,
|
||||
"ignored_index": -100,
|
||||
"image_token_id": 100295,
|
||||
"intermediate_size": 32,
|
||||
"max_position_embeddings": 512,
|
||||
"model_type": "paddleocr_vl",
|
||||
"num_attention_heads": 4,
|
||||
"num_hidden_layers": 2,
|
||||
"num_key_value_heads": 2,
|
||||
"rms_norm_eps": 1e-05,
|
||||
"rope_scaling": {"mrope_section": [16, 24, 24], "rope_type": "default", "type": "default"},
|
||||
"rope_theta": 500000,
|
||||
"tie_word_embeddings": False,
|
||||
},
|
||||
vision_start_token_id=101305,
|
||||
vision_end_token_id=101306,
|
||||
image_token_id=100295,
|
||||
is_training=True,
|
||||
vision_config={
|
||||
"hidden_act": "gelu_pytorch_tanh",
|
||||
"hidden_size": 144,
|
||||
"intermediate_size": 32,
|
||||
"layer_norm_eps": 1e-06,
|
||||
"model_type": "paddleocr_vl",
|
||||
"num_attention_heads": 4,
|
||||
"num_channels": 3,
|
||||
"num_hidden_layers": 2,
|
||||
"pad_token_id": 0,
|
||||
"patch_size": 14,
|
||||
"spatial_merge_size": 2,
|
||||
},
|
||||
):
|
||||
self.parent = parent
|
||||
self.bos_token_id = text_config["bos_token_id"]
|
||||
self.eos_token_id = text_config["eos_token_id"]
|
||||
self.pad_token_id = text_config["pad_token_id"]
|
||||
self.num_hidden_layers = text_config["num_hidden_layers"]
|
||||
self.num_attention_heads = text_config["num_attention_heads"]
|
||||
self.hidden_size = text_config["hidden_size"]
|
||||
self.vision_start_token_id = vision_start_token_id
|
||||
self.vision_end_token_id = vision_end_token_id
|
||||
self.image_token_id = image_token_id
|
||||
self.text_config = text_config
|
||||
self.vision_config = vision_config
|
||||
self.batch_size = batch_size
|
||||
self.num_channels = num_channels
|
||||
self.image_height = image_height
|
||||
self.image_width = image_width
|
||||
self.is_training = is_training
|
||||
self.vocab_size = text_config["vocab_size"]
|
||||
self.num_image_tokens = 1
|
||||
self.seq_length = seq_length + self.num_image_tokens
|
||||
|
||||
def get_config(self):
|
||||
return PaddleOCRVLConfig(
|
||||
text_config=self.text_config,
|
||||
vision_config=self.vision_config,
|
||||
vision_start_token_id=self.vision_start_token_id,
|
||||
image_token_id=self.image_token_id,
|
||||
)
|
||||
|
||||
def prepare_config_and_inputs(self):
|
||||
config = self.get_config()
|
||||
patch_size = config.vision_config.patch_size
|
||||
pixel_values = floats_tensor(
|
||||
[
|
||||
self.batch_size * (self.image_height * self.image_width) // (patch_size**2),
|
||||
config.vision_config.num_channels,
|
||||
patch_size,
|
||||
patch_size,
|
||||
]
|
||||
)
|
||||
|
||||
return config, pixel_values
|
||||
|
||||
def prepare_config_and_inputs_for_common(self):
|
||||
config_and_inputs = self.prepare_config_and_inputs()
|
||||
config, pixel_values = config_and_inputs
|
||||
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
||||
attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
|
||||
|
||||
input_ids[:, :4] = torch.tensor([100273, 2969, 93963, 93919], dtype=input_ids.dtype, device=input_ids.device)
|
||||
input_ids[:, 4] = self.vision_start_token_id
|
||||
input_ids[:, 5 : 5 + self.num_image_tokens] = self.image_token_id
|
||||
input_ids[:, -8] = self.vision_end_token_id
|
||||
input_ids[:, -7:] = torch.tensor(
|
||||
[93972, 2497, 93963, 23, 92267, 93963, 93919], dtype=input_ids.dtype, device=input_ids.device
|
||||
)
|
||||
|
||||
mm_token_type_ids = torch.zeros_like(input_ids)
|
||||
mm_token_type_ids[input_ids == self.image_token_id] = 1
|
||||
inputs_dict = {
|
||||
"pixel_values": pixel_values,
|
||||
"image_grid_thw": torch.tensor([[1, 2, 2]] * self.batch_size, device=torch_device),
|
||||
"input_ids": input_ids,
|
||||
"attention_mask": attention_mask,
|
||||
"mm_token_type_ids": mm_token_type_ids,
|
||||
}
|
||||
return config, inputs_dict
|
||||
|
||||
|
||||
@require_torch
|
||||
class PaddleOCRVLModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
||||
"""
|
||||
Model tester for `PaddleOCRVLForConditionalGeneration`.
|
||||
"""
|
||||
|
||||
all_model_classes = (PaddleOCRVLForConditionalGeneration,) if is_torch_available() else ()
|
||||
pipeline_model_mapping = {"image-text-to-text": PaddleOCRVLForConditionalGeneration}
|
||||
_is_composite = True
|
||||
|
||||
def setUp(self):
|
||||
self.model_tester = PaddleOCRVLVisionText2TextModelTester(self)
|
||||
self.config_tester = ConfigTester(self, config_class=PaddleOCRVLConfig, has_text_modality=False)
|
||||
|
||||
def test_config(self):
|
||||
self.config_tester.run_common_tests()
|
||||
|
||||
@unittest.skip(
|
||||
reason="embed_tokens is ~80% of test model size, exceeding the 70% GPU budget so device_map puts everything on CPU"
|
||||
)
|
||||
def test_cpu_offload(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
reason="embed_tokens is ~80% of test model size, exceeding the 70% GPU budget so device_map puts everything on CPU"
|
||||
)
|
||||
def test_disk_offload_bin(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
reason="embed_tokens is ~80% of test model size, exceeding the 70% GPU budget so device_map puts everything on CPU"
|
||||
)
|
||||
def test_disk_offload_safetensors(self):
|
||||
pass
|
||||
|
||||
def test_mismatching_num_image_tokens(self):
|
||||
"""
|
||||
Tests that an explicit error is thrown when the number of image tokens
|
||||
doesn't match the number of image placeholders in the text.
|
||||
We also test multi-image cases when one prompt has multiple image tokens.
|
||||
"""
|
||||
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
||||
for model_class in self.all_model_classes:
|
||||
model = model_class(config).to(torch_device)
|
||||
model.eval()
|
||||
curr_input_dict = copy.deepcopy(input_dict) # in-place modifications further
|
||||
_ = model(**curr_input_dict) # successful forward with no modifications
|
||||
|
||||
# remove one image but leave all the image tokens in text
|
||||
patch_size = config.vision_config.patch_size
|
||||
one_img_length = (self.model_tester.image_height * self.model_tester.image_width) // (patch_size**2)
|
||||
curr_input_dict["pixel_values"] = curr_input_dict["pixel_values"][-one_img_length:, ...]
|
||||
curr_input_dict["image_grid_thw"] = curr_input_dict["image_grid_thw"][-1:, ...]
|
||||
with self.assertRaisesRegex(ValueError, "Image features and image tokens do not match"):
|
||||
_ = model(**curr_input_dict)
|
||||
|
||||
# simulate multi-image case by concatenating inputs where each has exactly one image/image-token
|
||||
input_ids = curr_input_dict["input_ids"][:1]
|
||||
pixel_values = curr_input_dict["pixel_values"][:one_img_length]
|
||||
image_grid_thw = curr_input_dict["image_grid_thw"][:1]
|
||||
mm_token_type_ids = curr_input_dict["mm_token_type_ids"][:1]
|
||||
input_ids = torch.cat([input_ids, input_ids], dim=0)
|
||||
|
||||
# one image and two image tokens raise an error
|
||||
with self.assertRaisesRegex(ValueError, "Image features and image tokens do not match"):
|
||||
_ = model(
|
||||
input_ids=input_ids,
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=torch.cat([mm_token_type_ids, mm_token_type_ids], dim=0),
|
||||
)
|
||||
|
||||
# two images and two image tokens don't raise an error
|
||||
pixel_values = torch.cat([pixel_values, pixel_values], dim=0)
|
||||
image_grid_thw = torch.cat([image_grid_thw, image_grid_thw], dim=0)
|
||||
mm_token_type_ids = torch.cat([mm_token_type_ids, mm_token_type_ids], dim=0)
|
||||
_ = model(
|
||||
input_ids=input_ids,
|
||||
pixel_values=pixel_values,
|
||||
image_grid_thw=image_grid_thw,
|
||||
mm_token_type_ids=mm_token_type_ids,
|
||||
)
|
||||
|
||||
# PaddleOCRVL has pixel_values shaped as (bs*patch_len, image_channels, patch_size, patch_size) so we can't slice to batches in generate
|
||||
def prepare_config_and_inputs_for_generate(self, batch_size=2):
|
||||
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
||||
|
||||
# We don't want a few model inputs in our model input dictionary for generation tests
|
||||
input_keys_to_ignore = [
|
||||
# we don't want encoder-decoder models to start from filled decoder ids
|
||||
"decoder_input_ids",
|
||||
"decoder_attention_mask",
|
||||
# we'll set cache use in each test differently
|
||||
"use_cache",
|
||||
# Ignore labels if it is in the input dict
|
||||
"labels",
|
||||
# model-specific exceptions should overload/overwrite this function
|
||||
]
|
||||
|
||||
# The diff from the general `prepare_config_and_inputs_for_generate` lies here
|
||||
patch_size = config.vision_config.patch_size
|
||||
filtered_image_length = (
|
||||
batch_size * (self.model_tester.image_height * self.model_tester.image_width) // (patch_size**2)
|
||||
)
|
||||
filtered_inputs_dict = {
|
||||
k: v[:batch_size, ...] if isinstance(v, torch.Tensor) else v
|
||||
for k, v in inputs_dict.items()
|
||||
if k not in input_keys_to_ignore
|
||||
}
|
||||
filtered_inputs_dict["pixel_values"] = inputs_dict["pixel_values"][:filtered_image_length]
|
||||
|
||||
# It is important set `eos_token_id` to `None` to avoid early stopping (would break for length-based checks)
|
||||
text_gen_config = config.get_text_config(decoder=True)
|
||||
if text_gen_config.eos_token_id is not None and text_gen_config.pad_token_id is None:
|
||||
text_gen_config.pad_token_id = (
|
||||
text_gen_config.eos_token_id
|
||||
if isinstance(text_gen_config.eos_token_id, int)
|
||||
else text_gen_config.eos_token_id[0]
|
||||
)
|
||||
text_gen_config.eos_token_id = None
|
||||
text_gen_config.forced_eos_token_id = None
|
||||
|
||||
return config, filtered_inputs_dict
|
||||
|
||||
@unittest.skip(reason="PaddleOCRVL does not support.")
|
||||
def test_generate_compile_model_forward_fullgraph(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(reason="PaddleOCRVL does not support.")
|
||||
def test_multi_gpu_data_parallel_forward(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_beam_sample_generate(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_beam_search_generate(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_beam_search_generate_dict_output(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_beam_search_generate_dict_outputs_use_cache(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_beam_sample_generate_dict_output(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(reason="PaddleOCRVL needs to apply weight conversions.")
|
||||
def test_can_load_from_already_mapped_keys(self):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support beam search.")
|
||||
def test_generate_from_inputs_embeds_1_beam_search(self, _, num_beams):
|
||||
pass
|
||||
|
||||
@parameterized.expand([("random",), ("same",)])
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support assisted decoding.")
|
||||
def test_assisted_decoding_matches_greedy_search(self, assistant_type):
|
||||
pass
|
||||
|
||||
@pytest.mark.generate
|
||||
@unittest.skip(reason="PaddleOCRVL does not support assisted decoding.")
|
||||
def test_assisted_decoding_sample(self):
|
||||
pass
|
||||
|
||||
@unittest.skip("PaddleOCRVL does not support this test.")
|
||||
def test_model_is_small(self):
|
||||
pass
|
||||
|
||||
|
||||
@require_torch
|
||||
@slow
|
||||
class PaddleOCRVLIntegrationTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.processor = AutoProcessor.from_pretrained("PaddlePaddle/PaddleOCR-VL")
|
||||
self.messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "image",
|
||||
"url": url_to_local_path(
|
||||
"https://paddle-model-ecology.bj.bcebos.com/paddlex/imgs/demo_image/ocr_demo2.jpg"
|
||||
),
|
||||
},
|
||||
{"type": "text", "text": "OCR:"},
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
def tearDown(self):
|
||||
gc.collect()
|
||||
backend_empty_cache(torch_device)
|
||||
|
||||
def test_small_model_integration_test(self):
|
||||
model = (
|
||||
PaddleOCRVLForConditionalGeneration.from_pretrained(
|
||||
"PaddlePaddle/PaddleOCR-VL",
|
||||
dtype="bfloat16",
|
||||
)
|
||||
.to(torch_device)
|
||||
.eval()
|
||||
)
|
||||
|
||||
inputs = self.processor.apply_chat_template(
|
||||
self.messages,
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
expected_input_ids_length = 211
|
||||
assert expected_input_ids_length == len(inputs.input_ids[0])
|
||||
|
||||
expected_input_ids = [100273, 2969, 93963, 93919, 101305, 100295, 100295, 100295, 100295, 100295] # fmt: skip
|
||||
assert expected_input_ids == inputs.input_ids[0].tolist()[:10]
|
||||
|
||||
expected_pixel_slice = torch.tensor(
|
||||
[
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[0.9922, 0.9922, 0.9922],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
],
|
||||
dtype=torch.float32,
|
||||
device="cpu",
|
||||
)
|
||||
|
||||
assert torch.allclose(expected_pixel_slice, inputs.pixel_values[:5, :, 0, 0], atol=3e-3)
|
||||
|
||||
# verify generation
|
||||
inputs = inputs.to(torch_device)
|
||||
output = model.generate(**inputs, max_new_tokens=30)
|
||||
result = self.processor.decode(output[0][inputs["input_ids"].shape[-1] : -1])
|
||||
|
||||
EXPECTED_DECODED_TEXT = "生甘草"
|
||||
|
||||
self.assertEqual(
|
||||
result,
|
||||
EXPECTED_DECODED_TEXT,
|
||||
)
|
||||
|
||||
def test_small_model_integration_test_batch(self):
|
||||
model = (
|
||||
PaddleOCRVLForConditionalGeneration.from_pretrained("PaddlePaddle/PaddleOCR-VL", dtype="bfloat16")
|
||||
.to(torch_device)
|
||||
.eval()
|
||||
)
|
||||
|
||||
inputs = self.processor.apply_chat_template(
|
||||
[self.messages, self.messages],
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
padding=True,
|
||||
padding_side="left",
|
||||
).to(torch_device)
|
||||
|
||||
# it should not matter whether two images are the same size or not
|
||||
output = model.generate(**inputs, max_new_tokens=30)
|
||||
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, output)]
|
||||
result = self.processor.batch_decode(
|
||||
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
||||
)
|
||||
|
||||
EXPECTED_DECODED_TEXT = ["生甘草", "生甘草"]
|
||||
|
||||
self.assertEqual(
|
||||
result,
|
||||
EXPECTED_DECODED_TEXT,
|
||||
)
|
||||
|
||||
@require_flash_attn
|
||||
@require_torch_accelerator
|
||||
@pytest.mark.flash_attn_test
|
||||
def test_small_model_integration_test_flashatt2(self):
|
||||
model = (
|
||||
PaddleOCRVLForConditionalGeneration.from_pretrained(
|
||||
"PaddlePaddle/PaddleOCR-VL", dtype="bfloat16", attn_implementation="flash_attention_2"
|
||||
)
|
||||
.to(torch_device)
|
||||
.eval()
|
||||
)
|
||||
|
||||
inputs = self.processor.apply_chat_template(
|
||||
self.messages,
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
)
|
||||
|
||||
expected_input_ids_length = 211
|
||||
assert expected_input_ids_length == len(inputs.input_ids[0])
|
||||
|
||||
expected_input_ids = [100273, 2969, 93963, 93919, 101305, 100295, 100295, 100295, 100295, 100295] # fmt: skip
|
||||
assert expected_input_ids == inputs.input_ids[0].tolist()[:10]
|
||||
|
||||
expected_pixel_slice = torch.tensor(
|
||||
[
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[0.9922, 0.9922, 0.9922],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
[1.0000, 1.0000, 1.0000],
|
||||
],
|
||||
dtype=torch.float32,
|
||||
device="cpu",
|
||||
)
|
||||
assert torch.allclose(expected_pixel_slice, inputs.pixel_values[:5, :, 0, 0], atol=3e-3)
|
||||
|
||||
# verify generation
|
||||
inputs = inputs.to(torch_device)
|
||||
output = model.generate(**inputs, max_new_tokens=30)
|
||||
result = self.processor.decode(output[0][inputs["input_ids"].shape[-1] : -1])
|
||||
|
||||
EXPECTED_DECODED_TEXT = "生甘草"
|
||||
|
||||
self.assertEqual(
|
||||
result,
|
||||
EXPECTED_DECODED_TEXT,
|
||||
)
|
||||
|
||||
@require_flash_attn
|
||||
@require_torch_accelerator
|
||||
@pytest.mark.flash_attn_test
|
||||
def test_small_model_integration_test_batch_flashatt2(self):
|
||||
model = (
|
||||
PaddleOCRVLForConditionalGeneration.from_pretrained(
|
||||
"PaddlePaddle/PaddleOCR-VL", dtype="bfloat16", attn_implementation="flash_attention_2"
|
||||
)
|
||||
.to(torch_device)
|
||||
.eval()
|
||||
)
|
||||
|
||||
inputs = self.processor.apply_chat_template(
|
||||
[self.messages, self.messages],
|
||||
add_generation_prompt=True,
|
||||
tokenize=True,
|
||||
return_dict=True,
|
||||
return_tensors="pt",
|
||||
padding=True,
|
||||
padding_side="left",
|
||||
).to(torch_device)
|
||||
|
||||
# it should not matter whether two images are the same size or not
|
||||
output = model.generate(**inputs, max_new_tokens=30)
|
||||
generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, output)]
|
||||
result = self.processor.batch_decode(
|
||||
generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
|
||||
)
|
||||
|
||||
EXPECTED_DECODED_TEXT = ["生甘草", "生甘草"]
|
||||
|
||||
self.assertEqual(
|
||||
result,
|
||||
EXPECTED_DECODED_TEXT,
|
||||
)
|
||||
Reference in New Issue
Block a user