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/granite4_vision/__init__.py
Normal file
0
tests/models/granite4_vision/__init__.py
Normal file
243
tests/models/granite4_vision/test_modeling_granite4_vision.py
Normal file
243
tests/models/granite4_vision/test_modeling_granite4_vision.py
Normal file
@@ -0,0 +1,243 @@
|
||||
# Copyright 2026 IBM and 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.
|
||||
"""Testing suite for the PyTorch Granite4Vision model."""
|
||||
|
||||
import unittest
|
||||
|
||||
from transformers import (
|
||||
AutoProcessor,
|
||||
CLIPVisionConfig,
|
||||
Granite4VisionConfig,
|
||||
Granite4VisionForConditionalGeneration,
|
||||
Granite4VisionModel,
|
||||
GraniteConfig,
|
||||
is_torch_available,
|
||||
)
|
||||
from transformers.image_utils import load_image
|
||||
from transformers.testing_utils import (
|
||||
Expectations,
|
||||
cleanup,
|
||||
require_deterministic_for_xpu,
|
||||
require_torch,
|
||||
slow,
|
||||
torch_device,
|
||||
)
|
||||
|
||||
from ...test_modeling_common import floats_tensor
|
||||
from ...test_processing_common import url_to_local_path
|
||||
from ...vlm_tester import VLMModelTest, VLMModelTester
|
||||
|
||||
|
||||
if is_torch_available():
|
||||
import torch
|
||||
|
||||
|
||||
class Granite4VisionModelTester(VLMModelTester):
|
||||
base_model_class = Granite4VisionModel
|
||||
config_class = Granite4VisionConfig
|
||||
conditional_generation_class = Granite4VisionForConditionalGeneration
|
||||
text_config_class = GraniteConfig
|
||||
vision_config_class = CLIPVisionConfig
|
||||
|
||||
def __init__(self, parent, **kwargs):
|
||||
# Vision hidden_size must be divisible by 64 (QFormer num_attention_heads = hidden_size // 64)
|
||||
kwargs.setdefault("hidden_size", 64)
|
||||
kwargs.setdefault("intermediate_size", 64)
|
||||
kwargs.setdefault("num_attention_heads", 2)
|
||||
kwargs.setdefault("num_key_value_heads", 2)
|
||||
kwargs.setdefault("num_hidden_layers", 2)
|
||||
# Image/patch sizes: image_side = image_size // patch_size must be divisible by window_side
|
||||
kwargs.setdefault("image_size", 8)
|
||||
kwargs.setdefault("patch_size", 2)
|
||||
kwargs.setdefault("projection_dim", 64)
|
||||
kwargs.setdefault("num_patches_per_image", 2)
|
||||
# Granite4Vision-specific
|
||||
kwargs.setdefault("downsample_rate", "1/2")
|
||||
kwargs.setdefault("deepstack_layer_map", [[1, 0]])
|
||||
kwargs.setdefault("projector_dropout", 0.0)
|
||||
kwargs.setdefault("image_token_index", kwargs.get("image_token_id", 3))
|
||||
|
||||
# Compute num_image_tokens after downsampling:
|
||||
# image_side = image_size/patch_size = 4, ds 1/2 -> patches_h = patches_w = 2
|
||||
# pinpoints [[8,8]] -> scale 1x1 -> current_h = current_w = 2
|
||||
# unpadded = 2*2 = 4, newline = 2, base = 2*2 = 4 -> total = 10
|
||||
kwargs.setdefault("num_image_tokens", 10)
|
||||
|
||||
super().__init__(parent, **kwargs)
|
||||
|
||||
def create_pixel_values(self):
|
||||
"""Granite4Vision expects 5D pixel_values: (batch_size, num_patches, channels, height, width)"""
|
||||
return floats_tensor(
|
||||
[
|
||||
self.batch_size,
|
||||
self.num_patches_per_image,
|
||||
self.num_channels,
|
||||
self.image_size,
|
||||
self.image_size,
|
||||
]
|
||||
)
|
||||
|
||||
def get_additional_inputs(self, config, input_ids, pixel_values):
|
||||
"""Granite4Vision requires image_sizes tensor"""
|
||||
return {
|
||||
"image_sizes": torch.tensor([[self.image_size, self.image_size]] * self.batch_size),
|
||||
}
|
||||
|
||||
def get_config(self):
|
||||
config = super().get_config()
|
||||
config.image_grid_pinpoints = [[self.image_size, self.image_size]]
|
||||
config.downsample_rate = self.downsample_rate
|
||||
config.deepstack_layer_map = self.deepstack_layer_map
|
||||
config.projector_dropout = self.projector_dropout
|
||||
config.qformer_config.intermediate_size = 64
|
||||
return config
|
||||
|
||||
|
||||
@require_torch
|
||||
class Granite4VisionModelTest(VLMModelTest, unittest.TestCase):
|
||||
"""
|
||||
Model tester for `Granite4VisionForConditionalGeneration`.
|
||||
"""
|
||||
|
||||
model_tester_class = Granite4VisionModelTester
|
||||
skip_test_image_features_output_shape = True
|
||||
test_torch_exportable = False
|
||||
# Custom layer-by-layer forward doesn't support output_attentions
|
||||
# (GraniteDecoderLayer discards attention weights internally)
|
||||
test_attention_outputs = False
|
||||
has_attentions = False
|
||||
test_all_params_have_gradient = False
|
||||
|
||||
@unittest.skip(
|
||||
"VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
|
||||
)
|
||||
def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
|
||||
pass
|
||||
|
||||
@unittest.skip(
|
||||
"VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
|
||||
)
|
||||
def test_eager_padding_matches_padding_free_with_position_ids(self):
|
||||
pass
|
||||
|
||||
@unittest.skip("Custom layer-by-layer forward has graph breaks incompatible with fullgraph compile")
|
||||
def test_generate_compile_model_forward_fullgraph(self):
|
||||
pass
|
||||
|
||||
@unittest.skip("Blip2QFormerModel in WindowQFormerDownsampler does not support SDPA dispatch")
|
||||
def test_can_set_attention_dynamically_composite_model(self):
|
||||
pass
|
||||
|
||||
|
||||
@require_torch
|
||||
class Granite4VisionIntegrationTest(unittest.TestCase):
|
||||
model_id = "ibm-granite/granite-vision-4.1-4b"
|
||||
|
||||
def setUp(self):
|
||||
self.processor = AutoProcessor.from_pretrained(self.model_id)
|
||||
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
||||
self.image = load_image(url_to_local_path(url))
|
||||
|
||||
def make_prompt(self, question):
|
||||
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": question}]}]
|
||||
return self.processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
||||
|
||||
def tearDown(self):
|
||||
cleanup(torch_device, gc_collect=True)
|
||||
|
||||
@require_deterministic_for_xpu
|
||||
@slow
|
||||
def test_small_model_integration_test(self):
|
||||
model = Granite4VisionForConditionalGeneration.from_pretrained(self.model_id, torch_dtype=torch.bfloat16).to(
|
||||
torch_device
|
||||
)
|
||||
|
||||
prompt = self.make_prompt("Describe this image briefly.")
|
||||
inputs = self.processor(text=prompt, images=self.image, return_tensors="pt").to(model.device)
|
||||
output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
|
||||
new_tokens = output[:, inputs["input_ids"].shape[1] :]
|
||||
|
||||
EXPECTED_RESPONSE = Expectations({
|
||||
("cuda", None): "The image depicts two cats resting on a pink couch. They are lying in a relaxed, sprawled position, with one cat appearing to be in a",
|
||||
("cuda", (8, 6)): "The image depicts two cats resting on a pink blanket. They are lying in a relaxed, sprawled position, with one cat appearing to be in a",
|
||||
("xpu", None): "The image depicts two cats resting on a pink blanket. They are lying in a relaxed, sprawled position, with one cat appearing to be in a",
|
||||
}).get_expectation() # fmt: skip
|
||||
|
||||
self.assertEqual(self.processor.decode(new_tokens[0], skip_special_tokens=True), EXPECTED_RESPONSE)
|
||||
|
||||
@require_deterministic_for_xpu
|
||||
@slow
|
||||
def test_small_model_integration_test_batch(self):
|
||||
model = Granite4VisionForConditionalGeneration.from_pretrained(self.model_id, torch_dtype=torch.bfloat16).to(
|
||||
torch_device
|
||||
)
|
||||
|
||||
url2 = "http://images.cocodataset.org/val2017/000000001000.jpg"
|
||||
image2 = load_image(url_to_local_path(url2))
|
||||
|
||||
prompt = self.make_prompt("What do you see in this image?")
|
||||
inputs = self.processor(
|
||||
text=[prompt, prompt],
|
||||
images=[self.image, image2],
|
||||
return_tensors="pt",
|
||||
padding=True,
|
||||
).to(model.device)
|
||||
output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
|
||||
new_tokens = output[:, inputs["input_ids"].shape[1] :]
|
||||
responses = self.processor.batch_decode(new_tokens, skip_special_tokens=True)
|
||||
|
||||
EXPECTED_RESPONSE = Expectations({
|
||||
("cuda", (8, 6)): [
|
||||
'i see two cats lying on a pink blanket. one cat is on the left side, and the other is on the right side. there are two',
|
||||
'in the image, i see a group of people, including children and adults, standing on a tennis court. they appear to be posing for a group',
|
||||
],
|
||||
("xpu", None): [
|
||||
'i see two cats lying on a pink blanket. one cat is on the left side, and the other is on the right side. there are two',
|
||||
'in the image, i see a group of people, including children and adults, standing on a tennis court. they appear to be posing for a group',
|
||||
]
|
||||
}).get_expectation() # fmt: skip
|
||||
|
||||
self.assertEqual(responses[0].lower(), EXPECTED_RESPONSE[0])
|
||||
self.assertEqual(responses[1].lower(), EXPECTED_RESPONSE[1])
|
||||
|
||||
@slow
|
||||
def test_small_model_integration_test_batch_matches_single(self):
|
||||
model = Granite4VisionForConditionalGeneration.from_pretrained(self.model_id, torch_dtype=torch.bfloat16).to(
|
||||
torch_device
|
||||
)
|
||||
|
||||
prompt = self.make_prompt("What do you see in this image?")
|
||||
|
||||
# Single inference
|
||||
inputs_single = self.processor(text=prompt, images=self.image, return_tensors="pt").to(model.device)
|
||||
output_single = model.generate(**inputs_single, max_new_tokens=30, do_sample=False)
|
||||
decoded_single = self.processor.decode(
|
||||
output_single[0, inputs_single["input_ids"].shape[1] :], skip_special_tokens=True
|
||||
)
|
||||
|
||||
# Batch inference (same image as first in batch)
|
||||
url2 = "http://images.cocodataset.org/val2017/000000001000.jpg"
|
||||
image2 = load_image(url_to_local_path(url2))
|
||||
inputs_batch = self.processor(
|
||||
text=[prompt, prompt],
|
||||
images=[self.image, image2],
|
||||
return_tensors="pt",
|
||||
padding=True,
|
||||
).to(model.device)
|
||||
output_batch = model.generate(**inputs_batch, max_new_tokens=30, do_sample=False)
|
||||
decoded_batch = self.processor.decode(
|
||||
output_batch[0, inputs_batch["input_ids"].shape[1] :], skip_special_tokens=True
|
||||
)
|
||||
|
||||
self.assertEqual(decoded_single, decoded_batch)
|
||||
120
tests/models/granite4_vision/test_processing_granite4_vision.py
Normal file
120
tests/models/granite4_vision/test_processing_granite4_vision.py
Normal file
@@ -0,0 +1,120 @@
|
||||
# Copyright 2026 IBM. 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 json
|
||||
import unittest
|
||||
|
||||
import torch
|
||||
|
||||
from transformers import Granite4VisionProcessor
|
||||
from transformers.testing_utils import require_vision
|
||||
|
||||
from ...test_processing_common import ProcessorTesterMixin
|
||||
|
||||
|
||||
@require_vision
|
||||
class Granite4VisionProcessorTest(ProcessorTesterMixin, unittest.TestCase):
|
||||
processor_class = Granite4VisionProcessor
|
||||
# Image token expansion with downsample_rate="1/2" produces more tokens than the defaults
|
||||
image_text_kwargs_max_length = 300
|
||||
image_text_kwargs_override_max_length = 280
|
||||
image_unstructured_max_length = 260
|
||||
|
||||
@classmethod
|
||||
def _setup_tokenizer(cls):
|
||||
tokenizer_class = cls._get_component_class_from_processor("tokenizer")
|
||||
tokenizer = tokenizer_class.from_pretrained("huggyllama/llama-7b")
|
||||
tokenizer.add_special_tokens({"additional_special_tokens": ["<image>"]})
|
||||
if not tokenizer.pad_token:
|
||||
tokenizer.pad_token = "[PAD]"
|
||||
if tokenizer.pad_token_id is None:
|
||||
tokenizer.pad_token_id = 0
|
||||
return tokenizer
|
||||
|
||||
@classmethod
|
||||
def _setup_test_attributes(cls, processor):
|
||||
cls.image_token = processor.image_token
|
||||
|
||||
@staticmethod
|
||||
def prepare_processor_dict():
|
||||
return {
|
||||
"chat_template": "{% for message in messages %}{% if message['role'] != 'system' %}{{ message['role'].upper() + ': '}}{% endif %}{# Render all images first #}{% for content in message['content'] | selectattr('type', 'equalto', 'image') %}{{ '<image>\n' }}{% endfor %}{# Render all text next #}{% if message['role'] != 'assistant' %}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{{ content['text'] + ' '}}{% endfor %}{% else %}{% for content in message['content'] | selectattr('type', 'equalto', 'text') %}{% generation %}{{ content['text'] + ' '}}{% endgeneration %}{% endfor %}{% endif %}{% endfor %}{% if add_generation_prompt %}{{ 'ASSISTANT:' }}{% endif %}",
|
||||
"patch_size": 14,
|
||||
"vision_feature_select_strategy": "default",
|
||||
"downsample_rate": "1/2",
|
||||
} # fmt: skip
|
||||
|
||||
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)
|
||||
|
||||
def test_chat_template_is_saved(self):
|
||||
processor_loaded = self.processor_class.from_pretrained(self.tmpdirname)
|
||||
processor_dict_loaded = json.loads(processor_loaded.to_json_string())
|
||||
# chat templates aren't serialized to json in processors
|
||||
self.assertFalse("chat_template" in processor_dict_loaded)
|
||||
|
||||
# they have to be saved as separate file and loaded back from that file
|
||||
# so we check if the same template is loaded
|
||||
processor_dict = self.prepare_processor_dict()
|
||||
self.assertTrue(processor_loaded.chat_template == processor_dict.get("chat_template", None))
|
||||
|
||||
def test_image_token_filling(self):
|
||||
processor = self.processor_class.from_pretrained(self.tmpdirname)
|
||||
processor.patch_size = 14
|
||||
processor.vision_feature_select_strategy = "default"
|
||||
processor.downsample_rate = "1/2"
|
||||
processor.image_processor.crop_size = {"height": 336, "width": 336}
|
||||
processor.image_processor.size = {"shortest_edge": 336}
|
||||
processor.image_processor.image_grid_pinpoints = [[672, 336]]
|
||||
# Important to check with non square image
|
||||
image = torch.randint(0, 2, (3, 503, 316))
|
||||
image_token_index = processor.image_token_id
|
||||
|
||||
# With downsample_rate="1/2" and patch_size=14:
|
||||
# patches = 336/14 = 24, after ds: 24*1/2 = 12
|
||||
# best resolution for (503, 316): [672, 336]
|
||||
# scale_height=2, scale_width=1
|
||||
# current = 12*2=24 h, 12*1=12 w
|
||||
# aspect: 316/503 = 0.628, 12/24 = 0.5 -> orig > current -> new_height = round(503*(12/316)) = 19
|
||||
# padding = (24-19)//2 = 2, current_height = 24 - 4 = 20
|
||||
# unpadded = 20*12 = 240, newline = 20
|
||||
# base = 12*12 + 0 = 144
|
||||
# total = 240 + 20 + 144 = 404
|
||||
# with "default" strategy: 404 - 1 = 403
|
||||
expected_image_tokens = 403
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "user",
|
||||
"content": [
|
||||
{"type": "image"},
|
||||
{"type": "text", "text": "What is shown in this image?"},
|
||||
],
|
||||
},
|
||||
]
|
||||
inputs = processor(
|
||||
text=[processor.apply_chat_template(messages)],
|
||||
images=[image],
|
||||
return_tensors="pt",
|
||||
)
|
||||
image_tokens = (inputs["input_ids"] == image_token_index).sum().item()
|
||||
self.assertEqual(expected_image_tokens, image_tokens)
|
||||
Reference in New Issue
Block a user