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
210 lines
7.5 KiB
Python
210 lines
7.5 KiB
Python
# 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 PyTorch MLCD model."""
|
|
|
|
import unittest
|
|
|
|
import requests
|
|
from PIL import Image
|
|
|
|
from transformers import (
|
|
AutoProcessor,
|
|
MLCDVisionConfig,
|
|
MLCDVisionModel,
|
|
is_torch_available,
|
|
)
|
|
from transformers.testing_utils import (
|
|
require_torch,
|
|
slow,
|
|
torch_device,
|
|
)
|
|
|
|
from ...test_configuration_common import ConfigTester
|
|
from ...test_modeling_common import ModelTesterMixin, floats_tensor
|
|
|
|
|
|
if is_torch_available():
|
|
import torch
|
|
|
|
|
|
class MLCDVisionModelTester:
|
|
def __init__(
|
|
self,
|
|
parent,
|
|
batch_size=12,
|
|
image_size=30,
|
|
patch_size=2,
|
|
num_channels=3,
|
|
is_training=True,
|
|
hidden_size=32,
|
|
num_hidden_layers=2,
|
|
num_attention_heads=4,
|
|
intermediate_size=37,
|
|
dropout=0.1,
|
|
attention_dropout=0.1,
|
|
initializer_range=0.02,
|
|
scope=None,
|
|
):
|
|
self.parent = parent
|
|
self.batch_size = batch_size
|
|
self.image_size = image_size
|
|
self.patch_size = patch_size
|
|
self.num_channels = num_channels
|
|
self.is_training = is_training
|
|
self.hidden_size = hidden_size
|
|
self.num_hidden_layers = num_hidden_layers
|
|
self.num_attention_heads = num_attention_heads
|
|
self.intermediate_size = intermediate_size
|
|
self.dropout = dropout
|
|
self.attention_dropout = attention_dropout
|
|
self.initializer_range = initializer_range
|
|
self.scope = scope
|
|
|
|
# in MLCD, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
|
|
num_patches = (image_size // patch_size) ** 2
|
|
self.seq_length = num_patches + 1
|
|
|
|
def prepare_config_and_inputs(self):
|
|
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
|
config = self.get_config()
|
|
|
|
return config, pixel_values
|
|
|
|
def get_config(self):
|
|
return MLCDVisionConfig(
|
|
image_size=self.image_size,
|
|
patch_size=self.patch_size,
|
|
num_channels=self.num_channels,
|
|
hidden_size=self.hidden_size,
|
|
num_hidden_layers=self.num_hidden_layers,
|
|
num_attention_heads=self.num_attention_heads,
|
|
intermediate_size=self.intermediate_size,
|
|
dropout=self.dropout,
|
|
attention_dropout=self.attention_dropout,
|
|
initializer_range=self.initializer_range,
|
|
)
|
|
|
|
def create_and_check_model(self, config, pixel_values):
|
|
model = MLCDVisionModel(config=config)
|
|
model.to(torch_device)
|
|
model.eval()
|
|
with torch.no_grad():
|
|
result = model(pixel_values)
|
|
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
|
|
image_size = (self.image_size, self.image_size)
|
|
patch_size = (self.patch_size, self.patch_size)
|
|
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
|
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
|
|
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
|
|
|
|
def prepare_config_and_inputs_for_common(self):
|
|
config_and_inputs = self.prepare_config_and_inputs()
|
|
config, pixel_values = config_and_inputs
|
|
inputs_dict = {"pixel_values": pixel_values}
|
|
return config, inputs_dict
|
|
|
|
|
|
@require_torch
|
|
class MLCDVisionModelTest(ModelTesterMixin, unittest.TestCase):
|
|
"""
|
|
Model tester for `MLCDVisionModel`.
|
|
"""
|
|
|
|
all_model_classes = (MLCDVisionModel,) if is_torch_available() else ()
|
|
|
|
test_resize_embeddings = False
|
|
|
|
def setUp(self):
|
|
self.model_tester = MLCDVisionModelTester(self)
|
|
self.config_tester = ConfigTester(self, config_class=MLCDVisionConfig, has_text_modality=False)
|
|
|
|
def test_model_get_set_embeddings(self):
|
|
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
|
|
|
for model_class in self.all_model_classes:
|
|
model = model_class(config)
|
|
self.assertIsInstance(model.get_input_embeddings(), (torch.nn.Module))
|
|
x = model.get_output_embeddings()
|
|
self.assertTrue(x is None or isinstance(x, torch.nn.Linear))
|
|
|
|
@unittest.skip(
|
|
reason="MLCD passes position embeddings as tuples in its vision encoder, which breaks reentrant GC."
|
|
)
|
|
def test_enable_input_require_grads_with_gradient_checkpointing(self):
|
|
pass
|
|
|
|
|
|
@require_torch
|
|
class MLCDVisionModelIntegrationTest(unittest.TestCase):
|
|
@slow
|
|
def test_inference(self):
|
|
model_name = "DeepGlint-AI/mlcd-vit-bigG-patch14-448"
|
|
model = MLCDVisionModel.from_pretrained(model_name, attn_implementation="eager").to(torch_device)
|
|
processor = AutoProcessor.from_pretrained(model_name)
|
|
|
|
# process single image
|
|
url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
|
image = Image.open(requests.get(url, stream=True).raw)
|
|
inputs = processor(images=image, return_tensors="pt")
|
|
|
|
# move inputs to the same device as the model
|
|
inputs = {k: v.to(torch_device) for k, v in inputs.items()}
|
|
|
|
# forward pass
|
|
with torch.no_grad():
|
|
outputs = model(**inputs, output_attentions=True)
|
|
|
|
last_hidden_state = outputs.last_hidden_state
|
|
last_attention = outputs.attentions[-1]
|
|
|
|
# verify the shapes of last_hidden_state and last_attention
|
|
self.assertEqual(
|
|
last_hidden_state.shape,
|
|
torch.Size([1, 1025, 1664]),
|
|
)
|
|
self.assertEqual(
|
|
last_attention.shape,
|
|
torch.Size([1, 16, 1025, 1025]),
|
|
)
|
|
|
|
# verify the values of last_hidden_state and last_attention
|
|
# fmt: off
|
|
expected_partial_5x5_last_hidden_state = torch.tensor(
|
|
[
|
|
[-0.8976, -0.1173, 0.4770, 0.4768, -0.5785],
|
|
[0.2828, -2.6036, 0.4997, 0.5538, -1.0822],
|
|
[0.3285, -0.3092, -0.4157, -0.1794, -0.7793],
|
|
[-1.5005, -1.0548, -1.2262, 0.2269, -0.9054],
|
|
[0.2317, -0.8372, -0.9653, -0.3017, 0.0871],
|
|
]
|
|
).to(torch_device)
|
|
|
|
expected_partial_5x5_last_attention = torch.tensor(
|
|
[
|
|
[2.0956e-01, 6.4854e-05, 1.5120e-03, 2.6588e-05, 3.0168e-03],
|
|
[1.6095e-04, 2.0924e-03, 4.7327e-04, 1.8991e-03, 5.4792e-04],
|
|
[5.8087e-04, 1.1215e-03, 1.3588e-03, 1.1862e-03, 1.2509e-03],
|
|
[9.5609e-05, 1.6015e-03, 2.8401e-04, 3.2878e-03, 2.0171e-04],
|
|
[6.2485e-04, 1.1751e-03, 1.4737e-03, 8.2471e-04, 2.6918e-03],
|
|
]
|
|
).to(torch_device)
|
|
# fmt: on
|
|
|
|
torch.testing.assert_close(
|
|
last_hidden_state[0, :5, :5], expected_partial_5x5_last_hidden_state, rtol=1e-3, atol=1e-3
|
|
)
|
|
torch.testing.assert_close(
|
|
last_attention[0, 0, :5, :5], expected_partial_5x5_last_attention, rtol=1e-4, atol=1e-4
|
|
)
|