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
195 lines
9.0 KiB
Python
195 lines
9.0 KiB
Python
# Copyright 2025 The HuggingFace 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.
|
|
|
|
import unittest
|
|
|
|
import numpy as np
|
|
|
|
from transformers import Gemma3Processor
|
|
from transformers.testing_utils import get_tests_dir, require_vision
|
|
|
|
from ...test_processing_common import ProcessorTesterMixin
|
|
|
|
|
|
SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
|
|
|
|
|
|
@require_vision
|
|
class Gemma3ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
|
|
processor_class = Gemma3Processor
|
|
|
|
@classmethod
|
|
def _setup_test_attributes(cls, processor):
|
|
cls.image_token = processor.boi_token
|
|
|
|
@classmethod
|
|
def _setup_image_processor(cls):
|
|
image_processor_class = cls._get_component_class_from_processor("image_processor")
|
|
gemma3_image_processor_kwargs = {
|
|
"do_pan_and_scan": True,
|
|
"pan_and_scan_min_crop_size": 256,
|
|
"pan_and_scan_max_num_crops": 4,
|
|
"pan_and_scan_min_ratio_to_activate": 1.2,
|
|
}
|
|
return image_processor_class(**gemma3_image_processor_kwargs)
|
|
|
|
@classmethod
|
|
def _setup_tokenizer(cls):
|
|
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
|
|
extra_special_tokens = {
|
|
"image_token": "<image_soft_token>",
|
|
"boi_token": "<start_of_image>",
|
|
"eoi_token": "<end_of_image>",
|
|
}
|
|
tokenizer = tokenizer_class.from_pretrained(
|
|
SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens
|
|
)
|
|
return tokenizer
|
|
|
|
def test_get_num_vision_tokens(self):
|
|
"Tests general functionality of the helper used internally in vLLM"
|
|
|
|
processor = self.get_processor()
|
|
|
|
output = processor._get_num_multimodal_tokens(image_sizes=[(100, 100), (300, 100), (500, 30)])
|
|
self.assertTrue("num_image_tokens" in output)
|
|
self.assertEqual(len(output["num_image_tokens"]), 3)
|
|
|
|
self.assertTrue("num_image_patches" in output)
|
|
self.assertEqual(len(output["num_image_patches"]), 3)
|
|
|
|
@staticmethod
|
|
def prepare_processor_dict():
|
|
return {
|
|
"chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n", "image_seq_length": 3,
|
|
} # fmt: skip
|
|
|
|
# Override as Gemma3 needs images to be an explicitly nested batch
|
|
def prepare_image_inputs(self, batch_size: int | None = 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 test_text_with_image_tokens(self):
|
|
image_processor = self.get_component("image_processor")
|
|
tokenizer = self.get_component("tokenizer")
|
|
|
|
processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
|
|
text_multi_images = f"{processor.boi_token}{processor.boi_token}Dummy text!"
|
|
text_single_image = f"{processor.boi_token}Dummy text!"
|
|
text_no_image = "Dummy text!"
|
|
|
|
image = self.prepare_image_inputs()
|
|
|
|
# If text has no image tokens, image should be `None`
|
|
with self.assertRaises(ValueError):
|
|
_ = processor(text=text_no_image, images=image, return_tensors="pt")
|
|
|
|
# We can't be sure what is users intention: if user wants one image per text OR two images for first text and no image for second text
|
|
with self.assertRaises(ValueError):
|
|
_ = processor(text=[text_single_image, text_single_image], images=[image, image], return_tensors="pt")
|
|
|
|
# The users is expected to be explicit about which image belong to which text by nesting the images list
|
|
out_multiimages = processor(text=text_multi_images, images=[image, image], return_tensors="pt")
|
|
out_batch_oneimage = processor(
|
|
text=[text_single_image, text_single_image], images=[[image], [image]], return_tensors="pt"
|
|
)
|
|
self.assertListEqual(
|
|
out_batch_oneimage[self.images_input_name].tolist(), out_multiimages[self.images_input_name].tolist()
|
|
)
|
|
|
|
def test_pan_and_scan(self):
|
|
processor_components = self.prepare_components()
|
|
processor_kwargs = self.prepare_processor_dict()
|
|
processor = self.processor_class(**processor_components, **processor_kwargs)
|
|
|
|
input_str = self.prepare_text_inputs(modalities="image")
|
|
image_input = self.prepare_image_inputs()
|
|
inputs = processor(
|
|
text=input_str,
|
|
images=image_input,
|
|
return_tensors="pt",
|
|
do_pan_and_scan=True,
|
|
image_seq_length=2,
|
|
pan_and_scan_min_crop_size=10,
|
|
)
|
|
|
|
# base image + 4 crops
|
|
self.assertEqual(len(inputs[self.images_input_name]), 5)
|
|
baseline = processor(
|
|
text=input_str,
|
|
images=image_input,
|
|
return_tensors="pt",
|
|
do_pan_and_scan=False,
|
|
image_seq_length=2,
|
|
pan_and_scan_min_crop_size=10,
|
|
)
|
|
self.assertGreater(len(inputs[self.text_input_name][0]), len(baseline[self.text_input_name][0]))
|
|
|
|
def test_special_mm_token_truncation(self):
|
|
"""Tests that special vision tokens do not get truncated when `truncation=True` is set."""
|
|
|
|
processor = self.get_processor()
|
|
|
|
input_str = self.prepare_text_inputs(batch_size=2, modalities="image")
|
|
image_input = self.prepare_image_inputs(batch_size=2)
|
|
_ = processor(
|
|
text=input_str,
|
|
images=image_input,
|
|
return_tensors="pt",
|
|
truncation=None,
|
|
padding=True,
|
|
)
|
|
|
|
with self.assertRaises(ValueError):
|
|
_ = processor(
|
|
text=input_str,
|
|
images=image_input,
|
|
return_tensors="pt",
|
|
truncation=True,
|
|
padding=True,
|
|
max_length=5,
|
|
)
|
|
|
|
def test_get_num_multimodal_tokens_matches_processor_call(self):
|
|
"Tests that the helper used internally in vLLM works correctly"
|
|
|
|
processor = self.get_processor()
|
|
if processor.tokenizer.pad_token_id is None:
|
|
processor.tokenizer.pad_token_id = processor.tokenizer.eos_token_id
|
|
|
|
if not hasattr(processor, "_get_num_multimodal_tokens"):
|
|
self.skipTest("Processor doesn't support `_get_num_multimodal_tokens` yet")
|
|
|
|
image_sizes = [(100, 100), (300, 100), (500, 30), (213, 167)]
|
|
|
|
# Overwritten because Gemma3 needs nested image inputs
|
|
image_inputs = []
|
|
for h, w in image_sizes:
|
|
image_inputs.append([np.random.randint(255, size=(h, w, 3), dtype=np.uint8)])
|
|
|
|
text = [f"This is an image {getattr(self, 'image_token', '')}"] * len(image_inputs)
|
|
inputs = processor(
|
|
text=text, images=image_inputs, padding=True, return_mm_token_type_ids=True, return_tensors="pt"
|
|
)
|
|
|
|
if "mm_token_type_ids" not in inputs:
|
|
self.skipTest("Processor doesn't support `mm_token_type_ids`")
|
|
|
|
num_image_tokens_from_call = inputs.mm_token_type_ids.sum(-1).tolist()
|
|
num_image_tokens_from_helper = processor._get_num_multimodal_tokens(image_sizes=image_sizes)
|
|
self.assertListEqual(num_image_tokens_from_call, num_image_tokens_from_helper["num_image_tokens"])
|