Stage Harbor release files 16501-17000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/data2vec/test_modeling_data2vec_vision.py +581 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/data2vec/test_modeling_tf_data2vec_vision.py +496 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dbrx/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dbrx/test_modeling_dbrx.py +397 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_modeling_deberta.py +313 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_modeling_tf_deberta.py +300 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_tokenization_deberta.py +168 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_modeling_deberta_v2.py +331 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_modeling_tf_deberta_v2.py +314 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_tokenization_deberta_v2.py +262 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/decision_transformer/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/decision_transformer/test_modeling_decision_transformer.py +248 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/test_image_processing_deformable_detr.py +736 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/test_modeling_deformable_detr.py +776 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_image_processing_deit.py +121 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_modeling_deit.py +467 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_modeling_tf_deit.py +312 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/depth_anything/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/depth_anything/test_modeling_depth_anything.py +320 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/test_image_processing_detr.py +791 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/test_modeling_detr.py +716 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/diffllama/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/diffllama/test_modeling_diffllama.py +992 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinat/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinat/test_modeling_dinat.py +378 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2/test_modeling_dinov2.py +344 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2/test_modeling_flax_dinov2.py +263 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2_with_registers/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2_with_registers/test_modeling_dinov2_with_registers.py +369 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_distilbert.py +466 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_flax_distilbert.py +153 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_tf_distilbert.py +260 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_tokenization_distilbert.py +43 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dit/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dit/test_modeling_dit.py +61 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_image_processing_donut.py +229 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_modeling_donut_swin.py +349 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_processor_donut.py +63 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/__init__.py +0 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_modeling_dpr.py +307 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_modeling_tf_dpr.py +257 -0
- tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_tokenization_dpr.py +88 -0
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/data2vec/test_modeling_data2vec_vision.py
ADDED
|
@@ -0,0 +1,581 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Data2VecVision model."""
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
from parameterized import parameterized
|
| 23 |
+
|
| 24 |
+
from transformers import Data2VecVisionConfig
|
| 25 |
+
from transformers.testing_utils import (
|
| 26 |
+
require_torch,
|
| 27 |
+
require_torch_multi_gpu,
|
| 28 |
+
require_torch_sdpa,
|
| 29 |
+
require_vision,
|
| 30 |
+
slow,
|
| 31 |
+
torch_device,
|
| 32 |
+
)
|
| 33 |
+
from transformers.utils import (
|
| 34 |
+
cached_property,
|
| 35 |
+
is_torch_available,
|
| 36 |
+
is_torch_bf16_available_on_device,
|
| 37 |
+
is_torch_fp16_available_on_device,
|
| 38 |
+
is_vision_available,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ...test_configuration_common import ConfigTester
|
| 42 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor, sdpa_kernel
|
| 43 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_torch_available():
|
| 47 |
+
import torch
|
| 48 |
+
from torch import nn
|
| 49 |
+
|
| 50 |
+
from transformers import (
|
| 51 |
+
Data2VecVisionForImageClassification,
|
| 52 |
+
Data2VecVisionForSemanticSegmentation,
|
| 53 |
+
Data2VecVisionModel,
|
| 54 |
+
)
|
| 55 |
+
from transformers.models.auto.modeling_auto import MODEL_MAPPING_NAMES
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if is_vision_available():
|
| 59 |
+
from PIL import Image
|
| 60 |
+
|
| 61 |
+
from transformers import BeitImageProcessor
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class Data2VecVisionModelTester:
|
| 65 |
+
def __init__(
|
| 66 |
+
self,
|
| 67 |
+
parent,
|
| 68 |
+
vocab_size=100,
|
| 69 |
+
batch_size=13,
|
| 70 |
+
image_size=30,
|
| 71 |
+
patch_size=2,
|
| 72 |
+
num_channels=3,
|
| 73 |
+
is_training=True,
|
| 74 |
+
use_labels=True,
|
| 75 |
+
hidden_size=32,
|
| 76 |
+
num_hidden_layers=2,
|
| 77 |
+
num_attention_heads=4,
|
| 78 |
+
intermediate_size=37,
|
| 79 |
+
hidden_act="gelu",
|
| 80 |
+
hidden_dropout_prob=0.1,
|
| 81 |
+
attention_probs_dropout_prob=0.1,
|
| 82 |
+
type_sequence_label_size=10,
|
| 83 |
+
initializer_range=0.02,
|
| 84 |
+
num_labels=3,
|
| 85 |
+
scope=None,
|
| 86 |
+
out_indices=[0, 1, 2, 3],
|
| 87 |
+
attn_implementation="eager",
|
| 88 |
+
mask_ratio=0.5,
|
| 89 |
+
):
|
| 90 |
+
self.parent = parent
|
| 91 |
+
self.vocab_size = 100
|
| 92 |
+
self.batch_size = batch_size
|
| 93 |
+
self.image_size = image_size
|
| 94 |
+
self.patch_size = patch_size
|
| 95 |
+
self.num_channels = num_channels
|
| 96 |
+
self.is_training = is_training
|
| 97 |
+
self.use_labels = use_labels
|
| 98 |
+
self.hidden_size = hidden_size
|
| 99 |
+
self.num_hidden_layers = num_hidden_layers
|
| 100 |
+
self.num_attention_heads = num_attention_heads
|
| 101 |
+
self.intermediate_size = intermediate_size
|
| 102 |
+
self.hidden_act = hidden_act
|
| 103 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 104 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 105 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 106 |
+
self.initializer_range = initializer_range
|
| 107 |
+
self.scope = scope
|
| 108 |
+
self.out_indices = out_indices
|
| 109 |
+
self.num_labels = num_labels
|
| 110 |
+
|
| 111 |
+
# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
|
| 112 |
+
num_patches = (image_size // patch_size) ** 2
|
| 113 |
+
self.seq_length = num_patches + 1
|
| 114 |
+
self.num_masks = int(mask_ratio * self.seq_length)
|
| 115 |
+
self.attn_implementation = attn_implementation
|
| 116 |
+
|
| 117 |
+
def prepare_config_and_inputs(self):
|
| 118 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 119 |
+
|
| 120 |
+
labels = None
|
| 121 |
+
pixel_labels = None
|
| 122 |
+
if self.use_labels:
|
| 123 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 124 |
+
pixel_labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
|
| 125 |
+
|
| 126 |
+
config = self.get_config()
|
| 127 |
+
|
| 128 |
+
return config, pixel_values, labels, pixel_labels
|
| 129 |
+
|
| 130 |
+
def get_config(self):
|
| 131 |
+
return Data2VecVisionConfig(
|
| 132 |
+
vocab_size=self.vocab_size,
|
| 133 |
+
image_size=self.image_size,
|
| 134 |
+
patch_size=self.patch_size,
|
| 135 |
+
num_channels=self.num_channels,
|
| 136 |
+
hidden_size=self.hidden_size,
|
| 137 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 138 |
+
num_attention_heads=self.num_attention_heads,
|
| 139 |
+
intermediate_size=self.intermediate_size,
|
| 140 |
+
hidden_act=self.hidden_act,
|
| 141 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 142 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 143 |
+
is_decoder=False,
|
| 144 |
+
initializer_range=self.initializer_range,
|
| 145 |
+
out_indices=self.out_indices,
|
| 146 |
+
attn_implementation=self.attn_implementation,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
def create_and_check_model(self, config, pixel_values, labels, pixel_labels):
|
| 150 |
+
model = Data2VecVisionModel(config=config)
|
| 151 |
+
model.to(torch_device)
|
| 152 |
+
model.eval()
|
| 153 |
+
result = model(pixel_values)
|
| 154 |
+
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
|
| 155 |
+
num_patches = (self.image_size // self.patch_size) ** 2
|
| 156 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
|
| 157 |
+
|
| 158 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels, pixel_labels):
|
| 159 |
+
config.num_labels = self.type_sequence_label_size
|
| 160 |
+
model = Data2VecVisionForImageClassification(config)
|
| 161 |
+
model.to(torch_device)
|
| 162 |
+
model.eval()
|
| 163 |
+
result = model(pixel_values, labels=labels)
|
| 164 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 165 |
+
|
| 166 |
+
def create_and_check_for_image_segmentation(self, config, pixel_values, labels, pixel_labels):
|
| 167 |
+
config.num_labels = self.num_labels
|
| 168 |
+
model = Data2VecVisionForSemanticSegmentation(config)
|
| 169 |
+
model.to(torch_device)
|
| 170 |
+
model.eval()
|
| 171 |
+
result = model(pixel_values)
|
| 172 |
+
self.parent.assertEqual(
|
| 173 |
+
result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
|
| 174 |
+
)
|
| 175 |
+
result = model(pixel_values, labels=pixel_labels)
|
| 176 |
+
self.parent.assertEqual(
|
| 177 |
+
result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def prepare_config_and_inputs_for_common(self):
|
| 181 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 182 |
+
config, pixel_values, labels, pixel_labels = config_and_inputs
|
| 183 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 184 |
+
return config, inputs_dict
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@require_torch
|
| 188 |
+
class Data2VecVisionModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 189 |
+
"""
|
| 190 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as Data2VecVision does not use input_ids, inputs_embeds,
|
| 191 |
+
attention_mask and seq_length.
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
all_model_classes = (
|
| 195 |
+
(Data2VecVisionModel, Data2VecVisionForImageClassification, Data2VecVisionForSemanticSegmentation)
|
| 196 |
+
if is_torch_available()
|
| 197 |
+
else ()
|
| 198 |
+
)
|
| 199 |
+
pipeline_model_mapping = (
|
| 200 |
+
{
|
| 201 |
+
"image-feature-extraction": Data2VecVisionModel,
|
| 202 |
+
"image-classification": Data2VecVisionForImageClassification,
|
| 203 |
+
"image-segmentation": Data2VecVisionForSemanticSegmentation,
|
| 204 |
+
}
|
| 205 |
+
if is_torch_available()
|
| 206 |
+
else {}
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
test_pruning = False
|
| 210 |
+
test_resize_embeddings = False
|
| 211 |
+
test_head_masking = False
|
| 212 |
+
|
| 213 |
+
def setUp(self):
|
| 214 |
+
self.model_tester = Data2VecVisionModelTester(self)
|
| 215 |
+
self.config_tester = ConfigTester(
|
| 216 |
+
self, config_class=Data2VecVisionConfig, has_text_modality=False, hidden_size=37
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def test_config(self):
|
| 220 |
+
self.config_tester.run_common_tests()
|
| 221 |
+
|
| 222 |
+
@unittest.skip(reason="Data2VecVision does not use inputs_embeds")
|
| 223 |
+
def test_inputs_embeds(self):
|
| 224 |
+
pass
|
| 225 |
+
|
| 226 |
+
@require_torch_multi_gpu
|
| 227 |
+
@unittest.skip(
|
| 228 |
+
reason="Data2VecVision has some layers using `add_module` which doesn't work well with `nn.DataParallel`"
|
| 229 |
+
)
|
| 230 |
+
def test_multi_gpu_data_parallel_forward(self):
|
| 231 |
+
pass
|
| 232 |
+
|
| 233 |
+
def test_model_get_set_embeddings(self):
|
| 234 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 235 |
+
|
| 236 |
+
for model_class in self.all_model_classes:
|
| 237 |
+
model = model_class(config)
|
| 238 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 239 |
+
x = model.get_output_embeddings()
|
| 240 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 241 |
+
|
| 242 |
+
def test_model(self):
|
| 243 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 244 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 245 |
+
|
| 246 |
+
def test_for_image_segmentation(self):
|
| 247 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 248 |
+
self.model_tester.create_and_check_for_image_segmentation(*config_and_inputs)
|
| 249 |
+
|
| 250 |
+
def test_training(self):
|
| 251 |
+
if not self.model_tester.is_training:
|
| 252 |
+
self.skipTest(reason="model_tester.is_training is set to False")
|
| 253 |
+
|
| 254 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 255 |
+
config.return_dict = True
|
| 256 |
+
|
| 257 |
+
for model_class in self.all_model_classes:
|
| 258 |
+
if model_class.__name__ in MODEL_MAPPING_NAMES.values():
|
| 259 |
+
continue
|
| 260 |
+
|
| 261 |
+
model = model_class(config)
|
| 262 |
+
model.to(torch_device)
|
| 263 |
+
model.train()
|
| 264 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 265 |
+
loss = model(**inputs).loss
|
| 266 |
+
loss.backward()
|
| 267 |
+
|
| 268 |
+
def test_training_gradient_checkpointing(self):
|
| 269 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 270 |
+
if not self.model_tester.is_training:
|
| 271 |
+
self.skipTest(reason="model_tester.is_training is set to False")
|
| 272 |
+
|
| 273 |
+
config.use_cache = False
|
| 274 |
+
config.return_dict = True
|
| 275 |
+
|
| 276 |
+
for model_class in self.all_model_classes:
|
| 277 |
+
if model_class.__name__ in MODEL_MAPPING_NAMES.values() or not model_class.supports_gradient_checkpointing:
|
| 278 |
+
continue
|
| 279 |
+
# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
|
| 280 |
+
# this can then be incorporated into _prepare_for_class in test_modeling_common.py
|
| 281 |
+
elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
|
| 282 |
+
batch_size, num_channels, height, width = inputs_dict["pixel_values"].shape
|
| 283 |
+
inputs_dict["labels"] = torch.zeros(
|
| 284 |
+
[self.model_tester.batch_size, height, width], device=torch_device
|
| 285 |
+
).long()
|
| 286 |
+
model = model_class(config)
|
| 287 |
+
model.gradient_checkpointing_enable()
|
| 288 |
+
model.to(torch_device)
|
| 289 |
+
model.train()
|
| 290 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 291 |
+
loss = model(**inputs).loss
|
| 292 |
+
loss.backward()
|
| 293 |
+
|
| 294 |
+
def test_initialization(self):
|
| 295 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 296 |
+
|
| 297 |
+
configs_no_init = _config_zero_init(config)
|
| 298 |
+
for model_class in self.all_model_classes:
|
| 299 |
+
model = model_class(config=configs_no_init)
|
| 300 |
+
for name, param in model.named_parameters():
|
| 301 |
+
# we skip lambda parameters as these require special initial values
|
| 302 |
+
# determined by config.layer_scale_init_value
|
| 303 |
+
if "lambda" in name:
|
| 304 |
+
continue
|
| 305 |
+
if param.requires_grad:
|
| 306 |
+
self.assertIn(
|
| 307 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 308 |
+
[0.0, 1.0],
|
| 309 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=2e-4, name="outputs", attributes=None):
|
| 313 |
+
# We override with a slightly higher tol value, as semseg models tend to diverge a bit more
|
| 314 |
+
super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes)
|
| 315 |
+
|
| 316 |
+
def test_for_image_classification(self):
|
| 317 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 318 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 319 |
+
|
| 320 |
+
@slow
|
| 321 |
+
def test_model_from_pretrained(self):
|
| 322 |
+
model_name = "facebook/data2vec-vision-base-ft1k"
|
| 323 |
+
model = Data2VecVisionModel.from_pretrained(model_name)
|
| 324 |
+
self.assertIsNotNone(model)
|
| 325 |
+
|
| 326 |
+
@parameterized.expand([("float16",), ("bfloat16",), ("float32",)])
|
| 327 |
+
@require_torch_sdpa
|
| 328 |
+
# Copied from tests.models.beit.test_modeling_beit.BeitModelTest.test_eager_matches_sdpa_inference with Beit->Data2VecVision
|
| 329 |
+
def test_eager_matches_sdpa_inference(self, torch_dtype: str):
|
| 330 |
+
# The common test modifies the num_hidden_layers to be 1. However, for Data2VecVision we want to
|
| 331 |
+
# avoid that because the num_hidden_layers is generally assumed to be 4. Also, the code
|
| 332 |
+
# related to attention masks in the original common tests is not required as the Data2VecVision
|
| 333 |
+
# model does not handle attention masks. Furthermore, some extra code like modifying
|
| 334 |
+
# the norm layers eps values for specialized configs and checking for the 'noise'
|
| 335 |
+
# has been omitted to simply the test.
|
| 336 |
+
if not self.has_attentions:
|
| 337 |
+
self.skipTest(reason="Model architecture does not support attentions")
|
| 338 |
+
|
| 339 |
+
if not self.all_model_classes[0]._supports_sdpa:
|
| 340 |
+
self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA")
|
| 341 |
+
|
| 342 |
+
if torch_dtype == "float16" and not is_torch_fp16_available_on_device(torch_device):
|
| 343 |
+
self.skipTest(f"float16 not supported on {torch_device} (on the specific device currently used)")
|
| 344 |
+
|
| 345 |
+
if torch_dtype == "bfloat16" and not is_torch_bf16_available_on_device(torch_device):
|
| 346 |
+
self.skipTest(
|
| 347 |
+
f"bfloat16 not supported on {torch_device} (on the specific device currently used, e.g. Nvidia T4 GPU)"
|
| 348 |
+
)
|
| 349 |
+
|
| 350 |
+
# Not sure whether it's fine to put torch.XXX in a decorator if torch is not available so hacking it here instead.
|
| 351 |
+
if torch_dtype == "float16":
|
| 352 |
+
torch_dtype = torch.float16
|
| 353 |
+
elif torch_dtype == "bfloat16":
|
| 354 |
+
torch_dtype = torch.bfloat16
|
| 355 |
+
elif torch_dtype == "float32":
|
| 356 |
+
torch_dtype = torch.float32
|
| 357 |
+
|
| 358 |
+
atols = {
|
| 359 |
+
("cpu", False, torch.float32): 1e-6,
|
| 360 |
+
("cpu", False, torch.float16): 5e-3,
|
| 361 |
+
("cpu", False, torch.bfloat16): 1e-2,
|
| 362 |
+
("cpu", True, torch.float32): 1e-6,
|
| 363 |
+
("cpu", True, torch.float16): 5e-3,
|
| 364 |
+
("cpu", True, torch.bfloat16): 1e-2,
|
| 365 |
+
("cuda", False, torch.float32): 1e-6,
|
| 366 |
+
("cuda", False, torch.bfloat16): 1e-2,
|
| 367 |
+
("cuda", False, torch.float16): 5e-3,
|
| 368 |
+
("cuda", True, torch.float32): 1e-6,
|
| 369 |
+
("cuda", True, torch.bfloat16): 1e-2,
|
| 370 |
+
("cuda", True, torch.float16): 5e-3,
|
| 371 |
+
}
|
| 372 |
+
rtols = {
|
| 373 |
+
("cpu", False, torch.float32): 1e-4,
|
| 374 |
+
("cpu", False, torch.float16): 5e-3,
|
| 375 |
+
("cpu", False, torch.bfloat16): 1e-2,
|
| 376 |
+
("cpu", True, torch.float32): 1e-4,
|
| 377 |
+
("cpu", True, torch.float16): 5e-3,
|
| 378 |
+
("cpu", True, torch.bfloat16): 1e-2,
|
| 379 |
+
("cuda", False, torch.float32): 1e-4,
|
| 380 |
+
("cuda", False, torch.bfloat16): 1e-2,
|
| 381 |
+
("cuda", False, torch.float16): 5e-3,
|
| 382 |
+
("cuda", True, torch.float32): 1e-4,
|
| 383 |
+
("cuda", True, torch.bfloat16): 3e-2,
|
| 384 |
+
("cuda", True, torch.float16): 5e-3,
|
| 385 |
+
}
|
| 386 |
+
|
| 387 |
+
def get_mean_reldiff(failcase, x, ref, atol, rtol):
|
| 388 |
+
return f"{failcase}: mean relative difference: {((x - ref).abs() / (ref.abs() + 1e-12)).mean():.3e}, torch atol = {atol}, torch rtol = {rtol}"
|
| 389 |
+
|
| 390 |
+
for model_class in self.all_model_classes:
|
| 391 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 392 |
+
|
| 393 |
+
config.rms_norm_eps = 1.0
|
| 394 |
+
config.layer_norm_eps = 1.0
|
| 395 |
+
config.norm_eps = 1.0
|
| 396 |
+
config.norm_epsilon = 1.0
|
| 397 |
+
config.layer_norm_epsilon = 1.0
|
| 398 |
+
|
| 399 |
+
model = model_class(config)
|
| 400 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 401 |
+
model.save_pretrained(tmpdirname)
|
| 402 |
+
model_sdpa = model_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype, use_mask_token=True)
|
| 403 |
+
model_sdpa = model_sdpa.eval().to(torch_device, dtype=torch_dtype)
|
| 404 |
+
|
| 405 |
+
model_eager = model_class.from_pretrained(
|
| 406 |
+
tmpdirname,
|
| 407 |
+
torch_dtype=torch_dtype,
|
| 408 |
+
attn_implementation="eager",
|
| 409 |
+
use_mask_token=True,
|
| 410 |
+
)
|
| 411 |
+
model_eager = model_eager.eval().to(torch_device, dtype=torch_dtype)
|
| 412 |
+
|
| 413 |
+
# Another way to make sure norm layers have desired epsilon. (Some models don't set it from its config.)
|
| 414 |
+
for x in model_eager.modules():
|
| 415 |
+
if isinstance(x, (nn.LayerNorm, nn.GroupNorm)):
|
| 416 |
+
x.eps = 1.0
|
| 417 |
+
for x in model_sdpa.modules():
|
| 418 |
+
if isinstance(x, (nn.LayerNorm, nn.GroupNorm)):
|
| 419 |
+
x.eps = 1.0
|
| 420 |
+
|
| 421 |
+
# We use these for loops instead of parameterized.expand just for the interest of avoiding loading/saving 16 times the model,
|
| 422 |
+
# but it would be nicer to have an efficient way to use parameterized.expand
|
| 423 |
+
fail_cases = []
|
| 424 |
+
for padding_side in ["left", "right"]:
|
| 425 |
+
for use_mask in [False, True]:
|
| 426 |
+
for output_attentions in [True, False]:
|
| 427 |
+
can_output_attn = "output_attentions" in inspect.signature(model_sdpa.forward).parameters
|
| 428 |
+
if not (self.has_attentions and can_output_attn) and output_attentions:
|
| 429 |
+
continue
|
| 430 |
+
# TODO: if we can also check with `batch_size=1` without being flaky?
|
| 431 |
+
for batch_size in [7]:
|
| 432 |
+
dummy_input = inputs_dict[model.main_input_name]
|
| 433 |
+
|
| 434 |
+
if dummy_input.dtype in [torch.float32, torch.bfloat16, torch.float16]:
|
| 435 |
+
dummy_input = dummy_input.to(torch_dtype)
|
| 436 |
+
|
| 437 |
+
dummy_input = dummy_input[:batch_size]
|
| 438 |
+
for enable_kernels in [False, True]:
|
| 439 |
+
failcase = f"padding_side={padding_side}, use_mask={use_mask}, enable_kernels={enable_kernels}"
|
| 440 |
+
processed_inputs = {
|
| 441 |
+
model.main_input_name: dummy_input,
|
| 442 |
+
"output_hidden_states": True,
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
if (
|
| 446 |
+
self.has_attentions
|
| 447 |
+
and "output_attentions" in inspect.signature(model_sdpa.forward).parameters
|
| 448 |
+
):
|
| 449 |
+
processed_inputs["output_attentions"] = output_attentions
|
| 450 |
+
|
| 451 |
+
if "bool_masked_pos" in inspect.signature(model_eager.forward).parameters:
|
| 452 |
+
dummy_mask = torch.ones((self.model_tester.num_masks,))
|
| 453 |
+
mask_length = self.model_tester.seq_length - 1 - dummy_mask.size(0)
|
| 454 |
+
dummy_mask = torch.cat([dummy_mask, torch.zeros(mask_length)])
|
| 455 |
+
dummy_bool_masked_pos = dummy_mask.expand(batch_size, -1).bool()
|
| 456 |
+
processed_inputs["bool_masked_pos"] = dummy_bool_masked_pos.to(torch_device)
|
| 457 |
+
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
with sdpa_kernel(
|
| 460 |
+
enable_flash=enable_kernels,
|
| 461 |
+
enable_math=True,
|
| 462 |
+
enable_mem_efficient=enable_kernels,
|
| 463 |
+
):
|
| 464 |
+
prepared_inputs = self._prepare_for_class(processed_inputs, model_class)
|
| 465 |
+
outputs_eager = model_eager(**prepared_inputs)
|
| 466 |
+
outputs_sdpa = model_sdpa(**prepared_inputs)
|
| 467 |
+
|
| 468 |
+
logits_eager = outputs_eager.hidden_states[-1]
|
| 469 |
+
logits_sdpa = outputs_sdpa.hidden_states[-1]
|
| 470 |
+
if torch_device in ["cpu", "cuda"]:
|
| 471 |
+
atol = atols[torch_device, enable_kernels, torch_dtype]
|
| 472 |
+
rtol = rtols[torch_device, enable_kernels, torch_dtype]
|
| 473 |
+
elif torch_device == "xpu":
|
| 474 |
+
# As of PyTorch 2.5 XPU backend supports only torch.nn.attention.SDPBackend.MATH
|
| 475 |
+
# which is implemented on PyTorch level using aten operators and is
|
| 476 |
+
# device agnostic with respect to implementation of each aten operator.
|
| 477 |
+
atol = atols["cuda", False, torch_dtype]
|
| 478 |
+
rtol = rtols["cuda", False, torch_dtype]
|
| 479 |
+
else:
|
| 480 |
+
atol = 1e-7
|
| 481 |
+
rtol = 1e-4
|
| 482 |
+
|
| 483 |
+
# Masked tokens output slightly deviates - we don't mind that.
|
| 484 |
+
if use_mask:
|
| 485 |
+
_logits_sdpa = torch.zeros_like(input=logits_sdpa)
|
| 486 |
+
_logits_eager = torch.zeros_like(input=logits_eager)
|
| 487 |
+
|
| 488 |
+
_logits_sdpa[:-1] = logits_sdpa[:-1]
|
| 489 |
+
_logits_eager[:-1] = logits_eager[:-1]
|
| 490 |
+
|
| 491 |
+
if padding_side == "left":
|
| 492 |
+
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, 2:]
|
| 493 |
+
_logits_eager[-1:, 2:] = logits_eager[-1:, 2:]
|
| 494 |
+
|
| 495 |
+
elif padding_side == "right":
|
| 496 |
+
_logits_sdpa[-1:, 2:] = logits_sdpa[-1:, :-2]
|
| 497 |
+
_logits_eager[-1:, 2:] = logits_eager[-1:, :-2]
|
| 498 |
+
|
| 499 |
+
logits_sdpa = _logits_sdpa
|
| 500 |
+
logits_eager = _logits_eager
|
| 501 |
+
|
| 502 |
+
results = [
|
| 503 |
+
torch.allclose(_logits_sdpa, _logits_eager, atol=atol, rtol=rtol)
|
| 504 |
+
for (_logits_sdpa, _logits_eager) in zip(logits_sdpa, logits_eager)
|
| 505 |
+
]
|
| 506 |
+
# If 80% batch elements have matched results, it's fine
|
| 507 |
+
if np.mean(results) < 0.8:
|
| 508 |
+
fail_cases.append(
|
| 509 |
+
get_mean_reldiff(failcase, logits_sdpa, logits_eager, atol, rtol)
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
self.assertTrue(len(fail_cases) == 0, "\n".join(fail_cases))
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
# We will verify our results on an image of cute cats
|
| 516 |
+
def prepare_img():
|
| 517 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 518 |
+
return image
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
@require_torch
|
| 522 |
+
@require_vision
|
| 523 |
+
class Data2VecVisionModelIntegrationTest(unittest.TestCase):
|
| 524 |
+
@cached_property
|
| 525 |
+
def default_image_processor(self):
|
| 526 |
+
return (
|
| 527 |
+
BeitImageProcessor.from_pretrained("facebook/data2vec-vision-base-ft1k") if is_vision_available() else None
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
@slow
|
| 531 |
+
def test_inference_image_classification_head_imagenet_1k(self):
|
| 532 |
+
model = Data2VecVisionForImageClassification.from_pretrained("facebook/data2vec-vision-base-ft1k").to(
|
| 533 |
+
torch_device
|
| 534 |
+
)
|
| 535 |
+
|
| 536 |
+
image_processor = self.default_image_processor
|
| 537 |
+
image = prepare_img()
|
| 538 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 539 |
+
|
| 540 |
+
# forward pass
|
| 541 |
+
with torch.no_grad():
|
| 542 |
+
outputs = model(**inputs)
|
| 543 |
+
logits = outputs.logits
|
| 544 |
+
|
| 545 |
+
# verify the logits
|
| 546 |
+
expected_shape = torch.Size((1, 1000))
|
| 547 |
+
self.assertEqual(logits.shape, expected_shape)
|
| 548 |
+
|
| 549 |
+
expected_slice = torch.tensor([0.3277, -0.1395, 0.0911]).to(torch_device)
|
| 550 |
+
|
| 551 |
+
self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
|
| 552 |
+
|
| 553 |
+
expected_top2 = [model.config.label2id[i] for i in ["remote control, remote", "tabby, tabby cat"]]
|
| 554 |
+
self.assertEqual(logits[0].topk(2).indices.cpu().tolist(), expected_top2)
|
| 555 |
+
|
| 556 |
+
@slow
|
| 557 |
+
def test_inference_interpolate_pos_encoding(self):
|
| 558 |
+
model_name = "facebook/data2vec-vision-base-ft1k"
|
| 559 |
+
model = Data2VecVisionModel.from_pretrained(model_name, **{"use_absolute_position_embeddings": True}).to(
|
| 560 |
+
torch_device
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 564 |
+
processor = BeitImageProcessor.from_pretrained("facebook/data2vec-vision-base-ft1k")
|
| 565 |
+
inputs = processor(images=image, return_tensors="pt", size={"height": 480, "width": 480})
|
| 566 |
+
pixel_values = inputs.pixel_values.to(torch_device)
|
| 567 |
+
|
| 568 |
+
# with interpolate_pos_encoding being False an exception should be raised with higher resolution
|
| 569 |
+
# images than what the model supports.
|
| 570 |
+
self.assertFalse(processor.do_center_crop)
|
| 571 |
+
with torch.no_grad():
|
| 572 |
+
with self.assertRaises(ValueError, msg="doesn't match model"):
|
| 573 |
+
model(pixel_values, interpolate_pos_encoding=False)
|
| 574 |
+
|
| 575 |
+
# with interpolate_pos_encoding being True the model should process the higher resolution image
|
| 576 |
+
# successfully and produce the expected output.
|
| 577 |
+
with torch.no_grad():
|
| 578 |
+
outputs = model(pixel_values, interpolate_pos_encoding=True)
|
| 579 |
+
|
| 580 |
+
expected_shape = torch.Size((1, 1801, 768))
|
| 581 |
+
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/data2vec/test_modeling_tf_data2vec_vision.py
ADDED
|
@@ -0,0 +1,496 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the TensorFlow Data2VecVision model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import collections.abc
|
| 20 |
+
import inspect
|
| 21 |
+
import unittest
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
|
| 25 |
+
from transformers import Data2VecVisionConfig
|
| 26 |
+
from transformers.file_utils import cached_property, is_tf_available, is_vision_available
|
| 27 |
+
from transformers.testing_utils import require_tf, require_vision, slow
|
| 28 |
+
|
| 29 |
+
from ...test_configuration_common import ConfigTester
|
| 30 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
|
| 31 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_tf_available():
|
| 35 |
+
import tensorflow as tf
|
| 36 |
+
|
| 37 |
+
from transformers import (
|
| 38 |
+
TFData2VecVisionForImageClassification,
|
| 39 |
+
TFData2VecVisionForSemanticSegmentation,
|
| 40 |
+
TFData2VecVisionModel,
|
| 41 |
+
)
|
| 42 |
+
from transformers.modeling_tf_utils import keras
|
| 43 |
+
|
| 44 |
+
if is_vision_available():
|
| 45 |
+
from PIL import Image
|
| 46 |
+
|
| 47 |
+
from transformers import BeitImageProcessor
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TFData2VecVisionModelTester:
|
| 51 |
+
def __init__(
|
| 52 |
+
self,
|
| 53 |
+
parent,
|
| 54 |
+
vocab_size=100,
|
| 55 |
+
batch_size=13,
|
| 56 |
+
image_size=30,
|
| 57 |
+
patch_size=2,
|
| 58 |
+
num_channels=3,
|
| 59 |
+
is_training=True,
|
| 60 |
+
use_labels=True,
|
| 61 |
+
hidden_size=32,
|
| 62 |
+
num_hidden_layers=2,
|
| 63 |
+
num_attention_heads=4,
|
| 64 |
+
intermediate_size=37,
|
| 65 |
+
hidden_act="gelu",
|
| 66 |
+
hidden_dropout_prob=0.1,
|
| 67 |
+
attention_probs_dropout_prob=0.1,
|
| 68 |
+
type_sequence_label_size=10,
|
| 69 |
+
initializer_range=0.02,
|
| 70 |
+
num_labels=3,
|
| 71 |
+
scope=None,
|
| 72 |
+
out_indices=[0, 1, 2, 3],
|
| 73 |
+
):
|
| 74 |
+
self.parent = parent
|
| 75 |
+
self.vocab_size = 100
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.image_size = image_size
|
| 78 |
+
self.patch_size = patch_size
|
| 79 |
+
self.num_channels = num_channels
|
| 80 |
+
self.is_training = is_training
|
| 81 |
+
self.use_labels = use_labels
|
| 82 |
+
self.hidden_size = hidden_size
|
| 83 |
+
self.num_hidden_layers = num_hidden_layers
|
| 84 |
+
self.num_attention_heads = num_attention_heads
|
| 85 |
+
self.intermediate_size = intermediate_size
|
| 86 |
+
self.hidden_act = hidden_act
|
| 87 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 88 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 89 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 90 |
+
self.initializer_range = initializer_range
|
| 91 |
+
self.scope = scope
|
| 92 |
+
self.out_indices = out_indices
|
| 93 |
+
self.num_labels = num_labels
|
| 94 |
+
|
| 95 |
+
def prepare_config_and_inputs(self):
|
| 96 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 97 |
+
|
| 98 |
+
labels = None
|
| 99 |
+
pixel_labels = None
|
| 100 |
+
if self.use_labels:
|
| 101 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 102 |
+
pixel_labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
|
| 103 |
+
|
| 104 |
+
config = self.get_config()
|
| 105 |
+
|
| 106 |
+
return config, pixel_values, labels, pixel_labels
|
| 107 |
+
|
| 108 |
+
def get_config(self):
|
| 109 |
+
return Data2VecVisionConfig(
|
| 110 |
+
vocab_size=self.vocab_size,
|
| 111 |
+
image_size=self.image_size,
|
| 112 |
+
patch_size=self.patch_size,
|
| 113 |
+
num_channels=self.num_channels,
|
| 114 |
+
hidden_size=self.hidden_size,
|
| 115 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 116 |
+
num_attention_heads=self.num_attention_heads,
|
| 117 |
+
intermediate_size=self.intermediate_size,
|
| 118 |
+
hidden_act=self.hidden_act,
|
| 119 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 120 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 121 |
+
is_decoder=False,
|
| 122 |
+
initializer_range=self.initializer_range,
|
| 123 |
+
out_indices=self.out_indices,
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def create_and_check_model(self, config, pixel_values, labels, pixel_labels):
|
| 127 |
+
model = TFData2VecVisionModel(config=config)
|
| 128 |
+
result = model(pixel_values, training=False)
|
| 129 |
+
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
|
| 130 |
+
image_size = (
|
| 131 |
+
self.image_size
|
| 132 |
+
if isinstance(self.image_size, collections.abc.Iterable)
|
| 133 |
+
else (self.image_size, self.image_size)
|
| 134 |
+
)
|
| 135 |
+
patch_size = (
|
| 136 |
+
self.patch_size
|
| 137 |
+
if isinstance(self.image_size, collections.abc.Iterable)
|
| 138 |
+
else (self.patch_size, self.patch_size)
|
| 139 |
+
)
|
| 140 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 141 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
|
| 142 |
+
|
| 143 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels, pixel_labels):
|
| 144 |
+
config.num_labels = self.type_sequence_label_size
|
| 145 |
+
model = TFData2VecVisionForImageClassification(config)
|
| 146 |
+
|
| 147 |
+
result = model(pixel_values, labels=labels, training=False)
|
| 148 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 149 |
+
|
| 150 |
+
def create_and_check_for_image_segmentation(self, config, pixel_values, labels, pixel_labels):
|
| 151 |
+
config.num_labels = self.num_labels
|
| 152 |
+
model = TFData2VecVisionForSemanticSegmentation(config)
|
| 153 |
+
result = model(pixel_values, training=False)
|
| 154 |
+
self.parent.assertEqual(
|
| 155 |
+
result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
|
| 156 |
+
)
|
| 157 |
+
result = model(pixel_values, labels=pixel_labels)
|
| 158 |
+
self.parent.assertEqual(
|
| 159 |
+
result.logits.shape, (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
def prepare_config_and_inputs_for_common(self):
|
| 163 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 164 |
+
config, pixel_values, labels, pixel_labels = config_and_inputs
|
| 165 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 166 |
+
return config, inputs_dict
|
| 167 |
+
|
| 168 |
+
def prepare_config_and_inputs_for_keras_fit(self):
|
| 169 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 170 |
+
config, pixel_values, _, _ = config_and_inputs
|
| 171 |
+
inputs_dict = {"pixel_values": pixel_values, "labels": tf.zeros((self.batch_size))}
|
| 172 |
+
return config, inputs_dict
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
@require_tf
|
| 176 |
+
class TFData2VecVisionModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 177 |
+
"""
|
| 178 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as Data2VecVision does not use input_ids, inputs_embeds,
|
| 179 |
+
attention_mask and seq_length.
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
all_model_classes = (
|
| 183 |
+
(TFData2VecVisionModel, TFData2VecVisionForImageClassification, TFData2VecVisionForSemanticSegmentation)
|
| 184 |
+
if is_tf_available()
|
| 185 |
+
else ()
|
| 186 |
+
)
|
| 187 |
+
pipeline_model_mapping = (
|
| 188 |
+
{"feature-extraction": TFData2VecVisionModel, "image-classification": TFData2VecVisionForImageClassification}
|
| 189 |
+
if is_tf_available()
|
| 190 |
+
else {}
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
test_pruning = False
|
| 194 |
+
test_onnx = False
|
| 195 |
+
test_resize_embeddings = False
|
| 196 |
+
test_head_masking = False
|
| 197 |
+
|
| 198 |
+
def setUp(self):
|
| 199 |
+
self.model_tester = TFData2VecVisionModelTester(self)
|
| 200 |
+
self.config_tester = ConfigTester(
|
| 201 |
+
self, config_class=Data2VecVisionConfig, has_text_modality=False, hidden_size=37
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
def test_config(self):
|
| 205 |
+
self.config_tester.run_common_tests()
|
| 206 |
+
|
| 207 |
+
@unittest.skip(reason="Data2VecVision does not use inputs_embeds")
|
| 208 |
+
def test_inputs_embeds(self):
|
| 209 |
+
# Data2VecVision does not use inputs_embeds
|
| 210 |
+
pass
|
| 211 |
+
|
| 212 |
+
def test_model_common_attributes(self):
|
| 213 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 214 |
+
|
| 215 |
+
for model_class in self.all_model_classes:
|
| 216 |
+
model = model_class(config)
|
| 217 |
+
self.assertIsInstance(model.get_input_embeddings(), (keras.layers.Layer))
|
| 218 |
+
x = model.get_output_embeddings()
|
| 219 |
+
self.assertTrue(x is None or isinstance(x, keras.layers.Layer))
|
| 220 |
+
|
| 221 |
+
def test_forward_signature(self):
|
| 222 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 223 |
+
|
| 224 |
+
for model_class in self.all_model_classes:
|
| 225 |
+
model = model_class(config)
|
| 226 |
+
signature = inspect.signature(model.call)
|
| 227 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 228 |
+
arg_names = [*signature.parameters.keys()]
|
| 229 |
+
|
| 230 |
+
expected_arg_names = ["pixel_values"]
|
| 231 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 232 |
+
|
| 233 |
+
def test_model(self):
|
| 234 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 235 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 236 |
+
|
| 237 |
+
def test_for_image_segmentation(self):
|
| 238 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 239 |
+
self.model_tester.create_and_check_for_image_segmentation(*config_and_inputs)
|
| 240 |
+
|
| 241 |
+
def test_attention_outputs(self):
|
| 242 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 243 |
+
config.return_dict = True
|
| 244 |
+
|
| 245 |
+
# in Data2VecVision, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
|
| 246 |
+
image_size = (
|
| 247 |
+
self.model_tester.image_size
|
| 248 |
+
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
|
| 249 |
+
else (self.model_tester.image_size, self.model_tester.image_size)
|
| 250 |
+
)
|
| 251 |
+
patch_size = (
|
| 252 |
+
self.model_tester.patch_size
|
| 253 |
+
if isinstance(self.model_tester.patch_size, collections.abc.Iterable)
|
| 254 |
+
else (self.model_tester.patch_size, self.model_tester.patch_size)
|
| 255 |
+
)
|
| 256 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 257 |
+
seq_len = num_patches + 1
|
| 258 |
+
encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
|
| 259 |
+
encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
|
| 260 |
+
chunk_length = getattr(self.model_tester, "chunk_length", None)
|
| 261 |
+
if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
|
| 262 |
+
encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
|
| 263 |
+
|
| 264 |
+
for model_class in self.all_model_classes:
|
| 265 |
+
inputs_dict["output_attentions"] = True
|
| 266 |
+
inputs_dict["output_hidden_states"] = False
|
| 267 |
+
config.return_dict = True
|
| 268 |
+
model = model_class(config)
|
| 269 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
|
| 270 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 271 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 272 |
+
|
| 273 |
+
# check that output_attentions also work using config
|
| 274 |
+
del inputs_dict["output_attentions"]
|
| 275 |
+
config.output_attentions = True
|
| 276 |
+
model = model_class(config)
|
| 277 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
|
| 278 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 279 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 280 |
+
|
| 281 |
+
self.assertListEqual(
|
| 282 |
+
list(attentions[0].shape[-3:]),
|
| 283 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 284 |
+
)
|
| 285 |
+
out_len = len(outputs)
|
| 286 |
+
|
| 287 |
+
# Check attention is always last and order is fine
|
| 288 |
+
inputs_dict["output_attentions"] = True
|
| 289 |
+
inputs_dict["output_hidden_states"] = True
|
| 290 |
+
model = model_class(config)
|
| 291 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class), training=False)
|
| 292 |
+
|
| 293 |
+
self.assertEqual(out_len + 1, len(outputs))
|
| 294 |
+
|
| 295 |
+
self_attentions = outputs.attentions
|
| 296 |
+
|
| 297 |
+
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
|
| 298 |
+
self.assertListEqual(
|
| 299 |
+
list(self_attentions[0].shape[-3:]),
|
| 300 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def test_hidden_states_output(self):
|
| 304 |
+
def check_hidden_states_output(inputs_dict, config, model_class):
|
| 305 |
+
model = model_class(config)
|
| 306 |
+
|
| 307 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 308 |
+
|
| 309 |
+
hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
|
| 310 |
+
|
| 311 |
+
expected_num_layers = getattr(
|
| 312 |
+
self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
|
| 313 |
+
)
|
| 314 |
+
self.assertEqual(len(hidden_states), expected_num_layers)
|
| 315 |
+
|
| 316 |
+
# Data2VecVision has a different seq_length
|
| 317 |
+
image_size = (
|
| 318 |
+
self.model_tester.image_size
|
| 319 |
+
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
|
| 320 |
+
else (self.model_tester.image_size, self.model_tester.image_size)
|
| 321 |
+
)
|
| 322 |
+
patch_size = (
|
| 323 |
+
self.model_tester.patch_size
|
| 324 |
+
if isinstance(self.model_tester.patch_size, collections.abc.Iterable)
|
| 325 |
+
else (self.model_tester.patch_size, self.model_tester.patch_size)
|
| 326 |
+
)
|
| 327 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 328 |
+
seq_length = num_patches + 1
|
| 329 |
+
|
| 330 |
+
self.assertListEqual(
|
| 331 |
+
list(hidden_states[0].shape[-2:]),
|
| 332 |
+
[seq_length, self.model_tester.hidden_size],
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 336 |
+
|
| 337 |
+
for model_class in self.all_model_classes:
|
| 338 |
+
inputs_dict["output_hidden_states"] = True
|
| 339 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 340 |
+
|
| 341 |
+
# check that output_hidden_states also work using config
|
| 342 |
+
del inputs_dict["output_hidden_states"]
|
| 343 |
+
config.output_hidden_states = True
|
| 344 |
+
|
| 345 |
+
check_hidden_states_output(inputs_dict, config, model_class)
|
| 346 |
+
|
| 347 |
+
# Overriding this method since the base method won't be compatible with Data2VecVision.
|
| 348 |
+
@slow
|
| 349 |
+
def test_keras_fit(self):
|
| 350 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 351 |
+
for model_class in self.all_model_classes:
|
| 352 |
+
# Since `TFData2VecVisionModel` cannot operate with the default `fit()` method.
|
| 353 |
+
if model_class.__name__ != "TFData2VecVisionModel":
|
| 354 |
+
model = model_class(config)
|
| 355 |
+
if getattr(model, "hf_compute_loss", None):
|
| 356 |
+
# Test that model correctly compute the loss with kwargs
|
| 357 |
+
_, prepared_for_class = self.model_tester.prepare_config_and_inputs_for_keras_fit()
|
| 358 |
+
|
| 359 |
+
label_names = {"labels"}
|
| 360 |
+
self.assertGreater(len(label_names), 0, msg="No matching label names found!")
|
| 361 |
+
labels = {key: val for key, val in prepared_for_class.items() if key in label_names}
|
| 362 |
+
inputs_minus_labels = {
|
| 363 |
+
key: val for key, val in prepared_for_class.items() if key not in label_names
|
| 364 |
+
}
|
| 365 |
+
self.assertGreater(len(inputs_minus_labels), 0)
|
| 366 |
+
model.compile(optimizer=keras.optimizers.SGD(0.0), run_eagerly=True)
|
| 367 |
+
|
| 368 |
+
# Make sure the model fits without crashing regardless of where we pass the labels
|
| 369 |
+
history1 = model.fit(
|
| 370 |
+
prepared_for_class,
|
| 371 |
+
validation_data=prepared_for_class,
|
| 372 |
+
steps_per_epoch=1,
|
| 373 |
+
validation_steps=1,
|
| 374 |
+
shuffle=False,
|
| 375 |
+
)
|
| 376 |
+
val_loss1 = history1.history["val_loss"][0]
|
| 377 |
+
history2 = model.fit(
|
| 378 |
+
inputs_minus_labels,
|
| 379 |
+
labels,
|
| 380 |
+
validation_data=(inputs_minus_labels, labels),
|
| 381 |
+
steps_per_epoch=1,
|
| 382 |
+
validation_steps=1,
|
| 383 |
+
shuffle=False,
|
| 384 |
+
)
|
| 385 |
+
val_loss2 = history2.history["val_loss"][0]
|
| 386 |
+
self.assertTrue(np.allclose(val_loss1, val_loss2, atol=1e-2, rtol=1e-3))
|
| 387 |
+
|
| 388 |
+
def check_pt_tf_outputs(self, tf_outputs, pt_outputs, model_class, tol=2e-4, name="outputs", attributes=None):
|
| 389 |
+
# We override with a slightly higher tol value, as semseg models tend to diverge a bit more
|
| 390 |
+
super().check_pt_tf_outputs(tf_outputs, pt_outputs, model_class, tol, name, attributes)
|
| 391 |
+
|
| 392 |
+
# Overriding this method since the base method won't be compatible with Data2VecVision.
|
| 393 |
+
def test_loss_computation(self):
|
| 394 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 395 |
+
for model_class in self.all_model_classes:
|
| 396 |
+
# Since `TFData2VecVisionModel` won't have labels against which we
|
| 397 |
+
# could compute loss.
|
| 398 |
+
if model_class.__name__ != "TFData2VecVisionModel":
|
| 399 |
+
model = model_class(config)
|
| 400 |
+
if getattr(model, "hf_compute_loss", None):
|
| 401 |
+
# The number of elements in the loss should be the same as the number of elements in the label
|
| 402 |
+
_, prepared_for_class = self.model_tester.prepare_config_and_inputs_for_keras_fit()
|
| 403 |
+
added_label = prepared_for_class[
|
| 404 |
+
sorted(prepared_for_class.keys() - inputs_dict.keys(), reverse=True)[0]
|
| 405 |
+
]
|
| 406 |
+
loss_size = tf.size(added_label)
|
| 407 |
+
|
| 408 |
+
# Test that model correctly compute the loss with kwargs
|
| 409 |
+
possible_input_names = {"input_ids", "pixel_values", "input_features"}
|
| 410 |
+
input_name = possible_input_names.intersection(set(prepared_for_class)).pop()
|
| 411 |
+
model_input = prepared_for_class.pop(input_name)
|
| 412 |
+
|
| 413 |
+
loss = model(model_input, **prepared_for_class)[0]
|
| 414 |
+
self.assertEqual(loss.shape, [loss_size])
|
| 415 |
+
|
| 416 |
+
# Test that model correctly compute the loss with a dict
|
| 417 |
+
_, prepared_for_class = self.model_tester.prepare_config_and_inputs_for_keras_fit()
|
| 418 |
+
loss = model(**prepared_for_class)[0]
|
| 419 |
+
self.assertEqual(loss.shape, [loss_size])
|
| 420 |
+
|
| 421 |
+
# Test that model correctly compute the loss with a tuple
|
| 422 |
+
label_keys = prepared_for_class.keys() - inputs_dict.keys()
|
| 423 |
+
signature = inspect.signature(model.call).parameters
|
| 424 |
+
signature_names = list(signature.keys())
|
| 425 |
+
|
| 426 |
+
# Create a dictionary holding the location of the tensors in the tuple
|
| 427 |
+
tuple_index_mapping = {0: input_name}
|
| 428 |
+
for label_key in label_keys:
|
| 429 |
+
label_key_index = signature_names.index(label_key)
|
| 430 |
+
tuple_index_mapping[label_key_index] = label_key
|
| 431 |
+
sorted_tuple_index_mapping = sorted(tuple_index_mapping.items())
|
| 432 |
+
# Initialize a list with their default values, update the values and convert to a tuple
|
| 433 |
+
list_input = []
|
| 434 |
+
|
| 435 |
+
for name in signature_names:
|
| 436 |
+
if name != "kwargs":
|
| 437 |
+
list_input.append(signature[name].default)
|
| 438 |
+
|
| 439 |
+
for index, value in sorted_tuple_index_mapping:
|
| 440 |
+
list_input[index] = prepared_for_class[value]
|
| 441 |
+
|
| 442 |
+
tuple_input = tuple(list_input)
|
| 443 |
+
|
| 444 |
+
# Send to model
|
| 445 |
+
loss = model(tuple_input[:-1])[0]
|
| 446 |
+
|
| 447 |
+
self.assertEqual(loss.shape, [loss_size])
|
| 448 |
+
|
| 449 |
+
def test_for_image_classification(self):
|
| 450 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 451 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 452 |
+
|
| 453 |
+
@slow
|
| 454 |
+
def test_model_from_pretrained(self):
|
| 455 |
+
model_name = "facebook/data2vec-vision-base-ft1k"
|
| 456 |
+
model = TFData2VecVisionModel.from_pretrained(model_name)
|
| 457 |
+
self.assertIsNotNone(model)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
# We will verify our results on an image of cute cats
|
| 461 |
+
def prepare_img():
|
| 462 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 463 |
+
return image
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
@require_tf
|
| 467 |
+
@require_vision
|
| 468 |
+
class TFData2VecVisionModelIntegrationTest(unittest.TestCase):
|
| 469 |
+
@cached_property
|
| 470 |
+
def default_image_processor(self):
|
| 471 |
+
return (
|
| 472 |
+
BeitImageProcessor.from_pretrained("facebook/data2vec-vision-base-ft1k") if is_vision_available() else None
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
@slow
|
| 476 |
+
def test_inference_image_classification_head_imagenet_1k(self):
|
| 477 |
+
model = TFData2VecVisionForImageClassification.from_pretrained("facebook/data2vec-vision-base-ft1k")
|
| 478 |
+
|
| 479 |
+
image_processor = self.default_image_processor
|
| 480 |
+
image = prepare_img()
|
| 481 |
+
inputs = image_processor(images=image, return_tensors="tf")
|
| 482 |
+
|
| 483 |
+
# forward pass
|
| 484 |
+
outputs = model(**inputs)
|
| 485 |
+
logits = outputs.logits
|
| 486 |
+
|
| 487 |
+
# verify the logits
|
| 488 |
+
expected_shape = tf.convert_to_tensor([1, 1000])
|
| 489 |
+
self.assertEqual(logits.shape, expected_shape)
|
| 490 |
+
|
| 491 |
+
expected_slice = tf.convert_to_tensor([0.3277, -0.1395, 0.0911])
|
| 492 |
+
|
| 493 |
+
tf.debugging.assert_near(logits[0, :3], expected_slice, atol=1e-4)
|
| 494 |
+
|
| 495 |
+
expected_top2 = [model.config.label2id[i] for i in ["remote control, remote", "tabby, tabby cat"]]
|
| 496 |
+
self.assertEqual(tf.nn.top_k(outputs.logits[0], 2).indices.numpy().tolist(), expected_top2)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dbrx/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dbrx/test_modeling_dbrx.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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Face Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch DBRX model."""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import DbrxConfig, is_torch_available
|
| 20 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 21 |
+
|
| 22 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import DbrxForCausalLM, DbrxModel
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DbrxModelTester:
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
parent,
|
| 38 |
+
hidden_size=32,
|
| 39 |
+
ffn_hidden_size=32,
|
| 40 |
+
num_attention_heads=4,
|
| 41 |
+
kv_n_heads=4,
|
| 42 |
+
num_hidden_layers=5,
|
| 43 |
+
max_position_embeddings=512,
|
| 44 |
+
type_vocab_size=16,
|
| 45 |
+
batch_size=13,
|
| 46 |
+
seq_length=7,
|
| 47 |
+
is_training=True,
|
| 48 |
+
use_input_mask=True,
|
| 49 |
+
use_token_type_ids=False,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
use_cache=True,
|
| 52 |
+
type_sequence_label_size=2,
|
| 53 |
+
num_labels=3,
|
| 54 |
+
num_choices=4,
|
| 55 |
+
scope=None,
|
| 56 |
+
clip_qkv=8,
|
| 57 |
+
rope_theta=500000,
|
| 58 |
+
attn_config_model_type="",
|
| 59 |
+
emb_pdrop=0.0,
|
| 60 |
+
moe_jitter_eps=0,
|
| 61 |
+
moe_loss_weight=0.05,
|
| 62 |
+
moe_num_experts=16,
|
| 63 |
+
moe_top_k=4,
|
| 64 |
+
ffn_config_model_type="",
|
| 65 |
+
ffn_act_fn_name="gelu",
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
output_router_logits=False,
|
| 68 |
+
resid_pdrop=0.0,
|
| 69 |
+
tie_word_embeddings=False,
|
| 70 |
+
torch_dtype="bfloat16",
|
| 71 |
+
vocab_size=99,
|
| 72 |
+
is_decoder=True,
|
| 73 |
+
pad_token_id=0,
|
| 74 |
+
):
|
| 75 |
+
# Parameters unique to testing
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.seq_length = seq_length
|
| 78 |
+
self.type_vocab_size = type_vocab_size
|
| 79 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 80 |
+
self.num_labels = num_labels
|
| 81 |
+
self.num_choices = num_choices
|
| 82 |
+
self.scope = scope
|
| 83 |
+
self.parent = parent
|
| 84 |
+
self.is_training = is_training
|
| 85 |
+
self.use_input_mask = use_input_mask
|
| 86 |
+
self.use_token_type_ids = use_token_type_ids
|
| 87 |
+
self.use_labels = use_labels
|
| 88 |
+
|
| 89 |
+
# attn_config params
|
| 90 |
+
self.clip_qkv = clip_qkv
|
| 91 |
+
self.kv_n_heads = kv_n_heads
|
| 92 |
+
self.rope_theta = rope_theta
|
| 93 |
+
self.attn_config_model_type = attn_config_model_type
|
| 94 |
+
|
| 95 |
+
# ffn_config params
|
| 96 |
+
self.ffn_hidden_size = ffn_hidden_size
|
| 97 |
+
self.moe_jitter_eps = moe_jitter_eps
|
| 98 |
+
self.moe_loss_weight = moe_loss_weight
|
| 99 |
+
self.moe_num_experts = moe_num_experts
|
| 100 |
+
self.moe_top_k = moe_top_k
|
| 101 |
+
self.ffn_config_model_type = ffn_config_model_type
|
| 102 |
+
self.ffn_act_fn_name = ffn_act_fn_name
|
| 103 |
+
|
| 104 |
+
# Other model params
|
| 105 |
+
self.hidden_size = hidden_size
|
| 106 |
+
self.num_hidden_layers = num_hidden_layers
|
| 107 |
+
self.num_attention_heads = num_attention_heads
|
| 108 |
+
self.max_position_embeddings = max_position_embeddings
|
| 109 |
+
self.vocab_size = vocab_size
|
| 110 |
+
self.use_cache = use_cache
|
| 111 |
+
self.initializer_range = initializer_range
|
| 112 |
+
self.emb_pdrop = emb_pdrop
|
| 113 |
+
self.output_router_logits = output_router_logits
|
| 114 |
+
self.resid_pdrop = resid_pdrop
|
| 115 |
+
self.tie_word_embeddings = tie_word_embeddings
|
| 116 |
+
self.torch_dtype = torch_dtype
|
| 117 |
+
self.is_decoder = is_decoder
|
| 118 |
+
self.pad_token_id = pad_token_id
|
| 119 |
+
|
| 120 |
+
# Make the dictionaries
|
| 121 |
+
self.ffn_config = {
|
| 122 |
+
"ffn_hidden_size": self.ffn_hidden_size,
|
| 123 |
+
"moe_jitter_eps": self.moe_jitter_eps,
|
| 124 |
+
"moe_loss_weight": self.moe_loss_weight,
|
| 125 |
+
"moe_num_experts": self.moe_num_experts,
|
| 126 |
+
"moe_top_k": self.moe_top_k,
|
| 127 |
+
"model_type": self.ffn_config_model_type,
|
| 128 |
+
"ffn_act_fn": {"name": self.ffn_act_fn_name},
|
| 129 |
+
}
|
| 130 |
+
self.attn_config = {
|
| 131 |
+
"clip_qkv": self.clip_qkv,
|
| 132 |
+
"kv_n_heads": self.kv_n_heads,
|
| 133 |
+
"model_type": self.attn_config_model_type,
|
| 134 |
+
"rope_theta": self.rope_theta,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
def prepare_config_and_inputs(self):
|
| 138 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 139 |
+
|
| 140 |
+
input_mask = None
|
| 141 |
+
if self.use_input_mask:
|
| 142 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 143 |
+
|
| 144 |
+
token_type_ids = None
|
| 145 |
+
if self.use_token_type_ids:
|
| 146 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 147 |
+
|
| 148 |
+
sequence_labels = None
|
| 149 |
+
token_labels = None
|
| 150 |
+
choice_labels = None
|
| 151 |
+
if self.use_labels:
|
| 152 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 153 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 154 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 155 |
+
|
| 156 |
+
config = self.get_config()
|
| 157 |
+
|
| 158 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 159 |
+
|
| 160 |
+
def get_config(self):
|
| 161 |
+
# Behind the scenes, `DbrxConfig` maps the parameters `hidden_size`, `num_hidden_layers`,
|
| 162 |
+
# `num_attention_heads`, `max_position_embeddings` to the parameters `d_model`, `n_layers`,
|
| 163 |
+
# `n_heads`, `max_seq_len` respectively. We use the first group of parameters because
|
| 164 |
+
# other tests expect every model to have these parameters with these specific names.
|
| 165 |
+
config = DbrxConfig(
|
| 166 |
+
vocab_size=self.vocab_size,
|
| 167 |
+
hidden_size=self.hidden_size, # mapped to `d_model`
|
| 168 |
+
num_hidden_layers=self.num_hidden_layers, # mapped to `n_layers`
|
| 169 |
+
num_attention_heads=self.num_attention_heads, # mapped to `n_heads`
|
| 170 |
+
max_position_embeddings=self.max_position_embeddings, # mapped to `max_seq_len`
|
| 171 |
+
attn_config=self.attn_config,
|
| 172 |
+
ffn_config=self.ffn_config,
|
| 173 |
+
resid_pdrop=self.resid_pdrop,
|
| 174 |
+
emb_pdrop=self.emb_pdrop,
|
| 175 |
+
use_cache=self.use_cache,
|
| 176 |
+
initializer_range=self.initializer_range,
|
| 177 |
+
output_router_logits=self.output_router_logits,
|
| 178 |
+
is_decoder=self.is_decoder,
|
| 179 |
+
pad_token_id=self.pad_token_id,
|
| 180 |
+
)
|
| 181 |
+
return config
|
| 182 |
+
|
| 183 |
+
# Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model with Llama->Dbrx
|
| 184 |
+
def create_and_check_model(
|
| 185 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 186 |
+
):
|
| 187 |
+
model = DbrxModel(config=config)
|
| 188 |
+
model.to(torch_device)
|
| 189 |
+
model.eval()
|
| 190 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 191 |
+
result = model(input_ids)
|
| 192 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 193 |
+
|
| 194 |
+
# Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model_as_decoder with Llama->Dbrx
|
| 195 |
+
def create_and_check_model_as_decoder(
|
| 196 |
+
self,
|
| 197 |
+
config,
|
| 198 |
+
input_ids,
|
| 199 |
+
token_type_ids,
|
| 200 |
+
input_mask,
|
| 201 |
+
sequence_labels,
|
| 202 |
+
token_labels,
|
| 203 |
+
choice_labels,
|
| 204 |
+
encoder_hidden_states,
|
| 205 |
+
encoder_attention_mask,
|
| 206 |
+
):
|
| 207 |
+
config.add_cross_attention = True
|
| 208 |
+
model = DbrxModel(config)
|
| 209 |
+
model.to(torch_device)
|
| 210 |
+
model.eval()
|
| 211 |
+
result = model(
|
| 212 |
+
input_ids,
|
| 213 |
+
attention_mask=input_mask,
|
| 214 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 215 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 216 |
+
)
|
| 217 |
+
result = model(
|
| 218 |
+
input_ids,
|
| 219 |
+
attention_mask=input_mask,
|
| 220 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 221 |
+
)
|
| 222 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 223 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 224 |
+
|
| 225 |
+
# Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_for_causal_lm with Llama->Dbrx
|
| 226 |
+
def create_and_check_for_causal_lm(
|
| 227 |
+
self,
|
| 228 |
+
config,
|
| 229 |
+
input_ids,
|
| 230 |
+
token_type_ids,
|
| 231 |
+
input_mask,
|
| 232 |
+
sequence_labels,
|
| 233 |
+
token_labels,
|
| 234 |
+
choice_labels,
|
| 235 |
+
encoder_hidden_states,
|
| 236 |
+
encoder_attention_mask,
|
| 237 |
+
):
|
| 238 |
+
model = DbrxForCausalLM(config=config)
|
| 239 |
+
model.to(torch_device)
|
| 240 |
+
model.eval()
|
| 241 |
+
result = model(input_ids, attention_mask=input_mask, labels=token_labels)
|
| 242 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 243 |
+
|
| 244 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 245 |
+
self,
|
| 246 |
+
config,
|
| 247 |
+
input_ids,
|
| 248 |
+
token_type_ids,
|
| 249 |
+
input_mask,
|
| 250 |
+
sequence_labels,
|
| 251 |
+
token_labels,
|
| 252 |
+
choice_labels,
|
| 253 |
+
encoder_hidden_states,
|
| 254 |
+
encoder_attention_mask,
|
| 255 |
+
):
|
| 256 |
+
config.is_decoder = True
|
| 257 |
+
config.add_cross_attention = True
|
| 258 |
+
model = DbrxForCausalLM(config=config)
|
| 259 |
+
model.to(torch_device)
|
| 260 |
+
model.eval()
|
| 261 |
+
|
| 262 |
+
# first forward pass
|
| 263 |
+
outputs = model(
|
| 264 |
+
input_ids,
|
| 265 |
+
attention_mask=input_mask,
|
| 266 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 267 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 268 |
+
use_cache=True,
|
| 269 |
+
)
|
| 270 |
+
past_key_values = outputs.past_key_values
|
| 271 |
+
|
| 272 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 273 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 274 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 275 |
+
|
| 276 |
+
# append to next input_ids and
|
| 277 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 278 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 279 |
+
|
| 280 |
+
output_from_no_past = model(
|
| 281 |
+
next_input_ids,
|
| 282 |
+
attention_mask=next_attention_mask,
|
| 283 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 284 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 285 |
+
output_hidden_states=True,
|
| 286 |
+
)["hidden_states"][0]
|
| 287 |
+
output_from_past = model(
|
| 288 |
+
next_tokens,
|
| 289 |
+
attention_mask=next_attention_mask,
|
| 290 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 291 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 292 |
+
past_key_values=past_key_values,
|
| 293 |
+
output_hidden_states=True,
|
| 294 |
+
)["hidden_states"][0]
|
| 295 |
+
|
| 296 |
+
# select random slice
|
| 297 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 298 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 299 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 300 |
+
|
| 301 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 302 |
+
|
| 303 |
+
# test that outputs are equal for slice
|
| 304 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 305 |
+
|
| 306 |
+
# Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs_for_common with Llama->Dbrx
|
| 307 |
+
def prepare_config_and_inputs_for_common(self):
|
| 308 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 309 |
+
(
|
| 310 |
+
config,
|
| 311 |
+
input_ids,
|
| 312 |
+
token_type_ids,
|
| 313 |
+
input_mask,
|
| 314 |
+
sequence_labels,
|
| 315 |
+
token_labels,
|
| 316 |
+
choice_labels,
|
| 317 |
+
) = config_and_inputs
|
| 318 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 319 |
+
return config, inputs_dict
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
@require_torch
|
| 323 |
+
class DbrxModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 324 |
+
all_model_classes = (DbrxModel, DbrxForCausalLM) if is_torch_available() else ()
|
| 325 |
+
all_generative_model_classes = (DbrxForCausalLM,) if is_torch_available() else ()
|
| 326 |
+
pipeline_model_mapping = {"text-generation": DbrxForCausalLM} if is_torch_available() else {}
|
| 327 |
+
test_headmasking = False
|
| 328 |
+
test_pruning = False
|
| 329 |
+
|
| 330 |
+
def setUp(self):
|
| 331 |
+
self.model_tester = DbrxModelTester(self)
|
| 332 |
+
self.config_tester = ConfigTester(self, config_class=DbrxConfig, d_model=37)
|
| 333 |
+
|
| 334 |
+
def test_config(self):
|
| 335 |
+
self.config_tester.run_common_tests()
|
| 336 |
+
|
| 337 |
+
def test_model(self):
|
| 338 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 339 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 340 |
+
|
| 341 |
+
def test_model_various_embeddings(self):
|
| 342 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 343 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 344 |
+
config_and_inputs[0].position_embedding_type = type
|
| 345 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 346 |
+
|
| 347 |
+
@slow
|
| 348 |
+
def test_model_from_pretrained(self):
|
| 349 |
+
model_name = "eitanturok/dbrx-tiny"
|
| 350 |
+
model = DbrxModel.from_pretrained(model_name)
|
| 351 |
+
self.assertIsNotNone(model)
|
| 352 |
+
|
| 353 |
+
@unittest.skip(reason="Dbrx models have weight tying disabled.")
|
| 354 |
+
def test_tied_weights_keys(self):
|
| 355 |
+
pass
|
| 356 |
+
|
| 357 |
+
# Offload does not work with Dbrx models because of the forward of DbrxExperts where we chunk the experts.
|
| 358 |
+
# The issue is that the offloaded weights of the mlp layer are still on meta device (w1_chunked, v1_chunked, w2_chunked)
|
| 359 |
+
@unittest.skip(reason="Dbrx models do not work with offload")
|
| 360 |
+
def test_cpu_offload(self):
|
| 361 |
+
pass
|
| 362 |
+
|
| 363 |
+
@unittest.skip(reason="Dbrx models do not work with offload")
|
| 364 |
+
def test_disk_offload_safetensors(self):
|
| 365 |
+
pass
|
| 366 |
+
|
| 367 |
+
@unittest.skip(reason="Dbrx models do not work with offload")
|
| 368 |
+
def test_disk_offload_bin(self):
|
| 369 |
+
pass
|
| 370 |
+
|
| 371 |
+
@unittest.skip("Dbrx does not support `torch.compile` with `fullgraph=True`.")
|
| 372 |
+
def test_generate_compile_model_forward(self):
|
| 373 |
+
pass
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
@require_torch
|
| 377 |
+
class DbrxModelIntegrationTest(unittest.TestCase):
|
| 378 |
+
@slow
|
| 379 |
+
def test_tiny_model_logits(self):
|
| 380 |
+
model = DbrxForCausalLM.from_pretrained("Rocketknight1/dbrx-tiny-random")
|
| 381 |
+
input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
|
| 382 |
+
output = model(input_ids)[0]
|
| 383 |
+
vocab_size = model.vocab_size
|
| 384 |
+
|
| 385 |
+
expected_shape = torch.Size((1, 6, vocab_size))
|
| 386 |
+
self.assertEqual(output.shape, expected_shape)
|
| 387 |
+
|
| 388 |
+
expected_slice = torch.tensor(
|
| 389 |
+
[
|
| 390 |
+
[
|
| 391 |
+
[-1.6300e-04, 5.0118e-04, 2.5437e-04],
|
| 392 |
+
[2.0422e-05, 2.7210e-04, -1.5125e-04],
|
| 393 |
+
[-1.5105e-04, 4.6879e-04, 3.3309e-04],
|
| 394 |
+
]
|
| 395 |
+
]
|
| 396 |
+
)
|
| 397 |
+
self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_modeling_deberta.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Microsoft Authors and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
from transformers import DebertaConfig, is_torch_available
|
| 18 |
+
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
|
| 19 |
+
|
| 20 |
+
from ...test_configuration_common import ConfigTester
|
| 21 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor
|
| 22 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_torch_available():
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
from transformers import (
|
| 29 |
+
DebertaForMaskedLM,
|
| 30 |
+
DebertaForQuestionAnswering,
|
| 31 |
+
DebertaForSequenceClassification,
|
| 32 |
+
DebertaForTokenClassification,
|
| 33 |
+
DebertaModel,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class DebertaModelTester:
|
| 38 |
+
def __init__(
|
| 39 |
+
self,
|
| 40 |
+
parent,
|
| 41 |
+
batch_size=13,
|
| 42 |
+
seq_length=7,
|
| 43 |
+
is_training=True,
|
| 44 |
+
use_input_mask=True,
|
| 45 |
+
use_token_type_ids=True,
|
| 46 |
+
use_labels=True,
|
| 47 |
+
vocab_size=99,
|
| 48 |
+
hidden_size=32,
|
| 49 |
+
num_hidden_layers=2,
|
| 50 |
+
num_attention_heads=4,
|
| 51 |
+
intermediate_size=37,
|
| 52 |
+
hidden_act="gelu",
|
| 53 |
+
hidden_dropout_prob=0.1,
|
| 54 |
+
attention_probs_dropout_prob=0.1,
|
| 55 |
+
max_position_embeddings=512,
|
| 56 |
+
type_vocab_size=16,
|
| 57 |
+
type_sequence_label_size=2,
|
| 58 |
+
initializer_range=0.02,
|
| 59 |
+
relative_attention=False,
|
| 60 |
+
position_biased_input=True,
|
| 61 |
+
pos_att_type="None",
|
| 62 |
+
num_labels=3,
|
| 63 |
+
num_choices=4,
|
| 64 |
+
scope=None,
|
| 65 |
+
):
|
| 66 |
+
self.parent = parent
|
| 67 |
+
self.batch_size = batch_size
|
| 68 |
+
self.seq_length = seq_length
|
| 69 |
+
self.is_training = is_training
|
| 70 |
+
self.use_input_mask = use_input_mask
|
| 71 |
+
self.use_token_type_ids = use_token_type_ids
|
| 72 |
+
self.use_labels = use_labels
|
| 73 |
+
self.vocab_size = vocab_size
|
| 74 |
+
self.hidden_size = hidden_size
|
| 75 |
+
self.num_hidden_layers = num_hidden_layers
|
| 76 |
+
self.num_attention_heads = num_attention_heads
|
| 77 |
+
self.intermediate_size = intermediate_size
|
| 78 |
+
self.hidden_act = hidden_act
|
| 79 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 80 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 81 |
+
self.max_position_embeddings = max_position_embeddings
|
| 82 |
+
self.type_vocab_size = type_vocab_size
|
| 83 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 84 |
+
self.initializer_range = initializer_range
|
| 85 |
+
self.num_labels = num_labels
|
| 86 |
+
self.num_choices = num_choices
|
| 87 |
+
self.relative_attention = relative_attention
|
| 88 |
+
self.position_biased_input = position_biased_input
|
| 89 |
+
self.pos_att_type = pos_att_type
|
| 90 |
+
self.scope = scope
|
| 91 |
+
|
| 92 |
+
def prepare_config_and_inputs(self):
|
| 93 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 94 |
+
|
| 95 |
+
input_mask = None
|
| 96 |
+
if self.use_input_mask:
|
| 97 |
+
input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 98 |
+
|
| 99 |
+
token_type_ids = None
|
| 100 |
+
if self.use_token_type_ids:
|
| 101 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 102 |
+
|
| 103 |
+
sequence_labels = None
|
| 104 |
+
token_labels = None
|
| 105 |
+
choice_labels = None
|
| 106 |
+
if self.use_labels:
|
| 107 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 108 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 109 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 110 |
+
|
| 111 |
+
config = self.get_config()
|
| 112 |
+
|
| 113 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 114 |
+
|
| 115 |
+
def get_config(self):
|
| 116 |
+
return DebertaConfig(
|
| 117 |
+
vocab_size=self.vocab_size,
|
| 118 |
+
hidden_size=self.hidden_size,
|
| 119 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 120 |
+
num_attention_heads=self.num_attention_heads,
|
| 121 |
+
intermediate_size=self.intermediate_size,
|
| 122 |
+
hidden_act=self.hidden_act,
|
| 123 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 124 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 125 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 126 |
+
type_vocab_size=self.type_vocab_size,
|
| 127 |
+
initializer_range=self.initializer_range,
|
| 128 |
+
relative_attention=self.relative_attention,
|
| 129 |
+
position_biased_input=self.position_biased_input,
|
| 130 |
+
pos_att_type=self.pos_att_type,
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
def get_pipeline_config(self):
|
| 134 |
+
config = self.get_config()
|
| 135 |
+
config.vocab_size = 300
|
| 136 |
+
return config
|
| 137 |
+
|
| 138 |
+
def check_loss_output(self, result):
|
| 139 |
+
self.parent.assertListEqual(list(result.loss.size()), [])
|
| 140 |
+
|
| 141 |
+
def create_and_check_deberta_model(
|
| 142 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 143 |
+
):
|
| 144 |
+
model = DebertaModel(config=config)
|
| 145 |
+
model.to(torch_device)
|
| 146 |
+
model.eval()
|
| 147 |
+
sequence_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)[0]
|
| 148 |
+
sequence_output = model(input_ids, token_type_ids=token_type_ids)[0]
|
| 149 |
+
sequence_output = model(input_ids)[0]
|
| 150 |
+
|
| 151 |
+
self.parent.assertListEqual(list(sequence_output.size()), [self.batch_size, self.seq_length, self.hidden_size])
|
| 152 |
+
|
| 153 |
+
def create_and_check_deberta_for_masked_lm(
|
| 154 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 155 |
+
):
|
| 156 |
+
model = DebertaForMaskedLM(config=config)
|
| 157 |
+
model.to(torch_device)
|
| 158 |
+
model.eval()
|
| 159 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 160 |
+
|
| 161 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 162 |
+
|
| 163 |
+
def create_and_check_deberta_for_sequence_classification(
|
| 164 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 165 |
+
):
|
| 166 |
+
config.num_labels = self.num_labels
|
| 167 |
+
model = DebertaForSequenceClassification(config)
|
| 168 |
+
model.to(torch_device)
|
| 169 |
+
model.eval()
|
| 170 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
|
| 171 |
+
self.parent.assertListEqual(list(result.logits.size()), [self.batch_size, self.num_labels])
|
| 172 |
+
self.check_loss_output(result)
|
| 173 |
+
|
| 174 |
+
def create_and_check_deberta_for_token_classification(
|
| 175 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 176 |
+
):
|
| 177 |
+
config.num_labels = self.num_labels
|
| 178 |
+
model = DebertaForTokenClassification(config=config)
|
| 179 |
+
model.to(torch_device)
|
| 180 |
+
model.eval()
|
| 181 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 182 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 183 |
+
|
| 184 |
+
def create_and_check_deberta_for_question_answering(
|
| 185 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 186 |
+
):
|
| 187 |
+
model = DebertaForQuestionAnswering(config=config)
|
| 188 |
+
model.to(torch_device)
|
| 189 |
+
model.eval()
|
| 190 |
+
result = model(
|
| 191 |
+
input_ids,
|
| 192 |
+
attention_mask=input_mask,
|
| 193 |
+
token_type_ids=token_type_ids,
|
| 194 |
+
start_positions=sequence_labels,
|
| 195 |
+
end_positions=sequence_labels,
|
| 196 |
+
)
|
| 197 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 198 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 199 |
+
|
| 200 |
+
def prepare_config_and_inputs_for_common(self):
|
| 201 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 202 |
+
(
|
| 203 |
+
config,
|
| 204 |
+
input_ids,
|
| 205 |
+
token_type_ids,
|
| 206 |
+
input_mask,
|
| 207 |
+
sequence_labels,
|
| 208 |
+
token_labels,
|
| 209 |
+
choice_labels,
|
| 210 |
+
) = config_and_inputs
|
| 211 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 212 |
+
return config, inputs_dict
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
@require_torch
|
| 216 |
+
class DebertaModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 217 |
+
all_model_classes = (
|
| 218 |
+
(
|
| 219 |
+
DebertaModel,
|
| 220 |
+
DebertaForMaskedLM,
|
| 221 |
+
DebertaForSequenceClassification,
|
| 222 |
+
DebertaForTokenClassification,
|
| 223 |
+
DebertaForQuestionAnswering,
|
| 224 |
+
)
|
| 225 |
+
if is_torch_available()
|
| 226 |
+
else ()
|
| 227 |
+
)
|
| 228 |
+
pipeline_model_mapping = (
|
| 229 |
+
{
|
| 230 |
+
"feature-extraction": DebertaModel,
|
| 231 |
+
"fill-mask": DebertaForMaskedLM,
|
| 232 |
+
"question-answering": DebertaForQuestionAnswering,
|
| 233 |
+
"text-classification": DebertaForSequenceClassification,
|
| 234 |
+
"token-classification": DebertaForTokenClassification,
|
| 235 |
+
"zero-shot": DebertaForSequenceClassification,
|
| 236 |
+
}
|
| 237 |
+
if is_torch_available()
|
| 238 |
+
else {}
|
| 239 |
+
)
|
| 240 |
+
|
| 241 |
+
fx_compatible = True
|
| 242 |
+
test_torchscript = False
|
| 243 |
+
test_pruning = False
|
| 244 |
+
test_head_masking = False
|
| 245 |
+
is_encoder_decoder = False
|
| 246 |
+
|
| 247 |
+
def setUp(self):
|
| 248 |
+
self.model_tester = DebertaModelTester(self)
|
| 249 |
+
self.config_tester = ConfigTester(self, config_class=DebertaConfig, hidden_size=37)
|
| 250 |
+
|
| 251 |
+
def test_config(self):
|
| 252 |
+
self.config_tester.run_common_tests()
|
| 253 |
+
|
| 254 |
+
def test_deberta_model(self):
|
| 255 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 256 |
+
self.model_tester.create_and_check_deberta_model(*config_and_inputs)
|
| 257 |
+
|
| 258 |
+
def test_for_sequence_classification(self):
|
| 259 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 260 |
+
self.model_tester.create_and_check_deberta_for_sequence_classification(*config_and_inputs)
|
| 261 |
+
|
| 262 |
+
def test_for_masked_lm(self):
|
| 263 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 264 |
+
self.model_tester.create_and_check_deberta_for_masked_lm(*config_and_inputs)
|
| 265 |
+
|
| 266 |
+
def test_for_question_answering(self):
|
| 267 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 268 |
+
self.model_tester.create_and_check_deberta_for_question_answering(*config_and_inputs)
|
| 269 |
+
|
| 270 |
+
def test_for_token_classification(self):
|
| 271 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 272 |
+
self.model_tester.create_and_check_deberta_for_token_classification(*config_and_inputs)
|
| 273 |
+
|
| 274 |
+
@slow
|
| 275 |
+
def test_model_from_pretrained(self):
|
| 276 |
+
model_name = "microsoft/deberta-base"
|
| 277 |
+
model = DebertaModel.from_pretrained(model_name)
|
| 278 |
+
self.assertIsNotNone(model)
|
| 279 |
+
|
| 280 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 281 |
+
def test_torch_fx_output_loss(self):
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 285 |
+
def test_torch_fx(self):
|
| 286 |
+
pass
|
| 287 |
+
|
| 288 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 289 |
+
def test_pt_tf_model_equivalence(self):
|
| 290 |
+
pass
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
@require_torch
|
| 294 |
+
@require_sentencepiece
|
| 295 |
+
@require_tokenizers
|
| 296 |
+
class DebertaModelIntegrationTest(unittest.TestCase):
|
| 297 |
+
@unittest.skip(reason="Model not available yet")
|
| 298 |
+
def test_inference_masked_lm(self):
|
| 299 |
+
pass
|
| 300 |
+
|
| 301 |
+
@slow
|
| 302 |
+
def test_inference_no_head(self):
|
| 303 |
+
model = DebertaModel.from_pretrained("microsoft/deberta-base")
|
| 304 |
+
|
| 305 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 306 |
+
attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 307 |
+
with torch.no_grad():
|
| 308 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 309 |
+
# compare the actual values for a slice.
|
| 310 |
+
expected_slice = torch.tensor(
|
| 311 |
+
[[[-0.5986, -0.8055, -0.8462], [1.4484, -0.9348, -0.8059], [0.3123, 0.0032, -1.4131]]]
|
| 312 |
+
)
|
| 313 |
+
self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4), f"{output[:, 1:4, 1:4]}")
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_modeling_tf_deberta.py
ADDED
|
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import DebertaConfig, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_tf, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
TFDebertaForMaskedLM,
|
| 34 |
+
TFDebertaForQuestionAnswering,
|
| 35 |
+
TFDebertaForSequenceClassification,
|
| 36 |
+
TFDebertaForTokenClassification,
|
| 37 |
+
TFDebertaModel,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TFDebertaModelTester:
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
parent,
|
| 45 |
+
batch_size=13,
|
| 46 |
+
seq_length=7,
|
| 47 |
+
is_training=True,
|
| 48 |
+
use_input_mask=True,
|
| 49 |
+
use_token_type_ids=True,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
vocab_size=99,
|
| 52 |
+
hidden_size=32,
|
| 53 |
+
num_hidden_layers=2,
|
| 54 |
+
num_attention_heads=4,
|
| 55 |
+
intermediate_size=37,
|
| 56 |
+
hidden_act="gelu",
|
| 57 |
+
hidden_dropout_prob=0.1,
|
| 58 |
+
attention_probs_dropout_prob=0.1,
|
| 59 |
+
max_position_embeddings=512,
|
| 60 |
+
type_vocab_size=16,
|
| 61 |
+
type_sequence_label_size=2,
|
| 62 |
+
initializer_range=0.02,
|
| 63 |
+
num_labels=3,
|
| 64 |
+
num_choices=4,
|
| 65 |
+
scope=None,
|
| 66 |
+
):
|
| 67 |
+
self.parent = parent
|
| 68 |
+
self.batch_size = 13
|
| 69 |
+
self.seq_length = 7
|
| 70 |
+
self.is_training = True
|
| 71 |
+
self.use_input_mask = True
|
| 72 |
+
self.use_token_type_ids = True
|
| 73 |
+
self.use_labels = True
|
| 74 |
+
self.vocab_size = 99
|
| 75 |
+
self.hidden_size = 32
|
| 76 |
+
self.num_hidden_layers = 2
|
| 77 |
+
self.num_attention_heads = 4
|
| 78 |
+
self.intermediate_size = 37
|
| 79 |
+
self.hidden_act = "gelu"
|
| 80 |
+
self.hidden_dropout_prob = 0.1
|
| 81 |
+
self.attention_probs_dropout_prob = 0.1
|
| 82 |
+
self.max_position_embeddings = 512
|
| 83 |
+
self.type_vocab_size = 16
|
| 84 |
+
self.relative_attention = False
|
| 85 |
+
self.max_relative_positions = -1
|
| 86 |
+
self.position_biased_input = True
|
| 87 |
+
self.type_sequence_label_size = 2
|
| 88 |
+
self.initializer_range = 0.02
|
| 89 |
+
self.num_labels = 3
|
| 90 |
+
self.num_choices = 4
|
| 91 |
+
self.scope = None
|
| 92 |
+
|
| 93 |
+
def prepare_config_and_inputs(self):
|
| 94 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 95 |
+
|
| 96 |
+
input_mask = None
|
| 97 |
+
if self.use_input_mask:
|
| 98 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 99 |
+
|
| 100 |
+
token_type_ids = None
|
| 101 |
+
if self.use_token_type_ids:
|
| 102 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 103 |
+
|
| 104 |
+
sequence_labels = None
|
| 105 |
+
token_labels = None
|
| 106 |
+
choice_labels = None
|
| 107 |
+
if self.use_labels:
|
| 108 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 109 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 110 |
+
|
| 111 |
+
config = DebertaConfig(
|
| 112 |
+
vocab_size=self.vocab_size,
|
| 113 |
+
hidden_size=self.hidden_size,
|
| 114 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 115 |
+
num_attention_heads=self.num_attention_heads,
|
| 116 |
+
intermediate_size=self.intermediate_size,
|
| 117 |
+
hidden_act=self.hidden_act,
|
| 118 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 119 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 120 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 121 |
+
type_vocab_size=self.type_vocab_size,
|
| 122 |
+
relative_attention=self.relative_attention,
|
| 123 |
+
max_relative_positions=self.max_relative_positions,
|
| 124 |
+
position_biased_input=self.position_biased_input,
|
| 125 |
+
initializer_range=self.initializer_range,
|
| 126 |
+
return_dict=True,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 130 |
+
|
| 131 |
+
def create_and_check_model(
|
| 132 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 133 |
+
):
|
| 134 |
+
model = TFDebertaModel(config=config)
|
| 135 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 136 |
+
|
| 137 |
+
inputs = [input_ids, input_mask]
|
| 138 |
+
result = model(inputs)
|
| 139 |
+
|
| 140 |
+
result = model(input_ids)
|
| 141 |
+
|
| 142 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 143 |
+
|
| 144 |
+
def create_and_check_for_masked_lm(
|
| 145 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 146 |
+
):
|
| 147 |
+
model = TFDebertaForMaskedLM(config=config)
|
| 148 |
+
inputs = {
|
| 149 |
+
"input_ids": input_ids,
|
| 150 |
+
"attention_mask": input_mask,
|
| 151 |
+
"token_type_ids": token_type_ids,
|
| 152 |
+
}
|
| 153 |
+
result = model(inputs)
|
| 154 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 155 |
+
|
| 156 |
+
def create_and_check_for_sequence_classification(
|
| 157 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 158 |
+
):
|
| 159 |
+
config.num_labels = self.num_labels
|
| 160 |
+
model = TFDebertaForSequenceClassification(config=config)
|
| 161 |
+
inputs = {
|
| 162 |
+
"input_ids": input_ids,
|
| 163 |
+
"attention_mask": input_mask,
|
| 164 |
+
"token_type_ids": token_type_ids,
|
| 165 |
+
}
|
| 166 |
+
|
| 167 |
+
result = model(inputs)
|
| 168 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 169 |
+
|
| 170 |
+
def create_and_check_for_token_classification(
|
| 171 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 172 |
+
):
|
| 173 |
+
config.num_labels = self.num_labels
|
| 174 |
+
model = TFDebertaForTokenClassification(config=config)
|
| 175 |
+
inputs = {
|
| 176 |
+
"input_ids": input_ids,
|
| 177 |
+
"attention_mask": input_mask,
|
| 178 |
+
"token_type_ids": token_type_ids,
|
| 179 |
+
}
|
| 180 |
+
result = model(inputs)
|
| 181 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 182 |
+
|
| 183 |
+
def create_and_check_for_question_answering(
|
| 184 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 185 |
+
):
|
| 186 |
+
model = TFDebertaForQuestionAnswering(config=config)
|
| 187 |
+
inputs = {
|
| 188 |
+
"input_ids": input_ids,
|
| 189 |
+
"attention_mask": input_mask,
|
| 190 |
+
"token_type_ids": token_type_ids,
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
result = model(inputs)
|
| 194 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 195 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 196 |
+
|
| 197 |
+
def prepare_config_and_inputs_for_common(self):
|
| 198 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 199 |
+
(
|
| 200 |
+
config,
|
| 201 |
+
input_ids,
|
| 202 |
+
token_type_ids,
|
| 203 |
+
input_mask,
|
| 204 |
+
sequence_labels,
|
| 205 |
+
token_labels,
|
| 206 |
+
choice_labels,
|
| 207 |
+
) = config_and_inputs
|
| 208 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 209 |
+
return config, inputs_dict
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@require_tf
|
| 213 |
+
class TFDebertaModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 214 |
+
all_model_classes = (
|
| 215 |
+
(
|
| 216 |
+
TFDebertaModel,
|
| 217 |
+
TFDebertaForMaskedLM,
|
| 218 |
+
TFDebertaForQuestionAnswering,
|
| 219 |
+
TFDebertaForSequenceClassification,
|
| 220 |
+
TFDebertaForTokenClassification,
|
| 221 |
+
)
|
| 222 |
+
if is_tf_available()
|
| 223 |
+
else ()
|
| 224 |
+
)
|
| 225 |
+
pipeline_model_mapping = (
|
| 226 |
+
{
|
| 227 |
+
"feature-extraction": TFDebertaModel,
|
| 228 |
+
"fill-mask": TFDebertaForMaskedLM,
|
| 229 |
+
"question-answering": TFDebertaForQuestionAnswering,
|
| 230 |
+
"text-classification": TFDebertaForSequenceClassification,
|
| 231 |
+
"token-classification": TFDebertaForTokenClassification,
|
| 232 |
+
"zero-shot": TFDebertaForSequenceClassification,
|
| 233 |
+
}
|
| 234 |
+
if is_tf_available()
|
| 235 |
+
else {}
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
test_head_masking = False
|
| 239 |
+
test_onnx = False
|
| 240 |
+
|
| 241 |
+
def setUp(self):
|
| 242 |
+
self.model_tester = TFDebertaModelTester(self)
|
| 243 |
+
self.config_tester = ConfigTester(self, config_class=DebertaConfig, hidden_size=37)
|
| 244 |
+
|
| 245 |
+
def test_config(self):
|
| 246 |
+
self.config_tester.run_common_tests()
|
| 247 |
+
|
| 248 |
+
def test_model(self):
|
| 249 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 250 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 251 |
+
|
| 252 |
+
def test_for_masked_lm(self):
|
| 253 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 254 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 255 |
+
|
| 256 |
+
def test_for_question_answering(self):
|
| 257 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 258 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 259 |
+
|
| 260 |
+
def test_for_sequence_classification(self):
|
| 261 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 262 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 263 |
+
|
| 264 |
+
def test_for_token_classification(self):
|
| 265 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 266 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 267 |
+
|
| 268 |
+
@slow
|
| 269 |
+
def test_model_from_pretrained(self):
|
| 270 |
+
model = TFDebertaModel.from_pretrained("kamalkraj/deberta-base")
|
| 271 |
+
self.assertIsNotNone(model)
|
| 272 |
+
|
| 273 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 274 |
+
def test_pt_tf_model_equivalence(self):
|
| 275 |
+
pass
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@require_tf
|
| 279 |
+
class TFDeBERTaModelIntegrationTest(unittest.TestCase):
|
| 280 |
+
@unittest.skip(reason="Model not available yet")
|
| 281 |
+
def test_inference_masked_lm(self):
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
@slow
|
| 285 |
+
def test_inference_no_head(self):
|
| 286 |
+
model = TFDebertaModel.from_pretrained("kamalkraj/deberta-base")
|
| 287 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 288 |
+
attention_mask = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 289 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 290 |
+
|
| 291 |
+
expected_slice = tf.constant(
|
| 292 |
+
[
|
| 293 |
+
[
|
| 294 |
+
[-0.59855896, -0.80552566, -0.8462135],
|
| 295 |
+
[1.4484025, -0.93483794, -0.80593085],
|
| 296 |
+
[0.3122741, 0.00316059, -1.4131377],
|
| 297 |
+
]
|
| 298 |
+
]
|
| 299 |
+
)
|
| 300 |
+
tf.debugging.assert_near(output[:, 1:4, 1:4], expected_slice, atol=1e-4)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta/test_tokenization_deberta.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019 Hugging Face inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import DebertaTokenizer, DebertaTokenizerFast
|
| 22 |
+
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
|
| 23 |
+
from transformers.testing_utils import slow
|
| 24 |
+
|
| 25 |
+
from ...test_tokenization_common import TokenizerTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DebertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 29 |
+
from_pretrained_id = "microsoft/deberta-base"
|
| 30 |
+
tokenizer_class = DebertaTokenizer
|
| 31 |
+
test_rust_tokenizer = True
|
| 32 |
+
rust_tokenizer_class = DebertaTokenizerFast
|
| 33 |
+
|
| 34 |
+
def setUp(self):
|
| 35 |
+
super().setUp()
|
| 36 |
+
|
| 37 |
+
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
|
| 38 |
+
vocab = [
|
| 39 |
+
"l",
|
| 40 |
+
"o",
|
| 41 |
+
"w",
|
| 42 |
+
"e",
|
| 43 |
+
"r",
|
| 44 |
+
"s",
|
| 45 |
+
"t",
|
| 46 |
+
"i",
|
| 47 |
+
"d",
|
| 48 |
+
"n",
|
| 49 |
+
"\u0120",
|
| 50 |
+
"\u0120l",
|
| 51 |
+
"\u0120n",
|
| 52 |
+
"\u0120lo",
|
| 53 |
+
"\u0120low",
|
| 54 |
+
"er",
|
| 55 |
+
"\u0120lowest",
|
| 56 |
+
"\u0120newer",
|
| 57 |
+
"\u0120wider",
|
| 58 |
+
"[UNK]",
|
| 59 |
+
]
|
| 60 |
+
vocab_tokens = dict(zip(vocab, range(len(vocab))))
|
| 61 |
+
merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
|
| 62 |
+
self.special_tokens_map = {"unk_token": "[UNK]"}
|
| 63 |
+
|
| 64 |
+
self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
|
| 65 |
+
self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
|
| 66 |
+
with open(self.vocab_file, "w", encoding="utf-8") as fp:
|
| 67 |
+
fp.write(json.dumps(vocab_tokens) + "\n")
|
| 68 |
+
with open(self.merges_file, "w", encoding="utf-8") as fp:
|
| 69 |
+
fp.write("\n".join(merges))
|
| 70 |
+
|
| 71 |
+
def get_tokenizer(self, **kwargs):
|
| 72 |
+
kwargs.update(self.special_tokens_map)
|
| 73 |
+
return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
|
| 74 |
+
|
| 75 |
+
def get_input_output_texts(self, tokenizer):
|
| 76 |
+
input_text = "lower newer"
|
| 77 |
+
output_text = "lower newer"
|
| 78 |
+
return input_text, output_text
|
| 79 |
+
|
| 80 |
+
def test_full_tokenizer(self):
|
| 81 |
+
tokenizer = self.get_tokenizer()
|
| 82 |
+
text = "lower newer"
|
| 83 |
+
bpe_tokens = ["l", "o", "w", "er", "\u0120", "n", "e", "w", "er"]
|
| 84 |
+
tokens = tokenizer.tokenize(text)
|
| 85 |
+
self.assertListEqual(tokens, bpe_tokens)
|
| 86 |
+
|
| 87 |
+
input_tokens = tokens + [tokenizer.unk_token]
|
| 88 |
+
input_bpe_tokens = [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
|
| 89 |
+
self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
|
| 90 |
+
|
| 91 |
+
def test_token_type_ids(self):
|
| 92 |
+
tokenizer = self.get_tokenizer()
|
| 93 |
+
tokd = tokenizer("Hello", "World")
|
| 94 |
+
expected_token_type_ids = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
|
| 95 |
+
self.assertListEqual(tokd["token_type_ids"], expected_token_type_ids)
|
| 96 |
+
|
| 97 |
+
@slow
|
| 98 |
+
def test_sequence_builders(self):
|
| 99 |
+
tokenizer = self.tokenizer_class.from_pretrained("microsoft/deberta-base")
|
| 100 |
+
|
| 101 |
+
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
| 102 |
+
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
| 103 |
+
|
| 104 |
+
encoded_text_from_decode = tokenizer.encode(
|
| 105 |
+
"sequence builders", add_special_tokens=True, add_prefix_space=False
|
| 106 |
+
)
|
| 107 |
+
encoded_pair_from_decode = tokenizer.encode(
|
| 108 |
+
"sequence builders", "multi-sequence build", add_special_tokens=True, add_prefix_space=False
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 112 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 113 |
+
|
| 114 |
+
assert encoded_sentence == encoded_text_from_decode
|
| 115 |
+
assert encoded_pair == encoded_pair_from_decode
|
| 116 |
+
|
| 117 |
+
@slow
|
| 118 |
+
def test_tokenizer_integration(self):
|
| 119 |
+
tokenizer_classes = [self.tokenizer_class]
|
| 120 |
+
if self.test_rust_tokenizer:
|
| 121 |
+
tokenizer_classes.append(self.rust_tokenizer_class)
|
| 122 |
+
|
| 123 |
+
for tokenizer_class in tokenizer_classes:
|
| 124 |
+
tokenizer = tokenizer_class.from_pretrained("microsoft/deberta-base")
|
| 125 |
+
|
| 126 |
+
sequences = [
|
| 127 |
+
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
|
| 128 |
+
"ALBERT incorporates two parameter reduction techniques",
|
| 129 |
+
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
|
| 130 |
+
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
|
| 131 |
+
" vocabulary embedding.",
|
| 132 |
+
]
|
| 133 |
+
|
| 134 |
+
encoding = tokenizer(sequences, padding=True)
|
| 135 |
+
decoded_sequences = [tokenizer.decode(seq, skip_special_tokens=True) for seq in encoding["input_ids"]]
|
| 136 |
+
|
| 137 |
+
# fmt: off
|
| 138 |
+
expected_encoding = {
|
| 139 |
+
'input_ids': [
|
| 140 |
+
[1, 2118, 11126, 565, 35, 83, 25191, 163, 18854, 13, 12156, 12, 16101, 25376, 13807, 9, 22205, 27893, 1635, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 141 |
+
[1, 2118, 11126, 565, 24536, 80, 43797, 4878, 7373, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 142 |
+
[1, 133, 78, 65, 16, 10, 3724, 1538, 33183, 11303, 43797, 1938, 4, 870, 24165, 29105, 5, 739, 32644, 33183, 11303, 36173, 88, 80, 650, 7821, 45940, 6, 52, 2559, 5, 1836, 9, 5, 7397, 13171, 31, 5, 1836, 9, 32644, 33183, 11303, 4, 2]
|
| 143 |
+
],
|
| 144 |
+
'token_type_ids': [
|
| 145 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 146 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 147 |
+
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
| 148 |
+
],
|
| 149 |
+
'attention_mask': [
|
| 150 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 151 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 152 |
+
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
|
| 153 |
+
]
|
| 154 |
+
}
|
| 155 |
+
# fmt: on
|
| 156 |
+
|
| 157 |
+
expected_decoded_sequence = [
|
| 158 |
+
"ALBERT: A Lite BERT for Self-supervised Learning of Language Representations",
|
| 159 |
+
"ALBERT incorporates two parameter reduction techniques",
|
| 160 |
+
"The first one is a factorized embedding parameterization. By decomposing the large vocabulary"
|
| 161 |
+
" embedding matrix into two small matrices, we separate the size of the hidden layers from the size of"
|
| 162 |
+
" vocabulary embedding.",
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
self.assertDictEqual(encoding.data, expected_encoding)
|
| 166 |
+
|
| 167 |
+
for expected, decoded in zip(expected_decoded_sequence, decoded_sequences):
|
| 168 |
+
self.assertEqual(expected, decoded)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_modeling_deberta_v2.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2018 Microsoft Authors and the HuggingFace Inc. team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
from transformers import DebertaV2Config, is_torch_available
|
| 18 |
+
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
|
| 19 |
+
|
| 20 |
+
from ...test_configuration_common import ConfigTester
|
| 21 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor
|
| 22 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_torch_available():
|
| 26 |
+
import torch
|
| 27 |
+
|
| 28 |
+
from transformers import (
|
| 29 |
+
DebertaV2ForMaskedLM,
|
| 30 |
+
DebertaV2ForMultipleChoice,
|
| 31 |
+
DebertaV2ForQuestionAnswering,
|
| 32 |
+
DebertaV2ForSequenceClassification,
|
| 33 |
+
DebertaV2ForTokenClassification,
|
| 34 |
+
DebertaV2Model,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DebertaV2ModelTester:
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parent,
|
| 42 |
+
batch_size=13,
|
| 43 |
+
seq_length=7,
|
| 44 |
+
is_training=True,
|
| 45 |
+
use_input_mask=True,
|
| 46 |
+
use_token_type_ids=True,
|
| 47 |
+
use_labels=True,
|
| 48 |
+
vocab_size=99,
|
| 49 |
+
hidden_size=32,
|
| 50 |
+
num_hidden_layers=2,
|
| 51 |
+
num_attention_heads=4,
|
| 52 |
+
intermediate_size=37,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
hidden_dropout_prob=0.1,
|
| 55 |
+
attention_probs_dropout_prob=0.1,
|
| 56 |
+
max_position_embeddings=512,
|
| 57 |
+
type_vocab_size=16,
|
| 58 |
+
type_sequence_label_size=2,
|
| 59 |
+
initializer_range=0.02,
|
| 60 |
+
relative_attention=False,
|
| 61 |
+
position_biased_input=True,
|
| 62 |
+
pos_att_type="None",
|
| 63 |
+
num_labels=3,
|
| 64 |
+
num_choices=4,
|
| 65 |
+
scope=None,
|
| 66 |
+
):
|
| 67 |
+
self.parent = parent
|
| 68 |
+
self.batch_size = batch_size
|
| 69 |
+
self.seq_length = seq_length
|
| 70 |
+
self.is_training = is_training
|
| 71 |
+
self.use_input_mask = use_input_mask
|
| 72 |
+
self.use_token_type_ids = use_token_type_ids
|
| 73 |
+
self.use_labels = use_labels
|
| 74 |
+
self.vocab_size = vocab_size
|
| 75 |
+
self.hidden_size = hidden_size
|
| 76 |
+
self.num_hidden_layers = num_hidden_layers
|
| 77 |
+
self.num_attention_heads = num_attention_heads
|
| 78 |
+
self.intermediate_size = intermediate_size
|
| 79 |
+
self.hidden_act = hidden_act
|
| 80 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 81 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 82 |
+
self.max_position_embeddings = max_position_embeddings
|
| 83 |
+
self.type_vocab_size = type_vocab_size
|
| 84 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 85 |
+
self.initializer_range = initializer_range
|
| 86 |
+
self.num_labels = num_labels
|
| 87 |
+
self.num_choices = num_choices
|
| 88 |
+
self.relative_attention = relative_attention
|
| 89 |
+
self.position_biased_input = position_biased_input
|
| 90 |
+
self.pos_att_type = pos_att_type
|
| 91 |
+
self.scope = scope
|
| 92 |
+
|
| 93 |
+
def prepare_config_and_inputs(self):
|
| 94 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 95 |
+
|
| 96 |
+
input_mask = None
|
| 97 |
+
if self.use_input_mask:
|
| 98 |
+
input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
|
| 99 |
+
|
| 100 |
+
token_type_ids = None
|
| 101 |
+
if self.use_token_type_ids:
|
| 102 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 103 |
+
|
| 104 |
+
sequence_labels = None
|
| 105 |
+
token_labels = None
|
| 106 |
+
choice_labels = None
|
| 107 |
+
if self.use_labels:
|
| 108 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 109 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 110 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 111 |
+
|
| 112 |
+
config = self.get_config()
|
| 113 |
+
|
| 114 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 115 |
+
|
| 116 |
+
def get_config(self):
|
| 117 |
+
return DebertaV2Config(
|
| 118 |
+
vocab_size=self.vocab_size,
|
| 119 |
+
hidden_size=self.hidden_size,
|
| 120 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 121 |
+
num_attention_heads=self.num_attention_heads,
|
| 122 |
+
intermediate_size=self.intermediate_size,
|
| 123 |
+
hidden_act=self.hidden_act,
|
| 124 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 125 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 126 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 127 |
+
type_vocab_size=self.type_vocab_size,
|
| 128 |
+
initializer_range=self.initializer_range,
|
| 129 |
+
relative_attention=self.relative_attention,
|
| 130 |
+
position_biased_input=self.position_biased_input,
|
| 131 |
+
pos_att_type=self.pos_att_type,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
def check_loss_output(self, result):
|
| 135 |
+
self.parent.assertListEqual(list(result.loss.size()), [])
|
| 136 |
+
|
| 137 |
+
def create_and_check_deberta_model(
|
| 138 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 139 |
+
):
|
| 140 |
+
model = DebertaV2Model(config=config)
|
| 141 |
+
model.to(torch_device)
|
| 142 |
+
model.eval()
|
| 143 |
+
sequence_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)[0]
|
| 144 |
+
sequence_output = model(input_ids, token_type_ids=token_type_ids)[0]
|
| 145 |
+
sequence_output = model(input_ids)[0]
|
| 146 |
+
|
| 147 |
+
self.parent.assertListEqual(list(sequence_output.size()), [self.batch_size, self.seq_length, self.hidden_size])
|
| 148 |
+
|
| 149 |
+
def create_and_check_deberta_for_masked_lm(
|
| 150 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 151 |
+
):
|
| 152 |
+
model = DebertaV2ForMaskedLM(config=config)
|
| 153 |
+
model.to(torch_device)
|
| 154 |
+
model.eval()
|
| 155 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 156 |
+
|
| 157 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 158 |
+
|
| 159 |
+
def create_and_check_deberta_for_sequence_classification(
|
| 160 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 161 |
+
):
|
| 162 |
+
config.num_labels = self.num_labels
|
| 163 |
+
model = DebertaV2ForSequenceClassification(config)
|
| 164 |
+
model.to(torch_device)
|
| 165 |
+
model.eval()
|
| 166 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
|
| 167 |
+
self.parent.assertListEqual(list(result.logits.size()), [self.batch_size, self.num_labels])
|
| 168 |
+
self.check_loss_output(result)
|
| 169 |
+
|
| 170 |
+
def create_and_check_deberta_for_token_classification(
|
| 171 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 172 |
+
):
|
| 173 |
+
config.num_labels = self.num_labels
|
| 174 |
+
model = DebertaV2ForTokenClassification(config=config)
|
| 175 |
+
model.to(torch_device)
|
| 176 |
+
model.eval()
|
| 177 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
|
| 178 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 179 |
+
|
| 180 |
+
def create_and_check_deberta_for_question_answering(
|
| 181 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 182 |
+
):
|
| 183 |
+
model = DebertaV2ForQuestionAnswering(config=config)
|
| 184 |
+
model.to(torch_device)
|
| 185 |
+
model.eval()
|
| 186 |
+
result = model(
|
| 187 |
+
input_ids,
|
| 188 |
+
attention_mask=input_mask,
|
| 189 |
+
token_type_ids=token_type_ids,
|
| 190 |
+
start_positions=sequence_labels,
|
| 191 |
+
end_positions=sequence_labels,
|
| 192 |
+
)
|
| 193 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 194 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 195 |
+
|
| 196 |
+
def create_and_check_deberta_for_multiple_choice(
|
| 197 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 198 |
+
):
|
| 199 |
+
model = DebertaV2ForMultipleChoice(config=config)
|
| 200 |
+
model.to(torch_device)
|
| 201 |
+
model.eval()
|
| 202 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 203 |
+
multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 204 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 205 |
+
result = model(
|
| 206 |
+
multiple_choice_inputs_ids,
|
| 207 |
+
attention_mask=multiple_choice_input_mask,
|
| 208 |
+
token_type_ids=multiple_choice_token_type_ids,
|
| 209 |
+
labels=choice_labels,
|
| 210 |
+
)
|
| 211 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 212 |
+
|
| 213 |
+
def prepare_config_and_inputs_for_common(self):
|
| 214 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 215 |
+
(
|
| 216 |
+
config,
|
| 217 |
+
input_ids,
|
| 218 |
+
token_type_ids,
|
| 219 |
+
input_mask,
|
| 220 |
+
sequence_labels,
|
| 221 |
+
token_labels,
|
| 222 |
+
choice_labels,
|
| 223 |
+
) = config_and_inputs
|
| 224 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 225 |
+
return config, inputs_dict
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
@require_torch
|
| 229 |
+
class DebertaV2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 230 |
+
all_model_classes = (
|
| 231 |
+
(
|
| 232 |
+
DebertaV2Model,
|
| 233 |
+
DebertaV2ForMaskedLM,
|
| 234 |
+
DebertaV2ForSequenceClassification,
|
| 235 |
+
DebertaV2ForTokenClassification,
|
| 236 |
+
DebertaV2ForQuestionAnswering,
|
| 237 |
+
DebertaV2ForMultipleChoice,
|
| 238 |
+
)
|
| 239 |
+
if is_torch_available()
|
| 240 |
+
else ()
|
| 241 |
+
)
|
| 242 |
+
pipeline_model_mapping = (
|
| 243 |
+
{
|
| 244 |
+
"feature-extraction": DebertaV2Model,
|
| 245 |
+
"fill-mask": DebertaV2ForMaskedLM,
|
| 246 |
+
"question-answering": DebertaV2ForQuestionAnswering,
|
| 247 |
+
"text-classification": DebertaV2ForSequenceClassification,
|
| 248 |
+
"token-classification": DebertaV2ForTokenClassification,
|
| 249 |
+
"zero-shot": DebertaV2ForSequenceClassification,
|
| 250 |
+
}
|
| 251 |
+
if is_torch_available()
|
| 252 |
+
else {}
|
| 253 |
+
)
|
| 254 |
+
|
| 255 |
+
fx_compatible = True
|
| 256 |
+
test_torchscript = False
|
| 257 |
+
test_pruning = False
|
| 258 |
+
test_head_masking = False
|
| 259 |
+
is_encoder_decoder = False
|
| 260 |
+
|
| 261 |
+
def setUp(self):
|
| 262 |
+
self.model_tester = DebertaV2ModelTester(self)
|
| 263 |
+
self.config_tester = ConfigTester(self, config_class=DebertaV2Config, hidden_size=37)
|
| 264 |
+
|
| 265 |
+
def test_config(self):
|
| 266 |
+
self.config_tester.run_common_tests()
|
| 267 |
+
|
| 268 |
+
def test_deberta_model(self):
|
| 269 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 270 |
+
self.model_tester.create_and_check_deberta_model(*config_and_inputs)
|
| 271 |
+
|
| 272 |
+
def test_for_sequence_classification(self):
|
| 273 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 274 |
+
self.model_tester.create_and_check_deberta_for_sequence_classification(*config_and_inputs)
|
| 275 |
+
|
| 276 |
+
def test_for_masked_lm(self):
|
| 277 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 278 |
+
self.model_tester.create_and_check_deberta_for_masked_lm(*config_and_inputs)
|
| 279 |
+
|
| 280 |
+
def test_for_question_answering(self):
|
| 281 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 282 |
+
self.model_tester.create_and_check_deberta_for_question_answering(*config_and_inputs)
|
| 283 |
+
|
| 284 |
+
def test_for_token_classification(self):
|
| 285 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 286 |
+
self.model_tester.create_and_check_deberta_for_token_classification(*config_and_inputs)
|
| 287 |
+
|
| 288 |
+
def test_for_multiple_choice(self):
|
| 289 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 290 |
+
self.model_tester.create_and_check_deberta_for_multiple_choice(*config_and_inputs)
|
| 291 |
+
|
| 292 |
+
@slow
|
| 293 |
+
def test_model_from_pretrained(self):
|
| 294 |
+
model_name = "microsoft/deberta-v2-xlarge"
|
| 295 |
+
model = DebertaV2Model.from_pretrained(model_name)
|
| 296 |
+
self.assertIsNotNone(model)
|
| 297 |
+
|
| 298 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 299 |
+
def test_torch_fx_output_loss(self):
|
| 300 |
+
pass
|
| 301 |
+
|
| 302 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 303 |
+
def test_torch_fx(self):
|
| 304 |
+
pass
|
| 305 |
+
|
| 306 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 307 |
+
def test_pt_tf_model_equivalence(self):
|
| 308 |
+
pass
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
@require_torch
|
| 312 |
+
@require_sentencepiece
|
| 313 |
+
@require_tokenizers
|
| 314 |
+
class DebertaV2ModelIntegrationTest(unittest.TestCase):
|
| 315 |
+
@unittest.skip(reason="Model not available yet")
|
| 316 |
+
def test_inference_masked_lm(self):
|
| 317 |
+
pass
|
| 318 |
+
|
| 319 |
+
@slow
|
| 320 |
+
def test_inference_no_head(self):
|
| 321 |
+
model = DebertaV2Model.from_pretrained("microsoft/deberta-v2-xlarge")
|
| 322 |
+
|
| 323 |
+
input_ids = torch.tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 324 |
+
attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 325 |
+
with torch.no_grad():
|
| 326 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 327 |
+
# compare the actual values for a slice.
|
| 328 |
+
expected_slice = torch.tensor(
|
| 329 |
+
[[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]
|
| 330 |
+
)
|
| 331 |
+
self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4), f"{output[:, 1:4, 1:4]}")
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_modeling_tf_deberta_v2.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import DebertaV2Config, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_tf, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
TFDebertaV2ForMaskedLM,
|
| 34 |
+
TFDebertaV2ForMultipleChoice,
|
| 35 |
+
TFDebertaV2ForQuestionAnswering,
|
| 36 |
+
TFDebertaV2ForSequenceClassification,
|
| 37 |
+
TFDebertaV2ForTokenClassification,
|
| 38 |
+
TFDebertaV2Model,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TFDebertaV2ModelTester:
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
parent,
|
| 46 |
+
batch_size=13,
|
| 47 |
+
seq_length=7,
|
| 48 |
+
is_training=True,
|
| 49 |
+
use_input_mask=True,
|
| 50 |
+
use_token_type_ids=True,
|
| 51 |
+
use_labels=True,
|
| 52 |
+
vocab_size=99,
|
| 53 |
+
hidden_size=32,
|
| 54 |
+
num_hidden_layers=2,
|
| 55 |
+
num_attention_heads=4,
|
| 56 |
+
intermediate_size=37,
|
| 57 |
+
hidden_act="gelu",
|
| 58 |
+
hidden_dropout_prob=0.1,
|
| 59 |
+
attention_probs_dropout_prob=0.1,
|
| 60 |
+
max_position_embeddings=512,
|
| 61 |
+
type_vocab_size=16,
|
| 62 |
+
type_sequence_label_size=2,
|
| 63 |
+
initializer_range=0.02,
|
| 64 |
+
relative_attention=False,
|
| 65 |
+
position_biased_input=True,
|
| 66 |
+
pos_att_type="None",
|
| 67 |
+
num_labels=3,
|
| 68 |
+
num_choices=4,
|
| 69 |
+
scope=None,
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = batch_size
|
| 73 |
+
self.seq_length = seq_length
|
| 74 |
+
self.is_training = is_training
|
| 75 |
+
self.use_input_mask = use_input_mask
|
| 76 |
+
self.use_token_type_ids = use_token_type_ids
|
| 77 |
+
self.use_labels = use_labels
|
| 78 |
+
self.vocab_size = vocab_size
|
| 79 |
+
self.hidden_size = hidden_size
|
| 80 |
+
self.num_hidden_layers = num_hidden_layers
|
| 81 |
+
self.num_attention_heads = num_attention_heads
|
| 82 |
+
self.intermediate_size = intermediate_size
|
| 83 |
+
self.hidden_act = hidden_act
|
| 84 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 85 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 86 |
+
self.max_position_embeddings = max_position_embeddings
|
| 87 |
+
self.type_vocab_size = type_vocab_size
|
| 88 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.num_labels = num_labels
|
| 91 |
+
self.num_choices = num_choices
|
| 92 |
+
self.relative_attention = relative_attention
|
| 93 |
+
self.position_biased_input = position_biased_input
|
| 94 |
+
self.pos_att_type = pos_att_type
|
| 95 |
+
self.scope = scope
|
| 96 |
+
|
| 97 |
+
def prepare_config_and_inputs(self):
|
| 98 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 99 |
+
|
| 100 |
+
input_mask = None
|
| 101 |
+
if self.use_input_mask:
|
| 102 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 103 |
+
|
| 104 |
+
token_type_ids = None
|
| 105 |
+
if self.use_token_type_ids:
|
| 106 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 107 |
+
|
| 108 |
+
sequence_labels = None
|
| 109 |
+
token_labels = None
|
| 110 |
+
choice_labels = None
|
| 111 |
+
if self.use_labels:
|
| 112 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 113 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 114 |
+
|
| 115 |
+
config = DebertaV2Config(
|
| 116 |
+
vocab_size=self.vocab_size,
|
| 117 |
+
hidden_size=self.hidden_size,
|
| 118 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 119 |
+
num_attention_heads=self.num_attention_heads,
|
| 120 |
+
intermediate_size=self.intermediate_size,
|
| 121 |
+
hidden_act=self.hidden_act,
|
| 122 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 123 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 124 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 125 |
+
type_vocab_size=self.type_vocab_size,
|
| 126 |
+
relative_attention=self.relative_attention,
|
| 127 |
+
position_biased_input=self.position_biased_input,
|
| 128 |
+
initializer_range=self.initializer_range,
|
| 129 |
+
return_dict=True,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 133 |
+
|
| 134 |
+
def create_and_check_model(
|
| 135 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 136 |
+
):
|
| 137 |
+
model = TFDebertaV2Model(config=config)
|
| 138 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
|
| 139 |
+
|
| 140 |
+
inputs = [input_ids, input_mask]
|
| 141 |
+
result = model(inputs)
|
| 142 |
+
|
| 143 |
+
result = model(input_ids)
|
| 144 |
+
|
| 145 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 146 |
+
|
| 147 |
+
def create_and_check_for_masked_lm(
|
| 148 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 149 |
+
):
|
| 150 |
+
model = TFDebertaV2ForMaskedLM(config=config)
|
| 151 |
+
inputs = {
|
| 152 |
+
"input_ids": input_ids,
|
| 153 |
+
"attention_mask": input_mask,
|
| 154 |
+
"token_type_ids": token_type_ids,
|
| 155 |
+
}
|
| 156 |
+
result = model(inputs)
|
| 157 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 158 |
+
|
| 159 |
+
def create_and_check_for_sequence_classification(
|
| 160 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 161 |
+
):
|
| 162 |
+
config.num_labels = self.num_labels
|
| 163 |
+
model = TFDebertaV2ForSequenceClassification(config=config)
|
| 164 |
+
inputs = {
|
| 165 |
+
"input_ids": input_ids,
|
| 166 |
+
"attention_mask": input_mask,
|
| 167 |
+
"token_type_ids": token_type_ids,
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
result = model(inputs)
|
| 171 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 172 |
+
|
| 173 |
+
def create_and_check_for_token_classification(
|
| 174 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 175 |
+
):
|
| 176 |
+
config.num_labels = self.num_labels
|
| 177 |
+
model = TFDebertaV2ForTokenClassification(config=config)
|
| 178 |
+
inputs = {
|
| 179 |
+
"input_ids": input_ids,
|
| 180 |
+
"attention_mask": input_mask,
|
| 181 |
+
"token_type_ids": token_type_ids,
|
| 182 |
+
}
|
| 183 |
+
result = model(inputs)
|
| 184 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 185 |
+
|
| 186 |
+
def create_and_check_for_question_answering(
|
| 187 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 188 |
+
):
|
| 189 |
+
model = TFDebertaV2ForQuestionAnswering(config=config)
|
| 190 |
+
inputs = {
|
| 191 |
+
"input_ids": input_ids,
|
| 192 |
+
"attention_mask": input_mask,
|
| 193 |
+
"token_type_ids": token_type_ids,
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
result = model(inputs)
|
| 197 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 198 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 199 |
+
|
| 200 |
+
def create_and_check_for_multiple_choice(
|
| 201 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 202 |
+
):
|
| 203 |
+
config.num_choices = self.num_choices
|
| 204 |
+
model = TFDebertaV2ForMultipleChoice(config=config)
|
| 205 |
+
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
|
| 206 |
+
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
|
| 207 |
+
multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
|
| 208 |
+
inputs = {
|
| 209 |
+
"input_ids": multiple_choice_inputs_ids,
|
| 210 |
+
"attention_mask": multiple_choice_input_mask,
|
| 211 |
+
"token_type_ids": multiple_choice_token_type_ids,
|
| 212 |
+
}
|
| 213 |
+
result = model(inputs)
|
| 214 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 215 |
+
|
| 216 |
+
def prepare_config_and_inputs_for_common(self):
|
| 217 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 218 |
+
(
|
| 219 |
+
config,
|
| 220 |
+
input_ids,
|
| 221 |
+
token_type_ids,
|
| 222 |
+
input_mask,
|
| 223 |
+
sequence_labels,
|
| 224 |
+
token_labels,
|
| 225 |
+
choice_labels,
|
| 226 |
+
) = config_and_inputs
|
| 227 |
+
inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
|
| 228 |
+
return config, inputs_dict
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
@require_tf
|
| 232 |
+
class TFDebertaModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 233 |
+
all_model_classes = (
|
| 234 |
+
(
|
| 235 |
+
TFDebertaV2Model,
|
| 236 |
+
TFDebertaV2ForMaskedLM,
|
| 237 |
+
TFDebertaV2ForQuestionAnswering,
|
| 238 |
+
TFDebertaV2ForMultipleChoice,
|
| 239 |
+
TFDebertaV2ForSequenceClassification,
|
| 240 |
+
TFDebertaV2ForTokenClassification,
|
| 241 |
+
)
|
| 242 |
+
if is_tf_available()
|
| 243 |
+
else ()
|
| 244 |
+
)
|
| 245 |
+
pipeline_model_mapping = (
|
| 246 |
+
{
|
| 247 |
+
"feature-extraction": TFDebertaV2Model,
|
| 248 |
+
"fill-mask": TFDebertaV2ForMaskedLM,
|
| 249 |
+
"question-answering": TFDebertaV2ForQuestionAnswering,
|
| 250 |
+
"text-classification": TFDebertaV2ForSequenceClassification,
|
| 251 |
+
"token-classification": TFDebertaV2ForTokenClassification,
|
| 252 |
+
"zero-shot": TFDebertaV2ForSequenceClassification,
|
| 253 |
+
}
|
| 254 |
+
if is_tf_available()
|
| 255 |
+
else {}
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
test_head_masking = False
|
| 259 |
+
test_onnx = False
|
| 260 |
+
|
| 261 |
+
def setUp(self):
|
| 262 |
+
self.model_tester = TFDebertaV2ModelTester(self)
|
| 263 |
+
self.config_tester = ConfigTester(self, config_class=DebertaV2Config, hidden_size=37)
|
| 264 |
+
|
| 265 |
+
def test_config(self):
|
| 266 |
+
self.config_tester.run_common_tests()
|
| 267 |
+
|
| 268 |
+
def test_model(self):
|
| 269 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 270 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 271 |
+
|
| 272 |
+
def test_for_masked_lm(self):
|
| 273 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 274 |
+
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
|
| 275 |
+
|
| 276 |
+
def test_for_question_answering(self):
|
| 277 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 278 |
+
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
|
| 279 |
+
|
| 280 |
+
def test_for_sequence_classification(self):
|
| 281 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 282 |
+
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
|
| 283 |
+
|
| 284 |
+
def test_for_token_classification(self):
|
| 285 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 286 |
+
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
|
| 287 |
+
|
| 288 |
+
@slow
|
| 289 |
+
def test_model_from_pretrained(self):
|
| 290 |
+
model = TFDebertaV2Model.from_pretrained("kamalkraj/deberta-v2-xlarge")
|
| 291 |
+
self.assertIsNotNone(model)
|
| 292 |
+
|
| 293 |
+
@unittest.skip("This test was broken by the refactor in #22105, TODO @ArthurZucker")
|
| 294 |
+
def test_pt_tf_model_equivalence(self):
|
| 295 |
+
pass
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@require_tf
|
| 299 |
+
class TFDeBERTaV2ModelIntegrationTest(unittest.TestCase):
|
| 300 |
+
@unittest.skip(reason="Model not available yet")
|
| 301 |
+
def test_inference_masked_lm(self):
|
| 302 |
+
pass
|
| 303 |
+
|
| 304 |
+
@slow
|
| 305 |
+
def test_inference_no_head(self):
|
| 306 |
+
model = TFDebertaV2Model.from_pretrained("kamalkraj/deberta-v2-xlarge")
|
| 307 |
+
input_ids = tf.constant([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
|
| 308 |
+
attention_mask = tf.constant([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 309 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 310 |
+
|
| 311 |
+
expected_slice = tf.constant(
|
| 312 |
+
[[[0.2356, 0.1948, 0.0369], [-0.1063, 0.3586, -0.5152], [-0.6399, -0.0259, -0.2525]]]
|
| 313 |
+
)
|
| 314 |
+
tf.debugging.assert_near(output[:, 1:4, 1:4], expected_slice, atol=1e-4)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deberta_v2/test_tokenization_deberta_v2.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019 Hugging Face inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
from transformers import DebertaV2Tokenizer, DebertaV2TokenizerFast
|
| 19 |
+
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
|
| 20 |
+
|
| 21 |
+
from ...test_tokenization_common import TokenizerTesterMixin
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
SAMPLE_VOCAB = get_tests_dir("fixtures/spiece.model")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@require_sentencepiece
|
| 28 |
+
@require_tokenizers
|
| 29 |
+
class DebertaV2TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
|
| 30 |
+
from_pretrained_id = "microsoft/deberta-v2-xlarge"
|
| 31 |
+
tokenizer_class = DebertaV2Tokenizer
|
| 32 |
+
rust_tokenizer_class = DebertaV2TokenizerFast
|
| 33 |
+
test_sentencepiece = True
|
| 34 |
+
test_sentencepiece_ignore_case = True
|
| 35 |
+
|
| 36 |
+
def setUp(self):
|
| 37 |
+
super().setUp()
|
| 38 |
+
|
| 39 |
+
# We have a SentencePiece fixture for testing
|
| 40 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>")
|
| 41 |
+
tokenizer.save_pretrained(self.tmpdirname)
|
| 42 |
+
|
| 43 |
+
def get_input_output_texts(self, tokenizer):
|
| 44 |
+
input_text = "this is a test"
|
| 45 |
+
output_text = "this is a test"
|
| 46 |
+
return input_text, output_text
|
| 47 |
+
|
| 48 |
+
def test_convert_token_and_id(self):
|
| 49 |
+
"""Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
|
| 50 |
+
token = "<pad>"
|
| 51 |
+
token_id = 0
|
| 52 |
+
|
| 53 |
+
self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id)
|
| 54 |
+
self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
|
| 55 |
+
|
| 56 |
+
def test_get_vocab(self):
|
| 57 |
+
vocab_keys = list(self.get_tokenizer().get_vocab().keys())
|
| 58 |
+
self.assertEqual(vocab_keys[0], "<pad>")
|
| 59 |
+
self.assertEqual(vocab_keys[1], "<unk>")
|
| 60 |
+
self.assertEqual(vocab_keys[-1], "[PAD]")
|
| 61 |
+
self.assertEqual(len(vocab_keys), 30_001)
|
| 62 |
+
|
| 63 |
+
def test_vocab_size(self):
|
| 64 |
+
self.assertEqual(self.get_tokenizer().vocab_size, 30_000)
|
| 65 |
+
|
| 66 |
+
def test_do_lower_case(self):
|
| 67 |
+
# fmt: off
|
| 68 |
+
sequence = " \tHeLLo!how \n Are yoU? "
|
| 69 |
+
tokens_target = ["▁hello", "!", "how", "▁are", "▁you", "?"]
|
| 70 |
+
# fmt: on
|
| 71 |
+
|
| 72 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True)
|
| 73 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 74 |
+
|
| 75 |
+
self.assertListEqual(tokens, tokens_target)
|
| 76 |
+
|
| 77 |
+
rust_tokenizer = DebertaV2TokenizerFast(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True)
|
| 78 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 79 |
+
|
| 80 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 81 |
+
|
| 82 |
+
@unittest.skip(reason="There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.")
|
| 83 |
+
def test_sentencepiece_tokenize_and_convert_tokens_to_string(self):
|
| 84 |
+
pass
|
| 85 |
+
|
| 86 |
+
@unittest.skip(reason="There is an inconsistency between slow and fast tokenizer due to a bug in the fast one.")
|
| 87 |
+
def test_sentencepiece_tokenize_and_decode(self):
|
| 88 |
+
pass
|
| 89 |
+
|
| 90 |
+
def test_split_by_punct(self):
|
| 91 |
+
# fmt: off
|
| 92 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 93 |
+
tokens_target = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", "!", ]
|
| 94 |
+
# fmt: on
|
| 95 |
+
|
| 96 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", split_by_punct=True)
|
| 97 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 98 |
+
|
| 99 |
+
self.assertListEqual(tokens, tokens_target)
|
| 100 |
+
|
| 101 |
+
rust_tokenizer = DebertaV2TokenizerFast(SAMPLE_VOCAB, unk_token="<unk>", split_by_punct=True)
|
| 102 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 103 |
+
|
| 104 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 105 |
+
|
| 106 |
+
def test_do_lower_case_split_by_punct(self):
|
| 107 |
+
# fmt: off
|
| 108 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 109 |
+
tokens_target = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", "!", ]
|
| 110 |
+
# fmt: on
|
| 111 |
+
|
| 112 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True, split_by_punct=True)
|
| 113 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 114 |
+
self.assertListEqual(tokens, tokens_target)
|
| 115 |
+
|
| 116 |
+
rust_tokenizer = DebertaV2TokenizerFast(
|
| 117 |
+
SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True, split_by_punct=True
|
| 118 |
+
)
|
| 119 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 120 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 121 |
+
|
| 122 |
+
def test_do_lower_case_split_by_punct_false(self):
|
| 123 |
+
# fmt: off
|
| 124 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 125 |
+
tokens_target = ["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "!", ]
|
| 126 |
+
# fmt: on
|
| 127 |
+
|
| 128 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True, split_by_punct=False)
|
| 129 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 130 |
+
|
| 131 |
+
self.assertListEqual(tokens, tokens_target)
|
| 132 |
+
|
| 133 |
+
rust_tokenizer = DebertaV2TokenizerFast(
|
| 134 |
+
SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=True, split_by_punct=False
|
| 135 |
+
)
|
| 136 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 137 |
+
|
| 138 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 139 |
+
|
| 140 |
+
def test_do_lower_case_false_split_by_punct(self):
|
| 141 |
+
# fmt: off
|
| 142 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 143 |
+
tokens_target = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", "▁", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "▁", "!", ]
|
| 144 |
+
# fmt: on
|
| 145 |
+
|
| 146 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=False, split_by_punct=True)
|
| 147 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 148 |
+
|
| 149 |
+
self.assertListEqual(tokens, tokens_target)
|
| 150 |
+
|
| 151 |
+
rust_tokenizer = DebertaV2TokenizerFast(
|
| 152 |
+
SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=False, split_by_punct=True
|
| 153 |
+
)
|
| 154 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 155 |
+
|
| 156 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 157 |
+
|
| 158 |
+
def test_do_lower_case_false_split_by_punct_false(self):
|
| 159 |
+
# fmt: off
|
| 160 |
+
sequence = " \tHeLLo!how \n Are yoU? "
|
| 161 |
+
tokens_target = ["▁", "<unk>", "e", "<unk>", "o", "!", "how", "▁", "<unk>", "re", "▁yo", "<unk>", "?"]
|
| 162 |
+
# fmt: on
|
| 163 |
+
|
| 164 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=False, split_by_punct=False)
|
| 165 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 166 |
+
|
| 167 |
+
self.assertListEqual(tokens, tokens_target)
|
| 168 |
+
|
| 169 |
+
rust_tokenizer = DebertaV2TokenizerFast(
|
| 170 |
+
SAMPLE_VOCAB, unk_token="<unk>", do_lower_case=False, split_by_punct=False
|
| 171 |
+
)
|
| 172 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 173 |
+
|
| 174 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 175 |
+
|
| 176 |
+
def test_rust_and_python_full_tokenizers(self):
|
| 177 |
+
tokenizer = self.get_tokenizer()
|
| 178 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 179 |
+
|
| 180 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 181 |
+
|
| 182 |
+
tokens = tokenizer.convert_ids_to_tokens(tokenizer.encode(sequence, add_special_tokens=False))
|
| 183 |
+
rust_tokens = rust_tokenizer.convert_ids_to_tokens(rust_tokenizer.encode(sequence, add_special_tokens=False))
|
| 184 |
+
self.assertListEqual(tokens, rust_tokens)
|
| 185 |
+
|
| 186 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 187 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 188 |
+
self.assertListEqual(ids, rust_ids)
|
| 189 |
+
|
| 190 |
+
rust_tokenizer = self.get_rust_tokenizer()
|
| 191 |
+
ids = tokenizer.encode(sequence)
|
| 192 |
+
rust_ids = rust_tokenizer.encode(sequence)
|
| 193 |
+
self.assertListEqual(ids, rust_ids)
|
| 194 |
+
|
| 195 |
+
def test_full_tokenizer(self):
|
| 196 |
+
sequence = "This is a test"
|
| 197 |
+
ids_target = [13, 1, 4398, 25, 21, 1289]
|
| 198 |
+
tokens_target = ["▁", "T", "his", "▁is", "▁a", "▁test"]
|
| 199 |
+
back_tokens_target = ["▁", "<unk>", "his", "▁is", "▁a", "▁test"]
|
| 200 |
+
|
| 201 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB, unk_token="<unk>", keep_accents=True)
|
| 202 |
+
rust_tokenizer = DebertaV2TokenizerFast(SAMPLE_VOCAB, unk_token="<unk>", keep_accents=True)
|
| 203 |
+
|
| 204 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 205 |
+
self.assertListEqual(ids, ids_target)
|
| 206 |
+
tokens = tokenizer.tokenize(sequence)
|
| 207 |
+
self.assertListEqual(tokens, tokens_target)
|
| 208 |
+
back_tokens = tokenizer.convert_ids_to_tokens(ids)
|
| 209 |
+
self.assertListEqual(back_tokens, back_tokens_target)
|
| 210 |
+
|
| 211 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 212 |
+
self.assertListEqual(rust_ids, ids_target)
|
| 213 |
+
rust_tokens = rust_tokenizer.tokenize(sequence)
|
| 214 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 215 |
+
rust_back_tokens = rust_tokenizer.convert_ids_to_tokens(rust_ids)
|
| 216 |
+
self.assertListEqual(rust_back_tokens, back_tokens_target)
|
| 217 |
+
|
| 218 |
+
# fmt: off
|
| 219 |
+
sequence = "I was born in 92000, and this is falsé!"
|
| 220 |
+
ids_target = [13, 1, 23, 386, 19, 561, 3050, 15, 17, 48, 25, 8256, 18, 1, 187]
|
| 221 |
+
tokens_target = ["▁", "I", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "!", ]
|
| 222 |
+
back_tokens_target = ["▁", "<unk>", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "!", ]
|
| 223 |
+
# fmt: on
|
| 224 |
+
|
| 225 |
+
ids = tokenizer.encode(sequence, add_special_tokens=False)
|
| 226 |
+
self.assertListEqual(ids, ids_target)
|
| 227 |
+
tokens = tokenizer.tokenize(sequence)
|
| 228 |
+
self.assertListEqual(tokens, tokens_target)
|
| 229 |
+
back_tokens = tokenizer.convert_ids_to_tokens(ids)
|
| 230 |
+
self.assertListEqual(back_tokens, back_tokens_target)
|
| 231 |
+
|
| 232 |
+
rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
|
| 233 |
+
self.assertListEqual(rust_ids, ids_target)
|
| 234 |
+
rust_tokens = rust_tokenizer.tokenize(sequence)
|
| 235 |
+
self.assertListEqual(rust_tokens, tokens_target)
|
| 236 |
+
rust_back_tokens = rust_tokenizer.convert_ids_to_tokens(rust_ids)
|
| 237 |
+
self.assertListEqual(rust_back_tokens, back_tokens_target)
|
| 238 |
+
|
| 239 |
+
def test_sequence_builders(self):
|
| 240 |
+
tokenizer = DebertaV2Tokenizer(SAMPLE_VOCAB)
|
| 241 |
+
|
| 242 |
+
text = tokenizer.encode("sequence builders")
|
| 243 |
+
text_2 = tokenizer.encode("multi-sequence build")
|
| 244 |
+
|
| 245 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 246 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 247 |
+
|
| 248 |
+
self.assertEqual([tokenizer.cls_token_id] + text + [tokenizer.sep_token_id], encoded_sentence)
|
| 249 |
+
self.assertEqual(
|
| 250 |
+
[tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [tokenizer.sep_token_id],
|
| 251 |
+
encoded_pair,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
@slow
|
| 255 |
+
def test_tokenizer_integration(self):
|
| 256 |
+
expected_encoding = {'input_ids': [[1, 39867, 36, 19390, 486, 27, 35052, 81436, 18, 60685, 1225, 7, 35052, 81436, 18, 9367, 16899, 18, 15937, 53, 594, 773, 18, 16287, 30465, 36, 15937, 6, 41139, 38, 36979, 60763, 191, 6, 34132, 99, 6, 50538, 390, 43230, 6, 34132, 2779, 20850, 14, 699, 1072, 1194, 36, 382, 10901, 53, 7, 699, 1072, 2084, 36, 20422, 630, 53, 19, 105, 3049, 1896, 1053, 16899, 1506, 11, 37978, 4243, 7, 1237, 31869, 200, 16566, 654, 6, 35052, 81436, 7, 55630, 13593, 4, 2], [1, 26, 15011, 13, 667, 8, 1053, 18, 23611, 1237, 72356, 12820, 34, 104134, 1209, 35, 13313, 6627, 21, 202, 347, 7, 164, 2399, 11, 46, 4485, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 5, 1232, 2864, 15785, 14951, 105, 5, 8581, 1250, 4, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0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 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip
|
| 257 |
+
|
| 258 |
+
self.tokenizer_integration_test_util(
|
| 259 |
+
expected_encoding=expected_encoding,
|
| 260 |
+
model_name="microsoft/deberta-v2-xlarge",
|
| 261 |
+
revision="ad6e42c1532ddf3a15c39246b63f5559d558b670",
|
| 262 |
+
)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/decision_transformer/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/decision_transformer/test_modeling_decision_transformer.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch DecisionTransformer model."""
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import DecisionTransformerConfig, is_torch_available
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
|
| 23 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from transformers import DecisionTransformerModel
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class DecisionTransformerModelTester:
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
parent,
|
| 39 |
+
batch_size=13,
|
| 40 |
+
seq_length=7,
|
| 41 |
+
act_dim=6,
|
| 42 |
+
state_dim=17,
|
| 43 |
+
hidden_size=23,
|
| 44 |
+
is_training=True,
|
| 45 |
+
):
|
| 46 |
+
self.parent = parent
|
| 47 |
+
self.batch_size = batch_size
|
| 48 |
+
self.seq_length = seq_length
|
| 49 |
+
self.act_dim = act_dim
|
| 50 |
+
self.state_dim = state_dim
|
| 51 |
+
self.hidden_size = hidden_size
|
| 52 |
+
self.is_training = is_training
|
| 53 |
+
|
| 54 |
+
def prepare_config_and_inputs(self):
|
| 55 |
+
states = floats_tensor((self.batch_size, self.seq_length, self.state_dim))
|
| 56 |
+
actions = floats_tensor((self.batch_size, self.seq_length, self.act_dim))
|
| 57 |
+
rewards = floats_tensor((self.batch_size, self.seq_length, 1))
|
| 58 |
+
returns_to_go = floats_tensor((self.batch_size, self.seq_length, 1))
|
| 59 |
+
timesteps = ids_tensor((self.batch_size, self.seq_length), vocab_size=1000)
|
| 60 |
+
attention_mask = random_attention_mask((self.batch_size, self.seq_length))
|
| 61 |
+
|
| 62 |
+
config = self.get_config()
|
| 63 |
+
|
| 64 |
+
return (
|
| 65 |
+
config,
|
| 66 |
+
states,
|
| 67 |
+
actions,
|
| 68 |
+
rewards,
|
| 69 |
+
returns_to_go,
|
| 70 |
+
timesteps,
|
| 71 |
+
attention_mask,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def get_config(self):
|
| 75 |
+
return DecisionTransformerConfig(
|
| 76 |
+
batch_size=self.batch_size,
|
| 77 |
+
seq_length=self.seq_length,
|
| 78 |
+
act_dim=self.act_dim,
|
| 79 |
+
state_dim=self.state_dim,
|
| 80 |
+
hidden_size=self.hidden_size,
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
def create_and_check_model(
|
| 84 |
+
self,
|
| 85 |
+
config,
|
| 86 |
+
states,
|
| 87 |
+
actions,
|
| 88 |
+
rewards,
|
| 89 |
+
returns_to_go,
|
| 90 |
+
timesteps,
|
| 91 |
+
attention_mask,
|
| 92 |
+
):
|
| 93 |
+
model = DecisionTransformerModel(config=config)
|
| 94 |
+
model.to(torch_device)
|
| 95 |
+
model.eval()
|
| 96 |
+
result = model(states, actions, rewards, returns_to_go, timesteps, attention_mask)
|
| 97 |
+
|
| 98 |
+
self.parent.assertEqual(result.state_preds.shape, states.shape)
|
| 99 |
+
self.parent.assertEqual(result.action_preds.shape, actions.shape)
|
| 100 |
+
self.parent.assertEqual(result.return_preds.shape, returns_to_go.shape)
|
| 101 |
+
self.parent.assertEqual(
|
| 102 |
+
result.last_hidden_state.shape, (self.batch_size, self.seq_length * 3, self.hidden_size)
|
| 103 |
+
) # seq length *3 as there are 3 modelities: states, returns and actions
|
| 104 |
+
|
| 105 |
+
def prepare_config_and_inputs_for_common(self):
|
| 106 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 107 |
+
(
|
| 108 |
+
config,
|
| 109 |
+
states,
|
| 110 |
+
actions,
|
| 111 |
+
rewards,
|
| 112 |
+
returns_to_go,
|
| 113 |
+
timesteps,
|
| 114 |
+
attention_mask,
|
| 115 |
+
) = config_and_inputs
|
| 116 |
+
inputs_dict = {
|
| 117 |
+
"states": states,
|
| 118 |
+
"actions": actions,
|
| 119 |
+
"rewards": rewards,
|
| 120 |
+
"returns_to_go": returns_to_go,
|
| 121 |
+
"timesteps": timesteps,
|
| 122 |
+
"attention_mask": attention_mask,
|
| 123 |
+
}
|
| 124 |
+
return config, inputs_dict
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@require_torch
|
| 128 |
+
class DecisionTransformerModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 129 |
+
all_model_classes = (DecisionTransformerModel,) if is_torch_available() else ()
|
| 130 |
+
all_generative_model_classes = ()
|
| 131 |
+
pipeline_model_mapping = {"feature-extraction": DecisionTransformerModel} if is_torch_available() else {}
|
| 132 |
+
|
| 133 |
+
# Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids
|
| 134 |
+
test_generate_without_input_ids = False
|
| 135 |
+
|
| 136 |
+
# Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features
|
| 137 |
+
test_pruning = False
|
| 138 |
+
test_resize_embeddings = False
|
| 139 |
+
test_head_masking = False
|
| 140 |
+
test_attention_outputs = False
|
| 141 |
+
test_hidden_states_output = False
|
| 142 |
+
test_inputs_embeds = False
|
| 143 |
+
test_gradient_checkpointing = False
|
| 144 |
+
test_torchscript = False
|
| 145 |
+
|
| 146 |
+
def setUp(self):
|
| 147 |
+
self.model_tester = DecisionTransformerModelTester(self)
|
| 148 |
+
self.config_tester = ConfigTester(self, config_class=DecisionTransformerConfig, hidden_size=37)
|
| 149 |
+
|
| 150 |
+
def test_config(self):
|
| 151 |
+
self.config_tester.run_common_tests()
|
| 152 |
+
|
| 153 |
+
def test_model(self):
|
| 154 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 155 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 156 |
+
|
| 157 |
+
@slow
|
| 158 |
+
def test_model_from_pretrained(self):
|
| 159 |
+
model_name = "edbeeching/decision-transformer-gym-hopper-medium"
|
| 160 |
+
model = DecisionTransformerModel.from_pretrained(model_name)
|
| 161 |
+
self.assertIsNotNone(model)
|
| 162 |
+
|
| 163 |
+
def test_forward_signature(self):
|
| 164 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 165 |
+
|
| 166 |
+
for model_class in self.all_model_classes:
|
| 167 |
+
model = model_class(config)
|
| 168 |
+
signature = inspect.signature(model.forward)
|
| 169 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 170 |
+
arg_names = [*signature.parameters.keys()]
|
| 171 |
+
|
| 172 |
+
expected_arg_names = [
|
| 173 |
+
"states",
|
| 174 |
+
"actions",
|
| 175 |
+
"rewards",
|
| 176 |
+
"returns_to_go",
|
| 177 |
+
"timesteps",
|
| 178 |
+
"attention_mask",
|
| 179 |
+
]
|
| 180 |
+
|
| 181 |
+
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
|
| 182 |
+
|
| 183 |
+
@unittest.skip(reason="Model does not have input embeddings")
|
| 184 |
+
def test_model_get_set_embeddings(self):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
@require_torch
|
| 189 |
+
class DecisionTransformerModelIntegrationTest(unittest.TestCase):
|
| 190 |
+
@slow
|
| 191 |
+
def test_autoregressive_prediction(self):
|
| 192 |
+
"""
|
| 193 |
+
An integration test that performs autoregressive prediction of state, action and return
|
| 194 |
+
from a sequence of state, actions and returns. Test is performed over two timesteps.
|
| 195 |
+
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
NUM_STEPS = 2 # number of steps of autoregressive prediction we will perform
|
| 199 |
+
TARGET_RETURN = 10 # defined by the RL environment, may be normalized
|
| 200 |
+
model = DecisionTransformerModel.from_pretrained("edbeeching/decision-transformer-gym-hopper-expert")
|
| 201 |
+
model = model.to(torch_device)
|
| 202 |
+
config = model.config
|
| 203 |
+
torch.manual_seed(0)
|
| 204 |
+
state = torch.randn(1, 1, config.state_dim).to(device=torch_device, dtype=torch.float32) # env.reset()
|
| 205 |
+
|
| 206 |
+
expected_outputs = torch.tensor(
|
| 207 |
+
[[0.242793, -0.28693074, 0.8742613], [0.67815274, -0.08101085, -0.12952147]], device=torch_device
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
returns_to_go = torch.tensor(TARGET_RETURN, device=torch_device, dtype=torch.float32).reshape(1, 1, 1)
|
| 211 |
+
states = state
|
| 212 |
+
actions = torch.zeros(1, 0, config.act_dim, device=torch_device, dtype=torch.float32)
|
| 213 |
+
rewards = torch.zeros(1, 0, device=torch_device, dtype=torch.float32)
|
| 214 |
+
timesteps = torch.tensor(0, device=torch_device, dtype=torch.long).reshape(1, 1)
|
| 215 |
+
|
| 216 |
+
for step in range(NUM_STEPS):
|
| 217 |
+
actions = torch.cat([actions, torch.zeros(1, 1, config.act_dim, device=torch_device)], dim=1)
|
| 218 |
+
rewards = torch.cat([rewards, torch.zeros(1, 1, device=torch_device)], dim=1)
|
| 219 |
+
|
| 220 |
+
attention_mask = torch.ones(1, states.shape[1]).to(dtype=torch.long, device=states.device)
|
| 221 |
+
|
| 222 |
+
with torch.no_grad():
|
| 223 |
+
_, action_pred, _ = model(
|
| 224 |
+
states=states,
|
| 225 |
+
actions=actions,
|
| 226 |
+
rewards=rewards,
|
| 227 |
+
returns_to_go=returns_to_go,
|
| 228 |
+
timesteps=timesteps,
|
| 229 |
+
attention_mask=attention_mask,
|
| 230 |
+
return_dict=False,
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
self.assertEqual(action_pred.shape, actions.shape)
|
| 234 |
+
self.assertTrue(torch.allclose(action_pred[0, -1], expected_outputs[step], atol=1e-4))
|
| 235 |
+
state, reward, _, _ = ( # env.step(action)
|
| 236 |
+
torch.randn(1, 1, config.state_dim).to(device=torch_device, dtype=torch.float32),
|
| 237 |
+
1.0,
|
| 238 |
+
False,
|
| 239 |
+
{},
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
actions[-1] = action_pred[0, -1]
|
| 243 |
+
states = torch.cat([states, state], dim=1)
|
| 244 |
+
pred_return = returns_to_go[0, -1] - reward
|
| 245 |
+
returns_to_go = torch.cat([returns_to_go, pred_return.reshape(1, 1, 1)], dim=1)
|
| 246 |
+
timesteps = torch.cat(
|
| 247 |
+
[timesteps, torch.ones((1, 1), device=torch_device, dtype=torch.long) * (step + 1)], dim=1
|
| 248 |
+
)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/test_image_processing_deformable_detr.py
ADDED
|
@@ -0,0 +1,736 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import pathlib
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from transformers.testing_utils import require_torch, require_torch_gpu, require_vision, slow
|
| 24 |
+
from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
|
| 25 |
+
|
| 26 |
+
from ...test_image_processing_common import AnnotationFormatTestMixin, ImageProcessingTestMixin, prepare_image_inputs
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
if is_vision_available():
|
| 33 |
+
from PIL import Image
|
| 34 |
+
|
| 35 |
+
from transformers import DeformableDetrImageProcessor, DeformableDetrImageProcessorFast
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DeformableDetrImageProcessingTester(unittest.TestCase):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parent,
|
| 42 |
+
batch_size=7,
|
| 43 |
+
num_channels=3,
|
| 44 |
+
min_resolution=30,
|
| 45 |
+
max_resolution=400,
|
| 46 |
+
do_resize=True,
|
| 47 |
+
size=None,
|
| 48 |
+
do_normalize=True,
|
| 49 |
+
image_mean=[0.5, 0.5, 0.5],
|
| 50 |
+
image_std=[0.5, 0.5, 0.5],
|
| 51 |
+
do_rescale=True,
|
| 52 |
+
rescale_factor=1 / 255,
|
| 53 |
+
do_pad=True,
|
| 54 |
+
):
|
| 55 |
+
super().__init__()
|
| 56 |
+
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
|
| 57 |
+
size = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333}
|
| 58 |
+
self.parent = parent
|
| 59 |
+
self.batch_size = batch_size
|
| 60 |
+
self.num_channels = num_channels
|
| 61 |
+
self.min_resolution = min_resolution
|
| 62 |
+
self.max_resolution = max_resolution
|
| 63 |
+
self.do_resize = do_resize
|
| 64 |
+
self.size = size
|
| 65 |
+
self.do_normalize = do_normalize
|
| 66 |
+
self.image_mean = image_mean
|
| 67 |
+
self.image_std = image_std
|
| 68 |
+
self.do_rescale = do_rescale
|
| 69 |
+
self.rescale_factor = rescale_factor
|
| 70 |
+
self.do_pad = do_pad
|
| 71 |
+
|
| 72 |
+
def prepare_image_processor_dict(self):
|
| 73 |
+
return {
|
| 74 |
+
"do_resize": self.do_resize,
|
| 75 |
+
"size": self.size,
|
| 76 |
+
"do_normalize": self.do_normalize,
|
| 77 |
+
"image_mean": self.image_mean,
|
| 78 |
+
"image_std": self.image_std,
|
| 79 |
+
"do_rescale": self.do_rescale,
|
| 80 |
+
"rescale_factor": self.rescale_factor,
|
| 81 |
+
"do_pad": self.do_pad,
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
def get_expected_values(self, image_inputs, batched=False):
|
| 85 |
+
"""
|
| 86 |
+
This function computes the expected height and width when providing images to DeformableDetrImageProcessor,
|
| 87 |
+
assuming do_resize is set to True with a scalar size.
|
| 88 |
+
"""
|
| 89 |
+
if not batched:
|
| 90 |
+
image = image_inputs[0]
|
| 91 |
+
if isinstance(image, Image.Image):
|
| 92 |
+
w, h = image.size
|
| 93 |
+
elif isinstance(image, np.ndarray):
|
| 94 |
+
h, w = image.shape[0], image.shape[1]
|
| 95 |
+
else:
|
| 96 |
+
h, w = image.shape[1], image.shape[2]
|
| 97 |
+
if w < h:
|
| 98 |
+
expected_height = int(self.size["shortest_edge"] * h / w)
|
| 99 |
+
expected_width = self.size["shortest_edge"]
|
| 100 |
+
elif w > h:
|
| 101 |
+
expected_height = self.size["shortest_edge"]
|
| 102 |
+
expected_width = int(self.size["shortest_edge"] * w / h)
|
| 103 |
+
else:
|
| 104 |
+
expected_height = self.size["shortest_edge"]
|
| 105 |
+
expected_width = self.size["shortest_edge"]
|
| 106 |
+
|
| 107 |
+
else:
|
| 108 |
+
expected_values = []
|
| 109 |
+
for image in image_inputs:
|
| 110 |
+
expected_height, expected_width = self.get_expected_values([image])
|
| 111 |
+
expected_values.append((expected_height, expected_width))
|
| 112 |
+
expected_height = max(expected_values, key=lambda item: item[0])[0]
|
| 113 |
+
expected_width = max(expected_values, key=lambda item: item[1])[1]
|
| 114 |
+
|
| 115 |
+
return expected_height, expected_width
|
| 116 |
+
|
| 117 |
+
def expected_output_image_shape(self, images):
|
| 118 |
+
height, width = self.get_expected_values(images, batched=True)
|
| 119 |
+
return self.num_channels, height, width
|
| 120 |
+
|
| 121 |
+
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
| 122 |
+
return prepare_image_inputs(
|
| 123 |
+
batch_size=self.batch_size,
|
| 124 |
+
num_channels=self.num_channels,
|
| 125 |
+
min_resolution=self.min_resolution,
|
| 126 |
+
max_resolution=self.max_resolution,
|
| 127 |
+
equal_resolution=equal_resolution,
|
| 128 |
+
numpify=numpify,
|
| 129 |
+
torchify=torchify,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
@require_torch
|
| 134 |
+
@require_vision
|
| 135 |
+
class DeformableDetrImageProcessingTest(AnnotationFormatTestMixin, ImageProcessingTestMixin, unittest.TestCase):
|
| 136 |
+
image_processing_class = DeformableDetrImageProcessor if is_vision_available() else None
|
| 137 |
+
fast_image_processing_class = DeformableDetrImageProcessorFast if is_torchvision_available() else None
|
| 138 |
+
|
| 139 |
+
def setUp(self):
|
| 140 |
+
super().setUp()
|
| 141 |
+
self.image_processor_tester = DeformableDetrImageProcessingTester(self)
|
| 142 |
+
|
| 143 |
+
@property
|
| 144 |
+
def image_processor_dict(self):
|
| 145 |
+
return self.image_processor_tester.prepare_image_processor_dict()
|
| 146 |
+
|
| 147 |
+
def test_image_processor_properties(self):
|
| 148 |
+
for image_processing_class in self.image_processor_list:
|
| 149 |
+
image_processing = image_processing_class(**self.image_processor_dict)
|
| 150 |
+
self.assertTrue(hasattr(image_processing, "image_mean"))
|
| 151 |
+
self.assertTrue(hasattr(image_processing, "image_std"))
|
| 152 |
+
self.assertTrue(hasattr(image_processing, "do_normalize"))
|
| 153 |
+
self.assertTrue(hasattr(image_processing, "do_resize"))
|
| 154 |
+
self.assertTrue(hasattr(image_processing, "do_rescale"))
|
| 155 |
+
self.assertTrue(hasattr(image_processing, "do_pad"))
|
| 156 |
+
self.assertTrue(hasattr(image_processing, "size"))
|
| 157 |
+
|
| 158 |
+
def test_image_processor_from_dict_with_kwargs(self):
|
| 159 |
+
for image_processing_class in self.image_processor_list:
|
| 160 |
+
image_processor = image_processing_class.from_dict(self.image_processor_dict)
|
| 161 |
+
self.assertEqual(image_processor.size, {"shortest_edge": 18, "longest_edge": 1333})
|
| 162 |
+
self.assertEqual(image_processor.do_pad, True)
|
| 163 |
+
|
| 164 |
+
image_processor = image_processing_class.from_dict(
|
| 165 |
+
self.image_processor_dict, size=42, max_size=84, pad_and_return_pixel_mask=False
|
| 166 |
+
)
|
| 167 |
+
self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84})
|
| 168 |
+
self.assertEqual(image_processor.do_pad, False)
|
| 169 |
+
|
| 170 |
+
@slow
|
| 171 |
+
def test_call_pytorch_with_coco_detection_annotations(self):
|
| 172 |
+
# prepare image and target
|
| 173 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 174 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 175 |
+
target = json.loads(f.read())
|
| 176 |
+
|
| 177 |
+
target = {"image_id": 39769, "annotations": target}
|
| 178 |
+
|
| 179 |
+
for image_processing_class in self.image_processor_list:
|
| 180 |
+
# encode them
|
| 181 |
+
image_processing = image_processing_class()
|
| 182 |
+
encoding = image_processing(images=image, annotations=target, return_tensors="pt")
|
| 183 |
+
|
| 184 |
+
# verify pixel values
|
| 185 |
+
expected_shape = torch.Size([1, 3, 800, 1066])
|
| 186 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 187 |
+
|
| 188 |
+
expected_slice = torch.tensor([0.2796, 0.3138, 0.3481])
|
| 189 |
+
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4))
|
| 190 |
+
|
| 191 |
+
# verify area
|
| 192 |
+
expected_area = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438])
|
| 193 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area))
|
| 194 |
+
# verify boxes
|
| 195 |
+
expected_boxes_shape = torch.Size([6, 4])
|
| 196 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape)
|
| 197 |
+
expected_boxes_slice = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215])
|
| 198 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3))
|
| 199 |
+
# verify image_id
|
| 200 |
+
expected_image_id = torch.tensor([39769])
|
| 201 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id))
|
| 202 |
+
# verify is_crowd
|
| 203 |
+
expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0])
|
| 204 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd))
|
| 205 |
+
# verify class_labels
|
| 206 |
+
expected_class_labels = torch.tensor([75, 75, 63, 65, 17, 17])
|
| 207 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels))
|
| 208 |
+
# verify orig_size
|
| 209 |
+
expected_orig_size = torch.tensor([480, 640])
|
| 210 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size))
|
| 211 |
+
# verify size
|
| 212 |
+
expected_size = torch.tensor([800, 1066])
|
| 213 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size))
|
| 214 |
+
|
| 215 |
+
@slow
|
| 216 |
+
def test_call_pytorch_with_coco_panoptic_annotations(self):
|
| 217 |
+
# prepare image, target and masks_path
|
| 218 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 219 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 220 |
+
target = json.loads(f.read())
|
| 221 |
+
|
| 222 |
+
target = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 223 |
+
|
| 224 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 225 |
+
|
| 226 |
+
for image_processing_class in self.image_processor_list:
|
| 227 |
+
# encode them
|
| 228 |
+
image_processing = image_processing_class(format="coco_panoptic")
|
| 229 |
+
encoding = image_processing(images=image, annotations=target, masks_path=masks_path, return_tensors="pt")
|
| 230 |
+
|
| 231 |
+
# verify pixel values
|
| 232 |
+
expected_shape = torch.Size([1, 3, 800, 1066])
|
| 233 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 234 |
+
|
| 235 |
+
expected_slice = torch.tensor([0.2796, 0.3138, 0.3481])
|
| 236 |
+
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4))
|
| 237 |
+
|
| 238 |
+
# verify area
|
| 239 |
+
expected_area = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147])
|
| 240 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area))
|
| 241 |
+
# verify boxes
|
| 242 |
+
expected_boxes_shape = torch.Size([6, 4])
|
| 243 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape)
|
| 244 |
+
expected_boxes_slice = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625])
|
| 245 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3))
|
| 246 |
+
# verify image_id
|
| 247 |
+
expected_image_id = torch.tensor([39769])
|
| 248 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id))
|
| 249 |
+
# verify is_crowd
|
| 250 |
+
expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0])
|
| 251 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd))
|
| 252 |
+
# verify class_labels
|
| 253 |
+
expected_class_labels = torch.tensor([17, 17, 63, 75, 75, 93])
|
| 254 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels))
|
| 255 |
+
# verify masks
|
| 256 |
+
expected_masks_sum = 822873
|
| 257 |
+
relative_error = torch.abs(encoding["labels"][0]["masks"].sum() - expected_masks_sum) / expected_masks_sum
|
| 258 |
+
self.assertTrue(relative_error < 1e-3)
|
| 259 |
+
# verify orig_size
|
| 260 |
+
expected_orig_size = torch.tensor([480, 640])
|
| 261 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size))
|
| 262 |
+
# verify size
|
| 263 |
+
expected_size = torch.tensor([800, 1066])
|
| 264 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size))
|
| 265 |
+
|
| 266 |
+
@slow
|
| 267 |
+
# Copied from tests.models.detr.test_image_processing_detr.DetrImageProcessingTest.test_batched_coco_detection_annotations with Detr->DeformableDetr
|
| 268 |
+
def test_batched_coco_detection_annotations(self):
|
| 269 |
+
image_0 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 270 |
+
image_1 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png").resize((800, 800))
|
| 271 |
+
|
| 272 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 273 |
+
target = json.loads(f.read())
|
| 274 |
+
|
| 275 |
+
annotations_0 = {"image_id": 39769, "annotations": target}
|
| 276 |
+
annotations_1 = {"image_id": 39769, "annotations": target}
|
| 277 |
+
|
| 278 |
+
# Adjust the bounding boxes for the resized image
|
| 279 |
+
w_0, h_0 = image_0.size
|
| 280 |
+
w_1, h_1 = image_1.size
|
| 281 |
+
for i in range(len(annotations_1["annotations"])):
|
| 282 |
+
coords = annotations_1["annotations"][i]["bbox"]
|
| 283 |
+
new_bbox = [
|
| 284 |
+
coords[0] * w_1 / w_0,
|
| 285 |
+
coords[1] * h_1 / h_0,
|
| 286 |
+
coords[2] * w_1 / w_0,
|
| 287 |
+
coords[3] * h_1 / h_0,
|
| 288 |
+
]
|
| 289 |
+
annotations_1["annotations"][i]["bbox"] = new_bbox
|
| 290 |
+
|
| 291 |
+
images = [image_0, image_1]
|
| 292 |
+
annotations = [annotations_0, annotations_1]
|
| 293 |
+
|
| 294 |
+
for image_processing_class in self.image_processor_list:
|
| 295 |
+
image_processing = image_processing_class()
|
| 296 |
+
encoding = image_processing(
|
| 297 |
+
images=images,
|
| 298 |
+
annotations=annotations,
|
| 299 |
+
return_segmentation_masks=True,
|
| 300 |
+
return_tensors="pt", # do_convert_annotations=True
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# Check the pixel values have been padded
|
| 304 |
+
postprocessed_height, postprocessed_width = 800, 1066
|
| 305 |
+
expected_shape = torch.Size([2, 3, postprocessed_height, postprocessed_width])
|
| 306 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 307 |
+
|
| 308 |
+
# Check the bounding boxes have been adjusted for padded images
|
| 309 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 310 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 311 |
+
expected_boxes_0 = torch.tensor(
|
| 312 |
+
[
|
| 313 |
+
[0.6879, 0.4609, 0.0755, 0.3691],
|
| 314 |
+
[0.2118, 0.3359, 0.2601, 0.1566],
|
| 315 |
+
[0.5011, 0.5000, 0.9979, 1.0000],
|
| 316 |
+
[0.5010, 0.5020, 0.9979, 0.9959],
|
| 317 |
+
[0.3284, 0.5944, 0.5884, 0.8112],
|
| 318 |
+
[0.8394, 0.5445, 0.3213, 0.9110],
|
| 319 |
+
]
|
| 320 |
+
)
|
| 321 |
+
expected_boxes_1 = torch.tensor(
|
| 322 |
+
[
|
| 323 |
+
[0.4130, 0.2765, 0.0453, 0.2215],
|
| 324 |
+
[0.1272, 0.2016, 0.1561, 0.0940],
|
| 325 |
+
[0.3757, 0.4933, 0.7488, 0.9865],
|
| 326 |
+
[0.3759, 0.5002, 0.7492, 0.9955],
|
| 327 |
+
[0.1971, 0.5456, 0.3532, 0.8646],
|
| 328 |
+
[0.5790, 0.4115, 0.3430, 0.7161],
|
| 329 |
+
]
|
| 330 |
+
)
|
| 331 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1e-3))
|
| 332 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1e-3))
|
| 333 |
+
|
| 334 |
+
# Check the masks have also been padded
|
| 335 |
+
self.assertEqual(encoding["labels"][0]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 336 |
+
self.assertEqual(encoding["labels"][1]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 337 |
+
|
| 338 |
+
# Check if do_convert_annotations=False, then the annotations are not converted to centre_x, centre_y, width, height
|
| 339 |
+
# format and not in the range [0, 1]
|
| 340 |
+
encoding = image_processing(
|
| 341 |
+
images=images,
|
| 342 |
+
annotations=annotations,
|
| 343 |
+
return_segmentation_masks=True,
|
| 344 |
+
do_convert_annotations=False,
|
| 345 |
+
return_tensors="pt",
|
| 346 |
+
)
|
| 347 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 348 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 349 |
+
# Convert to absolute coordinates
|
| 350 |
+
unnormalized_boxes_0 = torch.vstack(
|
| 351 |
+
[
|
| 352 |
+
expected_boxes_0[:, 0] * postprocessed_width,
|
| 353 |
+
expected_boxes_0[:, 1] * postprocessed_height,
|
| 354 |
+
expected_boxes_0[:, 2] * postprocessed_width,
|
| 355 |
+
expected_boxes_0[:, 3] * postprocessed_height,
|
| 356 |
+
]
|
| 357 |
+
).T
|
| 358 |
+
unnormalized_boxes_1 = torch.vstack(
|
| 359 |
+
[
|
| 360 |
+
expected_boxes_1[:, 0] * postprocessed_width,
|
| 361 |
+
expected_boxes_1[:, 1] * postprocessed_height,
|
| 362 |
+
expected_boxes_1[:, 2] * postprocessed_width,
|
| 363 |
+
expected_boxes_1[:, 3] * postprocessed_height,
|
| 364 |
+
]
|
| 365 |
+
).T
|
| 366 |
+
# Convert from centre_x, centre_y, width, height to x_min, y_min, x_max, y_max
|
| 367 |
+
expected_boxes_0 = torch.vstack(
|
| 368 |
+
[
|
| 369 |
+
unnormalized_boxes_0[:, 0] - unnormalized_boxes_0[:, 2] / 2,
|
| 370 |
+
unnormalized_boxes_0[:, 1] - unnormalized_boxes_0[:, 3] / 2,
|
| 371 |
+
unnormalized_boxes_0[:, 0] + unnormalized_boxes_0[:, 2] / 2,
|
| 372 |
+
unnormalized_boxes_0[:, 1] + unnormalized_boxes_0[:, 3] / 2,
|
| 373 |
+
]
|
| 374 |
+
).T
|
| 375 |
+
expected_boxes_1 = torch.vstack(
|
| 376 |
+
[
|
| 377 |
+
unnormalized_boxes_1[:, 0] - unnormalized_boxes_1[:, 2] / 2,
|
| 378 |
+
unnormalized_boxes_1[:, 1] - unnormalized_boxes_1[:, 3] / 2,
|
| 379 |
+
unnormalized_boxes_1[:, 0] + unnormalized_boxes_1[:, 2] / 2,
|
| 380 |
+
unnormalized_boxes_1[:, 1] + unnormalized_boxes_1[:, 3] / 2,
|
| 381 |
+
]
|
| 382 |
+
).T
|
| 383 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1))
|
| 384 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1))
|
| 385 |
+
|
| 386 |
+
# Copied from tests.models.detr.test_image_processing_detr.DetrImageProcessingTest.test_batched_coco_panoptic_annotations with Detr->DeformableDetr
|
| 387 |
+
def test_batched_coco_panoptic_annotations(self):
|
| 388 |
+
# prepare image, target and masks_path
|
| 389 |
+
image_0 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 390 |
+
image_1 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png").resize((800, 800))
|
| 391 |
+
|
| 392 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 393 |
+
target = json.loads(f.read())
|
| 394 |
+
|
| 395 |
+
annotation_0 = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 396 |
+
annotation_1 = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 397 |
+
|
| 398 |
+
w_0, h_0 = image_0.size
|
| 399 |
+
w_1, h_1 = image_1.size
|
| 400 |
+
for i in range(len(annotation_1["segments_info"])):
|
| 401 |
+
coords = annotation_1["segments_info"][i]["bbox"]
|
| 402 |
+
new_bbox = [
|
| 403 |
+
coords[0] * w_1 / w_0,
|
| 404 |
+
coords[1] * h_1 / h_0,
|
| 405 |
+
coords[2] * w_1 / w_0,
|
| 406 |
+
coords[3] * h_1 / h_0,
|
| 407 |
+
]
|
| 408 |
+
annotation_1["segments_info"][i]["bbox"] = new_bbox
|
| 409 |
+
|
| 410 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 411 |
+
|
| 412 |
+
images = [image_0, image_1]
|
| 413 |
+
annotations = [annotation_0, annotation_1]
|
| 414 |
+
|
| 415 |
+
for image_processing_class in self.image_processor_list:
|
| 416 |
+
# encode them
|
| 417 |
+
image_processing = image_processing_class(format="coco_panoptic")
|
| 418 |
+
encoding = image_processing(
|
| 419 |
+
images=images,
|
| 420 |
+
annotations=annotations,
|
| 421 |
+
masks_path=masks_path,
|
| 422 |
+
return_tensors="pt",
|
| 423 |
+
return_segmentation_masks=True,
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
# Check the pixel values have been padded
|
| 427 |
+
postprocessed_height, postprocessed_width = 800, 1066
|
| 428 |
+
expected_shape = torch.Size([2, 3, postprocessed_height, postprocessed_width])
|
| 429 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 430 |
+
|
| 431 |
+
# Check the bounding boxes have been adjusted for padded images
|
| 432 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 433 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 434 |
+
expected_boxes_0 = torch.tensor(
|
| 435 |
+
[
|
| 436 |
+
[0.2625, 0.5437, 0.4688, 0.8625],
|
| 437 |
+
[0.7719, 0.4104, 0.4531, 0.7125],
|
| 438 |
+
[0.5000, 0.4927, 0.9969, 0.9854],
|
| 439 |
+
[0.1688, 0.2000, 0.2063, 0.0917],
|
| 440 |
+
[0.5492, 0.2760, 0.0578, 0.2187],
|
| 441 |
+
[0.4992, 0.4990, 0.9984, 0.9979],
|
| 442 |
+
]
|
| 443 |
+
)
|
| 444 |
+
expected_boxes_1 = torch.tensor(
|
| 445 |
+
[
|
| 446 |
+
[0.1576, 0.3262, 0.2814, 0.5175],
|
| 447 |
+
[0.4634, 0.2463, 0.2720, 0.4275],
|
| 448 |
+
[0.3002, 0.2956, 0.5985, 0.5913],
|
| 449 |
+
[0.1013, 0.1200, 0.1238, 0.0550],
|
| 450 |
+
[0.3297, 0.1656, 0.0347, 0.1312],
|
| 451 |
+
[0.2997, 0.2994, 0.5994, 0.5987],
|
| 452 |
+
]
|
| 453 |
+
)
|
| 454 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1e-3))
|
| 455 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1e-3))
|
| 456 |
+
|
| 457 |
+
# Check the masks have also been padded
|
| 458 |
+
self.assertEqual(encoding["labels"][0]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 459 |
+
self.assertEqual(encoding["labels"][1]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 460 |
+
|
| 461 |
+
# Check if do_convert_annotations=False, then the annotations are not converted to centre_x, centre_y, width, height
|
| 462 |
+
# format and not in the range [0, 1]
|
| 463 |
+
encoding = image_processing(
|
| 464 |
+
images=images,
|
| 465 |
+
annotations=annotations,
|
| 466 |
+
masks_path=masks_path,
|
| 467 |
+
return_segmentation_masks=True,
|
| 468 |
+
do_convert_annotations=False,
|
| 469 |
+
return_tensors="pt",
|
| 470 |
+
)
|
| 471 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 472 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 473 |
+
# Convert to absolute coordinates
|
| 474 |
+
unnormalized_boxes_0 = torch.vstack(
|
| 475 |
+
[
|
| 476 |
+
expected_boxes_0[:, 0] * postprocessed_width,
|
| 477 |
+
expected_boxes_0[:, 1] * postprocessed_height,
|
| 478 |
+
expected_boxes_0[:, 2] * postprocessed_width,
|
| 479 |
+
expected_boxes_0[:, 3] * postprocessed_height,
|
| 480 |
+
]
|
| 481 |
+
).T
|
| 482 |
+
unnormalized_boxes_1 = torch.vstack(
|
| 483 |
+
[
|
| 484 |
+
expected_boxes_1[:, 0] * postprocessed_width,
|
| 485 |
+
expected_boxes_1[:, 1] * postprocessed_height,
|
| 486 |
+
expected_boxes_1[:, 2] * postprocessed_width,
|
| 487 |
+
expected_boxes_1[:, 3] * postprocessed_height,
|
| 488 |
+
]
|
| 489 |
+
).T
|
| 490 |
+
# Convert from centre_x, centre_y, width, height to x_min, y_min, x_max, y_max
|
| 491 |
+
expected_boxes_0 = torch.vstack(
|
| 492 |
+
[
|
| 493 |
+
unnormalized_boxes_0[:, 0] - unnormalized_boxes_0[:, 2] / 2,
|
| 494 |
+
unnormalized_boxes_0[:, 1] - unnormalized_boxes_0[:, 3] / 2,
|
| 495 |
+
unnormalized_boxes_0[:, 0] + unnormalized_boxes_0[:, 2] / 2,
|
| 496 |
+
unnormalized_boxes_0[:, 1] + unnormalized_boxes_0[:, 3] / 2,
|
| 497 |
+
]
|
| 498 |
+
).T
|
| 499 |
+
expected_boxes_1 = torch.vstack(
|
| 500 |
+
[
|
| 501 |
+
unnormalized_boxes_1[:, 0] - unnormalized_boxes_1[:, 2] / 2,
|
| 502 |
+
unnormalized_boxes_1[:, 1] - unnormalized_boxes_1[:, 3] / 2,
|
| 503 |
+
unnormalized_boxes_1[:, 0] + unnormalized_boxes_1[:, 2] / 2,
|
| 504 |
+
unnormalized_boxes_1[:, 1] + unnormalized_boxes_1[:, 3] / 2,
|
| 505 |
+
]
|
| 506 |
+
).T
|
| 507 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1))
|
| 508 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1))
|
| 509 |
+
|
| 510 |
+
# Copied from tests.models.detr.test_image_processing_detr.DetrImageProcessingTest.test_max_width_max_height_resizing_and_pad_strategy with Detr->DeformableDetr
|
| 511 |
+
def test_max_width_max_height_resizing_and_pad_strategy(self):
|
| 512 |
+
for image_processing_class in self.image_processor_list:
|
| 513 |
+
image_1 = torch.ones([200, 100, 3], dtype=torch.uint8)
|
| 514 |
+
|
| 515 |
+
# do_pad=False, max_height=100, max_width=100, image=200x100 -> 100x50
|
| 516 |
+
image_processor = image_processing_class(
|
| 517 |
+
size={"max_height": 100, "max_width": 100},
|
| 518 |
+
do_pad=False,
|
| 519 |
+
)
|
| 520 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 521 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 100, 50]))
|
| 522 |
+
|
| 523 |
+
# do_pad=False, max_height=300, max_width=100, image=200x100 -> 200x100
|
| 524 |
+
image_processor = image_processing_class(
|
| 525 |
+
size={"max_height": 300, "max_width": 100},
|
| 526 |
+
do_pad=False,
|
| 527 |
+
)
|
| 528 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 529 |
+
|
| 530 |
+
# do_pad=True, max_height=100, max_width=100, image=200x100 -> 100x100
|
| 531 |
+
image_processor = image_processing_class(
|
| 532 |
+
size={"max_height": 100, "max_width": 100}, do_pad=True, pad_size={"height": 100, "width": 100}
|
| 533 |
+
)
|
| 534 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 535 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 100, 100]))
|
| 536 |
+
|
| 537 |
+
# do_pad=True, max_height=300, max_width=100, image=200x100 -> 300x100
|
| 538 |
+
image_processor = image_processing_class(
|
| 539 |
+
size={"max_height": 300, "max_width": 100},
|
| 540 |
+
do_pad=True,
|
| 541 |
+
pad_size={"height": 301, "width": 101},
|
| 542 |
+
)
|
| 543 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 544 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 301, 101]))
|
| 545 |
+
|
| 546 |
+
### Check for batch
|
| 547 |
+
image_2 = torch.ones([100, 150, 3], dtype=torch.uint8)
|
| 548 |
+
|
| 549 |
+
# do_pad=True, max_height=150, max_width=100, images=[200x100, 100x150] -> 150x100
|
| 550 |
+
image_processor = image_processing_class(
|
| 551 |
+
size={"max_height": 150, "max_width": 100},
|
| 552 |
+
do_pad=True,
|
| 553 |
+
pad_size={"height": 150, "width": 100},
|
| 554 |
+
)
|
| 555 |
+
inputs = image_processor(images=[image_1, image_2], return_tensors="pt")
|
| 556 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([2, 3, 150, 100]))
|
| 557 |
+
|
| 558 |
+
def test_longest_edge_shortest_edge_resizing_strategy(self):
|
| 559 |
+
for image_processing_class in self.image_processor_list:
|
| 560 |
+
image_1 = torch.ones([958, 653, 3], dtype=torch.uint8)
|
| 561 |
+
|
| 562 |
+
# max size is set; width < height;
|
| 563 |
+
# do_pad=False, longest_edge=640, shortest_edge=640, image=958x653 -> 640x436
|
| 564 |
+
image_processor = image_processing_class(
|
| 565 |
+
size={"longest_edge": 640, "shortest_edge": 640},
|
| 566 |
+
do_pad=False,
|
| 567 |
+
)
|
| 568 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 569 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 640, 436]))
|
| 570 |
+
|
| 571 |
+
image_2 = torch.ones([653, 958, 3], dtype=torch.uint8)
|
| 572 |
+
# max size is set; height < width;
|
| 573 |
+
# do_pad=False, longest_edge=640, shortest_edge=640, image=653x958 -> 436x640
|
| 574 |
+
image_processor = image_processing_class(
|
| 575 |
+
size={"longest_edge": 640, "shortest_edge": 640},
|
| 576 |
+
do_pad=False,
|
| 577 |
+
)
|
| 578 |
+
inputs = image_processor(images=[image_2], return_tensors="pt")
|
| 579 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 436, 640]))
|
| 580 |
+
|
| 581 |
+
image_3 = torch.ones([100, 120, 3], dtype=torch.uint8)
|
| 582 |
+
# max size is set; width == size; height > max_size;
|
| 583 |
+
# do_pad=False, longest_edge=118, shortest_edge=100, image=120x100 -> 118x98
|
| 584 |
+
image_processor = image_processing_class(
|
| 585 |
+
size={"longest_edge": 118, "shortest_edge": 100},
|
| 586 |
+
do_pad=False,
|
| 587 |
+
)
|
| 588 |
+
inputs = image_processor(images=[image_3], return_tensors="pt")
|
| 589 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 98, 118]))
|
| 590 |
+
|
| 591 |
+
image_4 = torch.ones([128, 50, 3], dtype=torch.uint8)
|
| 592 |
+
# max size is set; height == size; width < max_size;
|
| 593 |
+
# do_pad=False, longest_edge=256, shortest_edge=50, image=50x128 -> 50x128
|
| 594 |
+
image_processor = image_processing_class(
|
| 595 |
+
size={"longest_edge": 256, "shortest_edge": 50},
|
| 596 |
+
do_pad=False,
|
| 597 |
+
)
|
| 598 |
+
inputs = image_processor(images=[image_4], return_tensors="pt")
|
| 599 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 128, 50]))
|
| 600 |
+
|
| 601 |
+
image_5 = torch.ones([50, 50, 3], dtype=torch.uint8)
|
| 602 |
+
# max size is set; height == width; width < max_size;
|
| 603 |
+
# do_pad=False, longest_edge=117, shortest_edge=50, image=50x50 -> 50x50
|
| 604 |
+
image_processor = image_processing_class(
|
| 605 |
+
size={"longest_edge": 117, "shortest_edge": 50},
|
| 606 |
+
do_pad=False,
|
| 607 |
+
)
|
| 608 |
+
inputs = image_processor(images=[image_5], return_tensors="pt")
|
| 609 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 50, 50]))
|
| 610 |
+
|
| 611 |
+
@slow
|
| 612 |
+
@require_torch_gpu
|
| 613 |
+
# Copied from tests.models.detr.test_image_processing_detr.DetrImageProcessingTest.test_fast_processor_equivalence_cpu_gpu_coco_detection_annotations
|
| 614 |
+
def test_fast_processor_equivalence_cpu_gpu_coco_detection_annotations(self):
|
| 615 |
+
# prepare image and target
|
| 616 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 617 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 618 |
+
target = json.loads(f.read())
|
| 619 |
+
|
| 620 |
+
target = {"image_id": 39769, "annotations": target}
|
| 621 |
+
|
| 622 |
+
# Ignore copy
|
| 623 |
+
processor = self.image_processor_list[1]()
|
| 624 |
+
|
| 625 |
+
# 1. run processor on CPU
|
| 626 |
+
encoding_cpu = processor(images=image, annotations=target, return_tensors="pt", device="cpu")
|
| 627 |
+
# 2. run processor on GPU
|
| 628 |
+
encoding_gpu = processor(images=image, annotations=target, return_tensors="pt", device="cuda")
|
| 629 |
+
|
| 630 |
+
# verify pixel values
|
| 631 |
+
self.assertEqual(encoding_cpu["pixel_values"].shape, encoding_gpu["pixel_values"].shape)
|
| 632 |
+
self.assertTrue(
|
| 633 |
+
torch.allclose(
|
| 634 |
+
encoding_cpu["pixel_values"][0, 0, 0, :3],
|
| 635 |
+
encoding_gpu["pixel_values"][0, 0, 0, :3].to("cpu"),
|
| 636 |
+
atol=1e-4,
|
| 637 |
+
)
|
| 638 |
+
)
|
| 639 |
+
# verify area
|
| 640 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["area"], encoding_gpu["labels"][0]["area"].to("cpu")))
|
| 641 |
+
# verify boxes
|
| 642 |
+
self.assertEqual(encoding_cpu["labels"][0]["boxes"].shape, encoding_gpu["labels"][0]["boxes"].shape)
|
| 643 |
+
self.assertTrue(
|
| 644 |
+
torch.allclose(
|
| 645 |
+
encoding_cpu["labels"][0]["boxes"][0], encoding_gpu["labels"][0]["boxes"][0].to("cpu"), atol=1e-3
|
| 646 |
+
)
|
| 647 |
+
)
|
| 648 |
+
# verify image_id
|
| 649 |
+
self.assertTrue(
|
| 650 |
+
torch.allclose(encoding_cpu["labels"][0]["image_id"], encoding_gpu["labels"][0]["image_id"].to("cpu"))
|
| 651 |
+
)
|
| 652 |
+
# verify is_crowd
|
| 653 |
+
self.assertTrue(
|
| 654 |
+
torch.allclose(encoding_cpu["labels"][0]["iscrowd"], encoding_gpu["labels"][0]["iscrowd"].to("cpu"))
|
| 655 |
+
)
|
| 656 |
+
# verify class_labels
|
| 657 |
+
self.assertTrue(
|
| 658 |
+
torch.allclose(
|
| 659 |
+
encoding_cpu["labels"][0]["class_labels"], encoding_gpu["labels"][0]["class_labels"].to("cpu")
|
| 660 |
+
)
|
| 661 |
+
)
|
| 662 |
+
# verify orig_size
|
| 663 |
+
self.assertTrue(
|
| 664 |
+
torch.allclose(encoding_cpu["labels"][0]["orig_size"], encoding_gpu["labels"][0]["orig_size"].to("cpu"))
|
| 665 |
+
)
|
| 666 |
+
# verify size
|
| 667 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["size"], encoding_gpu["labels"][0]["size"].to("cpu")))
|
| 668 |
+
|
| 669 |
+
@slow
|
| 670 |
+
@require_torch_gpu
|
| 671 |
+
# Copied from tests.models.detr.test_image_processing_detr.DetrImageProcessingTest.test_fast_processor_equivalence_cpu_gpu_coco_panoptic_annotations
|
| 672 |
+
def test_fast_processor_equivalence_cpu_gpu_coco_panoptic_annotations(self):
|
| 673 |
+
# prepare image, target and masks_path
|
| 674 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 675 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 676 |
+
target = json.loads(f.read())
|
| 677 |
+
|
| 678 |
+
target = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 679 |
+
|
| 680 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 681 |
+
|
| 682 |
+
# Ignore copy
|
| 683 |
+
processor = self.image_processor_list[1](format="coco_panoptic")
|
| 684 |
+
|
| 685 |
+
# 1. run processor on CPU
|
| 686 |
+
encoding_cpu = processor(
|
| 687 |
+
images=image, annotations=target, masks_path=masks_path, return_tensors="pt", device="cpu"
|
| 688 |
+
)
|
| 689 |
+
# 2. run processor on GPU
|
| 690 |
+
encoding_gpu = processor(
|
| 691 |
+
images=image, annotations=target, masks_path=masks_path, return_tensors="pt", device="cuda"
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
# verify pixel values
|
| 695 |
+
self.assertEqual(encoding_cpu["pixel_values"].shape, encoding_gpu["pixel_values"].shape)
|
| 696 |
+
self.assertTrue(
|
| 697 |
+
torch.allclose(
|
| 698 |
+
encoding_cpu["pixel_values"][0, 0, 0, :3],
|
| 699 |
+
encoding_gpu["pixel_values"][0, 0, 0, :3].to("cpu"),
|
| 700 |
+
atol=1e-4,
|
| 701 |
+
)
|
| 702 |
+
)
|
| 703 |
+
# verify area
|
| 704 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["area"], encoding_gpu["labels"][0]["area"].to("cpu")))
|
| 705 |
+
# verify boxes
|
| 706 |
+
self.assertEqual(encoding_cpu["labels"][0]["boxes"].shape, encoding_gpu["labels"][0]["boxes"].shape)
|
| 707 |
+
self.assertTrue(
|
| 708 |
+
torch.allclose(
|
| 709 |
+
encoding_cpu["labels"][0]["boxes"][0], encoding_gpu["labels"][0]["boxes"][0].to("cpu"), atol=1e-3
|
| 710 |
+
)
|
| 711 |
+
)
|
| 712 |
+
# verify image_id
|
| 713 |
+
self.assertTrue(
|
| 714 |
+
torch.allclose(encoding_cpu["labels"][0]["image_id"], encoding_gpu["labels"][0]["image_id"].to("cpu"))
|
| 715 |
+
)
|
| 716 |
+
# verify is_crowd
|
| 717 |
+
self.assertTrue(
|
| 718 |
+
torch.allclose(encoding_cpu["labels"][0]["iscrowd"], encoding_gpu["labels"][0]["iscrowd"].to("cpu"))
|
| 719 |
+
)
|
| 720 |
+
# verify class_labels
|
| 721 |
+
self.assertTrue(
|
| 722 |
+
torch.allclose(
|
| 723 |
+
encoding_cpu["labels"][0]["class_labels"], encoding_gpu["labels"][0]["class_labels"].to("cpu")
|
| 724 |
+
)
|
| 725 |
+
)
|
| 726 |
+
# verify masks
|
| 727 |
+
masks_sum_cpu = encoding_cpu["labels"][0]["masks"].sum()
|
| 728 |
+
masks_sum_gpu = encoding_gpu["labels"][0]["masks"].sum()
|
| 729 |
+
relative_error = torch.abs(masks_sum_cpu - masks_sum_gpu) / masks_sum_cpu
|
| 730 |
+
self.assertTrue(relative_error < 1e-3)
|
| 731 |
+
# verify orig_size
|
| 732 |
+
self.assertTrue(
|
| 733 |
+
torch.allclose(encoding_cpu["labels"][0]["orig_size"], encoding_gpu["labels"][0]["orig_size"].to("cpu"))
|
| 734 |
+
)
|
| 735 |
+
# verify size
|
| 736 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["size"], encoding_gpu["labels"][0]["size"].to("cpu")))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deformable_detr/test_modeling_deformable_detr.py
ADDED
|
@@ -0,0 +1,776 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Deformable DETR model."""
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import math
|
| 19 |
+
import unittest
|
| 20 |
+
from typing import Dict, List, Tuple
|
| 21 |
+
|
| 22 |
+
from transformers import DeformableDetrConfig, ResNetConfig, is_torch_available, is_vision_available
|
| 23 |
+
from transformers.file_utils import cached_property
|
| 24 |
+
from transformers.testing_utils import (
|
| 25 |
+
require_timm,
|
| 26 |
+
require_torch,
|
| 27 |
+
require_torch_accelerator,
|
| 28 |
+
require_torch_bf16,
|
| 29 |
+
require_vision,
|
| 30 |
+
slow,
|
| 31 |
+
torch_device,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 35 |
+
from ...test_configuration_common import ConfigTester
|
| 36 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
|
| 37 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if is_torch_available():
|
| 41 |
+
import torch
|
| 42 |
+
|
| 43 |
+
from transformers import DeformableDetrForObjectDetection, DeformableDetrModel
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
if is_vision_available():
|
| 47 |
+
from PIL import Image
|
| 48 |
+
|
| 49 |
+
from transformers import AutoImageProcessor
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class DeformableDetrModelTester:
|
| 53 |
+
def __init__(
|
| 54 |
+
self,
|
| 55 |
+
parent,
|
| 56 |
+
batch_size=8,
|
| 57 |
+
is_training=True,
|
| 58 |
+
use_labels=True,
|
| 59 |
+
hidden_size=32,
|
| 60 |
+
num_hidden_layers=2,
|
| 61 |
+
num_attention_heads=8,
|
| 62 |
+
intermediate_size=4,
|
| 63 |
+
hidden_act="gelu",
|
| 64 |
+
hidden_dropout_prob=0.1,
|
| 65 |
+
attention_probs_dropout_prob=0.1,
|
| 66 |
+
num_queries=12,
|
| 67 |
+
num_channels=3,
|
| 68 |
+
image_size=196,
|
| 69 |
+
n_targets=8,
|
| 70 |
+
num_labels=91,
|
| 71 |
+
num_feature_levels=4,
|
| 72 |
+
encoder_n_points=2,
|
| 73 |
+
decoder_n_points=6,
|
| 74 |
+
):
|
| 75 |
+
self.parent = parent
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.is_training = is_training
|
| 78 |
+
self.use_labels = use_labels
|
| 79 |
+
self.hidden_size = hidden_size
|
| 80 |
+
self.num_hidden_layers = num_hidden_layers
|
| 81 |
+
self.num_attention_heads = num_attention_heads
|
| 82 |
+
self.intermediate_size = intermediate_size
|
| 83 |
+
self.hidden_act = hidden_act
|
| 84 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 85 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 86 |
+
self.num_queries = num_queries
|
| 87 |
+
self.num_channels = num_channels
|
| 88 |
+
self.image_size = image_size
|
| 89 |
+
self.n_targets = n_targets
|
| 90 |
+
self.num_labels = num_labels
|
| 91 |
+
self.num_feature_levels = num_feature_levels
|
| 92 |
+
self.encoder_n_points = encoder_n_points
|
| 93 |
+
self.decoder_n_points = decoder_n_points
|
| 94 |
+
|
| 95 |
+
# we also set the expected seq length for both encoder and decoder
|
| 96 |
+
self.encoder_seq_length = (
|
| 97 |
+
math.ceil(self.image_size / 8) ** 2
|
| 98 |
+
+ math.ceil(self.image_size / 16) ** 2
|
| 99 |
+
+ math.ceil(self.image_size / 32) ** 2
|
| 100 |
+
+ math.ceil(self.image_size / 64) ** 2
|
| 101 |
+
)
|
| 102 |
+
self.decoder_seq_length = self.num_queries
|
| 103 |
+
|
| 104 |
+
def prepare_config_and_inputs(self):
|
| 105 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 106 |
+
|
| 107 |
+
pixel_mask = torch.ones([self.batch_size, self.image_size, self.image_size], device=torch_device)
|
| 108 |
+
|
| 109 |
+
labels = None
|
| 110 |
+
if self.use_labels:
|
| 111 |
+
# labels is a list of Dict (each Dict being the labels for a given example in the batch)
|
| 112 |
+
labels = []
|
| 113 |
+
for i in range(self.batch_size):
|
| 114 |
+
target = {}
|
| 115 |
+
target["class_labels"] = torch.randint(
|
| 116 |
+
high=self.num_labels, size=(self.n_targets,), device=torch_device
|
| 117 |
+
)
|
| 118 |
+
target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device)
|
| 119 |
+
target["masks"] = torch.rand(self.n_targets, self.image_size, self.image_size, device=torch_device)
|
| 120 |
+
labels.append(target)
|
| 121 |
+
|
| 122 |
+
config = self.get_config()
|
| 123 |
+
return config, pixel_values, pixel_mask, labels
|
| 124 |
+
|
| 125 |
+
def get_config(self):
|
| 126 |
+
resnet_config = ResNetConfig(
|
| 127 |
+
num_channels=3,
|
| 128 |
+
embeddings_size=10,
|
| 129 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 130 |
+
depths=[1, 1, 2, 1],
|
| 131 |
+
hidden_act="relu",
|
| 132 |
+
num_labels=3,
|
| 133 |
+
out_features=["stage2", "stage3", "stage4"],
|
| 134 |
+
out_indices=[2, 3, 4],
|
| 135 |
+
)
|
| 136 |
+
return DeformableDetrConfig(
|
| 137 |
+
d_model=self.hidden_size,
|
| 138 |
+
encoder_layers=self.num_hidden_layers,
|
| 139 |
+
decoder_layers=self.num_hidden_layers,
|
| 140 |
+
encoder_attention_heads=self.num_attention_heads,
|
| 141 |
+
decoder_attention_heads=self.num_attention_heads,
|
| 142 |
+
encoder_ffn_dim=self.intermediate_size,
|
| 143 |
+
decoder_ffn_dim=self.intermediate_size,
|
| 144 |
+
dropout=self.hidden_dropout_prob,
|
| 145 |
+
attention_dropout=self.attention_probs_dropout_prob,
|
| 146 |
+
num_queries=self.num_queries,
|
| 147 |
+
num_labels=self.num_labels,
|
| 148 |
+
num_feature_levels=self.num_feature_levels,
|
| 149 |
+
encoder_n_points=self.encoder_n_points,
|
| 150 |
+
decoder_n_points=self.decoder_n_points,
|
| 151 |
+
use_timm_backbone=False,
|
| 152 |
+
backbone=None,
|
| 153 |
+
backbone_config=resnet_config,
|
| 154 |
+
use_pretrained_backbone=False,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
def prepare_config_and_inputs_for_common(self):
|
| 158 |
+
config, pixel_values, pixel_mask, labels = self.prepare_config_and_inputs()
|
| 159 |
+
inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
|
| 160 |
+
return config, inputs_dict
|
| 161 |
+
|
| 162 |
+
def create_and_check_deformable_detr_model(self, config, pixel_values, pixel_mask, labels):
|
| 163 |
+
model = DeformableDetrModel(config=config)
|
| 164 |
+
model.to(torch_device)
|
| 165 |
+
model.eval()
|
| 166 |
+
|
| 167 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
|
| 168 |
+
result = model(pixel_values)
|
| 169 |
+
|
| 170 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.num_queries, self.hidden_size))
|
| 171 |
+
|
| 172 |
+
def create_and_check_deformable_detr_object_detection_head_model(self, config, pixel_values, pixel_mask, labels):
|
| 173 |
+
model = DeformableDetrForObjectDetection(config=config)
|
| 174 |
+
model.to(torch_device)
|
| 175 |
+
model.eval()
|
| 176 |
+
|
| 177 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
|
| 178 |
+
result = model(pixel_values)
|
| 179 |
+
|
| 180 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels))
|
| 181 |
+
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
|
| 182 |
+
|
| 183 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
|
| 184 |
+
|
| 185 |
+
self.parent.assertEqual(result.loss.shape, ())
|
| 186 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels))
|
| 187 |
+
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@require_torch
|
| 191 |
+
class DeformableDetrModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 192 |
+
all_model_classes = (DeformableDetrModel, DeformableDetrForObjectDetection) if is_torch_available() else ()
|
| 193 |
+
pipeline_model_mapping = (
|
| 194 |
+
{"image-feature-extraction": DeformableDetrModel, "object-detection": DeformableDetrForObjectDetection}
|
| 195 |
+
if is_torch_available()
|
| 196 |
+
else {}
|
| 197 |
+
)
|
| 198 |
+
is_encoder_decoder = True
|
| 199 |
+
test_torchscript = False
|
| 200 |
+
test_pruning = False
|
| 201 |
+
test_head_masking = False
|
| 202 |
+
test_missing_keys = False
|
| 203 |
+
|
| 204 |
+
# special case for head models
|
| 205 |
+
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
| 206 |
+
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
| 207 |
+
|
| 208 |
+
if return_labels:
|
| 209 |
+
if model_class.__name__ == "DeformableDetrForObjectDetection":
|
| 210 |
+
labels = []
|
| 211 |
+
for i in range(self.model_tester.batch_size):
|
| 212 |
+
target = {}
|
| 213 |
+
target["class_labels"] = torch.ones(
|
| 214 |
+
size=(self.model_tester.n_targets,), device=torch_device, dtype=torch.long
|
| 215 |
+
)
|
| 216 |
+
target["boxes"] = torch.ones(
|
| 217 |
+
self.model_tester.n_targets, 4, device=torch_device, dtype=torch.float
|
| 218 |
+
)
|
| 219 |
+
target["masks"] = torch.ones(
|
| 220 |
+
self.model_tester.n_targets,
|
| 221 |
+
self.model_tester.image_size,
|
| 222 |
+
self.model_tester.image_size,
|
| 223 |
+
device=torch_device,
|
| 224 |
+
dtype=torch.float,
|
| 225 |
+
)
|
| 226 |
+
labels.append(target)
|
| 227 |
+
inputs_dict["labels"] = labels
|
| 228 |
+
|
| 229 |
+
return inputs_dict
|
| 230 |
+
|
| 231 |
+
def setUp(self):
|
| 232 |
+
self.model_tester = DeformableDetrModelTester(self)
|
| 233 |
+
self.config_tester = ConfigTester(
|
| 234 |
+
self,
|
| 235 |
+
config_class=DeformableDetrConfig,
|
| 236 |
+
has_text_modality=False,
|
| 237 |
+
common_properties=["num_channels", "d_model", "encoder_attention_heads", "decoder_attention_heads"],
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
def test_config(self):
|
| 241 |
+
self.config_tester.run_common_tests()
|
| 242 |
+
|
| 243 |
+
def test_deformable_detr_model(self):
|
| 244 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 245 |
+
self.model_tester.create_and_check_deformable_detr_model(*config_and_inputs)
|
| 246 |
+
|
| 247 |
+
def test_deformable_detr_object_detection_head_model(self):
|
| 248 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 249 |
+
self.model_tester.create_and_check_deformable_detr_object_detection_head_model(*config_and_inputs)
|
| 250 |
+
|
| 251 |
+
@unittest.skip(reason="Deformable DETR does not use inputs_embeds")
|
| 252 |
+
def test_inputs_embeds(self):
|
| 253 |
+
pass
|
| 254 |
+
|
| 255 |
+
@unittest.skip(reason="Deformable DETR does not use inputs_embeds")
|
| 256 |
+
def test_inputs_embeds_matches_input_ids(self):
|
| 257 |
+
pass
|
| 258 |
+
|
| 259 |
+
@unittest.skip(reason="Deformable DETR does not have a get_input_embeddings method")
|
| 260 |
+
def test_model_get_set_embeddings(self):
|
| 261 |
+
pass
|
| 262 |
+
|
| 263 |
+
@unittest.skip(reason="Deformable DETR is not a generative model")
|
| 264 |
+
def test_generate_without_input_ids(self):
|
| 265 |
+
pass
|
| 266 |
+
|
| 267 |
+
@unittest.skip(reason="Deformable DETR does not use token embeddings")
|
| 268 |
+
def test_resize_tokens_embeddings(self):
|
| 269 |
+
pass
|
| 270 |
+
|
| 271 |
+
@unittest.skip(reason="Feed forward chunking is not implemented")
|
| 272 |
+
def test_feed_forward_chunking(self):
|
| 273 |
+
pass
|
| 274 |
+
|
| 275 |
+
def test_attention_outputs(self):
|
| 276 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 277 |
+
config.return_dict = True
|
| 278 |
+
|
| 279 |
+
for model_class in self.all_model_classes:
|
| 280 |
+
inputs_dict["output_attentions"] = True
|
| 281 |
+
inputs_dict["output_hidden_states"] = False
|
| 282 |
+
config.return_dict = True
|
| 283 |
+
model = model_class(config)
|
| 284 |
+
model.to(torch_device)
|
| 285 |
+
model.eval()
|
| 286 |
+
with torch.no_grad():
|
| 287 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 288 |
+
attentions = outputs.encoder_attentions
|
| 289 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 290 |
+
|
| 291 |
+
# check that output_attentions also work using config
|
| 292 |
+
del inputs_dict["output_attentions"]
|
| 293 |
+
config.output_attentions = True
|
| 294 |
+
model = model_class(config)
|
| 295 |
+
model.to(torch_device)
|
| 296 |
+
model.eval()
|
| 297 |
+
with torch.no_grad():
|
| 298 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 299 |
+
attentions = outputs.encoder_attentions
|
| 300 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 301 |
+
|
| 302 |
+
self.assertListEqual(
|
| 303 |
+
list(attentions[0].shape[-3:]),
|
| 304 |
+
[
|
| 305 |
+
self.model_tester.num_attention_heads,
|
| 306 |
+
self.model_tester.num_feature_levels,
|
| 307 |
+
self.model_tester.encoder_n_points,
|
| 308 |
+
],
|
| 309 |
+
)
|
| 310 |
+
out_len = len(outputs)
|
| 311 |
+
|
| 312 |
+
correct_outlen = 8
|
| 313 |
+
|
| 314 |
+
# loss is at first position
|
| 315 |
+
if "labels" in inputs_dict:
|
| 316 |
+
correct_outlen += 1 # loss is added to beginning
|
| 317 |
+
# Object Detection model returns pred_logits and pred_boxes
|
| 318 |
+
if model_class.__name__ == "DeformableDetrForObjectDetection":
|
| 319 |
+
correct_outlen += 2
|
| 320 |
+
|
| 321 |
+
self.assertEqual(out_len, correct_outlen)
|
| 322 |
+
|
| 323 |
+
# decoder attentions
|
| 324 |
+
decoder_attentions = outputs.decoder_attentions
|
| 325 |
+
self.assertIsInstance(decoder_attentions, (list, tuple))
|
| 326 |
+
self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
|
| 327 |
+
self.assertListEqual(
|
| 328 |
+
list(decoder_attentions[0].shape[-3:]),
|
| 329 |
+
[self.model_tester.num_attention_heads, self.model_tester.num_queries, self.model_tester.num_queries],
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
# cross attentions
|
| 333 |
+
cross_attentions = outputs.cross_attentions
|
| 334 |
+
self.assertIsInstance(cross_attentions, (list, tuple))
|
| 335 |
+
self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
|
| 336 |
+
self.assertListEqual(
|
| 337 |
+
list(cross_attentions[0].shape[-3:]),
|
| 338 |
+
[
|
| 339 |
+
self.model_tester.num_attention_heads,
|
| 340 |
+
self.model_tester.num_feature_levels,
|
| 341 |
+
self.model_tester.decoder_n_points,
|
| 342 |
+
],
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# Check attention is always last and order is fine
|
| 346 |
+
inputs_dict["output_attentions"] = True
|
| 347 |
+
inputs_dict["output_hidden_states"] = True
|
| 348 |
+
model = model_class(config)
|
| 349 |
+
model.to(torch_device)
|
| 350 |
+
model.eval()
|
| 351 |
+
with torch.no_grad():
|
| 352 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 353 |
+
|
| 354 |
+
if hasattr(self.model_tester, "num_hidden_states_types"):
|
| 355 |
+
added_hidden_states = self.model_tester.num_hidden_states_types
|
| 356 |
+
elif self.is_encoder_decoder:
|
| 357 |
+
added_hidden_states = 2
|
| 358 |
+
else:
|
| 359 |
+
added_hidden_states = 1
|
| 360 |
+
self.assertEqual(out_len + added_hidden_states, len(outputs))
|
| 361 |
+
|
| 362 |
+
self_attentions = outputs.encoder_attentions
|
| 363 |
+
|
| 364 |
+
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
|
| 365 |
+
self.assertListEqual(
|
| 366 |
+
list(self_attentions[0].shape[-3:]),
|
| 367 |
+
[
|
| 368 |
+
self.model_tester.num_attention_heads,
|
| 369 |
+
self.model_tester.num_feature_levels,
|
| 370 |
+
self.model_tester.encoder_n_points,
|
| 371 |
+
],
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
def test_model_outputs_equivalence(self):
|
| 375 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 376 |
+
|
| 377 |
+
def set_nan_tensor_to_zero(t):
|
| 378 |
+
t[t != t] = 0
|
| 379 |
+
return t
|
| 380 |
+
|
| 381 |
+
def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
|
| 382 |
+
with torch.no_grad():
|
| 383 |
+
tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
|
| 384 |
+
dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple()
|
| 385 |
+
|
| 386 |
+
def recursive_check(tuple_object, dict_object):
|
| 387 |
+
if isinstance(tuple_object, (List, Tuple)):
|
| 388 |
+
for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
|
| 389 |
+
recursive_check(tuple_iterable_value, dict_iterable_value)
|
| 390 |
+
elif isinstance(tuple_object, Dict):
|
| 391 |
+
for tuple_iterable_value, dict_iterable_value in zip(
|
| 392 |
+
tuple_object.values(), dict_object.values()
|
| 393 |
+
):
|
| 394 |
+
recursive_check(tuple_iterable_value, dict_iterable_value)
|
| 395 |
+
elif tuple_object is None:
|
| 396 |
+
return
|
| 397 |
+
else:
|
| 398 |
+
self.assertTrue(
|
| 399 |
+
torch.allclose(
|
| 400 |
+
set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5
|
| 401 |
+
),
|
| 402 |
+
msg=(
|
| 403 |
+
"Tuple and dict output are not equal. Difference:"
|
| 404 |
+
f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
|
| 405 |
+
f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
|
| 406 |
+
f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
|
| 407 |
+
),
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
recursive_check(tuple_output, dict_output)
|
| 411 |
+
|
| 412 |
+
for model_class in self.all_model_classes:
|
| 413 |
+
print("Model class:", model_class)
|
| 414 |
+
model = model_class(config)
|
| 415 |
+
model.to(torch_device)
|
| 416 |
+
model.eval()
|
| 417 |
+
|
| 418 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 419 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 420 |
+
check_equivalence(model, tuple_inputs, dict_inputs)
|
| 421 |
+
|
| 422 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 423 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 424 |
+
check_equivalence(model, tuple_inputs, dict_inputs)
|
| 425 |
+
|
| 426 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 427 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 428 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
|
| 429 |
+
|
| 430 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 431 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 432 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
|
| 433 |
+
|
| 434 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 435 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 436 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
|
| 437 |
+
|
| 438 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 439 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 440 |
+
check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
|
| 441 |
+
|
| 442 |
+
tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 443 |
+
dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 444 |
+
check_equivalence(
|
| 445 |
+
model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True}
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
def test_retain_grad_hidden_states_attentions(self):
|
| 449 |
+
# removed retain_grad and grad on decoder_hidden_states, as queries don't require grad
|
| 450 |
+
|
| 451 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 452 |
+
config.output_hidden_states = True
|
| 453 |
+
config.output_attentions = True
|
| 454 |
+
|
| 455 |
+
# no need to test all models as different heads yield the same functionality
|
| 456 |
+
model_class = self.all_model_classes[0]
|
| 457 |
+
model = model_class(config)
|
| 458 |
+
model.to(torch_device)
|
| 459 |
+
|
| 460 |
+
inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 461 |
+
|
| 462 |
+
outputs = model(**inputs)
|
| 463 |
+
|
| 464 |
+
# we take the second output since last_hidden_state is the second item
|
| 465 |
+
output = outputs[1]
|
| 466 |
+
|
| 467 |
+
encoder_hidden_states = outputs.encoder_hidden_states[0]
|
| 468 |
+
encoder_attentions = outputs.encoder_attentions[0]
|
| 469 |
+
encoder_hidden_states.retain_grad()
|
| 470 |
+
encoder_attentions.retain_grad()
|
| 471 |
+
|
| 472 |
+
decoder_attentions = outputs.decoder_attentions[0]
|
| 473 |
+
decoder_attentions.retain_grad()
|
| 474 |
+
|
| 475 |
+
cross_attentions = outputs.cross_attentions[0]
|
| 476 |
+
cross_attentions.retain_grad()
|
| 477 |
+
|
| 478 |
+
output.flatten()[0].backward(retain_graph=True)
|
| 479 |
+
|
| 480 |
+
self.assertIsNotNone(encoder_hidden_states.grad)
|
| 481 |
+
self.assertIsNotNone(encoder_attentions.grad)
|
| 482 |
+
self.assertIsNotNone(decoder_attentions.grad)
|
| 483 |
+
self.assertIsNotNone(cross_attentions.grad)
|
| 484 |
+
|
| 485 |
+
def test_forward_auxiliary_loss(self):
|
| 486 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 487 |
+
config.auxiliary_loss = True
|
| 488 |
+
|
| 489 |
+
# only test for object detection and segmentation model
|
| 490 |
+
for model_class in self.all_model_classes[1:]:
|
| 491 |
+
model = model_class(config)
|
| 492 |
+
model.to(torch_device)
|
| 493 |
+
|
| 494 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 495 |
+
|
| 496 |
+
outputs = model(**inputs)
|
| 497 |
+
|
| 498 |
+
self.assertIsNotNone(outputs.auxiliary_outputs)
|
| 499 |
+
self.assertEqual(len(outputs.auxiliary_outputs), self.model_tester.num_hidden_layers - 1)
|
| 500 |
+
|
| 501 |
+
def test_forward_signature(self):
|
| 502 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 503 |
+
|
| 504 |
+
for model_class in self.all_model_classes:
|
| 505 |
+
model = model_class(config)
|
| 506 |
+
signature = inspect.signature(model.forward)
|
| 507 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 508 |
+
arg_names = [*signature.parameters.keys()]
|
| 509 |
+
|
| 510 |
+
if model.config.is_encoder_decoder:
|
| 511 |
+
expected_arg_names = ["pixel_values", "pixel_mask"]
|
| 512 |
+
expected_arg_names.extend(
|
| 513 |
+
["head_mask", "decoder_head_mask", "encoder_outputs"]
|
| 514 |
+
if "head_mask" and "decoder_head_mask" in arg_names
|
| 515 |
+
else []
|
| 516 |
+
)
|
| 517 |
+
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
|
| 518 |
+
else:
|
| 519 |
+
expected_arg_names = ["pixel_values", "pixel_mask"]
|
| 520 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 521 |
+
|
| 522 |
+
def test_different_timm_backbone(self):
|
| 523 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 524 |
+
|
| 525 |
+
# let's pick a random timm backbone
|
| 526 |
+
config.backbone = "tf_mobilenetv3_small_075"
|
| 527 |
+
config.backbone_config = None
|
| 528 |
+
config.use_timm_backbone = True
|
| 529 |
+
config.backbone_kwargs = {"out_indices": [1, 2, 3, 4]}
|
| 530 |
+
|
| 531 |
+
for model_class in self.all_model_classes:
|
| 532 |
+
model = model_class(config)
|
| 533 |
+
model.to(torch_device)
|
| 534 |
+
model.eval()
|
| 535 |
+
with torch.no_grad():
|
| 536 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 537 |
+
|
| 538 |
+
if model_class.__name__ == "DeformableDetrForObjectDetection":
|
| 539 |
+
expected_shape = (
|
| 540 |
+
self.model_tester.batch_size,
|
| 541 |
+
self.model_tester.num_queries,
|
| 542 |
+
self.model_tester.num_labels,
|
| 543 |
+
)
|
| 544 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 545 |
+
# Confirm out_indices was propogated to backbone
|
| 546 |
+
self.assertEqual(len(model.model.backbone.conv_encoder.intermediate_channel_sizes), 4)
|
| 547 |
+
else:
|
| 548 |
+
# Confirm out_indices was propogated to backbone
|
| 549 |
+
self.assertEqual(len(model.backbone.conv_encoder.intermediate_channel_sizes), 4)
|
| 550 |
+
|
| 551 |
+
self.assertTrue(outputs)
|
| 552 |
+
|
| 553 |
+
def test_hf_backbone(self):
|
| 554 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 555 |
+
|
| 556 |
+
# Load a pretrained HF checkpoint as backbone
|
| 557 |
+
config.backbone = "microsoft/resnet-18"
|
| 558 |
+
config.backbone_config = None
|
| 559 |
+
config.use_timm_backbone = False
|
| 560 |
+
config.use_pretrained_backbone = True
|
| 561 |
+
config.backbone_kwargs = {"out_indices": [1, 2, 3, 4]}
|
| 562 |
+
|
| 563 |
+
for model_class in self.all_model_classes:
|
| 564 |
+
model = model_class(config)
|
| 565 |
+
model.to(torch_device)
|
| 566 |
+
model.eval()
|
| 567 |
+
with torch.no_grad():
|
| 568 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 569 |
+
|
| 570 |
+
if model_class.__name__ == "DeformableDetrForObjectDetection":
|
| 571 |
+
expected_shape = (
|
| 572 |
+
self.model_tester.batch_size,
|
| 573 |
+
self.model_tester.num_queries,
|
| 574 |
+
self.model_tester.num_labels,
|
| 575 |
+
)
|
| 576 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 577 |
+
# Confirm out_indices was propogated to backbone
|
| 578 |
+
self.assertEqual(len(model.model.backbone.conv_encoder.intermediate_channel_sizes), 4)
|
| 579 |
+
else:
|
| 580 |
+
# Confirm out_indices was propogated to backbone
|
| 581 |
+
self.assertEqual(len(model.backbone.conv_encoder.intermediate_channel_sizes), 4)
|
| 582 |
+
|
| 583 |
+
self.assertTrue(outputs)
|
| 584 |
+
|
| 585 |
+
def test_initialization(self):
|
| 586 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 587 |
+
|
| 588 |
+
configs_no_init = _config_zero_init(config)
|
| 589 |
+
for model_class in self.all_model_classes:
|
| 590 |
+
print("Model class:", model_class)
|
| 591 |
+
model = model_class(config=configs_no_init)
|
| 592 |
+
for name, param in model.named_parameters():
|
| 593 |
+
if param.requires_grad:
|
| 594 |
+
if param.requires_grad:
|
| 595 |
+
if (
|
| 596 |
+
"level_embed" in name
|
| 597 |
+
or "sampling_offsets.bias" in name
|
| 598 |
+
or "value_proj" in name
|
| 599 |
+
or "output_proj" in name
|
| 600 |
+
or "reference_points" in name
|
| 601 |
+
):
|
| 602 |
+
continue
|
| 603 |
+
self.assertIn(
|
| 604 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 605 |
+
[0.0, 1.0],
|
| 606 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 607 |
+
)
|
| 608 |
+
|
| 609 |
+
@unittest.skip(reason="No support for low_cpu_mem_usage=True.")
|
| 610 |
+
def test_save_load_low_cpu_mem_usage(self):
|
| 611 |
+
pass
|
| 612 |
+
|
| 613 |
+
@unittest.skip(reason="No support for low_cpu_mem_usage=True.")
|
| 614 |
+
def test_save_load_low_cpu_mem_usage_checkpoints(self):
|
| 615 |
+
pass
|
| 616 |
+
|
| 617 |
+
@unittest.skip(reason="No support for low_cpu_mem_usage=True.")
|
| 618 |
+
def test_save_load_low_cpu_mem_usage_no_safetensors(self):
|
| 619 |
+
pass
|
| 620 |
+
|
| 621 |
+
def test_two_stage_training(self):
|
| 622 |
+
model_class = DeformableDetrForObjectDetection
|
| 623 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 624 |
+
config.return_dict = True
|
| 625 |
+
config.two_stage = True
|
| 626 |
+
config.auxiliary_loss = True
|
| 627 |
+
config.with_box_refine = True
|
| 628 |
+
|
| 629 |
+
model = model_class(config)
|
| 630 |
+
model.to(torch_device)
|
| 631 |
+
model.train()
|
| 632 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 633 |
+
loss = model(**inputs).loss
|
| 634 |
+
loss.backward()
|
| 635 |
+
|
| 636 |
+
def create_and_check_model_fp16_forward(self):
|
| 637 |
+
model_class = DeformableDetrForObjectDetection
|
| 638 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 639 |
+
|
| 640 |
+
model = model_class(config)
|
| 641 |
+
model.to(torch_device)
|
| 642 |
+
model.half()
|
| 643 |
+
model.eval()
|
| 644 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 645 |
+
output = model(**inputs)["last_hidden_state"]
|
| 646 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 647 |
+
|
| 648 |
+
@require_torch_bf16
|
| 649 |
+
def create_and_check_model_bf16_forward(self):
|
| 650 |
+
model_class = DeformableDetrForObjectDetection
|
| 651 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 652 |
+
|
| 653 |
+
model = model_class(config, torch_dtype=torch.bfloat16)
|
| 654 |
+
model.to(torch_device)
|
| 655 |
+
model.eval()
|
| 656 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 657 |
+
output = model(**inputs)["last_hidden_state"]
|
| 658 |
+
self.parent.assertFalse(torch.isnan(output).any().item())
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
TOLERANCE = 1e-4
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
# We will verify our results on an image of cute cats
|
| 665 |
+
def prepare_img():
|
| 666 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 667 |
+
return image
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
@require_timm
|
| 671 |
+
@require_vision
|
| 672 |
+
@slow
|
| 673 |
+
class DeformableDetrModelIntegrationTests(unittest.TestCase):
|
| 674 |
+
@cached_property
|
| 675 |
+
def default_image_processor(self):
|
| 676 |
+
return AutoImageProcessor.from_pretrained("SenseTime/deformable-detr") if is_vision_available() else None
|
| 677 |
+
|
| 678 |
+
def test_inference_object_detection_head(self):
|
| 679 |
+
model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr").to(torch_device)
|
| 680 |
+
|
| 681 |
+
image_processor = self.default_image_processor
|
| 682 |
+
image = prepare_img()
|
| 683 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 684 |
+
pixel_values = encoding["pixel_values"].to(torch_device)
|
| 685 |
+
pixel_mask = encoding["pixel_mask"].to(torch_device)
|
| 686 |
+
|
| 687 |
+
with torch.no_grad():
|
| 688 |
+
outputs = model(pixel_values, pixel_mask)
|
| 689 |
+
|
| 690 |
+
expected_shape_logits = torch.Size((1, model.config.num_queries, model.config.num_labels))
|
| 691 |
+
self.assertEqual(outputs.logits.shape, expected_shape_logits)
|
| 692 |
+
|
| 693 |
+
expected_logits = torch.tensor(
|
| 694 |
+
[[-9.6645, -4.3449, -5.8705], [-9.7035, -3.8504, -5.0724], [-10.5634, -5.3379, -7.5116]]
|
| 695 |
+
).to(torch_device)
|
| 696 |
+
expected_boxes = torch.tensor(
|
| 697 |
+
[[0.8693, 0.2289, 0.2492], [0.3150, 0.5489, 0.5845], [0.5563, 0.7580, 0.8518]]
|
| 698 |
+
).to(torch_device)
|
| 699 |
+
|
| 700 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_logits, atol=1e-4))
|
| 701 |
+
|
| 702 |
+
expected_shape_boxes = torch.Size((1, model.config.num_queries, 4))
|
| 703 |
+
self.assertEqual(outputs.pred_boxes.shape, expected_shape_boxes)
|
| 704 |
+
self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes, atol=1e-4))
|
| 705 |
+
|
| 706 |
+
# verify postprocessing
|
| 707 |
+
results = image_processor.post_process_object_detection(
|
| 708 |
+
outputs, threshold=0.3, target_sizes=[image.size[::-1]]
|
| 709 |
+
)[0]
|
| 710 |
+
expected_scores = torch.tensor([0.7999, 0.7894, 0.6331, 0.4720, 0.4382]).to(torch_device)
|
| 711 |
+
expected_labels = [17, 17, 75, 75, 63]
|
| 712 |
+
expected_slice_boxes = torch.tensor([16.5028, 52.8390, 318.2544, 470.7841]).to(torch_device)
|
| 713 |
+
|
| 714 |
+
self.assertEqual(len(results["scores"]), 5)
|
| 715 |
+
self.assertTrue(torch.allclose(results["scores"], expected_scores, atol=1e-4))
|
| 716 |
+
self.assertSequenceEqual(results["labels"].tolist(), expected_labels)
|
| 717 |
+
self.assertTrue(torch.allclose(results["boxes"][0, :], expected_slice_boxes))
|
| 718 |
+
|
| 719 |
+
def test_inference_object_detection_head_with_box_refine_two_stage(self):
|
| 720 |
+
model = DeformableDetrForObjectDetection.from_pretrained(
|
| 721 |
+
"SenseTime/deformable-detr-with-box-refine-two-stage"
|
| 722 |
+
).to(torch_device)
|
| 723 |
+
|
| 724 |
+
image_processor = self.default_image_processor
|
| 725 |
+
image = prepare_img()
|
| 726 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 727 |
+
pixel_values = encoding["pixel_values"].to(torch_device)
|
| 728 |
+
pixel_mask = encoding["pixel_mask"].to(torch_device)
|
| 729 |
+
|
| 730 |
+
with torch.no_grad():
|
| 731 |
+
outputs = model(pixel_values, pixel_mask)
|
| 732 |
+
|
| 733 |
+
expected_shape_logits = torch.Size((1, model.config.num_queries, model.config.num_labels))
|
| 734 |
+
self.assertEqual(outputs.logits.shape, expected_shape_logits)
|
| 735 |
+
|
| 736 |
+
expected_logits = torch.tensor(
|
| 737 |
+
[[-6.7108, -4.3213, -6.3777], [-8.9014, -6.1799, -6.7240], [-6.9315, -4.4735, -6.2298]]
|
| 738 |
+
).to(torch_device)
|
| 739 |
+
expected_boxes = torch.tensor(
|
| 740 |
+
[[0.2583, 0.5499, 0.4683], [0.7652, 0.9068, 0.4882], [0.5490, 0.2763, 0.0564]]
|
| 741 |
+
).to(torch_device)
|
| 742 |
+
|
| 743 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_logits, atol=1e-4))
|
| 744 |
+
|
| 745 |
+
expected_shape_boxes = torch.Size((1, model.config.num_queries, 4))
|
| 746 |
+
self.assertEqual(outputs.pred_boxes.shape, expected_shape_boxes)
|
| 747 |
+
self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_boxes, atol=1e-4))
|
| 748 |
+
|
| 749 |
+
@require_torch_accelerator
|
| 750 |
+
def test_inference_object_detection_head_equivalence_cpu_gpu(self):
|
| 751 |
+
image_processor = self.default_image_processor
|
| 752 |
+
image = prepare_img()
|
| 753 |
+
encoding = image_processor(images=image, return_tensors="pt")
|
| 754 |
+
pixel_values = encoding["pixel_values"]
|
| 755 |
+
pixel_mask = encoding["pixel_mask"]
|
| 756 |
+
|
| 757 |
+
# 1. run model on CPU
|
| 758 |
+
model = DeformableDetrForObjectDetection.from_pretrained("SenseTime/deformable-detr-single-scale")
|
| 759 |
+
|
| 760 |
+
with torch.no_grad():
|
| 761 |
+
cpu_outputs = model(pixel_values, pixel_mask)
|
| 762 |
+
|
| 763 |
+
# 2. run model on GPU
|
| 764 |
+
model.to(torch_device)
|
| 765 |
+
|
| 766 |
+
with torch.no_grad():
|
| 767 |
+
gpu_outputs = model(pixel_values.to(torch_device), pixel_mask.to(torch_device))
|
| 768 |
+
|
| 769 |
+
# 3. assert equivalence
|
| 770 |
+
for key in cpu_outputs.keys():
|
| 771 |
+
assert torch.allclose(cpu_outputs[key], gpu_outputs[key].cpu(), atol=1e-4)
|
| 772 |
+
|
| 773 |
+
expected_logits = torch.tensor(
|
| 774 |
+
[[-9.9051, -4.2541, -6.4852], [-9.6947, -4.0854, -6.8033], [-10.0665, -5.8470, -7.7003]]
|
| 775 |
+
)
|
| 776 |
+
assert torch.allclose(cpu_outputs.logits[0, :3, :3], expected_logits, atol=1e-4)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_image_processing_deit.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers.testing_utils import require_torch, require_vision
|
| 20 |
+
from transformers.utils import is_vision_available
|
| 21 |
+
|
| 22 |
+
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_vision_available():
|
| 26 |
+
from transformers import DeiTImageProcessor
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DeiTImageProcessingTester(unittest.TestCase):
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
parent,
|
| 33 |
+
batch_size=7,
|
| 34 |
+
num_channels=3,
|
| 35 |
+
image_size=18,
|
| 36 |
+
min_resolution=30,
|
| 37 |
+
max_resolution=400,
|
| 38 |
+
do_resize=True,
|
| 39 |
+
size=None,
|
| 40 |
+
do_center_crop=True,
|
| 41 |
+
crop_size=None,
|
| 42 |
+
do_normalize=True,
|
| 43 |
+
image_mean=[0.5, 0.5, 0.5],
|
| 44 |
+
image_std=[0.5, 0.5, 0.5],
|
| 45 |
+
):
|
| 46 |
+
super().__init__()
|
| 47 |
+
size = size if size is not None else {"height": 20, "width": 20}
|
| 48 |
+
crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18}
|
| 49 |
+
|
| 50 |
+
self.parent = parent
|
| 51 |
+
self.batch_size = batch_size
|
| 52 |
+
self.num_channels = num_channels
|
| 53 |
+
self.image_size = image_size
|
| 54 |
+
self.min_resolution = min_resolution
|
| 55 |
+
self.max_resolution = max_resolution
|
| 56 |
+
self.do_resize = do_resize
|
| 57 |
+
self.size = size
|
| 58 |
+
self.do_center_crop = do_center_crop
|
| 59 |
+
self.crop_size = crop_size
|
| 60 |
+
self.do_normalize = do_normalize
|
| 61 |
+
self.image_mean = image_mean
|
| 62 |
+
self.image_std = image_std
|
| 63 |
+
|
| 64 |
+
def prepare_image_processor_dict(self):
|
| 65 |
+
return {
|
| 66 |
+
"do_resize": self.do_resize,
|
| 67 |
+
"size": self.size,
|
| 68 |
+
"do_center_crop": self.do_center_crop,
|
| 69 |
+
"crop_size": self.crop_size,
|
| 70 |
+
"do_normalize": self.do_normalize,
|
| 71 |
+
"image_mean": self.image_mean,
|
| 72 |
+
"image_std": self.image_std,
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
def expected_output_image_shape(self, images):
|
| 76 |
+
return self.num_channels, self.crop_size["height"], self.crop_size["width"]
|
| 77 |
+
|
| 78 |
+
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
| 79 |
+
return prepare_image_inputs(
|
| 80 |
+
batch_size=self.batch_size,
|
| 81 |
+
num_channels=self.num_channels,
|
| 82 |
+
min_resolution=self.min_resolution,
|
| 83 |
+
max_resolution=self.max_resolution,
|
| 84 |
+
equal_resolution=equal_resolution,
|
| 85 |
+
numpify=numpify,
|
| 86 |
+
torchify=torchify,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@require_torch
|
| 91 |
+
@require_vision
|
| 92 |
+
class DeiTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
|
| 93 |
+
image_processing_class = DeiTImageProcessor if is_vision_available() else None
|
| 94 |
+
test_cast_dtype = True
|
| 95 |
+
|
| 96 |
+
def setUp(self):
|
| 97 |
+
super().setUp()
|
| 98 |
+
self.image_processor_tester = DeiTImageProcessingTester(self)
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def image_processor_dict(self):
|
| 102 |
+
return self.image_processor_tester.prepare_image_processor_dict()
|
| 103 |
+
|
| 104 |
+
def test_image_processor_properties(self):
|
| 105 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 106 |
+
self.assertTrue(hasattr(image_processing, "do_resize"))
|
| 107 |
+
self.assertTrue(hasattr(image_processing, "size"))
|
| 108 |
+
self.assertTrue(hasattr(image_processing, "do_center_crop"))
|
| 109 |
+
self.assertTrue(hasattr(image_processing, "center_crop"))
|
| 110 |
+
self.assertTrue(hasattr(image_processing, "do_normalize"))
|
| 111 |
+
self.assertTrue(hasattr(image_processing, "image_mean"))
|
| 112 |
+
self.assertTrue(hasattr(image_processing, "image_std"))
|
| 113 |
+
|
| 114 |
+
def test_image_processor_from_dict_with_kwargs(self):
|
| 115 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
|
| 116 |
+
self.assertEqual(image_processor.size, {"height": 20, "width": 20})
|
| 117 |
+
self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18})
|
| 118 |
+
|
| 119 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84)
|
| 120 |
+
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
|
| 121 |
+
self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84})
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_modeling_deit.py
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch DeiT model."""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
import warnings
|
| 19 |
+
|
| 20 |
+
from transformers import DeiTConfig
|
| 21 |
+
from transformers.testing_utils import (
|
| 22 |
+
require_accelerate,
|
| 23 |
+
require_torch,
|
| 24 |
+
require_torch_accelerator,
|
| 25 |
+
require_torch_fp16,
|
| 26 |
+
require_vision,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
from transformers.utils import cached_property, is_torch_available, is_vision_available
|
| 31 |
+
|
| 32 |
+
from ...test_configuration_common import ConfigTester
|
| 33 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 34 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if is_torch_available():
|
| 38 |
+
import torch
|
| 39 |
+
from torch import nn
|
| 40 |
+
|
| 41 |
+
from transformers import (
|
| 42 |
+
DeiTForImageClassification,
|
| 43 |
+
DeiTForImageClassificationWithTeacher,
|
| 44 |
+
DeiTForMaskedImageModeling,
|
| 45 |
+
DeiTModel,
|
| 46 |
+
)
|
| 47 |
+
from transformers.models.auto.modeling_auto import (
|
| 48 |
+
MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
|
| 49 |
+
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
|
| 50 |
+
MODEL_MAPPING_NAMES,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
if is_vision_available():
|
| 55 |
+
from PIL import Image
|
| 56 |
+
|
| 57 |
+
from transformers import DeiTImageProcessor
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class DeiTModelTester:
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
parent,
|
| 64 |
+
batch_size=13,
|
| 65 |
+
image_size=30,
|
| 66 |
+
patch_size=2,
|
| 67 |
+
num_channels=3,
|
| 68 |
+
is_training=True,
|
| 69 |
+
use_labels=True,
|
| 70 |
+
hidden_size=32,
|
| 71 |
+
num_hidden_layers=2,
|
| 72 |
+
num_attention_heads=4,
|
| 73 |
+
intermediate_size=37,
|
| 74 |
+
hidden_act="gelu",
|
| 75 |
+
hidden_dropout_prob=0.1,
|
| 76 |
+
attention_probs_dropout_prob=0.1,
|
| 77 |
+
type_sequence_label_size=10,
|
| 78 |
+
initializer_range=0.02,
|
| 79 |
+
num_labels=3,
|
| 80 |
+
scope=None,
|
| 81 |
+
encoder_stride=2,
|
| 82 |
+
mask_ratio=0.5,
|
| 83 |
+
attn_implementation="eager",
|
| 84 |
+
):
|
| 85 |
+
self.parent = parent
|
| 86 |
+
self.batch_size = batch_size
|
| 87 |
+
self.image_size = image_size
|
| 88 |
+
self.patch_size = patch_size
|
| 89 |
+
self.num_channels = num_channels
|
| 90 |
+
self.is_training = is_training
|
| 91 |
+
self.use_labels = use_labels
|
| 92 |
+
self.hidden_size = hidden_size
|
| 93 |
+
self.num_hidden_layers = num_hidden_layers
|
| 94 |
+
self.num_attention_heads = num_attention_heads
|
| 95 |
+
self.intermediate_size = intermediate_size
|
| 96 |
+
self.hidden_act = hidden_act
|
| 97 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 98 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 99 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 100 |
+
self.initializer_range = initializer_range
|
| 101 |
+
self.scope = scope
|
| 102 |
+
self.encoder_stride = encoder_stride
|
| 103 |
+
self.attn_implementation = attn_implementation
|
| 104 |
+
|
| 105 |
+
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
|
| 106 |
+
num_patches = (image_size // patch_size) ** 2
|
| 107 |
+
self.seq_length = num_patches + 2
|
| 108 |
+
self.mask_ratio = mask_ratio
|
| 109 |
+
self.num_masks = int(mask_ratio * self.seq_length)
|
| 110 |
+
self.mask_length = num_patches
|
| 111 |
+
|
| 112 |
+
def prepare_config_and_inputs(self):
|
| 113 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 114 |
+
|
| 115 |
+
labels = None
|
| 116 |
+
if self.use_labels:
|
| 117 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 118 |
+
|
| 119 |
+
config = self.get_config()
|
| 120 |
+
|
| 121 |
+
return config, pixel_values, labels
|
| 122 |
+
|
| 123 |
+
def get_config(self):
|
| 124 |
+
return DeiTConfig(
|
| 125 |
+
image_size=self.image_size,
|
| 126 |
+
patch_size=self.patch_size,
|
| 127 |
+
num_channels=self.num_channels,
|
| 128 |
+
hidden_size=self.hidden_size,
|
| 129 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 130 |
+
num_attention_heads=self.num_attention_heads,
|
| 131 |
+
intermediate_size=self.intermediate_size,
|
| 132 |
+
hidden_act=self.hidden_act,
|
| 133 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 134 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 135 |
+
is_decoder=False,
|
| 136 |
+
initializer_range=self.initializer_range,
|
| 137 |
+
encoder_stride=self.encoder_stride,
|
| 138 |
+
attn_implementation=self.attn_implementation,
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 142 |
+
model = DeiTModel(config=config)
|
| 143 |
+
model.to(torch_device)
|
| 144 |
+
model.eval()
|
| 145 |
+
result = model(pixel_values)
|
| 146 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 147 |
+
|
| 148 |
+
def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
|
| 149 |
+
model = DeiTForMaskedImageModeling(config=config)
|
| 150 |
+
model.to(torch_device)
|
| 151 |
+
model.eval()
|
| 152 |
+
result = model(pixel_values)
|
| 153 |
+
self.parent.assertEqual(
|
| 154 |
+
result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# test greyscale images
|
| 158 |
+
config.num_channels = 1
|
| 159 |
+
model = DeiTForMaskedImageModeling(config)
|
| 160 |
+
model.to(torch_device)
|
| 161 |
+
model.eval()
|
| 162 |
+
|
| 163 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 164 |
+
result = model(pixel_values)
|
| 165 |
+
self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size))
|
| 166 |
+
|
| 167 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 168 |
+
config.num_labels = self.type_sequence_label_size
|
| 169 |
+
model = DeiTForImageClassification(config)
|
| 170 |
+
model.to(torch_device)
|
| 171 |
+
model.eval()
|
| 172 |
+
result = model(pixel_values, labels=labels)
|
| 173 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 174 |
+
|
| 175 |
+
# test greyscale images
|
| 176 |
+
config.num_channels = 1
|
| 177 |
+
model = DeiTForImageClassification(config)
|
| 178 |
+
model.to(torch_device)
|
| 179 |
+
model.eval()
|
| 180 |
+
|
| 181 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 182 |
+
result = model(pixel_values, labels=labels)
|
| 183 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 184 |
+
|
| 185 |
+
def prepare_config_and_inputs_for_common(self):
|
| 186 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 187 |
+
(
|
| 188 |
+
config,
|
| 189 |
+
pixel_values,
|
| 190 |
+
labels,
|
| 191 |
+
) = config_and_inputs
|
| 192 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 193 |
+
return config, inputs_dict
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@require_torch
|
| 197 |
+
class DeiTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 198 |
+
"""
|
| 199 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as DeiT does not use input_ids, inputs_embeds,
|
| 200 |
+
attention_mask and seq_length.
|
| 201 |
+
"""
|
| 202 |
+
|
| 203 |
+
all_model_classes = (
|
| 204 |
+
(
|
| 205 |
+
DeiTModel,
|
| 206 |
+
DeiTForImageClassification,
|
| 207 |
+
DeiTForImageClassificationWithTeacher,
|
| 208 |
+
DeiTForMaskedImageModeling,
|
| 209 |
+
)
|
| 210 |
+
if is_torch_available()
|
| 211 |
+
else ()
|
| 212 |
+
)
|
| 213 |
+
pipeline_model_mapping = (
|
| 214 |
+
{
|
| 215 |
+
"image-feature-extraction": DeiTModel,
|
| 216 |
+
"image-classification": (DeiTForImageClassification, DeiTForImageClassificationWithTeacher),
|
| 217 |
+
}
|
| 218 |
+
if is_torch_available()
|
| 219 |
+
else {}
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
test_pruning = False
|
| 223 |
+
test_resize_embeddings = False
|
| 224 |
+
test_head_masking = False
|
| 225 |
+
|
| 226 |
+
def setUp(self):
|
| 227 |
+
self.model_tester = DeiTModelTester(self)
|
| 228 |
+
self.config_tester = ConfigTester(self, config_class=DeiTConfig, has_text_modality=False, hidden_size=37)
|
| 229 |
+
|
| 230 |
+
@unittest.skip(
|
| 231 |
+
"Since `torch==2.3+cu121`, although this test passes, many subsequent tests have `CUDA error: misaligned address`."
|
| 232 |
+
"If `nvidia-xxx-cu118` are also installed, no failure (even with `torch==2.3+cu121`)."
|
| 233 |
+
)
|
| 234 |
+
def test_multi_gpu_data_parallel_forward(self):
|
| 235 |
+
super().test_multi_gpu_data_parallel_forward()
|
| 236 |
+
|
| 237 |
+
def test_config(self):
|
| 238 |
+
self.config_tester.run_common_tests()
|
| 239 |
+
|
| 240 |
+
@unittest.skip(reason="DeiT does not use inputs_embeds")
|
| 241 |
+
def test_inputs_embeds(self):
|
| 242 |
+
pass
|
| 243 |
+
|
| 244 |
+
def test_model_get_set_embeddings(self):
|
| 245 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 246 |
+
|
| 247 |
+
for model_class in self.all_model_classes:
|
| 248 |
+
model = model_class(config)
|
| 249 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 250 |
+
x = model.get_output_embeddings()
|
| 251 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 252 |
+
|
| 253 |
+
def test_model(self):
|
| 254 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 255 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 256 |
+
|
| 257 |
+
def test_for_masked_image_modeling(self):
|
| 258 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 259 |
+
self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
|
| 260 |
+
|
| 261 |
+
def test_for_image_classification(self):
|
| 262 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 263 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 264 |
+
|
| 265 |
+
# special case for DeiTForImageClassificationWithTeacher model
|
| 266 |
+
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
| 267 |
+
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
| 268 |
+
|
| 269 |
+
if return_labels:
|
| 270 |
+
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
|
| 271 |
+
del inputs_dict["labels"]
|
| 272 |
+
|
| 273 |
+
return inputs_dict
|
| 274 |
+
|
| 275 |
+
def test_training(self):
|
| 276 |
+
if not self.model_tester.is_training:
|
| 277 |
+
self.skipTest(reason="model_tester.is_training is set to False")
|
| 278 |
+
|
| 279 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 280 |
+
config.return_dict = True
|
| 281 |
+
|
| 282 |
+
for model_class in self.all_model_classes:
|
| 283 |
+
# DeiTForImageClassificationWithTeacher supports inference-only
|
| 284 |
+
if (
|
| 285 |
+
model_class.__name__ in MODEL_MAPPING_NAMES.values()
|
| 286 |
+
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
|
| 287 |
+
):
|
| 288 |
+
continue
|
| 289 |
+
model = model_class(config)
|
| 290 |
+
model.to(torch_device)
|
| 291 |
+
model.train()
|
| 292 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 293 |
+
loss = model(**inputs).loss
|
| 294 |
+
loss.backward()
|
| 295 |
+
|
| 296 |
+
def test_training_gradient_checkpointing(self):
|
| 297 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 298 |
+
if not self.model_tester.is_training:
|
| 299 |
+
self.skipTest(reason="model_tester.is_training is set to False")
|
| 300 |
+
|
| 301 |
+
config.use_cache = False
|
| 302 |
+
config.return_dict = True
|
| 303 |
+
|
| 304 |
+
for model_class in self.all_model_classes:
|
| 305 |
+
if model_class.__name__ in MODEL_MAPPING_NAMES.values() or not model_class.supports_gradient_checkpointing:
|
| 306 |
+
continue
|
| 307 |
+
# DeiTForImageClassificationWithTeacher supports inference-only
|
| 308 |
+
if model_class.__name__ == "DeiTForImageClassificationWithTeacher":
|
| 309 |
+
continue
|
| 310 |
+
model = model_class(config)
|
| 311 |
+
model.gradient_checkpointing_enable()
|
| 312 |
+
model.to(torch_device)
|
| 313 |
+
model.train()
|
| 314 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 315 |
+
loss = model(**inputs).loss
|
| 316 |
+
loss.backward()
|
| 317 |
+
|
| 318 |
+
@unittest.skip(
|
| 319 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 320 |
+
)
|
| 321 |
+
def test_training_gradient_checkpointing_use_reentrant(self):
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
@unittest.skip(
|
| 325 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 326 |
+
)
|
| 327 |
+
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
| 328 |
+
pass
|
| 329 |
+
|
| 330 |
+
def test_problem_types(self):
|
| 331 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 332 |
+
|
| 333 |
+
problem_types = [
|
| 334 |
+
{"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
|
| 335 |
+
{"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
|
| 336 |
+
{"title": "regression", "num_labels": 1, "dtype": torch.float},
|
| 337 |
+
]
|
| 338 |
+
|
| 339 |
+
for model_class in self.all_model_classes:
|
| 340 |
+
if (
|
| 341 |
+
model_class.__name__
|
| 342 |
+
not in [
|
| 343 |
+
*MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(),
|
| 344 |
+
*MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES.values(),
|
| 345 |
+
]
|
| 346 |
+
or model_class.__name__ == "DeiTForImageClassificationWithTeacher"
|
| 347 |
+
):
|
| 348 |
+
continue
|
| 349 |
+
|
| 350 |
+
for problem_type in problem_types:
|
| 351 |
+
with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"):
|
| 352 |
+
config.problem_type = problem_type["title"]
|
| 353 |
+
config.num_labels = problem_type["num_labels"]
|
| 354 |
+
|
| 355 |
+
model = model_class(config)
|
| 356 |
+
model.to(torch_device)
|
| 357 |
+
model.train()
|
| 358 |
+
|
| 359 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 360 |
+
|
| 361 |
+
if problem_type["num_labels"] > 1:
|
| 362 |
+
inputs["labels"] = inputs["labels"].unsqueeze(1).repeat(1, problem_type["num_labels"])
|
| 363 |
+
|
| 364 |
+
inputs["labels"] = inputs["labels"].to(problem_type["dtype"])
|
| 365 |
+
|
| 366 |
+
# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
|
| 367 |
+
# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
|
| 368 |
+
# they have the same size." which is a symptom something in wrong for the regression problem.
|
| 369 |
+
# See https://github.com/huggingface/transformers/issues/11780
|
| 370 |
+
with warnings.catch_warnings(record=True) as warning_list:
|
| 371 |
+
loss = model(**inputs).loss
|
| 372 |
+
for w in warning_list:
|
| 373 |
+
if "Using a target size that is different to the input size" in str(w.message):
|
| 374 |
+
raise ValueError(
|
| 375 |
+
f"Something is going wrong in the regression problem: intercepted {w.message}"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
loss.backward()
|
| 379 |
+
|
| 380 |
+
@slow
|
| 381 |
+
def test_model_from_pretrained(self):
|
| 382 |
+
model_name = "facebook/deit-base-distilled-patch16-224"
|
| 383 |
+
model = DeiTModel.from_pretrained(model_name)
|
| 384 |
+
self.assertIsNotNone(model)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# We will verify our results on an image of cute cats
|
| 388 |
+
def prepare_img():
|
| 389 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 390 |
+
return image
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
@require_torch
|
| 394 |
+
@require_vision
|
| 395 |
+
class DeiTModelIntegrationTest(unittest.TestCase):
|
| 396 |
+
@cached_property
|
| 397 |
+
def default_image_processor(self):
|
| 398 |
+
return (
|
| 399 |
+
DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 400 |
+
if is_vision_available()
|
| 401 |
+
else None
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
@slow
|
| 405 |
+
def test_inference_image_classification_head(self):
|
| 406 |
+
model = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224").to(
|
| 407 |
+
torch_device
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
image_processor = self.default_image_processor
|
| 411 |
+
image = prepare_img()
|
| 412 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 413 |
+
|
| 414 |
+
# forward pass
|
| 415 |
+
with torch.no_grad():
|
| 416 |
+
outputs = model(**inputs)
|
| 417 |
+
|
| 418 |
+
# verify the logits
|
| 419 |
+
expected_shape = torch.Size((1, 1000))
|
| 420 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 421 |
+
|
| 422 |
+
expected_slice = torch.tensor([-1.0266, 0.1912, -1.2861]).to(torch_device)
|
| 423 |
+
|
| 424 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
| 425 |
+
|
| 426 |
+
@slow
|
| 427 |
+
def test_inference_interpolate_pos_encoding(self):
|
| 428 |
+
model = DeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224").to(
|
| 429 |
+
torch_device
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
image_processor = self.default_image_processor
|
| 433 |
+
|
| 434 |
+
# image size is {"height": 480, "width": 640}
|
| 435 |
+
image = prepare_img()
|
| 436 |
+
image_processor.size = {"height": 480, "width": 640}
|
| 437 |
+
# center crop set to False so image is not center cropped to 224x224
|
| 438 |
+
inputs = image_processor(images=image, return_tensors="pt", do_center_crop=False).to(torch_device)
|
| 439 |
+
|
| 440 |
+
# forward pass
|
| 441 |
+
with torch.no_grad():
|
| 442 |
+
outputs = model(**inputs, interpolate_pos_encoding=True)
|
| 443 |
+
|
| 444 |
+
# verify the logits
|
| 445 |
+
expected_shape = torch.Size((1, 1000))
|
| 446 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 447 |
+
|
| 448 |
+
@slow
|
| 449 |
+
@require_accelerate
|
| 450 |
+
@require_torch_accelerator
|
| 451 |
+
@require_torch_fp16
|
| 452 |
+
def test_inference_fp16(self):
|
| 453 |
+
r"""
|
| 454 |
+
A small test to make sure that inference work in half precision without any problem.
|
| 455 |
+
"""
|
| 456 |
+
model = DeiTModel.from_pretrained(
|
| 457 |
+
"facebook/deit-base-distilled-patch16-224", torch_dtype=torch.float16, device_map="auto"
|
| 458 |
+
)
|
| 459 |
+
image_processor = self.default_image_processor
|
| 460 |
+
|
| 461 |
+
image = prepare_img()
|
| 462 |
+
inputs = image_processor(images=image, return_tensors="pt")
|
| 463 |
+
pixel_values = inputs.pixel_values.to(torch_device)
|
| 464 |
+
|
| 465 |
+
# forward pass to make sure inference works in fp16
|
| 466 |
+
with torch.no_grad():
|
| 467 |
+
_ = model(pixel_values)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/deit/test_modeling_tf_deit.py
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the TensorFlow DeiT model."""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import inspect
|
| 20 |
+
import unittest
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from transformers import DeiTConfig
|
| 25 |
+
from transformers.testing_utils import require_tf, require_vision, slow
|
| 26 |
+
from transformers.utils import cached_property, is_tf_available, is_vision_available
|
| 27 |
+
|
| 28 |
+
from ...test_configuration_common import ConfigTester
|
| 29 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
|
| 30 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
if is_tf_available():
|
| 34 |
+
import tensorflow as tf
|
| 35 |
+
|
| 36 |
+
from transformers import (
|
| 37 |
+
TFDeiTForImageClassification,
|
| 38 |
+
TFDeiTForImageClassificationWithTeacher,
|
| 39 |
+
TFDeiTForMaskedImageModeling,
|
| 40 |
+
TFDeiTModel,
|
| 41 |
+
)
|
| 42 |
+
from transformers.modeling_tf_utils import keras
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_vision_available():
|
| 46 |
+
from PIL import Image
|
| 47 |
+
|
| 48 |
+
from transformers import DeiTImageProcessor
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TFDeiTModelTester:
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
parent,
|
| 55 |
+
batch_size=13,
|
| 56 |
+
image_size=30,
|
| 57 |
+
patch_size=2,
|
| 58 |
+
num_channels=3,
|
| 59 |
+
is_training=True,
|
| 60 |
+
use_labels=True,
|
| 61 |
+
hidden_size=32,
|
| 62 |
+
num_hidden_layers=2,
|
| 63 |
+
num_attention_heads=4,
|
| 64 |
+
intermediate_size=37,
|
| 65 |
+
hidden_act="gelu",
|
| 66 |
+
hidden_dropout_prob=0.1,
|
| 67 |
+
attention_probs_dropout_prob=0.1,
|
| 68 |
+
type_sequence_label_size=10,
|
| 69 |
+
initializer_range=0.02,
|
| 70 |
+
num_labels=3,
|
| 71 |
+
scope=None,
|
| 72 |
+
encoder_stride=2,
|
| 73 |
+
attn_implementation="eager",
|
| 74 |
+
):
|
| 75 |
+
self.parent = parent
|
| 76 |
+
self.batch_size = batch_size
|
| 77 |
+
self.image_size = image_size
|
| 78 |
+
self.patch_size = patch_size
|
| 79 |
+
self.num_channels = num_channels
|
| 80 |
+
self.is_training = is_training
|
| 81 |
+
self.use_labels = use_labels
|
| 82 |
+
self.hidden_size = hidden_size
|
| 83 |
+
self.num_hidden_layers = num_hidden_layers
|
| 84 |
+
self.num_attention_heads = num_attention_heads
|
| 85 |
+
self.intermediate_size = intermediate_size
|
| 86 |
+
self.hidden_act = hidden_act
|
| 87 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 88 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 89 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 90 |
+
self.initializer_range = initializer_range
|
| 91 |
+
self.scope = scope
|
| 92 |
+
self.encoder_stride = encoder_stride
|
| 93 |
+
self.attn_implementation = attn_implementation
|
| 94 |
+
|
| 95 |
+
# in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
|
| 96 |
+
num_patches = (image_size // patch_size) ** 2
|
| 97 |
+
self.seq_length = num_patches + 2
|
| 98 |
+
|
| 99 |
+
def prepare_config_and_inputs(self):
|
| 100 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 101 |
+
|
| 102 |
+
labels = None
|
| 103 |
+
if self.use_labels:
|
| 104 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 105 |
+
|
| 106 |
+
config = self.get_config()
|
| 107 |
+
|
| 108 |
+
return config, pixel_values, labels
|
| 109 |
+
|
| 110 |
+
def get_config(self):
|
| 111 |
+
return DeiTConfig(
|
| 112 |
+
image_size=self.image_size,
|
| 113 |
+
patch_size=self.patch_size,
|
| 114 |
+
num_channels=self.num_channels,
|
| 115 |
+
hidden_size=self.hidden_size,
|
| 116 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 117 |
+
num_attention_heads=self.num_attention_heads,
|
| 118 |
+
intermediate_size=self.intermediate_size,
|
| 119 |
+
hidden_act=self.hidden_act,
|
| 120 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 121 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 122 |
+
is_decoder=False,
|
| 123 |
+
initializer_range=self.initializer_range,
|
| 124 |
+
encoder_stride=self.encoder_stride,
|
| 125 |
+
attn_implementation=self.attn_implementation,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 129 |
+
model = TFDeiTModel(config=config)
|
| 130 |
+
result = model(pixel_values)
|
| 131 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 132 |
+
|
| 133 |
+
def create_and_check_for_masked_image_modeling(self, config, pixel_values, labels):
|
| 134 |
+
model = TFDeiTForMaskedImageModeling(config=config)
|
| 135 |
+
result = model(pixel_values)
|
| 136 |
+
self.parent.assertEqual(
|
| 137 |
+
result.reconstruction.shape, (self.batch_size, self.num_channels, self.image_size, self.image_size)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# test greyscale images
|
| 141 |
+
config.num_channels = 1
|
| 142 |
+
model = TFDeiTForMaskedImageModeling(config)
|
| 143 |
+
|
| 144 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 145 |
+
result = model(pixel_values)
|
| 146 |
+
self.parent.assertEqual(result.reconstruction.shape, (self.batch_size, 1, self.image_size, self.image_size))
|
| 147 |
+
|
| 148 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 149 |
+
config.num_labels = self.type_sequence_label_size
|
| 150 |
+
model = TFDeiTForImageClassification(config)
|
| 151 |
+
result = model(pixel_values, labels=labels)
|
| 152 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 153 |
+
|
| 154 |
+
# test greyscale images
|
| 155 |
+
config.num_channels = 1
|
| 156 |
+
model = TFDeiTForImageClassification(config)
|
| 157 |
+
|
| 158 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 159 |
+
result = model(pixel_values, labels=labels)
|
| 160 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 161 |
+
|
| 162 |
+
def prepare_config_and_inputs_for_common(self):
|
| 163 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 164 |
+
config, pixel_values, labels = config_and_inputs
|
| 165 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 166 |
+
return config, inputs_dict
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@require_tf
|
| 170 |
+
class TFDeiTModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 171 |
+
"""
|
| 172 |
+
Here we also overwrite some of the tests of test_modeling_tf_common.py, as DeiT does not use input_ids, inputs_embeds,
|
| 173 |
+
attention_mask and seq_length.
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
all_model_classes = (
|
| 177 |
+
(
|
| 178 |
+
TFDeiTModel,
|
| 179 |
+
TFDeiTForImageClassification,
|
| 180 |
+
TFDeiTForImageClassificationWithTeacher,
|
| 181 |
+
TFDeiTForMaskedImageModeling,
|
| 182 |
+
)
|
| 183 |
+
if is_tf_available()
|
| 184 |
+
else ()
|
| 185 |
+
)
|
| 186 |
+
pipeline_model_mapping = (
|
| 187 |
+
{
|
| 188 |
+
"feature-extraction": TFDeiTModel,
|
| 189 |
+
"image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
|
| 190 |
+
}
|
| 191 |
+
if is_tf_available()
|
| 192 |
+
else {}
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
test_pruning = False
|
| 196 |
+
test_resize_embeddings = False
|
| 197 |
+
test_head_masking = False
|
| 198 |
+
test_onnx = False
|
| 199 |
+
|
| 200 |
+
def setUp(self):
|
| 201 |
+
self.model_tester = TFDeiTModelTester(self)
|
| 202 |
+
self.config_tester = ConfigTester(self, config_class=DeiTConfig, has_text_modality=False, hidden_size=37)
|
| 203 |
+
|
| 204 |
+
def test_config(self):
|
| 205 |
+
self.config_tester.run_common_tests()
|
| 206 |
+
|
| 207 |
+
@unittest.skip(reason="DeiT does not use inputs_embeds")
|
| 208 |
+
def test_inputs_embeds(self):
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
def test_model_common_attributes(self):
|
| 212 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 213 |
+
|
| 214 |
+
for model_class in self.all_model_classes:
|
| 215 |
+
model = model_class(config)
|
| 216 |
+
self.assertIsInstance(model.get_input_embeddings(), (keras.layers.Layer))
|
| 217 |
+
x = model.get_output_embeddings()
|
| 218 |
+
self.assertTrue(x is None or isinstance(x, keras.layers.Dense))
|
| 219 |
+
|
| 220 |
+
def test_forward_signature(self):
|
| 221 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 222 |
+
|
| 223 |
+
for model_class in self.all_model_classes:
|
| 224 |
+
model = model_class(config)
|
| 225 |
+
signature = inspect.signature(model.call)
|
| 226 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 227 |
+
arg_names = [*signature.parameters.keys()]
|
| 228 |
+
|
| 229 |
+
expected_arg_names = ["pixel_values"]
|
| 230 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 231 |
+
|
| 232 |
+
def test_model(self):
|
| 233 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 234 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 235 |
+
|
| 236 |
+
def test_for_masked_image_modeling(self):
|
| 237 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 238 |
+
self.model_tester.create_and_check_for_masked_image_modeling(*config_and_inputs)
|
| 239 |
+
|
| 240 |
+
def test_for_image_classification(self):
|
| 241 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 242 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 243 |
+
|
| 244 |
+
# special case for DeiTForImageClassificationWithTeacher model
|
| 245 |
+
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
| 246 |
+
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
| 247 |
+
|
| 248 |
+
if return_labels:
|
| 249 |
+
if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call).parameters:
|
| 250 |
+
del inputs_dict["labels"]
|
| 251 |
+
|
| 252 |
+
return inputs_dict
|
| 253 |
+
|
| 254 |
+
@slow
|
| 255 |
+
def test_model_from_pretrained(self):
|
| 256 |
+
model_name = "facebook/deit-base-distilled-patch16-224"
|
| 257 |
+
model = TFDeiTModel.from_pretrained(model_name)
|
| 258 |
+
self.assertIsNotNone(model)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
# We will verify our results on an image of cute cats
|
| 262 |
+
def prepare_img():
|
| 263 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 264 |
+
return image
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
@require_tf
|
| 268 |
+
@require_vision
|
| 269 |
+
class DeiTModelIntegrationTest(unittest.TestCase):
|
| 270 |
+
@cached_property
|
| 271 |
+
def default_image_processor(self):
|
| 272 |
+
return (
|
| 273 |
+
DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 274 |
+
if is_vision_available()
|
| 275 |
+
else None
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
@slow
|
| 279 |
+
def test_inference_image_classification_head(self):
|
| 280 |
+
model = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 281 |
+
|
| 282 |
+
image_processor = self.default_image_processor
|
| 283 |
+
image = prepare_img()
|
| 284 |
+
inputs = image_processor(images=image, return_tensors="tf")
|
| 285 |
+
|
| 286 |
+
# forward pass
|
| 287 |
+
outputs = model(**inputs)
|
| 288 |
+
|
| 289 |
+
# verify the logits
|
| 290 |
+
expected_shape = tf.TensorShape((1, 1000))
|
| 291 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 292 |
+
|
| 293 |
+
expected_slice = tf.constant([-1.0266, 0.1912, -1.2861])
|
| 294 |
+
|
| 295 |
+
self.assertTrue(np.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
| 296 |
+
|
| 297 |
+
@slow
|
| 298 |
+
def test_inference_interpolate_pos_encoding(self):
|
| 299 |
+
model = TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224")
|
| 300 |
+
|
| 301 |
+
image_processor = self.default_image_processor
|
| 302 |
+
# image size is {"height": 480, "width": 640}
|
| 303 |
+
image = prepare_img()
|
| 304 |
+
image_processor.size = {"height": 480, "width": 640}
|
| 305 |
+
# center crop set to False so image is not center cropped to 224x224
|
| 306 |
+
inputs = image_processor(images=image, return_tensors="tf", do_center_crop=False)
|
| 307 |
+
# forward pass
|
| 308 |
+
outputs = model(**inputs, interpolate_pos_encoding=True)
|
| 309 |
+
|
| 310 |
+
# verify the logits
|
| 311 |
+
expected_shape = tf.TensorShape((1, 1000))
|
| 312 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/depth_anything/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/depth_anything/test_modeling_depth_anything.py
ADDED
|
@@ -0,0 +1,320 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Depth Anything model."""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import DepthAnythingConfig, Dinov2Config
|
| 20 |
+
from transformers.file_utils import is_torch_available, is_vision_available
|
| 21 |
+
from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_4
|
| 22 |
+
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from transformers import DepthAnythingForDepthEstimation
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_vision_available():
|
| 36 |
+
from PIL import Image
|
| 37 |
+
|
| 38 |
+
from transformers import DPTImageProcessor
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class DepthAnythingModelTester:
|
| 42 |
+
# Copied from tests.models.dpt.test_modeling_dpt_auto_backbone.DPTModelTester.__init__
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
parent,
|
| 46 |
+
batch_size=2,
|
| 47 |
+
num_channels=3,
|
| 48 |
+
image_size=32,
|
| 49 |
+
patch_size=16,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
num_labels=3,
|
| 52 |
+
is_training=True,
|
| 53 |
+
hidden_size=4,
|
| 54 |
+
num_hidden_layers=2,
|
| 55 |
+
num_attention_heads=2,
|
| 56 |
+
intermediate_size=8,
|
| 57 |
+
out_features=["stage1", "stage2"],
|
| 58 |
+
apply_layernorm=False,
|
| 59 |
+
reshape_hidden_states=False,
|
| 60 |
+
neck_hidden_sizes=[2, 2],
|
| 61 |
+
fusion_hidden_size=6,
|
| 62 |
+
):
|
| 63 |
+
self.parent = parent
|
| 64 |
+
self.batch_size = batch_size
|
| 65 |
+
self.num_channels = num_channels
|
| 66 |
+
self.image_size = image_size
|
| 67 |
+
self.patch_size = patch_size
|
| 68 |
+
self.hidden_size = hidden_size
|
| 69 |
+
self.num_hidden_layers = num_hidden_layers
|
| 70 |
+
self.num_attention_heads = num_attention_heads
|
| 71 |
+
self.intermediate_size = intermediate_size
|
| 72 |
+
self.out_features = out_features
|
| 73 |
+
self.apply_layernorm = apply_layernorm
|
| 74 |
+
self.reshape_hidden_states = reshape_hidden_states
|
| 75 |
+
self.use_labels = use_labels
|
| 76 |
+
self.num_labels = num_labels
|
| 77 |
+
self.is_training = is_training
|
| 78 |
+
self.neck_hidden_sizes = neck_hidden_sizes
|
| 79 |
+
self.fusion_hidden_size = fusion_hidden_size
|
| 80 |
+
# DPT's sequence length
|
| 81 |
+
self.seq_length = (self.image_size // self.patch_size) ** 2 + 1
|
| 82 |
+
|
| 83 |
+
# Copied from tests.models.dpt.test_modeling_dpt_auto_backbone.DPTModelTester.prepare_config_and_inputs
|
| 84 |
+
def prepare_config_and_inputs(self):
|
| 85 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 86 |
+
|
| 87 |
+
labels = None
|
| 88 |
+
if self.use_labels:
|
| 89 |
+
labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
|
| 90 |
+
|
| 91 |
+
config = self.get_config()
|
| 92 |
+
|
| 93 |
+
return config, pixel_values, labels
|
| 94 |
+
|
| 95 |
+
def get_config(self):
|
| 96 |
+
return DepthAnythingConfig(
|
| 97 |
+
backbone_config=self.get_backbone_config(),
|
| 98 |
+
reassemble_hidden_size=self.hidden_size,
|
| 99 |
+
patch_size=self.patch_size,
|
| 100 |
+
neck_hidden_sizes=self.neck_hidden_sizes,
|
| 101 |
+
fusion_hidden_size=self.fusion_hidden_size,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# Copied from tests.models.dpt.test_modeling_dpt_auto_backbone.DPTModelTester.get_backbone_config
|
| 105 |
+
def get_backbone_config(self):
|
| 106 |
+
return Dinov2Config(
|
| 107 |
+
image_size=self.image_size,
|
| 108 |
+
patch_size=self.patch_size,
|
| 109 |
+
num_channels=self.num_channels,
|
| 110 |
+
hidden_size=self.hidden_size,
|
| 111 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 112 |
+
num_attention_heads=self.num_attention_heads,
|
| 113 |
+
intermediate_size=self.intermediate_size,
|
| 114 |
+
is_training=self.is_training,
|
| 115 |
+
out_features=self.out_features,
|
| 116 |
+
reshape_hidden_states=self.reshape_hidden_states,
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
# Copied from tests.models.dpt.test_modeling_dpt_auto_backbone.DPTModelTester.create_and_check_for_depth_estimation with DPT->DepthAnything
|
| 120 |
+
def create_and_check_for_depth_estimation(self, config, pixel_values, labels):
|
| 121 |
+
config.num_labels = self.num_labels
|
| 122 |
+
model = DepthAnythingForDepthEstimation(config)
|
| 123 |
+
model.to(torch_device)
|
| 124 |
+
model.eval()
|
| 125 |
+
result = model(pixel_values)
|
| 126 |
+
self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size))
|
| 127 |
+
|
| 128 |
+
# Copied from tests.models.dpt.test_modeling_dpt_auto_backbone.DPTModelTester.prepare_config_and_inputs_for_common
|
| 129 |
+
def prepare_config_and_inputs_for_common(self):
|
| 130 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 131 |
+
config, pixel_values, labels = config_and_inputs
|
| 132 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 133 |
+
return config, inputs_dict
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@require_torch
|
| 137 |
+
class DepthAnythingModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 138 |
+
"""
|
| 139 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as Depth Anything does not use input_ids, inputs_embeds,
|
| 140 |
+
attention_mask and seq_length.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
all_model_classes = (DepthAnythingForDepthEstimation,) if is_torch_available() else ()
|
| 144 |
+
pipeline_model_mapping = {"depth-estimation": DepthAnythingForDepthEstimation} if is_torch_available() else {}
|
| 145 |
+
|
| 146 |
+
test_pruning = False
|
| 147 |
+
test_resize_embeddings = False
|
| 148 |
+
test_head_masking = False
|
| 149 |
+
|
| 150 |
+
def setUp(self):
|
| 151 |
+
self.model_tester = DepthAnythingModelTester(self)
|
| 152 |
+
self.config_tester = ConfigTester(
|
| 153 |
+
self,
|
| 154 |
+
config_class=DepthAnythingConfig,
|
| 155 |
+
has_text_modality=False,
|
| 156 |
+
hidden_size=37,
|
| 157 |
+
common_properties=["patch_size"],
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
def test_config(self):
|
| 161 |
+
self.config_tester.run_common_tests()
|
| 162 |
+
|
| 163 |
+
@unittest.skip(reason="Depth Anything with AutoBackbone does not have a base model and hence no input_embeddings")
|
| 164 |
+
def test_inputs_embeds(self):
|
| 165 |
+
pass
|
| 166 |
+
|
| 167 |
+
def test_for_depth_estimation(self):
|
| 168 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 169 |
+
self.model_tester.create_and_check_for_depth_estimation(*config_and_inputs)
|
| 170 |
+
|
| 171 |
+
@unittest.skip(reason="Depth Anything does not support training yet")
|
| 172 |
+
def test_training(self):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
@unittest.skip(reason="Depth Anything does not support training yet")
|
| 176 |
+
def test_training_gradient_checkpointing(self):
|
| 177 |
+
pass
|
| 178 |
+
|
| 179 |
+
@unittest.skip(reason="Depth Anything with AutoBackbone does not have a base model and hence no input_embeddings")
|
| 180 |
+
def test_model_get_set_embeddings(self):
|
| 181 |
+
pass
|
| 182 |
+
|
| 183 |
+
@unittest.skip(reason="Depth Anything with AutoBackbone does not have a base model")
|
| 184 |
+
def test_save_load_fast_init_from_base(self):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
@unittest.skip(reason="Depth Anything with AutoBackbone does not have a base model")
|
| 188 |
+
def test_save_load_fast_init_to_base(self):
|
| 189 |
+
pass
|
| 190 |
+
|
| 191 |
+
@unittest.skip(
|
| 192 |
+
reason="This architecture seems to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 193 |
+
)
|
| 194 |
+
def test_training_gradient_checkpointing_use_reentrant(self):
|
| 195 |
+
pass
|
| 196 |
+
|
| 197 |
+
@unittest.skip(
|
| 198 |
+
reason="This architecture seems to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 199 |
+
)
|
| 200 |
+
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
@slow
|
| 204 |
+
def test_model_from_pretrained(self):
|
| 205 |
+
model_name = "LiheYoung/depth-anything-small-hf"
|
| 206 |
+
model = DepthAnythingForDepthEstimation.from_pretrained(model_name)
|
| 207 |
+
self.assertIsNotNone(model)
|
| 208 |
+
|
| 209 |
+
def test_backbone_selection(self):
|
| 210 |
+
def _validate_backbone_init():
|
| 211 |
+
for model_class in self.all_model_classes:
|
| 212 |
+
model = model_class(config)
|
| 213 |
+
model.to(torch_device)
|
| 214 |
+
model.eval()
|
| 215 |
+
|
| 216 |
+
# Confirm out_indices propogated to backbone
|
| 217 |
+
self.assertEqual(len(model.backbone.out_indices), 2)
|
| 218 |
+
|
| 219 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 220 |
+
|
| 221 |
+
# Load a timm backbone
|
| 222 |
+
config.backbone = "resnet18"
|
| 223 |
+
config.use_pretrained_backbone = True
|
| 224 |
+
config.use_timm_backbone = True
|
| 225 |
+
config.backbone_config = None
|
| 226 |
+
# For transformer backbones we can't set the out_indices or just return the features
|
| 227 |
+
config.backbone_kwargs = {"out_indices": (-2, -1)}
|
| 228 |
+
_validate_backbone_init()
|
| 229 |
+
|
| 230 |
+
# Load a HF backbone
|
| 231 |
+
config.backbone = "facebook/dinov2-small"
|
| 232 |
+
config.use_pretrained_backbone = True
|
| 233 |
+
config.use_timm_backbone = False
|
| 234 |
+
config.backbone_config = None
|
| 235 |
+
config.backbone_kwargs = {"out_indices": [-2, -1]}
|
| 236 |
+
_validate_backbone_init()
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# We will verify our results on an image of cute cats
|
| 240 |
+
def prepare_img():
|
| 241 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 242 |
+
return image
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@require_torch
|
| 246 |
+
@require_vision
|
| 247 |
+
@slow
|
| 248 |
+
class DepthAnythingModelIntegrationTest(unittest.TestCase):
|
| 249 |
+
def test_inference(self):
|
| 250 |
+
# -- `relative` depth model --
|
| 251 |
+
image_processor = DPTImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 252 |
+
model = DepthAnythingForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf").to(torch_device)
|
| 253 |
+
|
| 254 |
+
image = prepare_img()
|
| 255 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 256 |
+
|
| 257 |
+
# forward pass
|
| 258 |
+
with torch.no_grad():
|
| 259 |
+
outputs = model(**inputs)
|
| 260 |
+
predicted_depth = outputs.predicted_depth
|
| 261 |
+
|
| 262 |
+
# verify the predicted depth
|
| 263 |
+
expected_shape = torch.Size([1, 518, 686])
|
| 264 |
+
self.assertEqual(predicted_depth.shape, expected_shape)
|
| 265 |
+
|
| 266 |
+
expected_slice = torch.tensor(
|
| 267 |
+
[[8.8223, 8.6483, 8.6216], [8.3332, 8.6047, 8.7545], [8.6547, 8.6885, 8.7472]],
|
| 268 |
+
).to(torch_device)
|
| 269 |
+
|
| 270 |
+
self.assertTrue(torch.allclose(predicted_depth[0, :3, :3], expected_slice, atol=1e-6))
|
| 271 |
+
|
| 272 |
+
# -- `metric` depth model --
|
| 273 |
+
image_processor = DPTImageProcessor.from_pretrained("depth-anything/depth-anything-V2-metric-indoor-small-hf")
|
| 274 |
+
model = DepthAnythingForDepthEstimation.from_pretrained(
|
| 275 |
+
"depth-anything/depth-anything-V2-metric-indoor-small-hf"
|
| 276 |
+
).to(torch_device)
|
| 277 |
+
|
| 278 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 279 |
+
|
| 280 |
+
# forward pass
|
| 281 |
+
with torch.no_grad():
|
| 282 |
+
outputs = model(**inputs)
|
| 283 |
+
predicted_depth = outputs.predicted_depth
|
| 284 |
+
|
| 285 |
+
# verify the predicted depth
|
| 286 |
+
expected_shape = torch.Size([1, 518, 686])
|
| 287 |
+
self.assertEqual(predicted_depth.shape, expected_shape)
|
| 288 |
+
|
| 289 |
+
expected_slice = torch.tensor(
|
| 290 |
+
[[1.3349, 1.2947, 1.2802], [1.2794, 1.2338, 1.2901], [1.2630, 1.2219, 1.2478]],
|
| 291 |
+
).to(torch_device)
|
| 292 |
+
|
| 293 |
+
self.assertTrue(torch.allclose(predicted_depth[0, :3, :3], expected_slice, atol=1e-4))
|
| 294 |
+
|
| 295 |
+
def test_export(self):
|
| 296 |
+
for strict in [True, False]:
|
| 297 |
+
with self.subTest(strict=strict):
|
| 298 |
+
if not is_torch_greater_or_equal_than_2_4:
|
| 299 |
+
self.skipTest(reason="This test requires torch >= 2.4 to run.")
|
| 300 |
+
model = (
|
| 301 |
+
DepthAnythingForDepthEstimation.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 302 |
+
.to(torch_device)
|
| 303 |
+
.eval()
|
| 304 |
+
)
|
| 305 |
+
image_processor = DPTImageProcessor.from_pretrained("LiheYoung/depth-anything-small-hf")
|
| 306 |
+
image = prepare_img()
|
| 307 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 308 |
+
|
| 309 |
+
exported_program = torch.export.export(
|
| 310 |
+
model,
|
| 311 |
+
args=(inputs["pixel_values"],),
|
| 312 |
+
strict=strict,
|
| 313 |
+
)
|
| 314 |
+
with torch.no_grad():
|
| 315 |
+
eager_outputs = model(**inputs)
|
| 316 |
+
exported_outputs = exported_program.module().forward(inputs["pixel_values"])
|
| 317 |
+
self.assertEqual(eager_outputs.predicted_depth.shape, exported_outputs.predicted_depth.shape)
|
| 318 |
+
self.assertTrue(
|
| 319 |
+
torch.allclose(eager_outputs.predicted_depth, exported_outputs.predicted_depth, atol=1e-4)
|
| 320 |
+
)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/test_image_processing_detr.py
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import pathlib
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from transformers.testing_utils import require_torch, require_torch_gpu, require_torchvision, require_vision, slow
|
| 23 |
+
from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
|
| 24 |
+
|
| 25 |
+
from ...test_image_processing_common import AnnotationFormatTestMixin, ImageProcessingTestMixin, prepare_image_inputs
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
if is_vision_available():
|
| 32 |
+
from PIL import Image
|
| 33 |
+
|
| 34 |
+
from transformers import DetrImageProcessor
|
| 35 |
+
|
| 36 |
+
if is_torchvision_available():
|
| 37 |
+
from transformers import DetrImageProcessorFast
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DetrImageProcessingTester(unittest.TestCase):
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
parent,
|
| 44 |
+
batch_size=7,
|
| 45 |
+
num_channels=3,
|
| 46 |
+
min_resolution=30,
|
| 47 |
+
max_resolution=400,
|
| 48 |
+
do_resize=True,
|
| 49 |
+
size=None,
|
| 50 |
+
do_rescale=True,
|
| 51 |
+
rescale_factor=1 / 255,
|
| 52 |
+
do_normalize=True,
|
| 53 |
+
image_mean=[0.5, 0.5, 0.5],
|
| 54 |
+
image_std=[0.5, 0.5, 0.5],
|
| 55 |
+
do_pad=True,
|
| 56 |
+
):
|
| 57 |
+
super().__init__()
|
| 58 |
+
# by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
|
| 59 |
+
size = size if size is not None else {"shortest_edge": 18, "longest_edge": 1333}
|
| 60 |
+
self.parent = parent
|
| 61 |
+
self.batch_size = batch_size
|
| 62 |
+
self.num_channels = num_channels
|
| 63 |
+
self.min_resolution = min_resolution
|
| 64 |
+
self.max_resolution = max_resolution
|
| 65 |
+
self.do_resize = do_resize
|
| 66 |
+
self.size = size
|
| 67 |
+
self.do_rescale = do_rescale
|
| 68 |
+
self.rescale_factor = rescale_factor
|
| 69 |
+
self.do_normalize = do_normalize
|
| 70 |
+
self.image_mean = image_mean
|
| 71 |
+
self.image_std = image_std
|
| 72 |
+
self.do_pad = do_pad
|
| 73 |
+
|
| 74 |
+
def prepare_image_processor_dict(self):
|
| 75 |
+
return {
|
| 76 |
+
"do_resize": self.do_resize,
|
| 77 |
+
"size": self.size,
|
| 78 |
+
"do_rescale": self.do_rescale,
|
| 79 |
+
"rescale_factor": self.rescale_factor,
|
| 80 |
+
"do_normalize": self.do_normalize,
|
| 81 |
+
"image_mean": self.image_mean,
|
| 82 |
+
"image_std": self.image_std,
|
| 83 |
+
"do_pad": self.do_pad,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
def get_expected_values(self, image_inputs, batched=False):
|
| 87 |
+
"""
|
| 88 |
+
This function computes the expected height and width when providing images to DetrImageProcessor,
|
| 89 |
+
assuming do_resize is set to True with a scalar size.
|
| 90 |
+
"""
|
| 91 |
+
if not batched:
|
| 92 |
+
image = image_inputs[0]
|
| 93 |
+
if isinstance(image, Image.Image):
|
| 94 |
+
w, h = image.size
|
| 95 |
+
elif isinstance(image, np.ndarray):
|
| 96 |
+
h, w = image.shape[0], image.shape[1]
|
| 97 |
+
else:
|
| 98 |
+
h, w = image.shape[1], image.shape[2]
|
| 99 |
+
if w < h:
|
| 100 |
+
expected_height = int(self.size["shortest_edge"] * h / w)
|
| 101 |
+
expected_width = self.size["shortest_edge"]
|
| 102 |
+
elif w > h:
|
| 103 |
+
expected_height = self.size["shortest_edge"]
|
| 104 |
+
expected_width = int(self.size["shortest_edge"] * w / h)
|
| 105 |
+
else:
|
| 106 |
+
expected_height = self.size["shortest_edge"]
|
| 107 |
+
expected_width = self.size["shortest_edge"]
|
| 108 |
+
|
| 109 |
+
else:
|
| 110 |
+
expected_values = []
|
| 111 |
+
for image in image_inputs:
|
| 112 |
+
expected_height, expected_width = self.get_expected_values([image])
|
| 113 |
+
expected_values.append((expected_height, expected_width))
|
| 114 |
+
expected_height = max(expected_values, key=lambda item: item[0])[0]
|
| 115 |
+
expected_width = max(expected_values, key=lambda item: item[1])[1]
|
| 116 |
+
|
| 117 |
+
return expected_height, expected_width
|
| 118 |
+
|
| 119 |
+
def expected_output_image_shape(self, images):
|
| 120 |
+
height, width = self.get_expected_values(images, batched=True)
|
| 121 |
+
return self.num_channels, height, width
|
| 122 |
+
|
| 123 |
+
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
| 124 |
+
return prepare_image_inputs(
|
| 125 |
+
batch_size=self.batch_size,
|
| 126 |
+
num_channels=self.num_channels,
|
| 127 |
+
min_resolution=self.min_resolution,
|
| 128 |
+
max_resolution=self.max_resolution,
|
| 129 |
+
equal_resolution=equal_resolution,
|
| 130 |
+
numpify=numpify,
|
| 131 |
+
torchify=torchify,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@require_torch
|
| 136 |
+
@require_vision
|
| 137 |
+
class DetrImageProcessingTest(AnnotationFormatTestMixin, ImageProcessingTestMixin, unittest.TestCase):
|
| 138 |
+
image_processing_class = DetrImageProcessor if is_vision_available() else None
|
| 139 |
+
fast_image_processing_class = DetrImageProcessorFast if is_torchvision_available() else None
|
| 140 |
+
|
| 141 |
+
def setUp(self):
|
| 142 |
+
super().setUp()
|
| 143 |
+
self.image_processor_tester = DetrImageProcessingTester(self)
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def image_processor_dict(self):
|
| 147 |
+
return self.image_processor_tester.prepare_image_processor_dict()
|
| 148 |
+
|
| 149 |
+
def test_image_processor_properties(self):
|
| 150 |
+
for image_processing_class in self.image_processor_list:
|
| 151 |
+
image_processing = image_processing_class(**self.image_processor_dict)
|
| 152 |
+
self.assertTrue(hasattr(image_processing, "image_mean"))
|
| 153 |
+
self.assertTrue(hasattr(image_processing, "image_std"))
|
| 154 |
+
self.assertTrue(hasattr(image_processing, "do_normalize"))
|
| 155 |
+
self.assertTrue(hasattr(image_processing, "do_rescale"))
|
| 156 |
+
self.assertTrue(hasattr(image_processing, "rescale_factor"))
|
| 157 |
+
self.assertTrue(hasattr(image_processing, "do_resize"))
|
| 158 |
+
self.assertTrue(hasattr(image_processing, "size"))
|
| 159 |
+
self.assertTrue(hasattr(image_processing, "do_pad"))
|
| 160 |
+
|
| 161 |
+
def test_image_processor_from_dict_with_kwargs(self):
|
| 162 |
+
for image_processing_class in self.image_processor_list:
|
| 163 |
+
image_processor = image_processing_class.from_dict(self.image_processor_dict)
|
| 164 |
+
self.assertEqual(image_processor.size, {"shortest_edge": 18, "longest_edge": 1333})
|
| 165 |
+
self.assertEqual(image_processor.do_pad, True)
|
| 166 |
+
|
| 167 |
+
image_processor = image_processing_class.from_dict(
|
| 168 |
+
self.image_processor_dict, size=42, max_size=84, pad_and_return_pixel_mask=False
|
| 169 |
+
)
|
| 170 |
+
self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84})
|
| 171 |
+
self.assertEqual(image_processor.do_pad, False)
|
| 172 |
+
|
| 173 |
+
def test_should_raise_if_annotation_format_invalid(self):
|
| 174 |
+
image_processor_dict = self.image_processor_tester.prepare_image_processor_dict()
|
| 175 |
+
|
| 176 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 177 |
+
detection_target = json.loads(f.read())
|
| 178 |
+
|
| 179 |
+
annotations = {"image_id": 39769, "annotations": detection_target}
|
| 180 |
+
|
| 181 |
+
params = {
|
| 182 |
+
"images": Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"),
|
| 183 |
+
"annotations": annotations,
|
| 184 |
+
"return_tensors": "pt",
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
image_processor_params = {**image_processor_dict, **{"format": "_INVALID_FORMAT_"}}
|
| 188 |
+
for image_processing_class in self.image_processor_list:
|
| 189 |
+
image_processor = image_processing_class(**image_processor_params)
|
| 190 |
+
|
| 191 |
+
with self.assertRaises(ValueError) as e:
|
| 192 |
+
image_processor(**params)
|
| 193 |
+
|
| 194 |
+
self.assertTrue(str(e.exception).startswith("_INVALID_FORMAT_ is not a valid AnnotationFormat"))
|
| 195 |
+
|
| 196 |
+
def test_valid_coco_detection_annotations(self):
|
| 197 |
+
# prepare image and target
|
| 198 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 199 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 200 |
+
target = json.loads(f.read())
|
| 201 |
+
|
| 202 |
+
params = {"image_id": 39769, "annotations": target}
|
| 203 |
+
|
| 204 |
+
for image_processing_class in self.image_processor_list:
|
| 205 |
+
# encode them
|
| 206 |
+
image_processing = image_processing_class.from_pretrained("facebook/detr-resnet-50")
|
| 207 |
+
|
| 208 |
+
# legal encodings (single image)
|
| 209 |
+
_ = image_processing(images=image, annotations=params, return_tensors="pt")
|
| 210 |
+
_ = image_processing(images=image, annotations=[params], return_tensors="pt")
|
| 211 |
+
|
| 212 |
+
# legal encodings (batch of one image)
|
| 213 |
+
_ = image_processing(images=[image], annotations=params, return_tensors="pt")
|
| 214 |
+
_ = image_processing(images=[image], annotations=[params], return_tensors="pt")
|
| 215 |
+
|
| 216 |
+
# legal encoding (batch of more than one image)
|
| 217 |
+
n = 5
|
| 218 |
+
_ = image_processing(images=[image] * n, annotations=[params] * n, return_tensors="pt")
|
| 219 |
+
|
| 220 |
+
# example of an illegal encoding (missing the 'image_id' key)
|
| 221 |
+
with self.assertRaises(ValueError) as e:
|
| 222 |
+
image_processing(images=image, annotations={"annotations": target}, return_tensors="pt")
|
| 223 |
+
|
| 224 |
+
self.assertTrue(str(e.exception).startswith("Invalid COCO detection annotations"))
|
| 225 |
+
|
| 226 |
+
# example of an illegal encoding (unequal lengths of images and annotations)
|
| 227 |
+
with self.assertRaises(ValueError) as e:
|
| 228 |
+
image_processing(images=[image] * n, annotations=[params] * (n - 1), return_tensors="pt")
|
| 229 |
+
|
| 230 |
+
self.assertTrue(str(e.exception) == "The number of images (5) and annotations (4) do not match.")
|
| 231 |
+
|
| 232 |
+
@slow
|
| 233 |
+
def test_call_pytorch_with_coco_detection_annotations(self):
|
| 234 |
+
# prepare image and target
|
| 235 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 236 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 237 |
+
target = json.loads(f.read())
|
| 238 |
+
|
| 239 |
+
target = {"image_id": 39769, "annotations": target}
|
| 240 |
+
|
| 241 |
+
for image_processing_class in self.image_processor_list:
|
| 242 |
+
# encode them
|
| 243 |
+
image_processing = image_processing_class.from_pretrained("facebook/detr-resnet-50")
|
| 244 |
+
encoding = image_processing(images=image, annotations=target, return_tensors="pt")
|
| 245 |
+
|
| 246 |
+
# verify pixel values
|
| 247 |
+
expected_shape = torch.Size([1, 3, 800, 1066])
|
| 248 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 249 |
+
|
| 250 |
+
expected_slice = torch.tensor([0.2796, 0.3138, 0.3481])
|
| 251 |
+
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4))
|
| 252 |
+
|
| 253 |
+
# verify area
|
| 254 |
+
expected_area = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438])
|
| 255 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area))
|
| 256 |
+
# verify boxes
|
| 257 |
+
expected_boxes_shape = torch.Size([6, 4])
|
| 258 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape)
|
| 259 |
+
expected_boxes_slice = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215])
|
| 260 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3))
|
| 261 |
+
# verify image_id
|
| 262 |
+
expected_image_id = torch.tensor([39769])
|
| 263 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id))
|
| 264 |
+
# verify is_crowd
|
| 265 |
+
expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0])
|
| 266 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd))
|
| 267 |
+
# verify class_labels
|
| 268 |
+
expected_class_labels = torch.tensor([75, 75, 63, 65, 17, 17])
|
| 269 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels))
|
| 270 |
+
# verify orig_size
|
| 271 |
+
expected_orig_size = torch.tensor([480, 640])
|
| 272 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size))
|
| 273 |
+
# verify size
|
| 274 |
+
expected_size = torch.tensor([800, 1066])
|
| 275 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size))
|
| 276 |
+
|
| 277 |
+
@slow
|
| 278 |
+
def test_call_pytorch_with_coco_panoptic_annotations(self):
|
| 279 |
+
# prepare image, target and masks_path
|
| 280 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 281 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 282 |
+
target = json.loads(f.read())
|
| 283 |
+
|
| 284 |
+
target = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 285 |
+
|
| 286 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 287 |
+
|
| 288 |
+
for image_processing_class in self.image_processor_list:
|
| 289 |
+
# encode them
|
| 290 |
+
image_processing = image_processing_class.from_pretrained("facebook/detr-resnet-50-panoptic")
|
| 291 |
+
encoding = image_processing(images=image, annotations=target, masks_path=masks_path, return_tensors="pt")
|
| 292 |
+
|
| 293 |
+
# verify pixel values
|
| 294 |
+
expected_shape = torch.Size([1, 3, 800, 1066])
|
| 295 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 296 |
+
|
| 297 |
+
expected_slice = torch.tensor([0.2796, 0.3138, 0.3481])
|
| 298 |
+
self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3], expected_slice, atol=1e-4))
|
| 299 |
+
|
| 300 |
+
# verify area
|
| 301 |
+
expected_area = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147])
|
| 302 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["area"], expected_area))
|
| 303 |
+
# verify boxes
|
| 304 |
+
expected_boxes_shape = torch.Size([6, 4])
|
| 305 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, expected_boxes_shape)
|
| 306 |
+
expected_boxes_slice = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625])
|
| 307 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0], expected_boxes_slice, atol=1e-3))
|
| 308 |
+
# verify image_id
|
| 309 |
+
expected_image_id = torch.tensor([39769])
|
| 310 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"], expected_image_id))
|
| 311 |
+
# verify is_crowd
|
| 312 |
+
expected_is_crowd = torch.tensor([0, 0, 0, 0, 0, 0])
|
| 313 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"], expected_is_crowd))
|
| 314 |
+
# verify class_labels
|
| 315 |
+
expected_class_labels = torch.tensor([17, 17, 63, 75, 75, 93])
|
| 316 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"], expected_class_labels))
|
| 317 |
+
# verify masks
|
| 318 |
+
expected_masks_sum = 822873
|
| 319 |
+
relative_error = torch.abs(encoding["labels"][0]["masks"].sum() - expected_masks_sum) / expected_masks_sum
|
| 320 |
+
self.assertTrue(relative_error < 1e-3)
|
| 321 |
+
# verify orig_size
|
| 322 |
+
expected_orig_size = torch.tensor([480, 640])
|
| 323 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"], expected_orig_size))
|
| 324 |
+
# verify size
|
| 325 |
+
expected_size = torch.tensor([800, 1066])
|
| 326 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["size"], expected_size))
|
| 327 |
+
|
| 328 |
+
@slow
|
| 329 |
+
def test_batched_coco_detection_annotations(self):
|
| 330 |
+
image_0 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 331 |
+
image_1 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png").resize((800, 800))
|
| 332 |
+
|
| 333 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 334 |
+
target = json.loads(f.read())
|
| 335 |
+
|
| 336 |
+
annotations_0 = {"image_id": 39769, "annotations": target}
|
| 337 |
+
annotations_1 = {"image_id": 39769, "annotations": target}
|
| 338 |
+
|
| 339 |
+
# Adjust the bounding boxes for the resized image
|
| 340 |
+
w_0, h_0 = image_0.size
|
| 341 |
+
w_1, h_1 = image_1.size
|
| 342 |
+
for i in range(len(annotations_1["annotations"])):
|
| 343 |
+
coords = annotations_1["annotations"][i]["bbox"]
|
| 344 |
+
new_bbox = [
|
| 345 |
+
coords[0] * w_1 / w_0,
|
| 346 |
+
coords[1] * h_1 / h_0,
|
| 347 |
+
coords[2] * w_1 / w_0,
|
| 348 |
+
coords[3] * h_1 / h_0,
|
| 349 |
+
]
|
| 350 |
+
annotations_1["annotations"][i]["bbox"] = new_bbox
|
| 351 |
+
|
| 352 |
+
images = [image_0, image_1]
|
| 353 |
+
annotations = [annotations_0, annotations_1]
|
| 354 |
+
|
| 355 |
+
for image_processing_class in self.image_processor_list:
|
| 356 |
+
image_processing = image_processing_class()
|
| 357 |
+
encoding = image_processing(
|
| 358 |
+
images=images,
|
| 359 |
+
annotations=annotations,
|
| 360 |
+
return_segmentation_masks=True,
|
| 361 |
+
return_tensors="pt", # do_convert_annotations=True
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
# Check the pixel values have been padded
|
| 365 |
+
postprocessed_height, postprocessed_width = 800, 1066
|
| 366 |
+
expected_shape = torch.Size([2, 3, postprocessed_height, postprocessed_width])
|
| 367 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 368 |
+
|
| 369 |
+
# Check the bounding boxes have been adjusted for padded images
|
| 370 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 371 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 372 |
+
expected_boxes_0 = torch.tensor(
|
| 373 |
+
[
|
| 374 |
+
[0.6879, 0.4609, 0.0755, 0.3691],
|
| 375 |
+
[0.2118, 0.3359, 0.2601, 0.1566],
|
| 376 |
+
[0.5011, 0.5000, 0.9979, 1.0000],
|
| 377 |
+
[0.5010, 0.5020, 0.9979, 0.9959],
|
| 378 |
+
[0.3284, 0.5944, 0.5884, 0.8112],
|
| 379 |
+
[0.8394, 0.5445, 0.3213, 0.9110],
|
| 380 |
+
]
|
| 381 |
+
)
|
| 382 |
+
expected_boxes_1 = torch.tensor(
|
| 383 |
+
[
|
| 384 |
+
[0.4130, 0.2765, 0.0453, 0.2215],
|
| 385 |
+
[0.1272, 0.2016, 0.1561, 0.0940],
|
| 386 |
+
[0.3757, 0.4933, 0.7488, 0.9865],
|
| 387 |
+
[0.3759, 0.5002, 0.7492, 0.9955],
|
| 388 |
+
[0.1971, 0.5456, 0.3532, 0.8646],
|
| 389 |
+
[0.5790, 0.4115, 0.3430, 0.7161],
|
| 390 |
+
]
|
| 391 |
+
)
|
| 392 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1e-3))
|
| 393 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1e-3))
|
| 394 |
+
|
| 395 |
+
# Check the masks have also been padded
|
| 396 |
+
self.assertEqual(encoding["labels"][0]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 397 |
+
self.assertEqual(encoding["labels"][1]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 398 |
+
|
| 399 |
+
# Check if do_convert_annotations=False, then the annotations are not converted to centre_x, centre_y, width, height
|
| 400 |
+
# format and not in the range [0, 1]
|
| 401 |
+
encoding = image_processing(
|
| 402 |
+
images=images,
|
| 403 |
+
annotations=annotations,
|
| 404 |
+
return_segmentation_masks=True,
|
| 405 |
+
do_convert_annotations=False,
|
| 406 |
+
return_tensors="pt",
|
| 407 |
+
)
|
| 408 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 409 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 410 |
+
# Convert to absolute coordinates
|
| 411 |
+
unnormalized_boxes_0 = torch.vstack(
|
| 412 |
+
[
|
| 413 |
+
expected_boxes_0[:, 0] * postprocessed_width,
|
| 414 |
+
expected_boxes_0[:, 1] * postprocessed_height,
|
| 415 |
+
expected_boxes_0[:, 2] * postprocessed_width,
|
| 416 |
+
expected_boxes_0[:, 3] * postprocessed_height,
|
| 417 |
+
]
|
| 418 |
+
).T
|
| 419 |
+
unnormalized_boxes_1 = torch.vstack(
|
| 420 |
+
[
|
| 421 |
+
expected_boxes_1[:, 0] * postprocessed_width,
|
| 422 |
+
expected_boxes_1[:, 1] * postprocessed_height,
|
| 423 |
+
expected_boxes_1[:, 2] * postprocessed_width,
|
| 424 |
+
expected_boxes_1[:, 3] * postprocessed_height,
|
| 425 |
+
]
|
| 426 |
+
).T
|
| 427 |
+
# Convert from centre_x, centre_y, width, height to x_min, y_min, x_max, y_max
|
| 428 |
+
expected_boxes_0 = torch.vstack(
|
| 429 |
+
[
|
| 430 |
+
unnormalized_boxes_0[:, 0] - unnormalized_boxes_0[:, 2] / 2,
|
| 431 |
+
unnormalized_boxes_0[:, 1] - unnormalized_boxes_0[:, 3] / 2,
|
| 432 |
+
unnormalized_boxes_0[:, 0] + unnormalized_boxes_0[:, 2] / 2,
|
| 433 |
+
unnormalized_boxes_0[:, 1] + unnormalized_boxes_0[:, 3] / 2,
|
| 434 |
+
]
|
| 435 |
+
).T
|
| 436 |
+
expected_boxes_1 = torch.vstack(
|
| 437 |
+
[
|
| 438 |
+
unnormalized_boxes_1[:, 0] - unnormalized_boxes_1[:, 2] / 2,
|
| 439 |
+
unnormalized_boxes_1[:, 1] - unnormalized_boxes_1[:, 3] / 2,
|
| 440 |
+
unnormalized_boxes_1[:, 0] + unnormalized_boxes_1[:, 2] / 2,
|
| 441 |
+
unnormalized_boxes_1[:, 1] + unnormalized_boxes_1[:, 3] / 2,
|
| 442 |
+
]
|
| 443 |
+
).T
|
| 444 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1))
|
| 445 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1))
|
| 446 |
+
|
| 447 |
+
def test_batched_coco_panoptic_annotations(self):
|
| 448 |
+
# prepare image, target and masks_path
|
| 449 |
+
image_0 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 450 |
+
image_1 = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png").resize((800, 800))
|
| 451 |
+
|
| 452 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 453 |
+
target = json.loads(f.read())
|
| 454 |
+
|
| 455 |
+
annotation_0 = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 456 |
+
annotation_1 = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 457 |
+
|
| 458 |
+
w_0, h_0 = image_0.size
|
| 459 |
+
w_1, h_1 = image_1.size
|
| 460 |
+
for i in range(len(annotation_1["segments_info"])):
|
| 461 |
+
coords = annotation_1["segments_info"][i]["bbox"]
|
| 462 |
+
new_bbox = [
|
| 463 |
+
coords[0] * w_1 / w_0,
|
| 464 |
+
coords[1] * h_1 / h_0,
|
| 465 |
+
coords[2] * w_1 / w_0,
|
| 466 |
+
coords[3] * h_1 / h_0,
|
| 467 |
+
]
|
| 468 |
+
annotation_1["segments_info"][i]["bbox"] = new_bbox
|
| 469 |
+
|
| 470 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 471 |
+
|
| 472 |
+
images = [image_0, image_1]
|
| 473 |
+
annotations = [annotation_0, annotation_1]
|
| 474 |
+
|
| 475 |
+
for image_processing_class in self.image_processor_list:
|
| 476 |
+
# encode them
|
| 477 |
+
image_processing = image_processing_class(format="coco_panoptic")
|
| 478 |
+
encoding = image_processing(
|
| 479 |
+
images=images,
|
| 480 |
+
annotations=annotations,
|
| 481 |
+
masks_path=masks_path,
|
| 482 |
+
return_tensors="pt",
|
| 483 |
+
return_segmentation_masks=True,
|
| 484 |
+
)
|
| 485 |
+
|
| 486 |
+
# Check the pixel values have been padded
|
| 487 |
+
postprocessed_height, postprocessed_width = 800, 1066
|
| 488 |
+
expected_shape = torch.Size([2, 3, postprocessed_height, postprocessed_width])
|
| 489 |
+
self.assertEqual(encoding["pixel_values"].shape, expected_shape)
|
| 490 |
+
|
| 491 |
+
# Check the bounding boxes have been adjusted for padded images
|
| 492 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 493 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 494 |
+
expected_boxes_0 = torch.tensor(
|
| 495 |
+
[
|
| 496 |
+
[0.2625, 0.5437, 0.4688, 0.8625],
|
| 497 |
+
[0.7719, 0.4104, 0.4531, 0.7125],
|
| 498 |
+
[0.5000, 0.4927, 0.9969, 0.9854],
|
| 499 |
+
[0.1688, 0.2000, 0.2063, 0.0917],
|
| 500 |
+
[0.5492, 0.2760, 0.0578, 0.2187],
|
| 501 |
+
[0.4992, 0.4990, 0.9984, 0.9979],
|
| 502 |
+
]
|
| 503 |
+
)
|
| 504 |
+
expected_boxes_1 = torch.tensor(
|
| 505 |
+
[
|
| 506 |
+
[0.1576, 0.3262, 0.2814, 0.5175],
|
| 507 |
+
[0.4634, 0.2463, 0.2720, 0.4275],
|
| 508 |
+
[0.3002, 0.2956, 0.5985, 0.5913],
|
| 509 |
+
[0.1013, 0.1200, 0.1238, 0.0550],
|
| 510 |
+
[0.3297, 0.1656, 0.0347, 0.1312],
|
| 511 |
+
[0.2997, 0.2994, 0.5994, 0.5987],
|
| 512 |
+
]
|
| 513 |
+
)
|
| 514 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1e-3))
|
| 515 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1e-3))
|
| 516 |
+
|
| 517 |
+
# Check the masks have also been padded
|
| 518 |
+
self.assertEqual(encoding["labels"][0]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 519 |
+
self.assertEqual(encoding["labels"][1]["masks"].shape, torch.Size([6, 800, 1066]))
|
| 520 |
+
|
| 521 |
+
# Check if do_convert_annotations=False, then the annotations are not converted to centre_x, centre_y, width, height
|
| 522 |
+
# format and not in the range [0, 1]
|
| 523 |
+
encoding = image_processing(
|
| 524 |
+
images=images,
|
| 525 |
+
annotations=annotations,
|
| 526 |
+
masks_path=masks_path,
|
| 527 |
+
return_segmentation_masks=True,
|
| 528 |
+
do_convert_annotations=False,
|
| 529 |
+
return_tensors="pt",
|
| 530 |
+
)
|
| 531 |
+
self.assertEqual(encoding["labels"][0]["boxes"].shape, torch.Size([6, 4]))
|
| 532 |
+
self.assertEqual(encoding["labels"][1]["boxes"].shape, torch.Size([6, 4]))
|
| 533 |
+
# Convert to absolute coordinates
|
| 534 |
+
unnormalized_boxes_0 = torch.vstack(
|
| 535 |
+
[
|
| 536 |
+
expected_boxes_0[:, 0] * postprocessed_width,
|
| 537 |
+
expected_boxes_0[:, 1] * postprocessed_height,
|
| 538 |
+
expected_boxes_0[:, 2] * postprocessed_width,
|
| 539 |
+
expected_boxes_0[:, 3] * postprocessed_height,
|
| 540 |
+
]
|
| 541 |
+
).T
|
| 542 |
+
unnormalized_boxes_1 = torch.vstack(
|
| 543 |
+
[
|
| 544 |
+
expected_boxes_1[:, 0] * postprocessed_width,
|
| 545 |
+
expected_boxes_1[:, 1] * postprocessed_height,
|
| 546 |
+
expected_boxes_1[:, 2] * postprocessed_width,
|
| 547 |
+
expected_boxes_1[:, 3] * postprocessed_height,
|
| 548 |
+
]
|
| 549 |
+
).T
|
| 550 |
+
# Convert from centre_x, centre_y, width, height to x_min, y_min, x_max, y_max
|
| 551 |
+
expected_boxes_0 = torch.vstack(
|
| 552 |
+
[
|
| 553 |
+
unnormalized_boxes_0[:, 0] - unnormalized_boxes_0[:, 2] / 2,
|
| 554 |
+
unnormalized_boxes_0[:, 1] - unnormalized_boxes_0[:, 3] / 2,
|
| 555 |
+
unnormalized_boxes_0[:, 0] + unnormalized_boxes_0[:, 2] / 2,
|
| 556 |
+
unnormalized_boxes_0[:, 1] + unnormalized_boxes_0[:, 3] / 2,
|
| 557 |
+
]
|
| 558 |
+
).T
|
| 559 |
+
expected_boxes_1 = torch.vstack(
|
| 560 |
+
[
|
| 561 |
+
unnormalized_boxes_1[:, 0] - unnormalized_boxes_1[:, 2] / 2,
|
| 562 |
+
unnormalized_boxes_1[:, 1] - unnormalized_boxes_1[:, 3] / 2,
|
| 563 |
+
unnormalized_boxes_1[:, 0] + unnormalized_boxes_1[:, 2] / 2,
|
| 564 |
+
unnormalized_boxes_1[:, 1] + unnormalized_boxes_1[:, 3] / 2,
|
| 565 |
+
]
|
| 566 |
+
).T
|
| 567 |
+
self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"], expected_boxes_0, rtol=1))
|
| 568 |
+
self.assertTrue(torch.allclose(encoding["labels"][1]["boxes"], expected_boxes_1, rtol=1))
|
| 569 |
+
|
| 570 |
+
def test_max_width_max_height_resizing_and_pad_strategy(self):
|
| 571 |
+
for image_processing_class in self.image_processor_list:
|
| 572 |
+
image_1 = torch.ones([200, 100, 3], dtype=torch.uint8)
|
| 573 |
+
|
| 574 |
+
# do_pad=False, max_height=100, max_width=100, image=200x100 -> 100x50
|
| 575 |
+
image_processor = image_processing_class(
|
| 576 |
+
size={"max_height": 100, "max_width": 100},
|
| 577 |
+
do_pad=False,
|
| 578 |
+
)
|
| 579 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 580 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 100, 50]))
|
| 581 |
+
|
| 582 |
+
# do_pad=False, max_height=300, max_width=100, image=200x100 -> 200x100
|
| 583 |
+
image_processor = image_processing_class(
|
| 584 |
+
size={"max_height": 300, "max_width": 100},
|
| 585 |
+
do_pad=False,
|
| 586 |
+
)
|
| 587 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 588 |
+
|
| 589 |
+
# do_pad=True, max_height=100, max_width=100, image=200x100 -> 100x100
|
| 590 |
+
image_processor = image_processing_class(
|
| 591 |
+
size={"max_height": 100, "max_width": 100}, do_pad=True, pad_size={"height": 100, "width": 100}
|
| 592 |
+
)
|
| 593 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 594 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 100, 100]))
|
| 595 |
+
|
| 596 |
+
# do_pad=True, max_height=300, max_width=100, image=200x100 -> 300x100
|
| 597 |
+
image_processor = image_processing_class(
|
| 598 |
+
size={"max_height": 300, "max_width": 100},
|
| 599 |
+
do_pad=True,
|
| 600 |
+
pad_size={"height": 301, "width": 101},
|
| 601 |
+
)
|
| 602 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 603 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 301, 101]))
|
| 604 |
+
|
| 605 |
+
### Check for batch
|
| 606 |
+
image_2 = torch.ones([100, 150, 3], dtype=torch.uint8)
|
| 607 |
+
|
| 608 |
+
# do_pad=True, max_height=150, max_width=100, images=[200x100, 100x150] -> 150x100
|
| 609 |
+
image_processor = image_processing_class(
|
| 610 |
+
size={"max_height": 150, "max_width": 100},
|
| 611 |
+
do_pad=True,
|
| 612 |
+
pad_size={"height": 150, "width": 100},
|
| 613 |
+
)
|
| 614 |
+
inputs = image_processor(images=[image_1, image_2], return_tensors="pt")
|
| 615 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([2, 3, 150, 100]))
|
| 616 |
+
|
| 617 |
+
def test_longest_edge_shortest_edge_resizing_strategy(self):
|
| 618 |
+
for image_processing_class in self.image_processor_list:
|
| 619 |
+
image_1 = torch.ones([958, 653, 3], dtype=torch.uint8)
|
| 620 |
+
|
| 621 |
+
# max size is set; width < height;
|
| 622 |
+
# do_pad=False, longest_edge=640, shortest_edge=640, image=958x653 -> 640x436
|
| 623 |
+
image_processor = image_processing_class(
|
| 624 |
+
size={"longest_edge": 640, "shortest_edge": 640},
|
| 625 |
+
do_pad=False,
|
| 626 |
+
)
|
| 627 |
+
inputs = image_processor(images=[image_1], return_tensors="pt")
|
| 628 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 640, 436]))
|
| 629 |
+
|
| 630 |
+
image_2 = torch.ones([653, 958, 3], dtype=torch.uint8)
|
| 631 |
+
# max size is set; height < width;
|
| 632 |
+
# do_pad=False, longest_edge=640, shortest_edge=640, image=653x958 -> 436x640
|
| 633 |
+
image_processor = image_processing_class(
|
| 634 |
+
size={"longest_edge": 640, "shortest_edge": 640},
|
| 635 |
+
do_pad=False,
|
| 636 |
+
)
|
| 637 |
+
inputs = image_processor(images=[image_2], return_tensors="pt")
|
| 638 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 436, 640]))
|
| 639 |
+
|
| 640 |
+
image_3 = torch.ones([100, 120, 3], dtype=torch.uint8)
|
| 641 |
+
# max size is set; width == size; height > max_size;
|
| 642 |
+
# do_pad=False, longest_edge=118, shortest_edge=100, image=120x100 -> 118x98
|
| 643 |
+
image_processor = image_processing_class(
|
| 644 |
+
size={"longest_edge": 118, "shortest_edge": 100},
|
| 645 |
+
do_pad=False,
|
| 646 |
+
)
|
| 647 |
+
inputs = image_processor(images=[image_3], return_tensors="pt")
|
| 648 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 98, 118]))
|
| 649 |
+
|
| 650 |
+
image_4 = torch.ones([128, 50, 3], dtype=torch.uint8)
|
| 651 |
+
# max size is set; height == size; width < max_size;
|
| 652 |
+
# do_pad=False, longest_edge=256, shortest_edge=50, image=50x128 -> 50x128
|
| 653 |
+
image_processor = image_processing_class(
|
| 654 |
+
size={"longest_edge": 256, "shortest_edge": 50},
|
| 655 |
+
do_pad=False,
|
| 656 |
+
)
|
| 657 |
+
inputs = image_processor(images=[image_4], return_tensors="pt")
|
| 658 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 128, 50]))
|
| 659 |
+
|
| 660 |
+
image_5 = torch.ones([50, 50, 3], dtype=torch.uint8)
|
| 661 |
+
# max size is set; height == width; width < max_size;
|
| 662 |
+
# do_pad=False, longest_edge=117, shortest_edge=50, image=50x50 -> 50x50
|
| 663 |
+
image_processor = image_processing_class(
|
| 664 |
+
size={"longest_edge": 117, "shortest_edge": 50},
|
| 665 |
+
do_pad=False,
|
| 666 |
+
)
|
| 667 |
+
inputs = image_processor(images=[image_5], return_tensors="pt")
|
| 668 |
+
self.assertEqual(inputs["pixel_values"].shape, torch.Size([1, 3, 50, 50]))
|
| 669 |
+
|
| 670 |
+
@slow
|
| 671 |
+
@require_torch_gpu
|
| 672 |
+
@require_torchvision
|
| 673 |
+
def test_fast_processor_equivalence_cpu_gpu_coco_detection_annotations(self):
|
| 674 |
+
# prepare image and target
|
| 675 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 676 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt", "r") as f:
|
| 677 |
+
target = json.loads(f.read())
|
| 678 |
+
|
| 679 |
+
target = {"image_id": 39769, "annotations": target}
|
| 680 |
+
|
| 681 |
+
processor = self.image_processor_list[1]()
|
| 682 |
+
# 1. run processor on CPU
|
| 683 |
+
encoding_cpu = processor(images=image, annotations=target, return_tensors="pt", device="cpu")
|
| 684 |
+
# 2. run processor on GPU
|
| 685 |
+
encoding_gpu = processor(images=image, annotations=target, return_tensors="pt", device="cuda")
|
| 686 |
+
|
| 687 |
+
# verify pixel values
|
| 688 |
+
self.assertEqual(encoding_cpu["pixel_values"].shape, encoding_gpu["pixel_values"].shape)
|
| 689 |
+
self.assertTrue(
|
| 690 |
+
torch.allclose(
|
| 691 |
+
encoding_cpu["pixel_values"][0, 0, 0, :3],
|
| 692 |
+
encoding_gpu["pixel_values"][0, 0, 0, :3].to("cpu"),
|
| 693 |
+
atol=1e-4,
|
| 694 |
+
)
|
| 695 |
+
)
|
| 696 |
+
# verify area
|
| 697 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["area"], encoding_gpu["labels"][0]["area"].to("cpu")))
|
| 698 |
+
# verify boxes
|
| 699 |
+
self.assertEqual(encoding_cpu["labels"][0]["boxes"].shape, encoding_gpu["labels"][0]["boxes"].shape)
|
| 700 |
+
self.assertTrue(
|
| 701 |
+
torch.allclose(
|
| 702 |
+
encoding_cpu["labels"][0]["boxes"][0], encoding_gpu["labels"][0]["boxes"][0].to("cpu"), atol=1e-3
|
| 703 |
+
)
|
| 704 |
+
)
|
| 705 |
+
# verify image_id
|
| 706 |
+
self.assertTrue(
|
| 707 |
+
torch.allclose(encoding_cpu["labels"][0]["image_id"], encoding_gpu["labels"][0]["image_id"].to("cpu"))
|
| 708 |
+
)
|
| 709 |
+
# verify is_crowd
|
| 710 |
+
self.assertTrue(
|
| 711 |
+
torch.allclose(encoding_cpu["labels"][0]["iscrowd"], encoding_gpu["labels"][0]["iscrowd"].to("cpu"))
|
| 712 |
+
)
|
| 713 |
+
# verify class_labels
|
| 714 |
+
self.assertTrue(
|
| 715 |
+
torch.allclose(
|
| 716 |
+
encoding_cpu["labels"][0]["class_labels"], encoding_gpu["labels"][0]["class_labels"].to("cpu")
|
| 717 |
+
)
|
| 718 |
+
)
|
| 719 |
+
# verify orig_size
|
| 720 |
+
self.assertTrue(
|
| 721 |
+
torch.allclose(encoding_cpu["labels"][0]["orig_size"], encoding_gpu["labels"][0]["orig_size"].to("cpu"))
|
| 722 |
+
)
|
| 723 |
+
# verify size
|
| 724 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["size"], encoding_gpu["labels"][0]["size"].to("cpu")))
|
| 725 |
+
|
| 726 |
+
@slow
|
| 727 |
+
@require_torch_gpu
|
| 728 |
+
@require_torchvision
|
| 729 |
+
def test_fast_processor_equivalence_cpu_gpu_coco_panoptic_annotations(self):
|
| 730 |
+
# prepare image, target and masks_path
|
| 731 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 732 |
+
with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt", "r") as f:
|
| 733 |
+
target = json.loads(f.read())
|
| 734 |
+
|
| 735 |
+
target = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": target}
|
| 736 |
+
|
| 737 |
+
masks_path = pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic")
|
| 738 |
+
|
| 739 |
+
processor = self.image_processor_list[1](format="coco_panoptic")
|
| 740 |
+
# 1. run processor on CPU
|
| 741 |
+
encoding_cpu = processor(
|
| 742 |
+
images=image, annotations=target, masks_path=masks_path, return_tensors="pt", device="cpu"
|
| 743 |
+
)
|
| 744 |
+
# 2. run processor on GPU
|
| 745 |
+
encoding_gpu = processor(
|
| 746 |
+
images=image, annotations=target, masks_path=masks_path, return_tensors="pt", device="cuda"
|
| 747 |
+
)
|
| 748 |
+
|
| 749 |
+
# verify pixel values
|
| 750 |
+
self.assertEqual(encoding_cpu["pixel_values"].shape, encoding_gpu["pixel_values"].shape)
|
| 751 |
+
self.assertTrue(
|
| 752 |
+
torch.allclose(
|
| 753 |
+
encoding_cpu["pixel_values"][0, 0, 0, :3],
|
| 754 |
+
encoding_gpu["pixel_values"][0, 0, 0, :3].to("cpu"),
|
| 755 |
+
atol=1e-4,
|
| 756 |
+
)
|
| 757 |
+
)
|
| 758 |
+
# verify area
|
| 759 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["area"], encoding_gpu["labels"][0]["area"].to("cpu")))
|
| 760 |
+
# verify boxes
|
| 761 |
+
self.assertEqual(encoding_cpu["labels"][0]["boxes"].shape, encoding_gpu["labels"][0]["boxes"].shape)
|
| 762 |
+
self.assertTrue(
|
| 763 |
+
torch.allclose(
|
| 764 |
+
encoding_cpu["labels"][0]["boxes"][0], encoding_gpu["labels"][0]["boxes"][0].to("cpu"), atol=1e-3
|
| 765 |
+
)
|
| 766 |
+
)
|
| 767 |
+
# verify image_id
|
| 768 |
+
self.assertTrue(
|
| 769 |
+
torch.allclose(encoding_cpu["labels"][0]["image_id"], encoding_gpu["labels"][0]["image_id"].to("cpu"))
|
| 770 |
+
)
|
| 771 |
+
# verify is_crowd
|
| 772 |
+
self.assertTrue(
|
| 773 |
+
torch.allclose(encoding_cpu["labels"][0]["iscrowd"], encoding_gpu["labels"][0]["iscrowd"].to("cpu"))
|
| 774 |
+
)
|
| 775 |
+
# verify class_labels
|
| 776 |
+
self.assertTrue(
|
| 777 |
+
torch.allclose(
|
| 778 |
+
encoding_cpu["labels"][0]["class_labels"], encoding_gpu["labels"][0]["class_labels"].to("cpu")
|
| 779 |
+
)
|
| 780 |
+
)
|
| 781 |
+
# verify masks
|
| 782 |
+
masks_sum_cpu = encoding_cpu["labels"][0]["masks"].sum()
|
| 783 |
+
masks_sum_gpu = encoding_gpu["labels"][0]["masks"].sum()
|
| 784 |
+
relative_error = torch.abs(masks_sum_cpu - masks_sum_gpu) / masks_sum_cpu
|
| 785 |
+
self.assertTrue(relative_error < 1e-3)
|
| 786 |
+
# verify orig_size
|
| 787 |
+
self.assertTrue(
|
| 788 |
+
torch.allclose(encoding_cpu["labels"][0]["orig_size"], encoding_gpu["labels"][0]["orig_size"].to("cpu"))
|
| 789 |
+
)
|
| 790 |
+
# verify size
|
| 791 |
+
self.assertTrue(torch.allclose(encoding_cpu["labels"][0]["size"], encoding_gpu["labels"][0]["size"].to("cpu")))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/detr/test_modeling_detr.py
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch DETR model."""
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import math
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import DetrConfig, ResNetConfig, is_torch_available, is_vision_available
|
| 22 |
+
from transformers.testing_utils import require_timm, require_torch, require_vision, slow, torch_device
|
| 23 |
+
from transformers.utils import cached_property
|
| 24 |
+
|
| 25 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 26 |
+
from ...test_configuration_common import ConfigTester
|
| 27 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor
|
| 28 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
if is_torch_available():
|
| 32 |
+
import torch
|
| 33 |
+
|
| 34 |
+
from transformers import DetrForObjectDetection, DetrForSegmentation, DetrModel
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if is_vision_available():
|
| 38 |
+
from PIL import Image
|
| 39 |
+
|
| 40 |
+
from transformers import DetrImageProcessor
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class DetrModelTester:
|
| 44 |
+
def __init__(
|
| 45 |
+
self,
|
| 46 |
+
parent,
|
| 47 |
+
batch_size=8,
|
| 48 |
+
is_training=True,
|
| 49 |
+
use_labels=True,
|
| 50 |
+
hidden_size=32,
|
| 51 |
+
num_hidden_layers=2,
|
| 52 |
+
num_attention_heads=8,
|
| 53 |
+
intermediate_size=4,
|
| 54 |
+
hidden_act="gelu",
|
| 55 |
+
hidden_dropout_prob=0.1,
|
| 56 |
+
attention_probs_dropout_prob=0.1,
|
| 57 |
+
num_queries=12,
|
| 58 |
+
num_channels=3,
|
| 59 |
+
min_size=200,
|
| 60 |
+
max_size=200,
|
| 61 |
+
n_targets=8,
|
| 62 |
+
num_labels=91,
|
| 63 |
+
):
|
| 64 |
+
self.parent = parent
|
| 65 |
+
self.batch_size = batch_size
|
| 66 |
+
self.is_training = is_training
|
| 67 |
+
self.use_labels = use_labels
|
| 68 |
+
self.hidden_size = hidden_size
|
| 69 |
+
self.num_hidden_layers = num_hidden_layers
|
| 70 |
+
self.num_attention_heads = num_attention_heads
|
| 71 |
+
self.intermediate_size = intermediate_size
|
| 72 |
+
self.hidden_act = hidden_act
|
| 73 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 74 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 75 |
+
self.num_queries = num_queries
|
| 76 |
+
self.num_channels = num_channels
|
| 77 |
+
self.min_size = min_size
|
| 78 |
+
self.max_size = max_size
|
| 79 |
+
self.n_targets = n_targets
|
| 80 |
+
self.num_labels = num_labels
|
| 81 |
+
|
| 82 |
+
# we also set the expected seq length for both encoder and decoder
|
| 83 |
+
self.encoder_seq_length = math.ceil(self.min_size / 32) * math.ceil(self.max_size / 32)
|
| 84 |
+
self.decoder_seq_length = self.num_queries
|
| 85 |
+
|
| 86 |
+
def prepare_config_and_inputs(self):
|
| 87 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size])
|
| 88 |
+
|
| 89 |
+
pixel_mask = torch.ones([self.batch_size, self.min_size, self.max_size], device=torch_device)
|
| 90 |
+
|
| 91 |
+
labels = None
|
| 92 |
+
if self.use_labels:
|
| 93 |
+
# labels is a list of Dict (each Dict being the labels for a given example in the batch)
|
| 94 |
+
labels = []
|
| 95 |
+
for i in range(self.batch_size):
|
| 96 |
+
target = {}
|
| 97 |
+
target["class_labels"] = torch.randint(
|
| 98 |
+
high=self.num_labels, size=(self.n_targets,), device=torch_device
|
| 99 |
+
)
|
| 100 |
+
target["boxes"] = torch.rand(self.n_targets, 4, device=torch_device)
|
| 101 |
+
target["masks"] = torch.rand(self.n_targets, self.min_size, self.max_size, device=torch_device)
|
| 102 |
+
labels.append(target)
|
| 103 |
+
|
| 104 |
+
config = self.get_config()
|
| 105 |
+
return config, pixel_values, pixel_mask, labels
|
| 106 |
+
|
| 107 |
+
def get_config(self):
|
| 108 |
+
resnet_config = ResNetConfig(
|
| 109 |
+
num_channels=3,
|
| 110 |
+
embeddings_size=10,
|
| 111 |
+
hidden_sizes=[10, 20, 30, 40],
|
| 112 |
+
depths=[1, 1, 2, 1],
|
| 113 |
+
hidden_act="relu",
|
| 114 |
+
num_labels=3,
|
| 115 |
+
out_features=["stage2", "stage3", "stage4"],
|
| 116 |
+
out_indices=[2, 3, 4],
|
| 117 |
+
)
|
| 118 |
+
return DetrConfig(
|
| 119 |
+
d_model=self.hidden_size,
|
| 120 |
+
encoder_layers=self.num_hidden_layers,
|
| 121 |
+
decoder_layers=self.num_hidden_layers,
|
| 122 |
+
encoder_attention_heads=self.num_attention_heads,
|
| 123 |
+
decoder_attention_heads=self.num_attention_heads,
|
| 124 |
+
encoder_ffn_dim=self.intermediate_size,
|
| 125 |
+
decoder_ffn_dim=self.intermediate_size,
|
| 126 |
+
dropout=self.hidden_dropout_prob,
|
| 127 |
+
attention_dropout=self.attention_probs_dropout_prob,
|
| 128 |
+
num_queries=self.num_queries,
|
| 129 |
+
num_labels=self.num_labels,
|
| 130 |
+
use_timm_backbone=False,
|
| 131 |
+
backbone_config=resnet_config,
|
| 132 |
+
backbone=None,
|
| 133 |
+
use_pretrained_backbone=False,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
def prepare_config_and_inputs_for_common(self):
|
| 137 |
+
config, pixel_values, pixel_mask, labels = self.prepare_config_and_inputs()
|
| 138 |
+
inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask}
|
| 139 |
+
return config, inputs_dict
|
| 140 |
+
|
| 141 |
+
def create_and_check_detr_model(self, config, pixel_values, pixel_mask, labels):
|
| 142 |
+
model = DetrModel(config=config)
|
| 143 |
+
model.to(torch_device)
|
| 144 |
+
model.eval()
|
| 145 |
+
|
| 146 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
|
| 147 |
+
result = model(pixel_values)
|
| 148 |
+
|
| 149 |
+
self.parent.assertEqual(
|
| 150 |
+
result.last_hidden_state.shape, (self.batch_size, self.decoder_seq_length, self.hidden_size)
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def create_and_check_detr_object_detection_head_model(self, config, pixel_values, pixel_mask, labels):
|
| 154 |
+
model = DetrForObjectDetection(config=config)
|
| 155 |
+
model.to(torch_device)
|
| 156 |
+
model.eval()
|
| 157 |
+
|
| 158 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask)
|
| 159 |
+
result = model(pixel_values)
|
| 160 |
+
|
| 161 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1))
|
| 162 |
+
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
|
| 163 |
+
|
| 164 |
+
result = model(pixel_values=pixel_values, pixel_mask=pixel_mask, labels=labels)
|
| 165 |
+
|
| 166 |
+
self.parent.assertEqual(result.loss.shape, ())
|
| 167 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1))
|
| 168 |
+
self.parent.assertEqual(result.pred_boxes.shape, (self.batch_size, self.num_queries, 4))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@require_torch
|
| 172 |
+
class DetrModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 173 |
+
all_model_classes = (
|
| 174 |
+
(
|
| 175 |
+
DetrModel,
|
| 176 |
+
DetrForObjectDetection,
|
| 177 |
+
DetrForSegmentation,
|
| 178 |
+
)
|
| 179 |
+
if is_torch_available()
|
| 180 |
+
else ()
|
| 181 |
+
)
|
| 182 |
+
pipeline_model_mapping = (
|
| 183 |
+
{
|
| 184 |
+
"image-feature-extraction": DetrModel,
|
| 185 |
+
"image-segmentation": DetrForSegmentation,
|
| 186 |
+
"object-detection": DetrForObjectDetection,
|
| 187 |
+
}
|
| 188 |
+
if is_torch_available()
|
| 189 |
+
else {}
|
| 190 |
+
)
|
| 191 |
+
is_encoder_decoder = True
|
| 192 |
+
test_torchscript = False
|
| 193 |
+
test_pruning = False
|
| 194 |
+
test_head_masking = False
|
| 195 |
+
test_missing_keys = False
|
| 196 |
+
zero_init_hidden_state = True
|
| 197 |
+
|
| 198 |
+
# special case for head models
|
| 199 |
+
def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
|
| 200 |
+
inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
|
| 201 |
+
|
| 202 |
+
if return_labels:
|
| 203 |
+
if model_class.__name__ in ["DetrForObjectDetection", "DetrForSegmentation"]:
|
| 204 |
+
labels = []
|
| 205 |
+
for i in range(self.model_tester.batch_size):
|
| 206 |
+
target = {}
|
| 207 |
+
target["class_labels"] = torch.ones(
|
| 208 |
+
size=(self.model_tester.n_targets,), device=torch_device, dtype=torch.long
|
| 209 |
+
)
|
| 210 |
+
target["boxes"] = torch.ones(
|
| 211 |
+
self.model_tester.n_targets, 4, device=torch_device, dtype=torch.float
|
| 212 |
+
)
|
| 213 |
+
target["masks"] = torch.ones(
|
| 214 |
+
self.model_tester.n_targets,
|
| 215 |
+
self.model_tester.min_size,
|
| 216 |
+
self.model_tester.max_size,
|
| 217 |
+
device=torch_device,
|
| 218 |
+
dtype=torch.float,
|
| 219 |
+
)
|
| 220 |
+
labels.append(target)
|
| 221 |
+
inputs_dict["labels"] = labels
|
| 222 |
+
|
| 223 |
+
return inputs_dict
|
| 224 |
+
|
| 225 |
+
def setUp(self):
|
| 226 |
+
self.model_tester = DetrModelTester(self)
|
| 227 |
+
self.config_tester = ConfigTester(self, config_class=DetrConfig, has_text_modality=False)
|
| 228 |
+
|
| 229 |
+
def test_config(self):
|
| 230 |
+
self.config_tester.run_common_tests()
|
| 231 |
+
|
| 232 |
+
def test_detr_model(self):
|
| 233 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 234 |
+
self.model_tester.create_and_check_detr_model(*config_and_inputs)
|
| 235 |
+
|
| 236 |
+
def test_detr_object_detection_head_model(self):
|
| 237 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 238 |
+
self.model_tester.create_and_check_detr_object_detection_head_model(*config_and_inputs)
|
| 239 |
+
|
| 240 |
+
# TODO: check if this works again for PyTorch 2.x.y
|
| 241 |
+
@unittest.skip(reason="Got `CUDA error: misaligned address` with PyTorch 2.0.0.")
|
| 242 |
+
def test_multi_gpu_data_parallel_forward(self):
|
| 243 |
+
pass
|
| 244 |
+
|
| 245 |
+
@unittest.skip(reason="DETR does not use inputs_embeds")
|
| 246 |
+
def test_inputs_embeds(self):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
@unittest.skip(reason="DETR does not use inputs_embeds")
|
| 250 |
+
def test_inputs_embeds_matches_input_ids(self):
|
| 251 |
+
pass
|
| 252 |
+
|
| 253 |
+
@unittest.skip(reason="DETR does not have a get_input_embeddings method")
|
| 254 |
+
def test_model_get_set_embeddings(self):
|
| 255 |
+
pass
|
| 256 |
+
|
| 257 |
+
@unittest.skip(reason="DETR is not a generative model")
|
| 258 |
+
def test_generate_without_input_ids(self):
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
@unittest.skip(reason="DETR does not use token embeddings")
|
| 262 |
+
def test_resize_tokens_embeddings(self):
|
| 263 |
+
pass
|
| 264 |
+
|
| 265 |
+
@slow
|
| 266 |
+
@unittest.skip(reason="TODO Niels: fix me!")
|
| 267 |
+
def test_model_outputs_equivalence(self):
|
| 268 |
+
pass
|
| 269 |
+
|
| 270 |
+
def test_attention_outputs(self):
|
| 271 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 272 |
+
config.return_dict = True
|
| 273 |
+
|
| 274 |
+
decoder_seq_length = self.model_tester.decoder_seq_length
|
| 275 |
+
encoder_seq_length = self.model_tester.encoder_seq_length
|
| 276 |
+
decoder_key_length = self.model_tester.decoder_seq_length
|
| 277 |
+
encoder_key_length = self.model_tester.encoder_seq_length
|
| 278 |
+
|
| 279 |
+
for model_class in self.all_model_classes:
|
| 280 |
+
inputs_dict["output_attentions"] = True
|
| 281 |
+
inputs_dict["output_hidden_states"] = False
|
| 282 |
+
config.return_dict = True
|
| 283 |
+
model = model_class(config)
|
| 284 |
+
model.to(torch_device)
|
| 285 |
+
model.eval()
|
| 286 |
+
with torch.no_grad():
|
| 287 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 288 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 289 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 290 |
+
|
| 291 |
+
# check that output_attentions also work using config
|
| 292 |
+
del inputs_dict["output_attentions"]
|
| 293 |
+
config.output_attentions = True
|
| 294 |
+
model = model_class(config)
|
| 295 |
+
model.to(torch_device)
|
| 296 |
+
model.eval()
|
| 297 |
+
with torch.no_grad():
|
| 298 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 299 |
+
attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 300 |
+
self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
|
| 301 |
+
|
| 302 |
+
self.assertListEqual(
|
| 303 |
+
list(attentions[0].shape[-3:]),
|
| 304 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 305 |
+
)
|
| 306 |
+
out_len = len(outputs)
|
| 307 |
+
|
| 308 |
+
if self.is_encoder_decoder:
|
| 309 |
+
correct_outlen = 5
|
| 310 |
+
|
| 311 |
+
# loss is at first position
|
| 312 |
+
if "labels" in inputs_dict:
|
| 313 |
+
correct_outlen += 1 # loss is added to beginning
|
| 314 |
+
# Object Detection model returns pred_logits and pred_boxes
|
| 315 |
+
if model_class.__name__ == "DetrForObjectDetection":
|
| 316 |
+
correct_outlen += 2
|
| 317 |
+
# Panoptic Segmentation model returns pred_logits, pred_boxes, pred_masks
|
| 318 |
+
if model_class.__name__ == "DetrForSegmentation":
|
| 319 |
+
correct_outlen += 3
|
| 320 |
+
if "past_key_values" in outputs:
|
| 321 |
+
correct_outlen += 1 # past_key_values have been returned
|
| 322 |
+
|
| 323 |
+
self.assertEqual(out_len, correct_outlen)
|
| 324 |
+
|
| 325 |
+
# decoder attentions
|
| 326 |
+
decoder_attentions = outputs.decoder_attentions
|
| 327 |
+
self.assertIsInstance(decoder_attentions, (list, tuple))
|
| 328 |
+
self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
|
| 329 |
+
self.assertListEqual(
|
| 330 |
+
list(decoder_attentions[0].shape[-3:]),
|
| 331 |
+
[self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length],
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# cross attentions
|
| 335 |
+
cross_attentions = outputs.cross_attentions
|
| 336 |
+
self.assertIsInstance(cross_attentions, (list, tuple))
|
| 337 |
+
self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
|
| 338 |
+
self.assertListEqual(
|
| 339 |
+
list(cross_attentions[0].shape[-3:]),
|
| 340 |
+
[
|
| 341 |
+
self.model_tester.num_attention_heads,
|
| 342 |
+
decoder_seq_length,
|
| 343 |
+
encoder_key_length,
|
| 344 |
+
],
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# Check attention is always last and order is fine
|
| 348 |
+
inputs_dict["output_attentions"] = True
|
| 349 |
+
inputs_dict["output_hidden_states"] = True
|
| 350 |
+
model = model_class(config)
|
| 351 |
+
model.to(torch_device)
|
| 352 |
+
model.eval()
|
| 353 |
+
with torch.no_grad():
|
| 354 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 355 |
+
|
| 356 |
+
if hasattr(self.model_tester, "num_hidden_states_types"):
|
| 357 |
+
added_hidden_states = self.model_tester.num_hidden_states_types
|
| 358 |
+
elif self.is_encoder_decoder:
|
| 359 |
+
added_hidden_states = 2
|
| 360 |
+
else:
|
| 361 |
+
added_hidden_states = 1
|
| 362 |
+
self.assertEqual(out_len + added_hidden_states, len(outputs))
|
| 363 |
+
|
| 364 |
+
self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
|
| 365 |
+
|
| 366 |
+
self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
|
| 367 |
+
self.assertListEqual(
|
| 368 |
+
list(self_attentions[0].shape[-3:]),
|
| 369 |
+
[self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length],
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
def test_retain_grad_hidden_states_attentions(self):
|
| 373 |
+
# removed retain_grad and grad on decoder_hidden_states, as queries don't require grad
|
| 374 |
+
|
| 375 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 376 |
+
config.output_hidden_states = True
|
| 377 |
+
config.output_attentions = True
|
| 378 |
+
|
| 379 |
+
# no need to test all models as different heads yield the same functionality
|
| 380 |
+
model_class = self.all_model_classes[0]
|
| 381 |
+
model = model_class(config)
|
| 382 |
+
model.to(torch_device)
|
| 383 |
+
|
| 384 |
+
inputs = self._prepare_for_class(inputs_dict, model_class)
|
| 385 |
+
|
| 386 |
+
outputs = model(**inputs)
|
| 387 |
+
|
| 388 |
+
output = outputs[0]
|
| 389 |
+
|
| 390 |
+
encoder_hidden_states = outputs.encoder_hidden_states[0]
|
| 391 |
+
encoder_attentions = outputs.encoder_attentions[0]
|
| 392 |
+
encoder_hidden_states.retain_grad()
|
| 393 |
+
encoder_attentions.retain_grad()
|
| 394 |
+
|
| 395 |
+
decoder_attentions = outputs.decoder_attentions[0]
|
| 396 |
+
decoder_attentions.retain_grad()
|
| 397 |
+
|
| 398 |
+
cross_attentions = outputs.cross_attentions[0]
|
| 399 |
+
cross_attentions.retain_grad()
|
| 400 |
+
|
| 401 |
+
output.flatten()[0].backward(retain_graph=True)
|
| 402 |
+
|
| 403 |
+
self.assertIsNotNone(encoder_hidden_states.grad)
|
| 404 |
+
self.assertIsNotNone(encoder_attentions.grad)
|
| 405 |
+
self.assertIsNotNone(decoder_attentions.grad)
|
| 406 |
+
self.assertIsNotNone(cross_attentions.grad)
|
| 407 |
+
|
| 408 |
+
def test_forward_auxiliary_loss(self):
|
| 409 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 410 |
+
config.auxiliary_loss = True
|
| 411 |
+
|
| 412 |
+
# only test for object detection and segmentation model
|
| 413 |
+
for model_class in self.all_model_classes[1:]:
|
| 414 |
+
model = model_class(config)
|
| 415 |
+
model.to(torch_device)
|
| 416 |
+
|
| 417 |
+
inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
|
| 418 |
+
|
| 419 |
+
outputs = model(**inputs)
|
| 420 |
+
|
| 421 |
+
self.assertIsNotNone(outputs.auxiliary_outputs)
|
| 422 |
+
self.assertEqual(len(outputs.auxiliary_outputs), self.model_tester.num_hidden_layers - 1)
|
| 423 |
+
|
| 424 |
+
def test_forward_signature(self):
|
| 425 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 426 |
+
|
| 427 |
+
for model_class in self.all_model_classes:
|
| 428 |
+
model = model_class(config)
|
| 429 |
+
signature = inspect.signature(model.forward)
|
| 430 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 431 |
+
arg_names = [*signature.parameters.keys()]
|
| 432 |
+
|
| 433 |
+
if model.config.is_encoder_decoder:
|
| 434 |
+
expected_arg_names = ["pixel_values", "pixel_mask"]
|
| 435 |
+
expected_arg_names.extend(
|
| 436 |
+
["head_mask", "decoder_head_mask", "encoder_outputs"]
|
| 437 |
+
if "head_mask" and "decoder_head_mask" in arg_names
|
| 438 |
+
else []
|
| 439 |
+
)
|
| 440 |
+
self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
|
| 441 |
+
else:
|
| 442 |
+
expected_arg_names = ["pixel_values", "pixel_mask"]
|
| 443 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 444 |
+
|
| 445 |
+
def test_different_timm_backbone(self):
|
| 446 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 447 |
+
|
| 448 |
+
# let's pick a random timm backbone
|
| 449 |
+
config.backbone = "tf_mobilenetv3_small_075"
|
| 450 |
+
config.backbone_config = None
|
| 451 |
+
config.use_timm_backbone = True
|
| 452 |
+
config.backbone_kwargs = {"out_indices": [2, 3, 4]}
|
| 453 |
+
|
| 454 |
+
for model_class in self.all_model_classes:
|
| 455 |
+
model = model_class(config)
|
| 456 |
+
model.to(torch_device)
|
| 457 |
+
model.eval()
|
| 458 |
+
with torch.no_grad():
|
| 459 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 460 |
+
|
| 461 |
+
if model_class.__name__ == "DetrForObjectDetection":
|
| 462 |
+
expected_shape = (
|
| 463 |
+
self.model_tester.batch_size,
|
| 464 |
+
self.model_tester.num_queries,
|
| 465 |
+
self.model_tester.num_labels + 1,
|
| 466 |
+
)
|
| 467 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 468 |
+
# Confirm out_indices was propogated to backbone
|
| 469 |
+
self.assertEqual(len(model.model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 470 |
+
elif model_class.__name__ == "DetrForSegmentation":
|
| 471 |
+
# Confirm out_indices was propogated to backbone
|
| 472 |
+
self.assertEqual(len(model.detr.model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 473 |
+
else:
|
| 474 |
+
# Confirm out_indices was propogated to backbone
|
| 475 |
+
self.assertEqual(len(model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 476 |
+
|
| 477 |
+
self.assertTrue(outputs)
|
| 478 |
+
|
| 479 |
+
def test_hf_backbone(self):
|
| 480 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 481 |
+
|
| 482 |
+
# Load a pretrained HF checkpoint as backbone
|
| 483 |
+
config.backbone = "microsoft/resnet-18"
|
| 484 |
+
config.backbone_config = None
|
| 485 |
+
config.use_timm_backbone = False
|
| 486 |
+
config.use_pretrained_backbone = True
|
| 487 |
+
config.backbone_kwargs = {"out_indices": [2, 3, 4]}
|
| 488 |
+
|
| 489 |
+
for model_class in self.all_model_classes:
|
| 490 |
+
model = model_class(config)
|
| 491 |
+
model.to(torch_device)
|
| 492 |
+
model.eval()
|
| 493 |
+
with torch.no_grad():
|
| 494 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 495 |
+
|
| 496 |
+
if model_class.__name__ == "DetrForObjectDetection":
|
| 497 |
+
expected_shape = (
|
| 498 |
+
self.model_tester.batch_size,
|
| 499 |
+
self.model_tester.num_queries,
|
| 500 |
+
self.model_tester.num_labels + 1,
|
| 501 |
+
)
|
| 502 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 503 |
+
# Confirm out_indices was propogated to backbone
|
| 504 |
+
self.assertEqual(len(model.model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 505 |
+
elif model_class.__name__ == "DetrForSegmentation":
|
| 506 |
+
# Confirm out_indices was propogated to backbone
|
| 507 |
+
self.assertEqual(len(model.detr.model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 508 |
+
else:
|
| 509 |
+
# Confirm out_indices was propogated to backbone
|
| 510 |
+
self.assertEqual(len(model.backbone.conv_encoder.intermediate_channel_sizes), 3)
|
| 511 |
+
|
| 512 |
+
self.assertTrue(outputs)
|
| 513 |
+
|
| 514 |
+
def test_greyscale_images(self):
|
| 515 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 516 |
+
|
| 517 |
+
# use greyscale pixel values
|
| 518 |
+
inputs_dict["pixel_values"] = floats_tensor(
|
| 519 |
+
[self.model_tester.batch_size, 1, self.model_tester.min_size, self.model_tester.max_size]
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
# let's set num_channels to 1
|
| 523 |
+
config.num_channels = 1
|
| 524 |
+
config.backbone_config.num_channels = 1
|
| 525 |
+
|
| 526 |
+
for model_class in self.all_model_classes:
|
| 527 |
+
model = model_class(config)
|
| 528 |
+
model.to(torch_device)
|
| 529 |
+
model.eval()
|
| 530 |
+
with torch.no_grad():
|
| 531 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 532 |
+
|
| 533 |
+
self.assertTrue(outputs)
|
| 534 |
+
|
| 535 |
+
def test_initialization(self):
|
| 536 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 537 |
+
|
| 538 |
+
configs_no_init = _config_zero_init(config)
|
| 539 |
+
configs_no_init.init_xavier_std = 1e9
|
| 540 |
+
|
| 541 |
+
for model_class in self.all_model_classes:
|
| 542 |
+
model = model_class(config=configs_no_init)
|
| 543 |
+
for name, param in model.named_parameters():
|
| 544 |
+
if param.requires_grad:
|
| 545 |
+
if "bbox_attention" in name and "bias" not in name:
|
| 546 |
+
self.assertLess(
|
| 547 |
+
100000,
|
| 548 |
+
abs(param.data.max().item()),
|
| 549 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 550 |
+
)
|
| 551 |
+
else:
|
| 552 |
+
self.assertIn(
|
| 553 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 554 |
+
[0.0, 1.0],
|
| 555 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 556 |
+
)
|
| 557 |
+
|
| 558 |
+
|
| 559 |
+
TOLERANCE = 1e-4
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# We will verify our results on an image of cute cats
|
| 563 |
+
def prepare_img():
|
| 564 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 565 |
+
return image
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
@require_timm
|
| 569 |
+
@require_vision
|
| 570 |
+
@slow
|
| 571 |
+
class DetrModelIntegrationTestsTimmBackbone(unittest.TestCase):
|
| 572 |
+
@cached_property
|
| 573 |
+
def default_image_processor(self):
|
| 574 |
+
return DetrImageProcessor.from_pretrained("facebook/detr-resnet-50") if is_vision_available() else None
|
| 575 |
+
|
| 576 |
+
def test_inference_no_head(self):
|
| 577 |
+
model = DetrModel.from_pretrained("facebook/detr-resnet-50").to(torch_device)
|
| 578 |
+
|
| 579 |
+
image_processor = self.default_image_processor
|
| 580 |
+
image = prepare_img()
|
| 581 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 582 |
+
|
| 583 |
+
with torch.no_grad():
|
| 584 |
+
outputs = model(**encoding)
|
| 585 |
+
|
| 586 |
+
expected_shape = torch.Size((1, 100, 256))
|
| 587 |
+
assert outputs.last_hidden_state.shape == expected_shape
|
| 588 |
+
expected_slice = torch.tensor(
|
| 589 |
+
[[0.0616, -0.5146, -0.4032], [-0.7629, -0.4934, -1.7153], [-0.4768, -0.6403, -0.7826]]
|
| 590 |
+
).to(torch_device)
|
| 591 |
+
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
| 592 |
+
|
| 593 |
+
def test_inference_object_detection_head(self):
|
| 594 |
+
model = DetrForObjectDetection.from_pretrained("facebook/detr-resnet-50").to(torch_device)
|
| 595 |
+
|
| 596 |
+
image_processor = self.default_image_processor
|
| 597 |
+
image = prepare_img()
|
| 598 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 599 |
+
pixel_values = encoding["pixel_values"].to(torch_device)
|
| 600 |
+
pixel_mask = encoding["pixel_mask"].to(torch_device)
|
| 601 |
+
|
| 602 |
+
with torch.no_grad():
|
| 603 |
+
outputs = model(pixel_values, pixel_mask)
|
| 604 |
+
|
| 605 |
+
# verify outputs
|
| 606 |
+
expected_shape_logits = torch.Size((1, model.config.num_queries, model.config.num_labels + 1))
|
| 607 |
+
self.assertEqual(outputs.logits.shape, expected_shape_logits)
|
| 608 |
+
expected_slice_logits = torch.tensor(
|
| 609 |
+
[[-19.1194, -0.0893, -11.0154], [-17.3640, -1.8035, -14.0219], [-20.0461, -0.5837, -11.1060]]
|
| 610 |
+
).to(torch_device)
|
| 611 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice_logits, atol=1e-4))
|
| 612 |
+
|
| 613 |
+
expected_shape_boxes = torch.Size((1, model.config.num_queries, 4))
|
| 614 |
+
self.assertEqual(outputs.pred_boxes.shape, expected_shape_boxes)
|
| 615 |
+
expected_slice_boxes = torch.tensor(
|
| 616 |
+
[[0.4433, 0.5302, 0.8853], [0.5494, 0.2517, 0.0529], [0.4998, 0.5360, 0.9956]]
|
| 617 |
+
).to(torch_device)
|
| 618 |
+
self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
|
| 619 |
+
|
| 620 |
+
# verify postprocessing
|
| 621 |
+
results = image_processor.post_process_object_detection(
|
| 622 |
+
outputs, threshold=0.3, target_sizes=[image.size[::-1]]
|
| 623 |
+
)[0]
|
| 624 |
+
expected_scores = torch.tensor([0.9982, 0.9960, 0.9955, 0.9988, 0.9987]).to(torch_device)
|
| 625 |
+
expected_labels = [75, 75, 63, 17, 17]
|
| 626 |
+
expected_slice_boxes = torch.tensor([40.1633, 70.8115, 175.5471, 117.9841]).to(torch_device)
|
| 627 |
+
|
| 628 |
+
self.assertEqual(len(results["scores"]), 5)
|
| 629 |
+
self.assertTrue(torch.allclose(results["scores"], expected_scores, atol=1e-4))
|
| 630 |
+
self.assertSequenceEqual(results["labels"].tolist(), expected_labels)
|
| 631 |
+
self.assertTrue(torch.allclose(results["boxes"][0, :], expected_slice_boxes))
|
| 632 |
+
|
| 633 |
+
def test_inference_panoptic_segmentation_head(self):
|
| 634 |
+
model = DetrForSegmentation.from_pretrained("facebook/detr-resnet-50-panoptic").to(torch_device)
|
| 635 |
+
|
| 636 |
+
image_processor = self.default_image_processor
|
| 637 |
+
image = prepare_img()
|
| 638 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 639 |
+
pixel_values = encoding["pixel_values"].to(torch_device)
|
| 640 |
+
pixel_mask = encoding["pixel_mask"].to(torch_device)
|
| 641 |
+
|
| 642 |
+
with torch.no_grad():
|
| 643 |
+
outputs = model(pixel_values, pixel_mask)
|
| 644 |
+
|
| 645 |
+
# verify outputs
|
| 646 |
+
expected_shape_logits = torch.Size((1, model.config.num_queries, model.config.num_labels + 1))
|
| 647 |
+
self.assertEqual(outputs.logits.shape, expected_shape_logits)
|
| 648 |
+
expected_slice_logits = torch.tensor(
|
| 649 |
+
[[-18.1565, -1.7568, -13.5029], [-16.8888, -1.4138, -14.1028], [-17.5709, -2.5080, -11.8654]]
|
| 650 |
+
).to(torch_device)
|
| 651 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice_logits, atol=1e-4))
|
| 652 |
+
|
| 653 |
+
expected_shape_boxes = torch.Size((1, model.config.num_queries, 4))
|
| 654 |
+
self.assertEqual(outputs.pred_boxes.shape, expected_shape_boxes)
|
| 655 |
+
expected_slice_boxes = torch.tensor(
|
| 656 |
+
[[0.5344, 0.1789, 0.9285], [0.4420, 0.0572, 0.0875], [0.6630, 0.6887, 0.1017]]
|
| 657 |
+
).to(torch_device)
|
| 658 |
+
self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
|
| 659 |
+
|
| 660 |
+
expected_shape_masks = torch.Size((1, model.config.num_queries, 200, 267))
|
| 661 |
+
self.assertEqual(outputs.pred_masks.shape, expected_shape_masks)
|
| 662 |
+
expected_slice_masks = torch.tensor(
|
| 663 |
+
[[-7.7558, -10.8788, -11.9797], [-11.8881, -16.4329, -17.7451], [-14.7316, -19.7383, -20.3004]]
|
| 664 |
+
).to(torch_device)
|
| 665 |
+
self.assertTrue(torch.allclose(outputs.pred_masks[0, 0, :3, :3], expected_slice_masks, atol=1e-3))
|
| 666 |
+
|
| 667 |
+
# verify postprocessing
|
| 668 |
+
results = image_processor.post_process_panoptic_segmentation(
|
| 669 |
+
outputs, threshold=0.3, target_sizes=[image.size[::-1]]
|
| 670 |
+
)[0]
|
| 671 |
+
|
| 672 |
+
expected_shape = torch.Size([480, 640])
|
| 673 |
+
expected_slice_segmentation = torch.tensor([[4, 4, 4], [4, 4, 4], [4, 4, 4]], dtype=torch.int32).to(
|
| 674 |
+
torch_device
|
| 675 |
+
)
|
| 676 |
+
expected_number_of_segments = 5
|
| 677 |
+
expected_first_segment = {"id": 1, "label_id": 17, "was_fused": False, "score": 0.994097}
|
| 678 |
+
|
| 679 |
+
number_of_unique_segments = len(torch.unique(results["segmentation"]))
|
| 680 |
+
self.assertTrue(
|
| 681 |
+
number_of_unique_segments, expected_number_of_segments + 1
|
| 682 |
+
) # we add 1 for the background class
|
| 683 |
+
self.assertTrue(results["segmentation"].shape, expected_shape)
|
| 684 |
+
self.assertTrue(torch.allclose(results["segmentation"][:3, :3], expected_slice_segmentation, atol=1e-4))
|
| 685 |
+
self.assertTrue(len(results["segments_info"]), expected_number_of_segments)
|
| 686 |
+
self.assertDictEqual(results["segments_info"][0], expected_first_segment)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
@require_vision
|
| 690 |
+
@require_torch
|
| 691 |
+
@slow
|
| 692 |
+
class DetrModelIntegrationTests(unittest.TestCase):
|
| 693 |
+
@cached_property
|
| 694 |
+
def default_image_processor(self):
|
| 695 |
+
return (
|
| 696 |
+
DetrImageProcessor.from_pretrained("facebook/detr-resnet-50", revision="no_timm")
|
| 697 |
+
if is_vision_available()
|
| 698 |
+
else None
|
| 699 |
+
)
|
| 700 |
+
|
| 701 |
+
def test_inference_no_head(self):
|
| 702 |
+
model = DetrModel.from_pretrained("facebook/detr-resnet-50", revision="no_timm").to(torch_device)
|
| 703 |
+
|
| 704 |
+
image_processor = self.default_image_processor
|
| 705 |
+
image = prepare_img()
|
| 706 |
+
encoding = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 707 |
+
|
| 708 |
+
with torch.no_grad():
|
| 709 |
+
outputs = model(**encoding)
|
| 710 |
+
|
| 711 |
+
expected_shape = torch.Size((1, 100, 256))
|
| 712 |
+
assert outputs.last_hidden_state.shape == expected_shape
|
| 713 |
+
expected_slice = torch.tensor(
|
| 714 |
+
[[0.0616, -0.5146, -0.4032], [-0.7629, -0.4934, -1.7153], [-0.4768, -0.6403, -0.7826]]
|
| 715 |
+
).to(torch_device)
|
| 716 |
+
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/diffllama/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/diffllama/test_modeling_diffllama.py
ADDED
|
@@ -0,0 +1,992 @@
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch DiffLlama model."""
|
| 16 |
+
|
| 17 |
+
import gc
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import pytest
|
| 22 |
+
from packaging import version
|
| 23 |
+
from parameterized import parameterized
|
| 24 |
+
|
| 25 |
+
from transformers import AutoTokenizer, DiffLlamaConfig, StaticCache, is_torch_available, set_seed
|
| 26 |
+
from transformers.testing_utils import (
|
| 27 |
+
backend_empty_cache,
|
| 28 |
+
require_bitsandbytes,
|
| 29 |
+
require_flash_attn,
|
| 30 |
+
require_read_token,
|
| 31 |
+
require_torch,
|
| 32 |
+
require_torch_accelerator,
|
| 33 |
+
require_torch_gpu,
|
| 34 |
+
require_torch_sdpa,
|
| 35 |
+
slow,
|
| 36 |
+
torch_device,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from ...generation.test_utils import GenerationTesterMixin
|
| 40 |
+
from ...test_configuration_common import ConfigTester
|
| 41 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor
|
| 42 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_torch_available():
|
| 46 |
+
import torch
|
| 47 |
+
|
| 48 |
+
from transformers import (
|
| 49 |
+
DiffLlamaForCausalLM,
|
| 50 |
+
DiffLlamaForQuestionAnswering,
|
| 51 |
+
DiffLlamaForSequenceClassification,
|
| 52 |
+
DiffLlamaForTokenClassification,
|
| 53 |
+
DiffLlamaModel,
|
| 54 |
+
)
|
| 55 |
+
from transformers.models.diffllama.modeling_diffllama import (
|
| 56 |
+
DiffLlamaRotaryEmbedding,
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class DiffLlamaModelTester:
|
| 61 |
+
def __init__(
|
| 62 |
+
self,
|
| 63 |
+
parent,
|
| 64 |
+
batch_size=13,
|
| 65 |
+
seq_length=7,
|
| 66 |
+
is_training=True,
|
| 67 |
+
use_input_mask=True,
|
| 68 |
+
use_token_type_ids=False,
|
| 69 |
+
use_labels=True,
|
| 70 |
+
vocab_size=99,
|
| 71 |
+
hidden_size=32,
|
| 72 |
+
num_hidden_layers=2,
|
| 73 |
+
num_attention_heads=4,
|
| 74 |
+
intermediate_size=37,
|
| 75 |
+
hidden_act="gelu",
|
| 76 |
+
hidden_dropout_prob=0.1,
|
| 77 |
+
attention_probs_dropout_prob=0.1,
|
| 78 |
+
max_position_embeddings=512,
|
| 79 |
+
type_vocab_size=16,
|
| 80 |
+
type_sequence_label_size=2,
|
| 81 |
+
initializer_range=0.02,
|
| 82 |
+
num_labels=3,
|
| 83 |
+
num_choices=4,
|
| 84 |
+
pad_token_id=0,
|
| 85 |
+
scope=None,
|
| 86 |
+
):
|
| 87 |
+
self.parent = parent
|
| 88 |
+
self.batch_size = batch_size
|
| 89 |
+
self.seq_length = seq_length
|
| 90 |
+
self.is_training = is_training
|
| 91 |
+
self.use_input_mask = use_input_mask
|
| 92 |
+
self.use_token_type_ids = use_token_type_ids
|
| 93 |
+
self.use_labels = use_labels
|
| 94 |
+
self.vocab_size = vocab_size
|
| 95 |
+
self.hidden_size = hidden_size
|
| 96 |
+
self.num_hidden_layers = num_hidden_layers
|
| 97 |
+
self.num_attention_heads = num_attention_heads
|
| 98 |
+
self.intermediate_size = intermediate_size
|
| 99 |
+
self.hidden_act = hidden_act
|
| 100 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 101 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 102 |
+
self.max_position_embeddings = max_position_embeddings
|
| 103 |
+
self.type_vocab_size = type_vocab_size
|
| 104 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 105 |
+
self.initializer_range = initializer_range
|
| 106 |
+
self.num_labels = num_labels
|
| 107 |
+
self.num_choices = num_choices
|
| 108 |
+
self.pad_token_id = pad_token_id
|
| 109 |
+
self.scope = scope
|
| 110 |
+
|
| 111 |
+
def prepare_config_and_inputs(self):
|
| 112 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 113 |
+
|
| 114 |
+
input_mask = None
|
| 115 |
+
if self.use_input_mask:
|
| 116 |
+
input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
|
| 117 |
+
|
| 118 |
+
token_type_ids = None
|
| 119 |
+
if self.use_token_type_ids:
|
| 120 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 121 |
+
|
| 122 |
+
sequence_labels = None
|
| 123 |
+
token_labels = None
|
| 124 |
+
choice_labels = None
|
| 125 |
+
if self.use_labels:
|
| 126 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 127 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 128 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 129 |
+
|
| 130 |
+
config = self.get_config()
|
| 131 |
+
|
| 132 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 133 |
+
|
| 134 |
+
def get_config(self):
|
| 135 |
+
return DiffLlamaConfig(
|
| 136 |
+
vocab_size=self.vocab_size,
|
| 137 |
+
hidden_size=self.hidden_size,
|
| 138 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 139 |
+
num_attention_heads=self.num_attention_heads,
|
| 140 |
+
intermediate_size=self.intermediate_size,
|
| 141 |
+
hidden_act=self.hidden_act,
|
| 142 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 143 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 144 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 145 |
+
type_vocab_size=self.type_vocab_size,
|
| 146 |
+
is_decoder=False,
|
| 147 |
+
initializer_range=self.initializer_range,
|
| 148 |
+
pad_token_id=self.pad_token_id,
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
def create_and_check_model(
|
| 152 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 153 |
+
):
|
| 154 |
+
model = DiffLlamaModel(config=config)
|
| 155 |
+
model.to(torch_device)
|
| 156 |
+
model.eval()
|
| 157 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 158 |
+
result = model(input_ids)
|
| 159 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 160 |
+
|
| 161 |
+
def create_and_check_model_as_decoder(
|
| 162 |
+
self,
|
| 163 |
+
config,
|
| 164 |
+
input_ids,
|
| 165 |
+
token_type_ids,
|
| 166 |
+
input_mask,
|
| 167 |
+
sequence_labels,
|
| 168 |
+
token_labels,
|
| 169 |
+
choice_labels,
|
| 170 |
+
encoder_hidden_states,
|
| 171 |
+
encoder_attention_mask,
|
| 172 |
+
):
|
| 173 |
+
config.add_cross_attention = True
|
| 174 |
+
model = DiffLlamaModel(config)
|
| 175 |
+
model.to(torch_device)
|
| 176 |
+
model.eval()
|
| 177 |
+
result = model(
|
| 178 |
+
input_ids,
|
| 179 |
+
attention_mask=input_mask,
|
| 180 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 181 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 182 |
+
)
|
| 183 |
+
result = model(
|
| 184 |
+
input_ids,
|
| 185 |
+
attention_mask=input_mask,
|
| 186 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 187 |
+
)
|
| 188 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 189 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 190 |
+
|
| 191 |
+
def create_and_check_for_causal_lm(
|
| 192 |
+
self,
|
| 193 |
+
config,
|
| 194 |
+
input_ids,
|
| 195 |
+
token_type_ids,
|
| 196 |
+
input_mask,
|
| 197 |
+
sequence_labels,
|
| 198 |
+
token_labels,
|
| 199 |
+
choice_labels,
|
| 200 |
+
encoder_hidden_states,
|
| 201 |
+
encoder_attention_mask,
|
| 202 |
+
):
|
| 203 |
+
model = DiffLlamaForCausalLM(config=config)
|
| 204 |
+
model.to(torch_device)
|
| 205 |
+
model.eval()
|
| 206 |
+
result = model(input_ids, attention_mask=input_mask, labels=token_labels)
|
| 207 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 208 |
+
|
| 209 |
+
def create_and_check_decoder_model_past_large_inputs(
|
| 210 |
+
self,
|
| 211 |
+
config,
|
| 212 |
+
input_ids,
|
| 213 |
+
token_type_ids,
|
| 214 |
+
input_mask,
|
| 215 |
+
sequence_labels,
|
| 216 |
+
token_labels,
|
| 217 |
+
choice_labels,
|
| 218 |
+
encoder_hidden_states,
|
| 219 |
+
encoder_attention_mask,
|
| 220 |
+
):
|
| 221 |
+
config.is_decoder = True
|
| 222 |
+
config.add_cross_attention = True
|
| 223 |
+
model = DiffLlamaForCausalLM(config=config)
|
| 224 |
+
model.to(torch_device)
|
| 225 |
+
model.eval()
|
| 226 |
+
|
| 227 |
+
# first forward pass
|
| 228 |
+
outputs = model(
|
| 229 |
+
input_ids,
|
| 230 |
+
attention_mask=input_mask,
|
| 231 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 232 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 233 |
+
use_cache=True,
|
| 234 |
+
)
|
| 235 |
+
past_key_values = outputs.past_key_values
|
| 236 |
+
|
| 237 |
+
# create hypothetical multiple next token and extent to next_input_ids
|
| 238 |
+
next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
|
| 239 |
+
next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
|
| 240 |
+
|
| 241 |
+
# append to next input_ids and
|
| 242 |
+
next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
|
| 243 |
+
next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
|
| 244 |
+
|
| 245 |
+
output_from_no_past = model(
|
| 246 |
+
next_input_ids,
|
| 247 |
+
attention_mask=next_attention_mask,
|
| 248 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 249 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 250 |
+
output_hidden_states=True,
|
| 251 |
+
)["hidden_states"][0]
|
| 252 |
+
output_from_past = model(
|
| 253 |
+
next_tokens,
|
| 254 |
+
attention_mask=next_attention_mask,
|
| 255 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 256 |
+
encoder_attention_mask=encoder_attention_mask,
|
| 257 |
+
past_key_values=past_key_values,
|
| 258 |
+
output_hidden_states=True,
|
| 259 |
+
)["hidden_states"][0]
|
| 260 |
+
|
| 261 |
+
# select random slice
|
| 262 |
+
random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
|
| 263 |
+
output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
|
| 264 |
+
output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
|
| 265 |
+
|
| 266 |
+
self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
|
| 267 |
+
|
| 268 |
+
# test that outputs are equal for slice
|
| 269 |
+
self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
|
| 270 |
+
|
| 271 |
+
def prepare_config_and_inputs_for_common(self):
|
| 272 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 273 |
+
(
|
| 274 |
+
config,
|
| 275 |
+
input_ids,
|
| 276 |
+
token_type_ids,
|
| 277 |
+
input_mask,
|
| 278 |
+
sequence_labels,
|
| 279 |
+
token_labels,
|
| 280 |
+
choice_labels,
|
| 281 |
+
) = config_and_inputs
|
| 282 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 283 |
+
return config, inputs_dict
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
@require_torch
|
| 287 |
+
class DiffLlamaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 288 |
+
all_model_classes = (
|
| 289 |
+
(
|
| 290 |
+
DiffLlamaModel,
|
| 291 |
+
DiffLlamaForCausalLM,
|
| 292 |
+
DiffLlamaForSequenceClassification,
|
| 293 |
+
DiffLlamaForQuestionAnswering,
|
| 294 |
+
DiffLlamaForTokenClassification,
|
| 295 |
+
)
|
| 296 |
+
if is_torch_available()
|
| 297 |
+
else ()
|
| 298 |
+
)
|
| 299 |
+
all_generative_model_classes = (DiffLlamaForCausalLM,) if is_torch_available() else ()
|
| 300 |
+
pipeline_model_mapping = (
|
| 301 |
+
{
|
| 302 |
+
"feature-extraction": DiffLlamaModel,
|
| 303 |
+
"text-classification": DiffLlamaForSequenceClassification,
|
| 304 |
+
"text-generation": DiffLlamaForCausalLM,
|
| 305 |
+
"zero-shot": DiffLlamaForSequenceClassification,
|
| 306 |
+
"question-answering": DiffLlamaForQuestionAnswering,
|
| 307 |
+
"token-classification": DiffLlamaForTokenClassification,
|
| 308 |
+
}
|
| 309 |
+
if is_torch_available()
|
| 310 |
+
else {}
|
| 311 |
+
)
|
| 312 |
+
test_headmasking = False
|
| 313 |
+
test_pruning = False
|
| 314 |
+
fx_compatible = False
|
| 315 |
+
|
| 316 |
+
# Need to use `0.8` instead of `0.9` for `test_cpu_offload`
|
| 317 |
+
# This is because we are hitting edge cases with the causal_mask buffer
|
| 318 |
+
model_split_percents = [0.5, 0.7, 0.8]
|
| 319 |
+
|
| 320 |
+
# used in `test_torch_compile_for_training`
|
| 321 |
+
_torch_compile_train_cls = DiffLlamaForCausalLM if is_torch_available() else None
|
| 322 |
+
|
| 323 |
+
def setUp(self):
|
| 324 |
+
self.model_tester = DiffLlamaModelTester(self)
|
| 325 |
+
self.config_tester = ConfigTester(self, config_class=DiffLlamaConfig, hidden_size=37)
|
| 326 |
+
|
| 327 |
+
def test_config(self):
|
| 328 |
+
self.config_tester.run_common_tests()
|
| 329 |
+
|
| 330 |
+
def test_model(self):
|
| 331 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 332 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 333 |
+
|
| 334 |
+
def test_model_various_embeddings(self):
|
| 335 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 336 |
+
for type in ["absolute", "relative_key", "relative_key_query"]:
|
| 337 |
+
config_and_inputs[0].position_embedding_type = type
|
| 338 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 339 |
+
|
| 340 |
+
def test_diffllama_sequence_classification_model(self):
|
| 341 |
+
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 342 |
+
config.num_labels = 3
|
| 343 |
+
input_ids = input_dict["input_ids"]
|
| 344 |
+
attention_mask = input_ids.ne(1).to(torch_device)
|
| 345 |
+
sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
|
| 346 |
+
model = DiffLlamaForSequenceClassification(config)
|
| 347 |
+
model.to(torch_device)
|
| 348 |
+
model.eval()
|
| 349 |
+
result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
|
| 350 |
+
self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
|
| 351 |
+
|
| 352 |
+
def test_diffllama_sequence_classification_model_for_single_label(self):
|
| 353 |
+
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 354 |
+
config.num_labels = 3
|
| 355 |
+
config.problem_type = "single_label_classification"
|
| 356 |
+
input_ids = input_dict["input_ids"]
|
| 357 |
+
attention_mask = input_ids.ne(1).to(torch_device)
|
| 358 |
+
sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
|
| 359 |
+
model = DiffLlamaForSequenceClassification(config)
|
| 360 |
+
model.to(torch_device)
|
| 361 |
+
model.eval()
|
| 362 |
+
result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
|
| 363 |
+
self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
|
| 364 |
+
|
| 365 |
+
def test_diffllama_sequence_classification_model_for_multi_label(self):
|
| 366 |
+
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 367 |
+
config.num_labels = 3
|
| 368 |
+
config.problem_type = "multi_label_classification"
|
| 369 |
+
input_ids = input_dict["input_ids"]
|
| 370 |
+
attention_mask = input_ids.ne(1).to(torch_device)
|
| 371 |
+
sequence_labels = ids_tensor(
|
| 372 |
+
[self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
|
| 373 |
+
).to(torch.float)
|
| 374 |
+
model = DiffLlamaForSequenceClassification(config)
|
| 375 |
+
model.to(torch_device)
|
| 376 |
+
model.eval()
|
| 377 |
+
result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
|
| 378 |
+
self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
|
| 379 |
+
|
| 380 |
+
def test_diffllama_token_classification_model(self):
|
| 381 |
+
config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 382 |
+
config.num_labels = 3
|
| 383 |
+
input_ids = input_dict["input_ids"]
|
| 384 |
+
attention_mask = input_ids.ne(1).to(torch_device)
|
| 385 |
+
token_labels = ids_tensor([self.model_tester.batch_size, self.model_tester.seq_length], config.num_labels)
|
| 386 |
+
model = DiffLlamaForTokenClassification(config=config)
|
| 387 |
+
model.to(torch_device)
|
| 388 |
+
model.eval()
|
| 389 |
+
result = model(input_ids, attention_mask=attention_mask, labels=token_labels)
|
| 390 |
+
self.assertEqual(
|
| 391 |
+
result.logits.shape,
|
| 392 |
+
(self.model_tester.batch_size, self.model_tester.seq_length, self.model_tester.num_labels),
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
@unittest.skip(reason="DiffLlama buffers include complex numbers, which breaks this test")
|
| 396 |
+
def test_save_load_fast_init_from_base(self):
|
| 397 |
+
pass
|
| 398 |
+
|
| 399 |
+
@parameterized.expand([("linear",), ("dynamic",), ("yarn",)])
|
| 400 |
+
def test_model_rope_scaling_from_config(self, scaling_type):
|
| 401 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 402 |
+
short_input = ids_tensor([1, 10], config.vocab_size)
|
| 403 |
+
long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
|
| 404 |
+
|
| 405 |
+
set_seed(42) # Fixed seed at init time so the two models get the same random weights
|
| 406 |
+
original_model = DiffLlamaModel(config)
|
| 407 |
+
original_model.to(torch_device)
|
| 408 |
+
original_model.eval()
|
| 409 |
+
original_short_output = original_model(short_input).last_hidden_state
|
| 410 |
+
original_long_output = original_model(long_input).last_hidden_state
|
| 411 |
+
|
| 412 |
+
set_seed(42) # Fixed seed at init time so the two models get the same random weights
|
| 413 |
+
config.rope_scaling = {"type": scaling_type, "factor": 10.0}
|
| 414 |
+
scaled_model = DiffLlamaModel(config)
|
| 415 |
+
scaled_model.to(torch_device)
|
| 416 |
+
scaled_model.eval()
|
| 417 |
+
scaled_short_output = scaled_model(short_input).last_hidden_state
|
| 418 |
+
scaled_long_output = scaled_model(long_input).last_hidden_state
|
| 419 |
+
|
| 420 |
+
# Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
|
| 421 |
+
# maximum sequence length, so the outputs for the short input should match.
|
| 422 |
+
if scaling_type == "dynamic":
|
| 423 |
+
self.assertTrue(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
|
| 424 |
+
else:
|
| 425 |
+
self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
|
| 426 |
+
|
| 427 |
+
# The output should be different for long inputs
|
| 428 |
+
self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
|
| 429 |
+
|
| 430 |
+
def test_model_rope_scaling(self):
|
| 431 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 432 |
+
scaling_factor = 10
|
| 433 |
+
short_input_length = 10
|
| 434 |
+
long_input_length = int(config.max_position_embeddings * 1.5)
|
| 435 |
+
|
| 436 |
+
# Inputs
|
| 437 |
+
x = torch.randn(1, dtype=torch.float32, device=torch_device) # used exlusively to get the dtype and the device
|
| 438 |
+
position_ids_short = torch.arange(short_input_length, dtype=torch.long, device=torch_device)
|
| 439 |
+
position_ids_short = position_ids_short.unsqueeze(0)
|
| 440 |
+
position_ids_long = torch.arange(long_input_length, dtype=torch.long, device=torch_device)
|
| 441 |
+
position_ids_long = position_ids_long.unsqueeze(0)
|
| 442 |
+
|
| 443 |
+
# Sanity check original RoPE
|
| 444 |
+
original_rope = DiffLlamaRotaryEmbedding(config=config).to(torch_device)
|
| 445 |
+
original_cos_short, original_sin_short = original_rope(x, position_ids_short)
|
| 446 |
+
original_cos_long, original_sin_long = original_rope(x, position_ids_long)
|
| 447 |
+
torch.testing.assert_close(original_cos_short, original_cos_long[:, :short_input_length, :])
|
| 448 |
+
torch.testing.assert_close(original_sin_short, original_sin_long[:, :short_input_length, :])
|
| 449 |
+
|
| 450 |
+
# Sanity check linear RoPE scaling
|
| 451 |
+
# New position "x" should match original position with index "x/scaling_factor"
|
| 452 |
+
config.rope_scaling = {"type": "linear", "factor": scaling_factor}
|
| 453 |
+
linear_scaling_rope = DiffLlamaRotaryEmbedding(config=config).to(torch_device)
|
| 454 |
+
linear_cos_short, linear_sin_short = linear_scaling_rope(x, position_ids_short)
|
| 455 |
+
linear_cos_long, linear_sin_long = linear_scaling_rope(x, position_ids_long)
|
| 456 |
+
torch.testing.assert_close(linear_cos_short, linear_cos_long[:, :short_input_length, :])
|
| 457 |
+
torch.testing.assert_close(linear_sin_short, linear_sin_long[:, :short_input_length, :])
|
| 458 |
+
for new_position in range(0, long_input_length, scaling_factor):
|
| 459 |
+
original_position = int(new_position // scaling_factor)
|
| 460 |
+
torch.testing.assert_close(linear_cos_long[:, new_position, :], original_cos_long[:, original_position, :])
|
| 461 |
+
torch.testing.assert_close(linear_sin_long[:, new_position, :], original_sin_long[:, original_position, :])
|
| 462 |
+
|
| 463 |
+
# Sanity check Dynamic NTK RoPE scaling
|
| 464 |
+
# Scaling should only be observed after a long input is fed. We can observe that the frequencies increase
|
| 465 |
+
# with scaling_factor (or that `inv_freq` decreases)
|
| 466 |
+
config.rope_scaling = {"type": "dynamic", "factor": scaling_factor}
|
| 467 |
+
ntk_scaling_rope = DiffLlamaRotaryEmbedding(config=config).to(torch_device)
|
| 468 |
+
ntk_cos_short, ntk_sin_short = ntk_scaling_rope(x, position_ids_short)
|
| 469 |
+
ntk_cos_long, ntk_sin_long = ntk_scaling_rope(x, position_ids_long)
|
| 470 |
+
torch.testing.assert_close(ntk_cos_short, original_cos_short)
|
| 471 |
+
torch.testing.assert_close(ntk_sin_short, original_sin_short)
|
| 472 |
+
with self.assertRaises(AssertionError):
|
| 473 |
+
torch.testing.assert_close(ntk_cos_long, original_cos_long)
|
| 474 |
+
with self.assertRaises(AssertionError):
|
| 475 |
+
torch.testing.assert_close(ntk_sin_long, original_sin_long)
|
| 476 |
+
self.assertTrue((ntk_scaling_rope.inv_freq <= original_rope.inv_freq).all())
|
| 477 |
+
|
| 478 |
+
# Sanity check Yarn RoPE scaling
|
| 479 |
+
# Scaling should be over the entire input
|
| 480 |
+
config.rope_scaling = {"type": "yarn", "factor": scaling_factor}
|
| 481 |
+
yarn_scaling_rope = DiffLlamaRotaryEmbedding(config=config).to(torch_device)
|
| 482 |
+
yarn_cos_short, yarn_sin_short = yarn_scaling_rope(x, position_ids_short)
|
| 483 |
+
yarn_cos_long, yarn_sin_long = yarn_scaling_rope(x, position_ids_long)
|
| 484 |
+
torch.testing.assert_close(yarn_cos_short, yarn_cos_long[:, :short_input_length, :])
|
| 485 |
+
torch.testing.assert_close(yarn_sin_short, yarn_sin_long[:, :short_input_length, :])
|
| 486 |
+
with self.assertRaises(AssertionError):
|
| 487 |
+
torch.testing.assert_close(yarn_cos_short, original_cos_short)
|
| 488 |
+
with self.assertRaises(AssertionError):
|
| 489 |
+
torch.testing.assert_close(yarn_sin_short, original_sin_short)
|
| 490 |
+
with self.assertRaises(AssertionError):
|
| 491 |
+
torch.testing.assert_close(yarn_cos_long, original_cos_long)
|
| 492 |
+
with self.assertRaises(AssertionError):
|
| 493 |
+
torch.testing.assert_close(yarn_sin_long, original_sin_long)
|
| 494 |
+
|
| 495 |
+
def test_model_loading_old_rope_configs(self):
|
| 496 |
+
def _reinitialize_config(base_config, new_kwargs):
|
| 497 |
+
# Reinitialize the config with the new kwargs, forcing the config to go through its __init__ validation
|
| 498 |
+
# steps.
|
| 499 |
+
base_config_dict = base_config.to_dict()
|
| 500 |
+
new_config = DiffLlamaConfig.from_dict(config_dict={**base_config_dict, **new_kwargs})
|
| 501 |
+
return new_config
|
| 502 |
+
|
| 503 |
+
# from untouched config -> ✅
|
| 504 |
+
base_config, model_inputs = self.model_tester.prepare_config_and_inputs_for_common()
|
| 505 |
+
original_model = DiffLlamaForCausalLM(base_config).to(torch_device)
|
| 506 |
+
original_model(**model_inputs)
|
| 507 |
+
|
| 508 |
+
# from a config with the expected rope configuration -> ✅
|
| 509 |
+
config = _reinitialize_config(base_config, {"rope_scaling": {"rope_type": "linear", "factor": 10.0}})
|
| 510 |
+
original_model = DiffLlamaForCausalLM(config).to(torch_device)
|
| 511 |
+
original_model(**model_inputs)
|
| 512 |
+
|
| 513 |
+
# from a config with the old rope configuration ('type' instead of 'rope_type') -> ✅ we gracefully handle BC
|
| 514 |
+
config = _reinitialize_config(base_config, {"rope_scaling": {"type": "linear", "factor": 10.0}})
|
| 515 |
+
original_model = DiffLlamaForCausalLM(config).to(torch_device)
|
| 516 |
+
original_model(**model_inputs)
|
| 517 |
+
|
| 518 |
+
# from a config with both 'type' and 'rope_type' -> ✅ they can coexist (and both are present in the config)
|
| 519 |
+
config = _reinitialize_config(
|
| 520 |
+
base_config, {"rope_scaling": {"type": "linear", "rope_type": "linear", "factor": 10.0}}
|
| 521 |
+
)
|
| 522 |
+
self.assertTrue(config.rope_scaling["type"] == "linear")
|
| 523 |
+
self.assertTrue(config.rope_scaling["rope_type"] == "linear")
|
| 524 |
+
original_model = DiffLlamaForCausalLM(config).to(torch_device)
|
| 525 |
+
original_model(**model_inputs)
|
| 526 |
+
|
| 527 |
+
# from a config with parameters in a bad range ('factor' should be >= 1.0) -> ⚠️ throws a warning
|
| 528 |
+
with self.assertLogs("transformers.modeling_rope_utils", level="WARNING") as logs:
|
| 529 |
+
config = _reinitialize_config(base_config, {"rope_scaling": {"rope_type": "linear", "factor": -999.0}})
|
| 530 |
+
original_model = DiffLlamaForCausalLM(config).to(torch_device)
|
| 531 |
+
original_model(**model_inputs)
|
| 532 |
+
self.assertEqual(len(logs.output), 1)
|
| 533 |
+
self.assertIn("factor field", logs.output[0])
|
| 534 |
+
|
| 535 |
+
# from a config with unknown parameters ('foo' isn't a rope option) -> ⚠️ throws a warning
|
| 536 |
+
with self.assertLogs("transformers.modeling_rope_utils", level="WARNING") as logs:
|
| 537 |
+
config = _reinitialize_config(
|
| 538 |
+
base_config, {"rope_scaling": {"rope_type": "linear", "factor": 10.0, "foo": "bar"}}
|
| 539 |
+
)
|
| 540 |
+
original_model = DiffLlamaForCausalLM(config).to(torch_device)
|
| 541 |
+
original_model(**model_inputs)
|
| 542 |
+
self.assertEqual(len(logs.output), 1)
|
| 543 |
+
self.assertIn("Unrecognized keys", logs.output[0])
|
| 544 |
+
|
| 545 |
+
# from a config with specific rope type but missing one of its mandatory parameters -> ❌ throws exception
|
| 546 |
+
with self.assertRaises(KeyError):
|
| 547 |
+
config = _reinitialize_config(base_config, {"rope_scaling": {"rope_type": "linear"}}) # missing "factor"
|
| 548 |
+
|
| 549 |
+
@require_flash_attn
|
| 550 |
+
@require_torch_gpu
|
| 551 |
+
@require_bitsandbytes
|
| 552 |
+
@pytest.mark.flash_attn_test
|
| 553 |
+
@require_read_token
|
| 554 |
+
@slow
|
| 555 |
+
def test_flash_attn_2_generate_padding_right(self):
|
| 556 |
+
"""
|
| 557 |
+
Overwritting the common test as the test is flaky on tiny models
|
| 558 |
+
"""
|
| 559 |
+
model = DiffLlamaForCausalLM.from_pretrained(
|
| 560 |
+
"kajuma/DiffLlama-0.3B-handcut",
|
| 561 |
+
load_in_4bit=True,
|
| 562 |
+
device_map={"": 0},
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
tokenizer = AutoTokenizer.from_pretrained("kajuma/DiffLlama-0.3B-handcut")
|
| 566 |
+
|
| 567 |
+
texts = ["hi", "Hello this is a very long sentence"]
|
| 568 |
+
|
| 569 |
+
tokenizer.padding_side = "right"
|
| 570 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 571 |
+
|
| 572 |
+
inputs = tokenizer(texts, return_tensors="pt", padding=True).to(0)
|
| 573 |
+
|
| 574 |
+
output_native = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
| 575 |
+
output_native = tokenizer.batch_decode(output_native)
|
| 576 |
+
|
| 577 |
+
model = DiffLlamaForCausalLM.from_pretrained(
|
| 578 |
+
"kajuma/DiffLlama-0.3B-handcut",
|
| 579 |
+
load_in_4bit=True,
|
| 580 |
+
device_map={"": 0},
|
| 581 |
+
attn_implementation="flash_attention_2",
|
| 582 |
+
)
|
| 583 |
+
|
| 584 |
+
output_fa_2 = model.generate(**inputs, max_new_tokens=20, do_sample=False)
|
| 585 |
+
output_fa_2 = tokenizer.batch_decode(output_fa_2)
|
| 586 |
+
|
| 587 |
+
self.assertListEqual(output_native, output_fa_2)
|
| 588 |
+
|
| 589 |
+
@require_flash_attn
|
| 590 |
+
@require_torch_gpu
|
| 591 |
+
@slow
|
| 592 |
+
@pytest.mark.flash_attn_test
|
| 593 |
+
def test_use_flash_attention_2_true(self):
|
| 594 |
+
"""
|
| 595 |
+
NOTE: this is the only test testing that the legacy `use_flash_attention=2` argument still works as intended.
|
| 596 |
+
"""
|
| 597 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 598 |
+
for model_class in self.all_model_classes:
|
| 599 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 600 |
+
model = model_class(config)
|
| 601 |
+
model.save_pretrained(tmp_dir)
|
| 602 |
+
|
| 603 |
+
new_model = DiffLlamaForCausalLM.from_pretrained(
|
| 604 |
+
tmp_dir, use_flash_attention_2=True, torch_dtype=torch.float16
|
| 605 |
+
).to("cuda")
|
| 606 |
+
|
| 607 |
+
self.assertTrue(new_model.config._attn_implementation == "flash_attention_2")
|
| 608 |
+
|
| 609 |
+
has_flash = False
|
| 610 |
+
for name, submodule in new_model.named_modules():
|
| 611 |
+
if "FlashAttention" in submodule.__class__.__name__:
|
| 612 |
+
has_flash = True
|
| 613 |
+
break
|
| 614 |
+
if not has_flash:
|
| 615 |
+
raise ValueError("The flash model should have flash attention layers")
|
| 616 |
+
|
| 617 |
+
@require_torch_sdpa
|
| 618 |
+
@slow
|
| 619 |
+
def test_eager_matches_sdpa_generate(self):
|
| 620 |
+
"""
|
| 621 |
+
Overwritting the common test as the test is flaky on tiny models
|
| 622 |
+
"""
|
| 623 |
+
max_new_tokens = 30
|
| 624 |
+
|
| 625 |
+
tokenizer = AutoTokenizer.from_pretrained("kajuma/DiffLlama-0.3B-handcut")
|
| 626 |
+
|
| 627 |
+
model_sdpa = DiffLlamaForCausalLM.from_pretrained(
|
| 628 |
+
"kajuma/DiffLlama-0.3B-handcut",
|
| 629 |
+
torch_dtype=torch.float16,
|
| 630 |
+
low_cpu_mem_usage=True,
|
| 631 |
+
).to(torch_device)
|
| 632 |
+
|
| 633 |
+
self.assertTrue(model_sdpa.config._attn_implementation == "sdpa")
|
| 634 |
+
|
| 635 |
+
model_eager = DiffLlamaForCausalLM.from_pretrained(
|
| 636 |
+
"kajuma/DiffLlama-0.3B-handcut",
|
| 637 |
+
torch_dtype=torch.float16,
|
| 638 |
+
low_cpu_mem_usage=True,
|
| 639 |
+
attn_implementation="eager",
|
| 640 |
+
).to(torch_device)
|
| 641 |
+
|
| 642 |
+
self.assertTrue(model_eager.config._attn_implementation == "eager")
|
| 643 |
+
|
| 644 |
+
for name, submodule in model_eager.named_modules():
|
| 645 |
+
if "SdpaAttention" in submodule.__class__.__name__:
|
| 646 |
+
raise ValueError("The eager model should not have SDPA attention layers")
|
| 647 |
+
|
| 648 |
+
has_sdpa = False
|
| 649 |
+
for name, submodule in model_sdpa.named_modules():
|
| 650 |
+
if "SdpaAttention" in submodule.__class__.__name__:
|
| 651 |
+
has_sdpa = True
|
| 652 |
+
break
|
| 653 |
+
if not has_sdpa:
|
| 654 |
+
raise ValueError("The SDPA model should have SDPA attention layers")
|
| 655 |
+
|
| 656 |
+
texts = [
|
| 657 |
+
"hi here's a longer context, getting longer and",
|
| 658 |
+
"Hello this is a very long sentence my friend, very long for real",
|
| 659 |
+
"Today I am in Paris and",
|
| 660 |
+
]
|
| 661 |
+
|
| 662 |
+
for padding_side in ["left", "right"]:
|
| 663 |
+
tokenizer.padding_side = padding_side
|
| 664 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 665 |
+
|
| 666 |
+
inputs = tokenizer(texts, return_tensors="pt", padding=True).to(torch_device)
|
| 667 |
+
|
| 668 |
+
res_eager = model_eager.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
|
| 669 |
+
res_sdpa = model_sdpa.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
|
| 670 |
+
|
| 671 |
+
with self.subTest(f"{padding_side}"):
|
| 672 |
+
torch.testing.assert_close(
|
| 673 |
+
res_eager,
|
| 674 |
+
res_sdpa,
|
| 675 |
+
msg=f"\n{tokenizer.batch_decode(res_eager)} \nvs\n{tokenizer.batch_decode(res_sdpa)}",
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@require_torch_accelerator
|
| 680 |
+
class DiffLlamaIntegrationTest(unittest.TestCase):
|
| 681 |
+
# This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
|
| 682 |
+
# Depending on the hardware we get different logits / generations
|
| 683 |
+
cuda_compute_capability_major_version = None
|
| 684 |
+
|
| 685 |
+
@classmethod
|
| 686 |
+
def setUpClass(cls):
|
| 687 |
+
if is_torch_available() and torch.cuda.is_available():
|
| 688 |
+
# 8 is for A100 / A10 and 7 for T4
|
| 689 |
+
cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
|
| 690 |
+
|
| 691 |
+
@slow
|
| 692 |
+
@require_torch_accelerator
|
| 693 |
+
@require_read_token
|
| 694 |
+
def test_compile_static_cache(self):
|
| 695 |
+
# `torch==2.2` will throw an error on this test (as in other compilation tests), but torch==2.1.2 and torch>2.2
|
| 696 |
+
# work as intended. See https://github.com/pytorch/pytorch/issues/121943
|
| 697 |
+
if version.parse(torch.__version__) < version.parse("2.3.0"):
|
| 698 |
+
self.skipTest(reason="This test requires torch >= 2.3 to run.")
|
| 699 |
+
|
| 700 |
+
NUM_TOKENS_TO_GENERATE = 40
|
| 701 |
+
# Note on `EXPECTED_TEXT_COMPLETION`'s diff: the current value matches the original test if the original test
|
| 702 |
+
# was changed to have a cache of 53 tokens (as opposed to 4096), on Ampere GPUs.
|
| 703 |
+
EXPECTED_TEXT_COMPLETION = [
|
| 704 |
+
"Simply put, the theory of relativity states that 1) the speed of light is constant in all inertial "
|
| 705 |
+
"reference frames, and 2) the laws of physics are the same for all inertial reference frames.\nThe "
|
| 706 |
+
"theory of relativ",
|
| 707 |
+
"My favorite all time favorite condiment is ketchup. I love it on everything. I love it on my eggs, "
|
| 708 |
+
"my fries, my chicken, my burgers, my hot dogs, my sandwiches, my salads, my p",
|
| 709 |
+
]
|
| 710 |
+
|
| 711 |
+
prompts = [
|
| 712 |
+
"Simply put, the theory of relativity states that ",
|
| 713 |
+
"My favorite all time favorite condiment is ketchup.",
|
| 714 |
+
]
|
| 715 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 716 |
+
"kajuma/DiffLlama-0.3B-handcut", pad_token="</s>", padding_side="right"
|
| 717 |
+
)
|
| 718 |
+
model = DiffLlamaForCausalLM.from_pretrained(
|
| 719 |
+
"kajuma/DiffLlama-0.3B-handcut", device_map=torch_device, torch_dtype=torch.float16
|
| 720 |
+
)
|
| 721 |
+
inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
|
| 722 |
+
|
| 723 |
+
# Dynamic Cache
|
| 724 |
+
generated_ids = model.generate(**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False)
|
| 725 |
+
dynamic_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 726 |
+
self.assertEqual(EXPECTED_TEXT_COMPLETION, dynamic_text)
|
| 727 |
+
|
| 728 |
+
# Static Cache
|
| 729 |
+
generated_ids = model.generate(
|
| 730 |
+
**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static"
|
| 731 |
+
)
|
| 732 |
+
static_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 733 |
+
self.assertEqual(EXPECTED_TEXT_COMPLETION, static_text)
|
| 734 |
+
|
| 735 |
+
# Static Cache + compile
|
| 736 |
+
model._cache = None # clear cache object, initialized when we pass `cache_implementation="static"`
|
| 737 |
+
model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
|
| 738 |
+
generated_ids = model.generate(
|
| 739 |
+
**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static"
|
| 740 |
+
)
|
| 741 |
+
static_compiled_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
|
| 742 |
+
self.assertEqual(EXPECTED_TEXT_COMPLETION, static_compiled_text)
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
@slow
|
| 746 |
+
@require_torch_accelerator
|
| 747 |
+
class Mask4DTestHard(unittest.TestCase):
|
| 748 |
+
def tearDown(self):
|
| 749 |
+
gc.collect()
|
| 750 |
+
backend_empty_cache(torch_device)
|
| 751 |
+
|
| 752 |
+
def setUp(self):
|
| 753 |
+
model_name = "kajuma/DiffLlama-0.3B-handcut"
|
| 754 |
+
self.model_dtype = torch.float32
|
| 755 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 756 |
+
self.model = DiffLlamaForCausalLM.from_pretrained(model_name, torch_dtype=self.model_dtype).to(torch_device)
|
| 757 |
+
|
| 758 |
+
def get_test_data(self):
|
| 759 |
+
template = "my favorite {}"
|
| 760 |
+
items = ("pet is a", "artist plays a", "name is L") # same number of tokens in each item
|
| 761 |
+
|
| 762 |
+
batch_separate = [template.format(x) for x in items] # 3 separate lines
|
| 763 |
+
batch_shared_prefix = template.format(" ".join(items)) # 1 line with options concatenated
|
| 764 |
+
|
| 765 |
+
input_ids = self.tokenizer(batch_separate, return_tensors="pt").input_ids.to(torch_device)
|
| 766 |
+
input_ids_shared_prefix = self.tokenizer(batch_shared_prefix, return_tensors="pt").input_ids.to(torch_device)
|
| 767 |
+
|
| 768 |
+
mask_shared_prefix = torch.tensor(
|
| 769 |
+
[
|
| 770 |
+
[
|
| 771 |
+
[
|
| 772 |
+
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 773 |
+
[1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 774 |
+
[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 775 |
+
[1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
|
| 776 |
+
[1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0],
|
| 777 |
+
[1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0],
|
| 778 |
+
[1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0],
|
| 779 |
+
[1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0],
|
| 780 |
+
[1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0],
|
| 781 |
+
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0],
|
| 782 |
+
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0],
|
| 783 |
+
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1],
|
| 784 |
+
]
|
| 785 |
+
]
|
| 786 |
+
],
|
| 787 |
+
device=torch_device,
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
position_ids = torch.arange(input_ids.shape[1]).tile(input_ids.shape[0], 1).to(torch_device)
|
| 791 |
+
|
| 792 |
+
# building custom positions ids based on custom mask
|
| 793 |
+
position_ids_shared_prefix = (mask_shared_prefix.sum(dim=-1) - 1).reshape(1, -1)
|
| 794 |
+
# effectively: position_ids_shared_prefix = torch.tensor([[0, 1, 2, 3, 4, 5, 3, 4, 5, 3, 4, 5]]).to(device)
|
| 795 |
+
|
| 796 |
+
# inverting the mask
|
| 797 |
+
min_dtype = torch.finfo(self.model_dtype).min
|
| 798 |
+
mask_shared_prefix = (mask_shared_prefix.eq(0.0)).to(dtype=self.model_dtype) * min_dtype
|
| 799 |
+
|
| 800 |
+
return input_ids, position_ids, input_ids_shared_prefix, mask_shared_prefix, position_ids_shared_prefix
|
| 801 |
+
|
| 802 |
+
def test_stacked_causal_mask(self):
|
| 803 |
+
(
|
| 804 |
+
input_ids,
|
| 805 |
+
position_ids,
|
| 806 |
+
input_ids_shared_prefix,
|
| 807 |
+
mask_shared_prefix,
|
| 808 |
+
position_ids_shared_prefix,
|
| 809 |
+
) = self.get_test_data()
|
| 810 |
+
|
| 811 |
+
# regular batch
|
| 812 |
+
logits = self.model.forward(input_ids, position_ids=position_ids).logits
|
| 813 |
+
logits_last = logits[:, -1, :] # last tokens in each batch line
|
| 814 |
+
decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)]
|
| 815 |
+
|
| 816 |
+
# single forward run with 4D custom mask
|
| 817 |
+
logits_shared_prefix = self.model.forward(
|
| 818 |
+
input_ids_shared_prefix, attention_mask=mask_shared_prefix, position_ids=position_ids_shared_prefix
|
| 819 |
+
).logits
|
| 820 |
+
logits_shared_prefix_last = logits_shared_prefix[
|
| 821 |
+
0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], :
|
| 822 |
+
] # last three tokens
|
| 823 |
+
decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)]
|
| 824 |
+
|
| 825 |
+
self.assertEqual(decoded, decoded_shared_prefix)
|
| 826 |
+
|
| 827 |
+
def test_partial_stacked_causal_mask(self):
|
| 828 |
+
# Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks
|
| 829 |
+
|
| 830 |
+
(
|
| 831 |
+
input_ids,
|
| 832 |
+
position_ids,
|
| 833 |
+
input_ids_shared_prefix,
|
| 834 |
+
mask_shared_prefix,
|
| 835 |
+
position_ids_shared_prefix,
|
| 836 |
+
) = self.get_test_data()
|
| 837 |
+
|
| 838 |
+
# regular batch
|
| 839 |
+
logits = self.model.forward(input_ids, position_ids=position_ids).logits
|
| 840 |
+
logits_last = logits[:, -1, :] # last tokens in each batch line
|
| 841 |
+
decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)]
|
| 842 |
+
|
| 843 |
+
# 2 forward runs with custom 4D masks
|
| 844 |
+
part_a = 3 # split point
|
| 845 |
+
|
| 846 |
+
input_1a = input_ids_shared_prefix[:, :part_a]
|
| 847 |
+
position_ids_1a = position_ids_shared_prefix[:, :part_a]
|
| 848 |
+
mask_1a = mask_shared_prefix[:, :, :part_a, :part_a]
|
| 849 |
+
|
| 850 |
+
outs_1a = self.model.forward(input_1a, attention_mask=mask_1a, position_ids=position_ids_1a)
|
| 851 |
+
past_key_values_a = outs_1a["past_key_values"]
|
| 852 |
+
|
| 853 |
+
# Case 1: we pass a 4D attention mask regarding the current sequence length (i.e. [..., seq_len, full_len])
|
| 854 |
+
input_1b = input_ids_shared_prefix[:, part_a:]
|
| 855 |
+
position_ids_1b = position_ids_shared_prefix[:, part_a:]
|
| 856 |
+
mask_1b = mask_shared_prefix[:, :, part_a:, :]
|
| 857 |
+
outs_1b = self.model.forward(
|
| 858 |
+
input_1b,
|
| 859 |
+
attention_mask=mask_1b,
|
| 860 |
+
position_ids=position_ids_1b,
|
| 861 |
+
past_key_values=past_key_values_a,
|
| 862 |
+
)
|
| 863 |
+
decoded_1b = [
|
| 864 |
+
self.tokenizer.decode(t)
|
| 865 |
+
for t in outs_1b.logits.argmax(-1)[
|
| 866 |
+
0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a
|
| 867 |
+
]
|
| 868 |
+
]
|
| 869 |
+
self.assertEqual(decoded, decoded_1b)
|
| 870 |
+
|
| 871 |
+
def test_stacked_causal_mask_static_cache(self):
|
| 872 |
+
"""same as above but with StaticCache"""
|
| 873 |
+
(
|
| 874 |
+
input_ids,
|
| 875 |
+
position_ids,
|
| 876 |
+
input_ids_shared_prefix,
|
| 877 |
+
mask_shared_prefix,
|
| 878 |
+
position_ids_shared_prefix,
|
| 879 |
+
) = self.get_test_data()
|
| 880 |
+
|
| 881 |
+
# regular batch
|
| 882 |
+
logits = self.model.forward(input_ids, position_ids=position_ids).logits
|
| 883 |
+
logits_last = logits[:, -1, :] # last tokens in each batch line
|
| 884 |
+
decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)]
|
| 885 |
+
|
| 886 |
+
# upgrade the model with StaticCache
|
| 887 |
+
max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1]
|
| 888 |
+
past_key_values = StaticCache(
|
| 889 |
+
config=self.model.config,
|
| 890 |
+
batch_size=1,
|
| 891 |
+
max_cache_len=max_cache_len,
|
| 892 |
+
device=torch_device,
|
| 893 |
+
dtype=self.model.dtype,
|
| 894 |
+
)
|
| 895 |
+
|
| 896 |
+
padded_attention_mask = torch.nn.functional.pad(
|
| 897 |
+
input=mask_shared_prefix,
|
| 898 |
+
pad=(0, max_cache_len - mask_shared_prefix.shape[-1]),
|
| 899 |
+
mode="constant",
|
| 900 |
+
value=torch.finfo(self.model_dtype).min,
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
# single forward run with 4D custom mask
|
| 904 |
+
logits_shared_prefix = self.model.forward(
|
| 905 |
+
input_ids_shared_prefix,
|
| 906 |
+
attention_mask=padded_attention_mask,
|
| 907 |
+
position_ids=position_ids_shared_prefix,
|
| 908 |
+
cache_position=torch.arange(input_ids_shared_prefix.shape[-1], device=torch_device),
|
| 909 |
+
past_key_values=past_key_values,
|
| 910 |
+
).logits
|
| 911 |
+
logits_shared_prefix_last = logits_shared_prefix[
|
| 912 |
+
0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1], :
|
| 913 |
+
] # last three tokens
|
| 914 |
+
decoded_shared_prefix = [self.tokenizer.decode(t) for t in logits_shared_prefix_last.argmax(dim=-1)]
|
| 915 |
+
|
| 916 |
+
self.assertEqual(decoded, decoded_shared_prefix)
|
| 917 |
+
|
| 918 |
+
def test_partial_stacked_causal_mask_static_cache(self):
|
| 919 |
+
# Same as the test above, but the input is passed in two groups. It tests that we can pass partial 4D attention masks
|
| 920 |
+
# we pass a 4D attention mask shaped [..., seq_len, full_static_cache_len])
|
| 921 |
+
(
|
| 922 |
+
input_ids,
|
| 923 |
+
position_ids,
|
| 924 |
+
input_ids_shared_prefix,
|
| 925 |
+
mask_shared_prefix,
|
| 926 |
+
position_ids_shared_prefix,
|
| 927 |
+
) = self.get_test_data()
|
| 928 |
+
|
| 929 |
+
# regular batch
|
| 930 |
+
logits = self.model.forward(input_ids, position_ids=position_ids).logits
|
| 931 |
+
logits_last = logits[:, -1, :] # last tokens in each batch line
|
| 932 |
+
decoded = [self.tokenizer.decode(t) for t in logits_last.argmax(dim=-1)]
|
| 933 |
+
|
| 934 |
+
# upgrade the model with StaticCache
|
| 935 |
+
max_cache_len = 16 # note that max_cache_len is greater than the attention_mask.shape[-1]
|
| 936 |
+
past_key_values = StaticCache(
|
| 937 |
+
config=self.model.config,
|
| 938 |
+
batch_size=1,
|
| 939 |
+
max_cache_len=max_cache_len,
|
| 940 |
+
device=torch_device,
|
| 941 |
+
dtype=self.model.dtype,
|
| 942 |
+
)
|
| 943 |
+
|
| 944 |
+
# forward run for the first part of input
|
| 945 |
+
part_a = 3 # split point
|
| 946 |
+
|
| 947 |
+
input_1a = input_ids_shared_prefix[:, :part_a]
|
| 948 |
+
position_ids_1a = position_ids_shared_prefix[:, :part_a]
|
| 949 |
+
mask_1a = mask_shared_prefix[:, :, :part_a, :part_a]
|
| 950 |
+
|
| 951 |
+
padded_mask_1a = torch.nn.functional.pad(
|
| 952 |
+
input=mask_1a,
|
| 953 |
+
pad=(0, max_cache_len - mask_1a.shape[-1]),
|
| 954 |
+
mode="constant",
|
| 955 |
+
value=torch.finfo(self.model_dtype).min,
|
| 956 |
+
)
|
| 957 |
+
|
| 958 |
+
_ = self.model.forward(
|
| 959 |
+
input_1a,
|
| 960 |
+
attention_mask=padded_mask_1a,
|
| 961 |
+
position_ids=position_ids_1a,
|
| 962 |
+
cache_position=torch.arange(part_a, device=torch_device),
|
| 963 |
+
past_key_values=past_key_values,
|
| 964 |
+
)
|
| 965 |
+
|
| 966 |
+
# forward run for the second part of input
|
| 967 |
+
input_1b = input_ids_shared_prefix[:, part_a:]
|
| 968 |
+
position_ids_1b = position_ids_shared_prefix[:, part_a:]
|
| 969 |
+
mask_1b = mask_shared_prefix[:, :, part_a:, :]
|
| 970 |
+
|
| 971 |
+
padded_mask_1b = torch.nn.functional.pad(
|
| 972 |
+
input=mask_1b, pad=(0, max_cache_len - mask_1b.shape[-1]), mode="constant", value=0
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
outs_1b = self.model.forward(
|
| 976 |
+
input_1b,
|
| 977 |
+
attention_mask=padded_mask_1b,
|
| 978 |
+
position_ids=position_ids_1b,
|
| 979 |
+
cache_position=torch.arange(
|
| 980 |
+
part_a,
|
| 981 |
+
input_ids_shared_prefix.shape[-1],
|
| 982 |
+
device=torch_device,
|
| 983 |
+
),
|
| 984 |
+
past_key_values=past_key_values,
|
| 985 |
+
)
|
| 986 |
+
decoded_1b = [
|
| 987 |
+
self.tokenizer.decode(t)
|
| 988 |
+
for t in outs_1b.logits.argmax(-1)[
|
| 989 |
+
0, torch.where(position_ids_shared_prefix == position_ids_shared_prefix.max())[1] - part_a
|
| 990 |
+
]
|
| 991 |
+
]
|
| 992 |
+
self.assertEqual(decoded, decoded_1b)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinat/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinat/test_modeling_dinat.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Dinat model."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import DinatConfig
|
| 21 |
+
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
|
| 22 |
+
from transformers.utils import cached_property, is_torch_available, is_vision_available
|
| 23 |
+
|
| 24 |
+
from ...test_backbone_common import BackboneTesterMixin
|
| 25 |
+
from ...test_configuration_common import ConfigTester
|
| 26 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
|
| 27 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_available():
|
| 31 |
+
import torch
|
| 32 |
+
from torch import nn
|
| 33 |
+
|
| 34 |
+
from transformers import DinatBackbone, DinatForImageClassification, DinatModel
|
| 35 |
+
|
| 36 |
+
if is_vision_available():
|
| 37 |
+
from PIL import Image
|
| 38 |
+
|
| 39 |
+
from transformers import AutoImageProcessor
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class DinatModelTester:
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
parent,
|
| 46 |
+
batch_size=13,
|
| 47 |
+
image_size=64,
|
| 48 |
+
patch_size=4,
|
| 49 |
+
num_channels=3,
|
| 50 |
+
embed_dim=16,
|
| 51 |
+
depths=[1, 2, 1],
|
| 52 |
+
num_heads=[2, 4, 8],
|
| 53 |
+
kernel_size=3,
|
| 54 |
+
dilations=[[3], [1, 2], [1]],
|
| 55 |
+
mlp_ratio=2.0,
|
| 56 |
+
qkv_bias=True,
|
| 57 |
+
hidden_dropout_prob=0.0,
|
| 58 |
+
attention_probs_dropout_prob=0.0,
|
| 59 |
+
drop_path_rate=0.1,
|
| 60 |
+
hidden_act="gelu",
|
| 61 |
+
patch_norm=True,
|
| 62 |
+
initializer_range=0.02,
|
| 63 |
+
layer_norm_eps=1e-5,
|
| 64 |
+
is_training=True,
|
| 65 |
+
scope=None,
|
| 66 |
+
use_labels=True,
|
| 67 |
+
num_labels=10,
|
| 68 |
+
out_features=["stage1", "stage2"],
|
| 69 |
+
out_indices=[1, 2],
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = batch_size
|
| 73 |
+
self.image_size = image_size
|
| 74 |
+
self.patch_size = patch_size
|
| 75 |
+
self.num_channels = num_channels
|
| 76 |
+
self.embed_dim = embed_dim
|
| 77 |
+
self.depths = depths
|
| 78 |
+
self.num_heads = num_heads
|
| 79 |
+
self.kernel_size = kernel_size
|
| 80 |
+
self.dilations = dilations
|
| 81 |
+
self.mlp_ratio = mlp_ratio
|
| 82 |
+
self.qkv_bias = qkv_bias
|
| 83 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 84 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 85 |
+
self.drop_path_rate = drop_path_rate
|
| 86 |
+
self.hidden_act = hidden_act
|
| 87 |
+
self.patch_norm = patch_norm
|
| 88 |
+
self.layer_norm_eps = layer_norm_eps
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.is_training = is_training
|
| 91 |
+
self.scope = scope
|
| 92 |
+
self.use_labels = use_labels
|
| 93 |
+
self.num_labels = num_labels
|
| 94 |
+
self.out_features = out_features
|
| 95 |
+
self.out_indices = out_indices
|
| 96 |
+
|
| 97 |
+
def prepare_config_and_inputs(self):
|
| 98 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 99 |
+
|
| 100 |
+
labels = None
|
| 101 |
+
if self.use_labels:
|
| 102 |
+
labels = ids_tensor([self.batch_size], self.num_labels)
|
| 103 |
+
|
| 104 |
+
config = self.get_config()
|
| 105 |
+
|
| 106 |
+
return config, pixel_values, labels
|
| 107 |
+
|
| 108 |
+
def get_config(self):
|
| 109 |
+
return DinatConfig(
|
| 110 |
+
num_labels=self.num_labels,
|
| 111 |
+
image_size=self.image_size,
|
| 112 |
+
patch_size=self.patch_size,
|
| 113 |
+
num_channels=self.num_channels,
|
| 114 |
+
embed_dim=self.embed_dim,
|
| 115 |
+
depths=self.depths,
|
| 116 |
+
num_heads=self.num_heads,
|
| 117 |
+
kernel_size=self.kernel_size,
|
| 118 |
+
dilations=self.dilations,
|
| 119 |
+
mlp_ratio=self.mlp_ratio,
|
| 120 |
+
qkv_bias=self.qkv_bias,
|
| 121 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 122 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 123 |
+
drop_path_rate=self.drop_path_rate,
|
| 124 |
+
hidden_act=self.hidden_act,
|
| 125 |
+
patch_norm=self.patch_norm,
|
| 126 |
+
layer_norm_eps=self.layer_norm_eps,
|
| 127 |
+
initializer_range=self.initializer_range,
|
| 128 |
+
out_features=self.out_features,
|
| 129 |
+
out_indices=self.out_indices,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 133 |
+
model = DinatModel(config=config)
|
| 134 |
+
model.to(torch_device)
|
| 135 |
+
model.eval()
|
| 136 |
+
result = model(pixel_values)
|
| 137 |
+
|
| 138 |
+
expected_height = expected_width = (config.image_size // config.patch_size) // (2 ** (len(config.depths) - 1))
|
| 139 |
+
expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1))
|
| 140 |
+
|
| 141 |
+
self.parent.assertEqual(
|
| 142 |
+
result.last_hidden_state.shape, (self.batch_size, expected_height, expected_width, expected_dim)
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 146 |
+
model = DinatForImageClassification(config)
|
| 147 |
+
model.to(torch_device)
|
| 148 |
+
model.eval()
|
| 149 |
+
result = model(pixel_values, labels=labels)
|
| 150 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 151 |
+
|
| 152 |
+
# test greyscale images
|
| 153 |
+
config.num_channels = 1
|
| 154 |
+
model = DinatForImageClassification(config)
|
| 155 |
+
model.to(torch_device)
|
| 156 |
+
model.eval()
|
| 157 |
+
|
| 158 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 159 |
+
result = model(pixel_values)
|
| 160 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 161 |
+
|
| 162 |
+
def create_and_check_backbone(self, config, pixel_values, labels):
|
| 163 |
+
model = DinatBackbone(config=config)
|
| 164 |
+
model.to(torch_device)
|
| 165 |
+
model.eval()
|
| 166 |
+
result = model(pixel_values)
|
| 167 |
+
|
| 168 |
+
# verify hidden states
|
| 169 |
+
self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
|
| 170 |
+
self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], 16, 16])
|
| 171 |
+
|
| 172 |
+
# verify channels
|
| 173 |
+
self.parent.assertEqual(len(model.channels), len(config.out_features))
|
| 174 |
+
|
| 175 |
+
# verify backbone works with out_features=None
|
| 176 |
+
config.out_features = None
|
| 177 |
+
model = DinatBackbone(config=config)
|
| 178 |
+
model.to(torch_device)
|
| 179 |
+
model.eval()
|
| 180 |
+
result = model(pixel_values)
|
| 181 |
+
|
| 182 |
+
# verify feature maps
|
| 183 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 184 |
+
self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, model.channels[-1], 4, 4])
|
| 185 |
+
|
| 186 |
+
# verify channels
|
| 187 |
+
self.parent.assertEqual(len(model.channels), 1)
|
| 188 |
+
|
| 189 |
+
def prepare_config_and_inputs_for_common(self):
|
| 190 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 191 |
+
config, pixel_values, labels = config_and_inputs
|
| 192 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 193 |
+
return config, inputs_dict
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
@require_natten
|
| 197 |
+
@require_torch
|
| 198 |
+
class DinatModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 199 |
+
all_model_classes = (
|
| 200 |
+
(
|
| 201 |
+
DinatModel,
|
| 202 |
+
DinatForImageClassification,
|
| 203 |
+
DinatBackbone,
|
| 204 |
+
)
|
| 205 |
+
if is_torch_available()
|
| 206 |
+
else ()
|
| 207 |
+
)
|
| 208 |
+
pipeline_model_mapping = (
|
| 209 |
+
{"image-feature-extraction": DinatModel, "image-classification": DinatForImageClassification}
|
| 210 |
+
if is_torch_available()
|
| 211 |
+
else {}
|
| 212 |
+
)
|
| 213 |
+
fx_compatible = False
|
| 214 |
+
|
| 215 |
+
test_torchscript = False
|
| 216 |
+
test_pruning = False
|
| 217 |
+
test_resize_embeddings = False
|
| 218 |
+
test_head_masking = False
|
| 219 |
+
|
| 220 |
+
def setUp(self):
|
| 221 |
+
self.model_tester = DinatModelTester(self)
|
| 222 |
+
self.config_tester = ConfigTester(
|
| 223 |
+
self, config_class=DinatConfig, embed_dim=37, common_properties=["patch_size", "num_channels"]
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
def test_config(self):
|
| 227 |
+
self.config_tester.run_common_tests()
|
| 228 |
+
|
| 229 |
+
def test_model(self):
|
| 230 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 231 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 232 |
+
|
| 233 |
+
def test_for_image_classification(self):
|
| 234 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 235 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 236 |
+
|
| 237 |
+
def test_backbone(self):
|
| 238 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 239 |
+
self.model_tester.create_and_check_backbone(*config_and_inputs)
|
| 240 |
+
|
| 241 |
+
@unittest.skip(reason="Dinat does not use inputs_embeds")
|
| 242 |
+
def test_inputs_embeds(self):
|
| 243 |
+
pass
|
| 244 |
+
|
| 245 |
+
@unittest.skip(reason="Dinat does not use feedforward chunking")
|
| 246 |
+
def test_feed_forward_chunking(self):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
def test_model_get_set_embeddings(self):
|
| 250 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 251 |
+
|
| 252 |
+
for model_class in self.all_model_classes:
|
| 253 |
+
model = model_class(config)
|
| 254 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 255 |
+
x = model.get_output_embeddings()
|
| 256 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 257 |
+
|
| 258 |
+
def test_attention_outputs(self):
|
| 259 |
+
self.skipTest(reason="Dinat's attention operation is handled entirely by NATTEN.")
|
| 260 |
+
|
| 261 |
+
def check_hidden_states_output(self, inputs_dict, config, model_class, image_size):
|
| 262 |
+
model = model_class(config)
|
| 263 |
+
model.to(torch_device)
|
| 264 |
+
model.eval()
|
| 265 |
+
|
| 266 |
+
with torch.no_grad():
|
| 267 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 268 |
+
|
| 269 |
+
hidden_states = outputs.hidden_states
|
| 270 |
+
|
| 271 |
+
expected_num_layers = getattr(
|
| 272 |
+
self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1
|
| 273 |
+
)
|
| 274 |
+
self.assertEqual(len(hidden_states), expected_num_layers)
|
| 275 |
+
|
| 276 |
+
# Dinat has a different seq_length
|
| 277 |
+
patch_size = (
|
| 278 |
+
config.patch_size
|
| 279 |
+
if isinstance(config.patch_size, collections.abc.Iterable)
|
| 280 |
+
else (config.patch_size, config.patch_size)
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
height = image_size[0] // patch_size[0]
|
| 284 |
+
width = image_size[1] // patch_size[1]
|
| 285 |
+
|
| 286 |
+
self.assertListEqual(
|
| 287 |
+
list(hidden_states[0].shape[-3:]),
|
| 288 |
+
[height, width, self.model_tester.embed_dim],
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
if model_class.__name__ != "DinatBackbone":
|
| 292 |
+
reshaped_hidden_states = outputs.reshaped_hidden_states
|
| 293 |
+
self.assertEqual(len(reshaped_hidden_states), expected_num_layers)
|
| 294 |
+
|
| 295 |
+
batch_size, num_channels, height, width = reshaped_hidden_states[0].shape
|
| 296 |
+
reshaped_hidden_states = (
|
| 297 |
+
reshaped_hidden_states[0].view(batch_size, num_channels, height, width).permute(0, 2, 3, 1)
|
| 298 |
+
)
|
| 299 |
+
self.assertListEqual(
|
| 300 |
+
list(reshaped_hidden_states.shape[-3:]),
|
| 301 |
+
[height, width, self.model_tester.embed_dim],
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def test_hidden_states_output(self):
|
| 305 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 306 |
+
|
| 307 |
+
image_size = (
|
| 308 |
+
self.model_tester.image_size
|
| 309 |
+
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
|
| 310 |
+
else (self.model_tester.image_size, self.model_tester.image_size)
|
| 311 |
+
)
|
| 312 |
+
|
| 313 |
+
for model_class in self.all_model_classes:
|
| 314 |
+
inputs_dict["output_hidden_states"] = True
|
| 315 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
|
| 316 |
+
|
| 317 |
+
# check that output_hidden_states also work using config
|
| 318 |
+
del inputs_dict["output_hidden_states"]
|
| 319 |
+
config.output_hidden_states = True
|
| 320 |
+
|
| 321 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
|
| 322 |
+
|
| 323 |
+
@slow
|
| 324 |
+
def test_model_from_pretrained(self):
|
| 325 |
+
model_name = "shi-labs/dinat-mini-in1k-224"
|
| 326 |
+
model = DinatModel.from_pretrained(model_name)
|
| 327 |
+
self.assertIsNotNone(model)
|
| 328 |
+
|
| 329 |
+
def test_initialization(self):
|
| 330 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 331 |
+
|
| 332 |
+
configs_no_init = _config_zero_init(config)
|
| 333 |
+
for model_class in self.all_model_classes:
|
| 334 |
+
model = model_class(config=configs_no_init)
|
| 335 |
+
for name, param in model.named_parameters():
|
| 336 |
+
if "embeddings" not in name and param.requires_grad:
|
| 337 |
+
self.assertIn(
|
| 338 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 339 |
+
[0.0, 1.0],
|
| 340 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 341 |
+
)
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
@require_natten
|
| 345 |
+
@require_vision
|
| 346 |
+
@require_torch
|
| 347 |
+
class DinatModelIntegrationTest(unittest.TestCase):
|
| 348 |
+
@cached_property
|
| 349 |
+
def default_image_processor(self):
|
| 350 |
+
return AutoImageProcessor.from_pretrained("shi-labs/dinat-mini-in1k-224") if is_vision_available() else None
|
| 351 |
+
|
| 352 |
+
@slow
|
| 353 |
+
def test_inference_image_classification_head(self):
|
| 354 |
+
model = DinatForImageClassification.from_pretrained("shi-labs/dinat-mini-in1k-224").to(torch_device)
|
| 355 |
+
image_processor = self.default_image_processor
|
| 356 |
+
|
| 357 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 358 |
+
inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
|
| 359 |
+
|
| 360 |
+
# forward pass
|
| 361 |
+
with torch.no_grad():
|
| 362 |
+
outputs = model(**inputs)
|
| 363 |
+
|
| 364 |
+
# verify the logits
|
| 365 |
+
expected_shape = torch.Size((1, 1000))
|
| 366 |
+
self.assertEqual(outputs.logits.shape, expected_shape)
|
| 367 |
+
expected_slice = torch.tensor([-0.1545, -0.7667, 0.4642]).to(torch_device)
|
| 368 |
+
self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@require_torch
|
| 372 |
+
@require_natten
|
| 373 |
+
class DinatBackboneTest(unittest.TestCase, BackboneTesterMixin):
|
| 374 |
+
all_model_classes = (DinatBackbone,) if is_torch_available() else ()
|
| 375 |
+
config_class = DinatConfig
|
| 376 |
+
|
| 377 |
+
def setUp(self):
|
| 378 |
+
self.model_tester = DinatModelTester(self)
|
tasks/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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Dinov2 model."""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import Dinov2Config
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
is_flaky,
|
| 22 |
+
require_torch,
|
| 23 |
+
require_vision,
|
| 24 |
+
slow,
|
| 25 |
+
torch_device,
|
| 26 |
+
)
|
| 27 |
+
from transformers.utils import cached_property, is_torch_available, is_vision_available
|
| 28 |
+
|
| 29 |
+
from ...test_backbone_common import BackboneTesterMixin
|
| 30 |
+
from ...test_configuration_common import ConfigTester
|
| 31 |
+
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
|
| 32 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
if is_torch_available():
|
| 36 |
+
import torch
|
| 37 |
+
from torch import nn
|
| 38 |
+
|
| 39 |
+
from transformers import Dinov2Backbone, Dinov2ForImageClassification, Dinov2Model
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
if is_vision_available():
|
| 43 |
+
from PIL import Image
|
| 44 |
+
|
| 45 |
+
from transformers import AutoImageProcessor
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Dinov2ModelTester:
|
| 49 |
+
def __init__(
|
| 50 |
+
self,
|
| 51 |
+
parent,
|
| 52 |
+
batch_size=13,
|
| 53 |
+
image_size=30,
|
| 54 |
+
patch_size=2,
|
| 55 |
+
num_channels=3,
|
| 56 |
+
is_training=True,
|
| 57 |
+
use_labels=True,
|
| 58 |
+
hidden_size=32,
|
| 59 |
+
num_hidden_layers=2,
|
| 60 |
+
num_attention_heads=4,
|
| 61 |
+
intermediate_size=37,
|
| 62 |
+
hidden_act="gelu",
|
| 63 |
+
hidden_dropout_prob=0.1,
|
| 64 |
+
attention_probs_dropout_prob=0.1,
|
| 65 |
+
type_sequence_label_size=10,
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
scope=None,
|
| 68 |
+
attn_implementation="eager",
|
| 69 |
+
mask_ratio=0.5,
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = batch_size
|
| 73 |
+
self.image_size = image_size
|
| 74 |
+
self.patch_size = patch_size
|
| 75 |
+
self.num_channels = num_channels
|
| 76 |
+
self.is_training = is_training
|
| 77 |
+
self.use_labels = use_labels
|
| 78 |
+
self.hidden_size = hidden_size
|
| 79 |
+
self.num_hidden_layers = num_hidden_layers
|
| 80 |
+
self.num_attention_heads = num_attention_heads
|
| 81 |
+
self.intermediate_size = intermediate_size
|
| 82 |
+
self.hidden_act = hidden_act
|
| 83 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 84 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 85 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 86 |
+
self.initializer_range = initializer_range
|
| 87 |
+
self.scope = scope
|
| 88 |
+
self.attn_implementation = attn_implementation
|
| 89 |
+
self.mask_ratio = mask_ratio
|
| 90 |
+
|
| 91 |
+
# in Dinov2, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
|
| 92 |
+
num_patches = (image_size // patch_size) ** 2
|
| 93 |
+
self.seq_length = num_patches + 1
|
| 94 |
+
self.num_masks = int(self.mask_ratio * self.seq_length)
|
| 95 |
+
self.mask_length = num_patches
|
| 96 |
+
|
| 97 |
+
def prepare_config_and_inputs(self):
|
| 98 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 99 |
+
|
| 100 |
+
labels = None
|
| 101 |
+
if self.use_labels:
|
| 102 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 103 |
+
|
| 104 |
+
config = self.get_config()
|
| 105 |
+
|
| 106 |
+
return config, pixel_values, labels
|
| 107 |
+
|
| 108 |
+
def get_config(self):
|
| 109 |
+
return Dinov2Config(
|
| 110 |
+
image_size=self.image_size,
|
| 111 |
+
patch_size=self.patch_size,
|
| 112 |
+
num_channels=self.num_channels,
|
| 113 |
+
hidden_size=self.hidden_size,
|
| 114 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 115 |
+
num_attention_heads=self.num_attention_heads,
|
| 116 |
+
intermediate_size=self.intermediate_size,
|
| 117 |
+
hidden_act=self.hidden_act,
|
| 118 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 119 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 120 |
+
is_decoder=False,
|
| 121 |
+
initializer_range=self.initializer_range,
|
| 122 |
+
attn_implementation=self.attn_implementation,
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 126 |
+
model = Dinov2Model(config=config)
|
| 127 |
+
model.to(torch_device)
|
| 128 |
+
model.eval()
|
| 129 |
+
result = model(pixel_values)
|
| 130 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 131 |
+
|
| 132 |
+
def create_and_check_backbone(self, config, pixel_values, labels):
|
| 133 |
+
model = Dinov2Backbone(config=config)
|
| 134 |
+
model.to(torch_device)
|
| 135 |
+
model.eval()
|
| 136 |
+
result = model(pixel_values)
|
| 137 |
+
|
| 138 |
+
# verify hidden states
|
| 139 |
+
self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
|
| 140 |
+
expected_size = self.image_size // config.patch_size
|
| 141 |
+
self.parent.assertListEqual(
|
| 142 |
+
list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], expected_size, expected_size]
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
# verify channels
|
| 146 |
+
self.parent.assertEqual(len(model.channels), len(config.out_features))
|
| 147 |
+
|
| 148 |
+
# verify backbone works with out_features=None
|
| 149 |
+
config.out_features = None
|
| 150 |
+
model = Dinov2Backbone(config=config)
|
| 151 |
+
model.to(torch_device)
|
| 152 |
+
model.eval()
|
| 153 |
+
result = model(pixel_values)
|
| 154 |
+
|
| 155 |
+
# verify feature maps
|
| 156 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 157 |
+
self.parent.assertListEqual(
|
| 158 |
+
list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], expected_size, expected_size]
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
# verify channels
|
| 162 |
+
self.parent.assertEqual(len(model.channels), 1)
|
| 163 |
+
|
| 164 |
+
# verify backbone works with apply_layernorm=False and reshape_hidden_states=False
|
| 165 |
+
config.apply_layernorm = False
|
| 166 |
+
config.reshape_hidden_states = False
|
| 167 |
+
|
| 168 |
+
model = Dinov2Backbone(config=config)
|
| 169 |
+
model.to(torch_device)
|
| 170 |
+
model.eval()
|
| 171 |
+
result = model(pixel_values)
|
| 172 |
+
|
| 173 |
+
# verify feature maps
|
| 174 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 175 |
+
self.parent.assertListEqual(
|
| 176 |
+
list(result.feature_maps[0].shape), [self.batch_size, self.seq_length, self.hidden_size]
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 180 |
+
config.num_labels = self.type_sequence_label_size
|
| 181 |
+
model = Dinov2ForImageClassification(config)
|
| 182 |
+
model.to(torch_device)
|
| 183 |
+
model.eval()
|
| 184 |
+
result = model(pixel_values, labels=labels)
|
| 185 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 186 |
+
|
| 187 |
+
# test greyscale images
|
| 188 |
+
config.num_channels = 1
|
| 189 |
+
model = Dinov2ForImageClassification(config)
|
| 190 |
+
model.to(torch_device)
|
| 191 |
+
model.eval()
|
| 192 |
+
|
| 193 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 194 |
+
result = model(pixel_values)
|
| 195 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 196 |
+
|
| 197 |
+
def prepare_config_and_inputs_for_common(self):
|
| 198 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 199 |
+
(
|
| 200 |
+
config,
|
| 201 |
+
pixel_values,
|
| 202 |
+
labels,
|
| 203 |
+
) = config_and_inputs
|
| 204 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 205 |
+
return config, inputs_dict
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@require_torch
|
| 209 |
+
class Dinov2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 210 |
+
"""
|
| 211 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as Dinov2 does not use input_ids, inputs_embeds,
|
| 212 |
+
attention_mask and seq_length.
|
| 213 |
+
"""
|
| 214 |
+
|
| 215 |
+
all_model_classes = (
|
| 216 |
+
(
|
| 217 |
+
Dinov2Model,
|
| 218 |
+
Dinov2ForImageClassification,
|
| 219 |
+
Dinov2Backbone,
|
| 220 |
+
)
|
| 221 |
+
if is_torch_available()
|
| 222 |
+
else ()
|
| 223 |
+
)
|
| 224 |
+
pipeline_model_mapping = (
|
| 225 |
+
{"image-feature-extraction": Dinov2Model, "image-classification": Dinov2ForImageClassification}
|
| 226 |
+
if is_torch_available()
|
| 227 |
+
else {}
|
| 228 |
+
)
|
| 229 |
+
fx_compatible = True
|
| 230 |
+
|
| 231 |
+
test_pruning = False
|
| 232 |
+
test_resize_embeddings = False
|
| 233 |
+
test_head_masking = False
|
| 234 |
+
|
| 235 |
+
def setUp(self):
|
| 236 |
+
self.model_tester = Dinov2ModelTester(self)
|
| 237 |
+
self.config_tester = ConfigTester(self, config_class=Dinov2Config, has_text_modality=False, hidden_size=37)
|
| 238 |
+
|
| 239 |
+
@is_flaky(max_attempts=3, description="`torch.nn.init.trunc_normal_` is flaky.")
|
| 240 |
+
def test_initialization(self):
|
| 241 |
+
super().test_initialization()
|
| 242 |
+
|
| 243 |
+
def test_config(self):
|
| 244 |
+
self.config_tester.run_common_tests()
|
| 245 |
+
|
| 246 |
+
@unittest.skip(reason="Dinov2 does not use inputs_embeds")
|
| 247 |
+
def test_inputs_embeds(self):
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
@unittest.skip(
|
| 251 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 252 |
+
)
|
| 253 |
+
def test_training_gradient_checkpointing(self):
|
| 254 |
+
pass
|
| 255 |
+
|
| 256 |
+
@unittest.skip(
|
| 257 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 258 |
+
)
|
| 259 |
+
def test_training_gradient_checkpointing_use_reentrant(self):
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
@unittest.skip(
|
| 263 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 264 |
+
)
|
| 265 |
+
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
| 266 |
+
pass
|
| 267 |
+
|
| 268 |
+
def test_model_get_set_embeddings(self):
|
| 269 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 270 |
+
|
| 271 |
+
for model_class in self.all_model_classes:
|
| 272 |
+
model = model_class(config)
|
| 273 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 274 |
+
x = model.get_output_embeddings()
|
| 275 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 276 |
+
|
| 277 |
+
def test_model(self):
|
| 278 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 279 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 280 |
+
|
| 281 |
+
def test_backbone(self):
|
| 282 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 283 |
+
self.model_tester.create_and_check_backbone(*config_and_inputs)
|
| 284 |
+
|
| 285 |
+
def test_for_image_classification(self):
|
| 286 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 287 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 288 |
+
|
| 289 |
+
@unittest.skip(reason="Dinov2 does not support feedforward chunking yet")
|
| 290 |
+
def test_feed_forward_chunking(self):
|
| 291 |
+
pass
|
| 292 |
+
|
| 293 |
+
@slow
|
| 294 |
+
def test_model_from_pretrained(self):
|
| 295 |
+
model_name = "facebook/dinov2-base"
|
| 296 |
+
model = Dinov2Model.from_pretrained(model_name)
|
| 297 |
+
self.assertIsNotNone(model)
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
# We will verify our results on an image of cute cats
|
| 301 |
+
def prepare_img():
|
| 302 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 303 |
+
return image
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@require_torch
|
| 307 |
+
@require_vision
|
| 308 |
+
class Dinov2ModelIntegrationTest(unittest.TestCase):
|
| 309 |
+
@cached_property
|
| 310 |
+
def default_image_processor(self):
|
| 311 |
+
return AutoImageProcessor.from_pretrained("facebook/dinov2-base") if is_vision_available() else None
|
| 312 |
+
|
| 313 |
+
@slow
|
| 314 |
+
def test_inference_no_head(self):
|
| 315 |
+
model = Dinov2Model.from_pretrained("facebook/dinov2-base").to(torch_device)
|
| 316 |
+
|
| 317 |
+
image_processor = self.default_image_processor
|
| 318 |
+
image = prepare_img()
|
| 319 |
+
inputs = image_processor(image, return_tensors="pt").to(torch_device)
|
| 320 |
+
|
| 321 |
+
# forward pass
|
| 322 |
+
with torch.no_grad():
|
| 323 |
+
outputs = model(**inputs)
|
| 324 |
+
|
| 325 |
+
# verify the last hidden states
|
| 326 |
+
expected_shape = torch.Size((1, 257, 768))
|
| 327 |
+
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
| 328 |
+
|
| 329 |
+
expected_slice = torch.tensor(
|
| 330 |
+
[[-2.1747, -0.4729, 1.0936], [-3.2780, -0.8269, -0.9210], [-2.9129, 1.1284, -0.7306]],
|
| 331 |
+
device=torch_device,
|
| 332 |
+
)
|
| 333 |
+
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
@require_torch
|
| 337 |
+
class Dinov2BackboneTest(unittest.TestCase, BackboneTesterMixin):
|
| 338 |
+
all_model_classes = (Dinov2Backbone,) if is_torch_available() else ()
|
| 339 |
+
config_class = Dinov2Config
|
| 340 |
+
|
| 341 |
+
has_attentions = False
|
| 342 |
+
|
| 343 |
+
def setUp(self):
|
| 344 |
+
self.model_tester = Dinov2ModelTester(self)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2/test_modeling_flax_dinov2.py
ADDED
|
@@ -0,0 +1,263 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the Flax Dinov2 model."""
|
| 16 |
+
|
| 17 |
+
import inspect
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from transformers import Dinov2Config
|
| 23 |
+
from transformers.testing_utils import require_flax, require_vision, slow
|
| 24 |
+
from transformers.utils import cached_property, is_flax_available, is_vision_available
|
| 25 |
+
|
| 26 |
+
from ...test_configuration_common import ConfigTester
|
| 27 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_flax_available():
|
| 31 |
+
import jax
|
| 32 |
+
|
| 33 |
+
from transformers.models.dinov2.modeling_flax_dinov2 import FlaxDinov2ForImageClassification, FlaxDinov2Model
|
| 34 |
+
|
| 35 |
+
if is_vision_available():
|
| 36 |
+
from PIL import Image
|
| 37 |
+
|
| 38 |
+
from transformers import AutoImageProcessor
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class FlaxDinov2ModelTester:
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
parent,
|
| 45 |
+
batch_size=2,
|
| 46 |
+
image_size=30,
|
| 47 |
+
patch_size=2,
|
| 48 |
+
num_channels=3,
|
| 49 |
+
is_training=True,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
hidden_size=32,
|
| 52 |
+
num_hidden_layers=2,
|
| 53 |
+
num_attention_heads=4,
|
| 54 |
+
intermediate_size=37,
|
| 55 |
+
hidden_act="gelu",
|
| 56 |
+
hidden_dropout_prob=0.1,
|
| 57 |
+
attention_probs_dropout_prob=0.1,
|
| 58 |
+
type_sequence_label_size=10,
|
| 59 |
+
initializer_range=0.02,
|
| 60 |
+
):
|
| 61 |
+
self.parent = parent
|
| 62 |
+
self.batch_size = batch_size
|
| 63 |
+
self.image_size = image_size
|
| 64 |
+
self.patch_size = patch_size
|
| 65 |
+
self.num_channels = num_channels
|
| 66 |
+
self.is_training = is_training
|
| 67 |
+
self.use_labels = use_labels
|
| 68 |
+
self.hidden_size = hidden_size
|
| 69 |
+
self.num_hidden_layers = num_hidden_layers
|
| 70 |
+
self.num_attention_heads = num_attention_heads
|
| 71 |
+
self.intermediate_size = intermediate_size
|
| 72 |
+
self.hidden_act = hidden_act
|
| 73 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 74 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 75 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 76 |
+
self.initializer_range = initializer_range
|
| 77 |
+
|
| 78 |
+
# in Dinov2, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
|
| 79 |
+
num_patches = (image_size // patch_size) ** 2
|
| 80 |
+
self.seq_length = num_patches + 1
|
| 81 |
+
|
| 82 |
+
def prepare_config_and_inputs(self):
|
| 83 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 84 |
+
|
| 85 |
+
config = Dinov2Config(
|
| 86 |
+
image_size=self.image_size,
|
| 87 |
+
patch_size=self.patch_size,
|
| 88 |
+
num_channels=self.num_channels,
|
| 89 |
+
hidden_size=self.hidden_size,
|
| 90 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 91 |
+
num_attention_heads=self.num_attention_heads,
|
| 92 |
+
intermediate_size=self.intermediate_size,
|
| 93 |
+
hidden_act=self.hidden_act,
|
| 94 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 95 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 96 |
+
is_decoder=False,
|
| 97 |
+
initializer_range=self.initializer_range,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
return config, pixel_values
|
| 101 |
+
|
| 102 |
+
# Copied from transformers.models.vit.test_modeling_flax_vit.FlaxViTModelTester.prepare_config_and_inputs with ViT -> Dinov2
|
| 103 |
+
def create_and_check_model(self, config, pixel_values):
|
| 104 |
+
model = FlaxDinov2Model(config=config)
|
| 105 |
+
result = model(pixel_values)
|
| 106 |
+
# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
|
| 107 |
+
image_size = (self.image_size, self.image_size)
|
| 108 |
+
patch_size = (self.patch_size, self.patch_size)
|
| 109 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 110 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
|
| 111 |
+
|
| 112 |
+
# Copied from transformers.models.vit.test_modeling_flax_vit.FlaxViTModelTester.create_and_check_for_image_classification with ViT -> Dinov2
|
| 113 |
+
def create_and_check_for_image_classification(self, config, pixel_values):
|
| 114 |
+
config.num_labels = self.type_sequence_label_size
|
| 115 |
+
model = FlaxDinov2ForImageClassification(config=config)
|
| 116 |
+
result = model(pixel_values)
|
| 117 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 118 |
+
|
| 119 |
+
# test greyscale images
|
| 120 |
+
config.num_channels = 1
|
| 121 |
+
model = FlaxDinov2ForImageClassification(config)
|
| 122 |
+
|
| 123 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 124 |
+
result = model(pixel_values)
|
| 125 |
+
|
| 126 |
+
# Copied from transformers.models.vit.test_modeling_flax_vit.FlaxViTModelTester.prepare_config_and_inputs_for_common
|
| 127 |
+
def prepare_config_and_inputs_for_common(self):
|
| 128 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 129 |
+
(
|
| 130 |
+
config,
|
| 131 |
+
pixel_values,
|
| 132 |
+
) = config_and_inputs
|
| 133 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 134 |
+
return config, inputs_dict
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@require_flax
|
| 138 |
+
# Copied from transformers.models.vit.test_modeling_flax_vit.FlaxViTModelTest with google/vit-base-patch16-224 -> facebook/dinov2-base
|
| 139 |
+
class FlaxDionv2ModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 140 |
+
all_model_classes = (FlaxDinov2Model, FlaxDinov2ForImageClassification) if is_flax_available() else ()
|
| 141 |
+
|
| 142 |
+
def setUp(self) -> None:
|
| 143 |
+
self.model_tester = FlaxDinov2ModelTester(self)
|
| 144 |
+
self.config_tester = ConfigTester(self, config_class=Dinov2Config, has_text_modality=False, hidden_size=37)
|
| 145 |
+
|
| 146 |
+
def test_config(self):
|
| 147 |
+
self.config_tester.run_common_tests()
|
| 148 |
+
|
| 149 |
+
def test_model(self):
|
| 150 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 151 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 152 |
+
|
| 153 |
+
def test_for_image_classification(self):
|
| 154 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 155 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 156 |
+
|
| 157 |
+
# We need to override this test because Dinov2's forward signature is different than text models.
|
| 158 |
+
def test_forward_signature(self):
|
| 159 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 160 |
+
|
| 161 |
+
for model_class in self.all_model_classes:
|
| 162 |
+
model = model_class(config)
|
| 163 |
+
signature = inspect.signature(model.__call__)
|
| 164 |
+
# signature.parameters is an OrderedDict => so arg_names order is deterministic
|
| 165 |
+
arg_names = [*signature.parameters.keys()]
|
| 166 |
+
|
| 167 |
+
expected_arg_names = ["pixel_values"]
|
| 168 |
+
self.assertListEqual(arg_names[:1], expected_arg_names)
|
| 169 |
+
|
| 170 |
+
# We need to override this test because Dinov2 expects pixel_values instead of input_ids
|
| 171 |
+
def test_jit_compilation(self):
|
| 172 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 173 |
+
|
| 174 |
+
for model_class in self.all_model_classes:
|
| 175 |
+
with self.subTest(model_class.__name__):
|
| 176 |
+
prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
|
| 177 |
+
model = model_class(config)
|
| 178 |
+
|
| 179 |
+
@jax.jit
|
| 180 |
+
def model_jitted(pixel_values, **kwargs):
|
| 181 |
+
return model(pixel_values=pixel_values, **kwargs)
|
| 182 |
+
|
| 183 |
+
with self.subTest("JIT Enabled"):
|
| 184 |
+
jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 185 |
+
|
| 186 |
+
with self.subTest("JIT Disabled"):
|
| 187 |
+
with jax.disable_jit():
|
| 188 |
+
outputs = model_jitted(**prepared_inputs_dict).to_tuple()
|
| 189 |
+
|
| 190 |
+
self.assertEqual(len(outputs), len(jitted_outputs))
|
| 191 |
+
for jitted_output, output in zip(jitted_outputs, outputs):
|
| 192 |
+
self.assertEqual(jitted_output.shape, output.shape)
|
| 193 |
+
|
| 194 |
+
@slow
|
| 195 |
+
def test_model_from_pretrained(self):
|
| 196 |
+
for model_class_name in self.all_model_classes:
|
| 197 |
+
model = model_class_name.from_pretrained("facebook/dinov2-base")
|
| 198 |
+
outputs = model(np.ones((1, 3, 224, 224)))
|
| 199 |
+
self.assertIsNotNone(outputs)
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# We will verify our results on an image of cute cats
|
| 203 |
+
def prepare_img():
|
| 204 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 205 |
+
return image
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
@require_vision
|
| 209 |
+
@require_flax
|
| 210 |
+
class FlaxDinov2ModelIntegrationTest(unittest.TestCase):
|
| 211 |
+
@cached_property
|
| 212 |
+
def default_image_processor(self):
|
| 213 |
+
return AutoImageProcessor.from_pretrained("facebook/dinov2-base") if is_vision_available() else None
|
| 214 |
+
|
| 215 |
+
@slow
|
| 216 |
+
def test_inference_no_head(self):
|
| 217 |
+
model = FlaxDinov2Model.from_pretrained("facebook/dinov2-base")
|
| 218 |
+
|
| 219 |
+
image_processor = self.default_image_processor
|
| 220 |
+
image = prepare_img()
|
| 221 |
+
pixel_values = image_processor(images=image, return_tensors="np").pixel_values
|
| 222 |
+
|
| 223 |
+
# forward pass
|
| 224 |
+
outputs = model(pixel_values=pixel_values)
|
| 225 |
+
|
| 226 |
+
# verify the logits
|
| 227 |
+
expected_shape = (1, 257, 768)
|
| 228 |
+
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
| 229 |
+
|
| 230 |
+
expected_slice = np.array(
|
| 231 |
+
[
|
| 232 |
+
[-2.1629121, -0.46566057, 1.0925977],
|
| 233 |
+
[-3.5971704, -1.0283585, -1.1780515],
|
| 234 |
+
[-2.900407, 1.1334689, -0.74357724],
|
| 235 |
+
]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
| 239 |
+
|
| 240 |
+
@slow
|
| 241 |
+
def test_inference_image_classification_head_imagenet_1k(self):
|
| 242 |
+
model = FlaxDinov2ForImageClassification.from_pretrained(
|
| 243 |
+
"facebook/dinov2-base-imagenet1k-1-layer", from_pt=True
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
image_processor = self.default_image_processor
|
| 247 |
+
image = prepare_img()
|
| 248 |
+
inputs = image_processor(images=image, return_tensors="np")
|
| 249 |
+
|
| 250 |
+
# forward pass
|
| 251 |
+
outputs = model(**inputs)
|
| 252 |
+
logits = outputs.logits
|
| 253 |
+
|
| 254 |
+
# verify the logits
|
| 255 |
+
expected_shape = (1, 1000)
|
| 256 |
+
self.assertEqual(logits.shape, expected_shape)
|
| 257 |
+
|
| 258 |
+
expected_slice = np.array([-2.1776447, 0.36716992, 0.13870952])
|
| 259 |
+
|
| 260 |
+
self.assertTrue(np.allclose(logits[0, :3], expected_slice, atol=1e-4))
|
| 261 |
+
|
| 262 |
+
expected_class_idx = 281
|
| 263 |
+
self.assertEqual(logits.argmax(-1).item(), expected_class_idx)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2_with_registers/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dinov2_with_registers/test_modeling_dinov2_with_registers.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2024 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Dinov2WithRegisters model."""
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from transformers import Dinov2WithRegistersConfig
|
| 20 |
+
from transformers.testing_utils import (
|
| 21 |
+
require_torch,
|
| 22 |
+
require_vision,
|
| 23 |
+
slow,
|
| 24 |
+
torch_device,
|
| 25 |
+
)
|
| 26 |
+
from transformers.utils import cached_property, is_torch_available, is_vision_available
|
| 27 |
+
|
| 28 |
+
from ...test_backbone_common import BackboneTesterMixin
|
| 29 |
+
from ...test_configuration_common import ConfigTester
|
| 30 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
|
| 31 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
if is_torch_available():
|
| 35 |
+
import torch
|
| 36 |
+
from torch import nn
|
| 37 |
+
|
| 38 |
+
from transformers import (
|
| 39 |
+
Dinov2WithRegistersBackbone,
|
| 40 |
+
Dinov2WithRegistersForImageClassification,
|
| 41 |
+
Dinov2WithRegistersModel,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
if is_vision_available():
|
| 46 |
+
from PIL import Image
|
| 47 |
+
|
| 48 |
+
from transformers import AutoImageProcessor
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class Dinov2WithRegistersModelTester:
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
parent,
|
| 55 |
+
batch_size=13,
|
| 56 |
+
image_size=30,
|
| 57 |
+
patch_size=2,
|
| 58 |
+
num_channels=3,
|
| 59 |
+
is_training=True,
|
| 60 |
+
use_labels=True,
|
| 61 |
+
hidden_size=32,
|
| 62 |
+
num_hidden_layers=2,
|
| 63 |
+
num_attention_heads=4,
|
| 64 |
+
intermediate_size=37,
|
| 65 |
+
hidden_act="gelu",
|
| 66 |
+
hidden_dropout_prob=0.1,
|
| 67 |
+
attention_probs_dropout_prob=0.1,
|
| 68 |
+
type_sequence_label_size=10,
|
| 69 |
+
initializer_range=0.02,
|
| 70 |
+
num_register_tokens=2,
|
| 71 |
+
mask_ratio=0.5,
|
| 72 |
+
scope=None,
|
| 73 |
+
):
|
| 74 |
+
self.parent = parent
|
| 75 |
+
self.batch_size = batch_size
|
| 76 |
+
self.image_size = image_size
|
| 77 |
+
self.patch_size = patch_size
|
| 78 |
+
self.num_channels = num_channels
|
| 79 |
+
self.is_training = is_training
|
| 80 |
+
self.use_labels = use_labels
|
| 81 |
+
self.hidden_size = hidden_size
|
| 82 |
+
self.num_hidden_layers = num_hidden_layers
|
| 83 |
+
self.num_attention_heads = num_attention_heads
|
| 84 |
+
self.intermediate_size = intermediate_size
|
| 85 |
+
self.hidden_act = hidden_act
|
| 86 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 87 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 88 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.num_register_tokens = num_register_tokens
|
| 91 |
+
self.scope = scope
|
| 92 |
+
|
| 93 |
+
# in DINOv2 with Registers, the seq length equals the number of patches + 1 + num_register_tokens (we add 1 for the [CLS] token)
|
| 94 |
+
num_patches = (image_size // patch_size) ** 2
|
| 95 |
+
self.seq_length = num_patches + 1 + self.num_register_tokens
|
| 96 |
+
self.mask_ratio = mask_ratio
|
| 97 |
+
self.num_masks = int(mask_ratio * self.seq_length)
|
| 98 |
+
self.mask_length = num_patches
|
| 99 |
+
|
| 100 |
+
def prepare_config_and_inputs(self):
|
| 101 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 102 |
+
|
| 103 |
+
labels = None
|
| 104 |
+
if self.use_labels:
|
| 105 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 106 |
+
|
| 107 |
+
config = self.get_config()
|
| 108 |
+
|
| 109 |
+
return config, pixel_values, labels
|
| 110 |
+
|
| 111 |
+
def get_config(self):
|
| 112 |
+
return Dinov2WithRegistersConfig(
|
| 113 |
+
image_size=self.image_size,
|
| 114 |
+
patch_size=self.patch_size,
|
| 115 |
+
num_channels=self.num_channels,
|
| 116 |
+
hidden_size=self.hidden_size,
|
| 117 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 118 |
+
num_attention_heads=self.num_attention_heads,
|
| 119 |
+
intermediate_size=self.intermediate_size,
|
| 120 |
+
hidden_act=self.hidden_act,
|
| 121 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 122 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 123 |
+
is_decoder=False,
|
| 124 |
+
initializer_range=self.initializer_range,
|
| 125 |
+
num_register_tokens=self.num_register_tokens,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 129 |
+
model = Dinov2WithRegistersModel(config=config)
|
| 130 |
+
model.to(torch_device)
|
| 131 |
+
model.eval()
|
| 132 |
+
result = model(pixel_values)
|
| 133 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 134 |
+
|
| 135 |
+
def create_and_check_backbone(self, config, pixel_values, labels):
|
| 136 |
+
model = Dinov2WithRegistersBackbone(config=config)
|
| 137 |
+
model.to(torch_device)
|
| 138 |
+
model.eval()
|
| 139 |
+
result = model(pixel_values)
|
| 140 |
+
|
| 141 |
+
# verify hidden states
|
| 142 |
+
self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
|
| 143 |
+
expected_size = self.image_size // config.patch_size
|
| 144 |
+
self.parent.assertListEqual(
|
| 145 |
+
list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], expected_size, expected_size]
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
# verify channels
|
| 149 |
+
self.parent.assertEqual(len(model.channels), len(config.out_features))
|
| 150 |
+
|
| 151 |
+
# verify backbone works with out_features=None
|
| 152 |
+
config.out_features = None
|
| 153 |
+
model = Dinov2WithRegistersBackbone(config=config)
|
| 154 |
+
model.to(torch_device)
|
| 155 |
+
model.eval()
|
| 156 |
+
result = model(pixel_values)
|
| 157 |
+
|
| 158 |
+
# verify feature maps
|
| 159 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 160 |
+
self.parent.assertListEqual(
|
| 161 |
+
list(result.feature_maps[0].shape), [self.batch_size, model.channels[0], expected_size, expected_size]
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# verify channels
|
| 165 |
+
self.parent.assertEqual(len(model.channels), 1)
|
| 166 |
+
|
| 167 |
+
# verify backbone works with apply_layernorm=False and reshape_hidden_states=False
|
| 168 |
+
config.apply_layernorm = False
|
| 169 |
+
config.reshape_hidden_states = False
|
| 170 |
+
|
| 171 |
+
model = Dinov2WithRegistersBackbone(config=config)
|
| 172 |
+
model.to(torch_device)
|
| 173 |
+
model.eval()
|
| 174 |
+
result = model(pixel_values)
|
| 175 |
+
|
| 176 |
+
# verify feature maps
|
| 177 |
+
self.parent.assertEqual(len(result.feature_maps), 1)
|
| 178 |
+
self.parent.assertListEqual(
|
| 179 |
+
list(result.feature_maps[0].shape), [self.batch_size, self.seq_length, self.hidden_size]
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def create_and_check_for_image_classification(self, config, pixel_values, labels):
|
| 183 |
+
config.num_labels = self.type_sequence_label_size
|
| 184 |
+
model = Dinov2WithRegistersForImageClassification(config)
|
| 185 |
+
model.to(torch_device)
|
| 186 |
+
model.eval()
|
| 187 |
+
result = model(pixel_values, labels=labels)
|
| 188 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 189 |
+
|
| 190 |
+
# test greyscale images
|
| 191 |
+
config.num_channels = 1
|
| 192 |
+
model = Dinov2WithRegistersForImageClassification(config)
|
| 193 |
+
model.to(torch_device)
|
| 194 |
+
model.eval()
|
| 195 |
+
|
| 196 |
+
pixel_values = floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
|
| 197 |
+
result = model(pixel_values)
|
| 198 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.type_sequence_label_size))
|
| 199 |
+
|
| 200 |
+
def prepare_config_and_inputs_for_common(self):
|
| 201 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 202 |
+
(
|
| 203 |
+
config,
|
| 204 |
+
pixel_values,
|
| 205 |
+
labels,
|
| 206 |
+
) = config_and_inputs
|
| 207 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 208 |
+
return config, inputs_dict
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@require_torch
|
| 212 |
+
class Dinov2WithRegistersModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 213 |
+
"""
|
| 214 |
+
Here we also overwrite some of the tests of test_modeling_common.py, as Dinov2WithRegisters does not use input_ids, inputs_embeds,
|
| 215 |
+
attention_mask and seq_length.
|
| 216 |
+
"""
|
| 217 |
+
|
| 218 |
+
all_model_classes = (
|
| 219 |
+
(
|
| 220 |
+
Dinov2WithRegistersModel,
|
| 221 |
+
Dinov2WithRegistersForImageClassification,
|
| 222 |
+
Dinov2WithRegistersBackbone,
|
| 223 |
+
)
|
| 224 |
+
if is_torch_available()
|
| 225 |
+
else ()
|
| 226 |
+
)
|
| 227 |
+
pipeline_model_mapping = (
|
| 228 |
+
{
|
| 229 |
+
"image-feature-extraction": Dinov2WithRegistersModel,
|
| 230 |
+
"image-classification": Dinov2WithRegistersForImageClassification,
|
| 231 |
+
}
|
| 232 |
+
if is_torch_available()
|
| 233 |
+
else {}
|
| 234 |
+
)
|
| 235 |
+
fx_compatible = False
|
| 236 |
+
|
| 237 |
+
test_pruning = False
|
| 238 |
+
test_resize_embeddings = False
|
| 239 |
+
test_head_masking = False
|
| 240 |
+
|
| 241 |
+
def setUp(self):
|
| 242 |
+
self.model_tester = Dinov2WithRegistersModelTester(self)
|
| 243 |
+
self.config_tester = ConfigTester(
|
| 244 |
+
self, config_class=Dinov2WithRegistersConfig, has_text_modality=False, hidden_size=37
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
def test_initialization(self):
|
| 248 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 249 |
+
|
| 250 |
+
configs_no_init = _config_zero_init(config)
|
| 251 |
+
for model_class in self.all_model_classes:
|
| 252 |
+
model = model_class(config=configs_no_init)
|
| 253 |
+
for name, param in model.named_parameters():
|
| 254 |
+
if param.requires_grad and "register_tokens" not in name:
|
| 255 |
+
self.assertIn(
|
| 256 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 257 |
+
[0.0, 1.0],
|
| 258 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 259 |
+
)
|
| 260 |
+
|
| 261 |
+
def test_config(self):
|
| 262 |
+
self.config_tester.run_common_tests()
|
| 263 |
+
|
| 264 |
+
@unittest.skip(reason="Dinov2WithRegisters does not use inputs_embeds")
|
| 265 |
+
def test_inputs_embeds(self):
|
| 266 |
+
pass
|
| 267 |
+
|
| 268 |
+
@unittest.skip(
|
| 269 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 270 |
+
)
|
| 271 |
+
def test_training_gradient_checkpointing(self):
|
| 272 |
+
pass
|
| 273 |
+
|
| 274 |
+
@unittest.skip(
|
| 275 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 276 |
+
)
|
| 277 |
+
def test_training_gradient_checkpointing_use_reentrant(self):
|
| 278 |
+
pass
|
| 279 |
+
|
| 280 |
+
@unittest.skip(
|
| 281 |
+
reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
|
| 282 |
+
)
|
| 283 |
+
def test_training_gradient_checkpointing_use_reentrant_false(self):
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
def test_model_get_set_embeddings(self):
|
| 287 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 288 |
+
|
| 289 |
+
for model_class in self.all_model_classes:
|
| 290 |
+
model = model_class(config)
|
| 291 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 292 |
+
x = model.get_output_embeddings()
|
| 293 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 294 |
+
|
| 295 |
+
def test_model(self):
|
| 296 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 297 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 298 |
+
|
| 299 |
+
def test_backbone(self):
|
| 300 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 301 |
+
self.model_tester.create_and_check_backbone(*config_and_inputs)
|
| 302 |
+
|
| 303 |
+
def test_for_image_classification(self):
|
| 304 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 305 |
+
self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
|
| 306 |
+
|
| 307 |
+
@unittest.skip(reason="Dinov2WithRegisters does not support feedforward chunking yet")
|
| 308 |
+
def test_feed_forward_chunking(self):
|
| 309 |
+
pass
|
| 310 |
+
|
| 311 |
+
@slow
|
| 312 |
+
def test_model_from_pretrained(self):
|
| 313 |
+
model_name = "facebook/dinov2-with-registers-base"
|
| 314 |
+
model = Dinov2WithRegistersModel.from_pretrained(model_name)
|
| 315 |
+
self.assertIsNotNone(model)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
# We will verify our results on an image of cute cats
|
| 319 |
+
def prepare_img():
|
| 320 |
+
image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
|
| 321 |
+
return image
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
@require_torch
|
| 325 |
+
@require_vision
|
| 326 |
+
class Dinov2WithRegistersModelIntegrationTest(unittest.TestCase):
|
| 327 |
+
@cached_property
|
| 328 |
+
def default_image_processor(self):
|
| 329 |
+
return (
|
| 330 |
+
AutoImageProcessor.from_pretrained("facebook/dinov2-with-registers-base")
|
| 331 |
+
if is_vision_available()
|
| 332 |
+
else None
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
@slow
|
| 336 |
+
def test_inference_no_head(self):
|
| 337 |
+
model = Dinov2WithRegistersModel.from_pretrained("facebook/dinov2-with-registers-base").to(torch_device)
|
| 338 |
+
|
| 339 |
+
image_processor = self.default_image_processor
|
| 340 |
+
image = prepare_img()
|
| 341 |
+
inputs = image_processor(image, return_tensors="pt").to(torch_device)
|
| 342 |
+
|
| 343 |
+
# forward pass
|
| 344 |
+
with torch.no_grad():
|
| 345 |
+
outputs = model(**inputs)
|
| 346 |
+
|
| 347 |
+
# verify the last hidden states
|
| 348 |
+
# in DINOv2 with Registers, the seq length equals the number of patches + 1 + num_register_tokens (we add 1 for the [CLS] token)
|
| 349 |
+
num_patches = (image_processor.crop_size["height"] // model.config.patch_size) ** 2
|
| 350 |
+
expected_seq_length = num_patches + 1 + model.config.num_register_tokens
|
| 351 |
+
expected_shape = torch.Size((1, expected_seq_length, model.config.hidden_size))
|
| 352 |
+
self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
|
| 353 |
+
|
| 354 |
+
expected_slice = torch.tensor(
|
| 355 |
+
[[-0.4636, -1.4582, -0.0274], [-1.4738, -0.8858, 0.3002], [0.0714, -0.2407, -1.5940]],
|
| 356 |
+
device=torch_device,
|
| 357 |
+
)
|
| 358 |
+
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@require_torch
|
| 362 |
+
class Dinov2WithRegistersBackboneTest(unittest.TestCase, BackboneTesterMixin):
|
| 363 |
+
all_model_classes = (Dinov2WithRegistersBackbone,) if is_torch_available() else ()
|
| 364 |
+
config_class = Dinov2WithRegistersConfig
|
| 365 |
+
|
| 366 |
+
has_attentions = False
|
| 367 |
+
|
| 368 |
+
def setUp(self):
|
| 369 |
+
self.model_tester = Dinov2WithRegistersModelTester(self)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_distilbert.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import os
|
| 16 |
+
import tempfile
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
|
| 21 |
+
from transformers import DistilBertConfig, is_torch_available
|
| 22 |
+
from transformers.testing_utils import require_flash_attn, require_torch, require_torch_accelerator, slow, torch_device
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
AutoTokenizer,
|
| 34 |
+
DistilBertForMaskedLM,
|
| 35 |
+
DistilBertForMultipleChoice,
|
| 36 |
+
DistilBertForQuestionAnswering,
|
| 37 |
+
DistilBertForSequenceClassification,
|
| 38 |
+
DistilBertForTokenClassification,
|
| 39 |
+
DistilBertModel,
|
| 40 |
+
)
|
| 41 |
+
from transformers.models.distilbert.modeling_distilbert import _create_sinusoidal_embeddings
|
| 42 |
+
from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_4
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class DistilBertModelTester:
|
| 46 |
+
def __init__(
|
| 47 |
+
self,
|
| 48 |
+
parent,
|
| 49 |
+
batch_size=13,
|
| 50 |
+
seq_length=7,
|
| 51 |
+
is_training=True,
|
| 52 |
+
use_input_mask=True,
|
| 53 |
+
use_token_type_ids=False,
|
| 54 |
+
use_labels=True,
|
| 55 |
+
vocab_size=99,
|
| 56 |
+
hidden_size=32,
|
| 57 |
+
num_hidden_layers=2,
|
| 58 |
+
num_attention_heads=4,
|
| 59 |
+
intermediate_size=37,
|
| 60 |
+
hidden_act="gelu",
|
| 61 |
+
hidden_dropout_prob=0.1,
|
| 62 |
+
attention_probs_dropout_prob=0.1,
|
| 63 |
+
max_position_embeddings=512,
|
| 64 |
+
type_vocab_size=16,
|
| 65 |
+
type_sequence_label_size=2,
|
| 66 |
+
initializer_range=0.02,
|
| 67 |
+
num_labels=3,
|
| 68 |
+
num_choices=4,
|
| 69 |
+
scope=None,
|
| 70 |
+
):
|
| 71 |
+
self.parent = parent
|
| 72 |
+
self.batch_size = batch_size
|
| 73 |
+
self.seq_length = seq_length
|
| 74 |
+
self.is_training = is_training
|
| 75 |
+
self.use_input_mask = use_input_mask
|
| 76 |
+
self.use_token_type_ids = use_token_type_ids
|
| 77 |
+
self.use_labels = use_labels
|
| 78 |
+
self.vocab_size = vocab_size
|
| 79 |
+
self.hidden_size = hidden_size
|
| 80 |
+
self.num_hidden_layers = num_hidden_layers
|
| 81 |
+
self.num_attention_heads = num_attention_heads
|
| 82 |
+
self.intermediate_size = intermediate_size
|
| 83 |
+
self.hidden_act = hidden_act
|
| 84 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 85 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 86 |
+
self.max_position_embeddings = max_position_embeddings
|
| 87 |
+
self.type_vocab_size = type_vocab_size
|
| 88 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 89 |
+
self.initializer_range = initializer_range
|
| 90 |
+
self.num_labels = num_labels
|
| 91 |
+
self.num_choices = num_choices
|
| 92 |
+
self.scope = scope
|
| 93 |
+
|
| 94 |
+
def prepare_config_and_inputs(self):
|
| 95 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 96 |
+
|
| 97 |
+
input_mask = None
|
| 98 |
+
if self.use_input_mask:
|
| 99 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 100 |
+
|
| 101 |
+
sequence_labels = None
|
| 102 |
+
token_labels = None
|
| 103 |
+
choice_labels = None
|
| 104 |
+
if self.use_labels:
|
| 105 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 106 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 107 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 108 |
+
|
| 109 |
+
config = self.get_config()
|
| 110 |
+
|
| 111 |
+
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 112 |
+
|
| 113 |
+
def get_config(self):
|
| 114 |
+
return DistilBertConfig(
|
| 115 |
+
vocab_size=self.vocab_size,
|
| 116 |
+
dim=self.hidden_size,
|
| 117 |
+
n_layers=self.num_hidden_layers,
|
| 118 |
+
n_heads=self.num_attention_heads,
|
| 119 |
+
hidden_dim=self.intermediate_size,
|
| 120 |
+
hidden_act=self.hidden_act,
|
| 121 |
+
dropout=self.hidden_dropout_prob,
|
| 122 |
+
attention_dropout=self.attention_probs_dropout_prob,
|
| 123 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 124 |
+
initializer_range=self.initializer_range,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
def create_and_check_distilbert_model(
|
| 128 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 129 |
+
):
|
| 130 |
+
model = DistilBertModel(config=config)
|
| 131 |
+
model.to(torch_device)
|
| 132 |
+
model.eval()
|
| 133 |
+
result = model(input_ids, input_mask)
|
| 134 |
+
result = model(input_ids)
|
| 135 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 136 |
+
|
| 137 |
+
def create_and_check_distilbert_for_masked_lm(
|
| 138 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 139 |
+
):
|
| 140 |
+
model = DistilBertForMaskedLM(config=config)
|
| 141 |
+
model.to(torch_device)
|
| 142 |
+
model.eval()
|
| 143 |
+
result = model(input_ids, attention_mask=input_mask, labels=token_labels)
|
| 144 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 145 |
+
|
| 146 |
+
def create_and_check_distilbert_for_question_answering(
|
| 147 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 148 |
+
):
|
| 149 |
+
model = DistilBertForQuestionAnswering(config=config)
|
| 150 |
+
model.to(torch_device)
|
| 151 |
+
model.eval()
|
| 152 |
+
result = model(
|
| 153 |
+
input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels
|
| 154 |
+
)
|
| 155 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 156 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 157 |
+
|
| 158 |
+
def create_and_check_distilbert_for_sequence_classification(
|
| 159 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 160 |
+
):
|
| 161 |
+
config.num_labels = self.num_labels
|
| 162 |
+
model = DistilBertForSequenceClassification(config)
|
| 163 |
+
model.to(torch_device)
|
| 164 |
+
model.eval()
|
| 165 |
+
result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
|
| 166 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 167 |
+
|
| 168 |
+
def create_and_check_distilbert_for_token_classification(
|
| 169 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 170 |
+
):
|
| 171 |
+
config.num_labels = self.num_labels
|
| 172 |
+
model = DistilBertForTokenClassification(config=config)
|
| 173 |
+
model.to(torch_device)
|
| 174 |
+
model.eval()
|
| 175 |
+
|
| 176 |
+
result = model(input_ids, attention_mask=input_mask, labels=token_labels)
|
| 177 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 178 |
+
|
| 179 |
+
def create_and_check_distilbert_for_multiple_choice(
|
| 180 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 181 |
+
):
|
| 182 |
+
config.num_choices = self.num_choices
|
| 183 |
+
model = DistilBertForMultipleChoice(config=config)
|
| 184 |
+
model.to(torch_device)
|
| 185 |
+
model.eval()
|
| 186 |
+
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 187 |
+
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
|
| 188 |
+
result = model(
|
| 189 |
+
multiple_choice_inputs_ids,
|
| 190 |
+
attention_mask=multiple_choice_input_mask,
|
| 191 |
+
labels=choice_labels,
|
| 192 |
+
)
|
| 193 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 194 |
+
|
| 195 |
+
def prepare_config_and_inputs_for_common(self):
|
| 196 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 197 |
+
(config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
|
| 198 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 199 |
+
return config, inputs_dict
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
@require_torch
|
| 203 |
+
class DistilBertModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 204 |
+
all_model_classes = (
|
| 205 |
+
(
|
| 206 |
+
DistilBertModel,
|
| 207 |
+
DistilBertForMaskedLM,
|
| 208 |
+
DistilBertForMultipleChoice,
|
| 209 |
+
DistilBertForQuestionAnswering,
|
| 210 |
+
DistilBertForSequenceClassification,
|
| 211 |
+
DistilBertForTokenClassification,
|
| 212 |
+
)
|
| 213 |
+
if is_torch_available()
|
| 214 |
+
else None
|
| 215 |
+
)
|
| 216 |
+
pipeline_model_mapping = (
|
| 217 |
+
{
|
| 218 |
+
"feature-extraction": DistilBertModel,
|
| 219 |
+
"fill-mask": DistilBertForMaskedLM,
|
| 220 |
+
"question-answering": DistilBertForQuestionAnswering,
|
| 221 |
+
"text-classification": DistilBertForSequenceClassification,
|
| 222 |
+
"token-classification": DistilBertForTokenClassification,
|
| 223 |
+
"zero-shot": DistilBertForSequenceClassification,
|
| 224 |
+
}
|
| 225 |
+
if is_torch_available()
|
| 226 |
+
else {}
|
| 227 |
+
)
|
| 228 |
+
fx_compatible = True
|
| 229 |
+
test_pruning = True
|
| 230 |
+
test_resize_embeddings = True
|
| 231 |
+
test_resize_position_embeddings = True
|
| 232 |
+
|
| 233 |
+
def setUp(self):
|
| 234 |
+
self.model_tester = DistilBertModelTester(self)
|
| 235 |
+
self.config_tester = ConfigTester(self, config_class=DistilBertConfig, dim=37)
|
| 236 |
+
|
| 237 |
+
def test_config(self):
|
| 238 |
+
self.config_tester.run_common_tests()
|
| 239 |
+
|
| 240 |
+
def test_distilbert_model(self):
|
| 241 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 242 |
+
self.model_tester.create_and_check_distilbert_model(*config_and_inputs)
|
| 243 |
+
|
| 244 |
+
def test_distilbert_model_with_sinusoidal_encodings(self):
|
| 245 |
+
config = DistilBertConfig(sinusoidal_pos_embds=True)
|
| 246 |
+
model = DistilBertModel(config=config)
|
| 247 |
+
sinusoidal_pos_embds = torch.empty((config.max_position_embeddings, config.dim), dtype=torch.float32)
|
| 248 |
+
_create_sinusoidal_embeddings(config.max_position_embeddings, config.dim, sinusoidal_pos_embds)
|
| 249 |
+
self.model_tester.parent.assertTrue(
|
| 250 |
+
torch.equal(model.embeddings.position_embeddings.weight, sinusoidal_pos_embds)
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def test_for_masked_lm(self):
|
| 254 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 255 |
+
self.model_tester.create_and_check_distilbert_for_masked_lm(*config_and_inputs)
|
| 256 |
+
|
| 257 |
+
def test_for_question_answering(self):
|
| 258 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 259 |
+
self.model_tester.create_and_check_distilbert_for_question_answering(*config_and_inputs)
|
| 260 |
+
|
| 261 |
+
def test_for_sequence_classification(self):
|
| 262 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 263 |
+
self.model_tester.create_and_check_distilbert_for_sequence_classification(*config_and_inputs)
|
| 264 |
+
|
| 265 |
+
def test_for_token_classification(self):
|
| 266 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 267 |
+
self.model_tester.create_and_check_distilbert_for_token_classification(*config_and_inputs)
|
| 268 |
+
|
| 269 |
+
def test_for_multiple_choice(self):
|
| 270 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 271 |
+
self.model_tester.create_and_check_distilbert_for_multiple_choice(*config_and_inputs)
|
| 272 |
+
|
| 273 |
+
@slow
|
| 274 |
+
def test_model_from_pretrained(self):
|
| 275 |
+
model_name = "distilbert-base-uncased"
|
| 276 |
+
model = DistilBertModel.from_pretrained(model_name)
|
| 277 |
+
self.assertIsNotNone(model)
|
| 278 |
+
|
| 279 |
+
@slow
|
| 280 |
+
@require_torch_accelerator
|
| 281 |
+
def test_torchscript_device_change(self):
|
| 282 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 283 |
+
for model_class in self.all_model_classes:
|
| 284 |
+
# BertForMultipleChoice behaves incorrectly in JIT environments.
|
| 285 |
+
if model_class == DistilBertForMultipleChoice:
|
| 286 |
+
self.skipTest(reason="DistilBertForMultipleChoice behaves incorrectly in JIT environments.")
|
| 287 |
+
|
| 288 |
+
config.torchscript = True
|
| 289 |
+
model = model_class(config=config)
|
| 290 |
+
|
| 291 |
+
inputs_dict = self._prepare_for_class(inputs_dict, model_class)
|
| 292 |
+
traced_model = torch.jit.trace(
|
| 293 |
+
model, (inputs_dict["input_ids"].to("cpu"), inputs_dict["attention_mask"].to("cpu"))
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 297 |
+
torch.jit.save(traced_model, os.path.join(tmp, "traced_model.pt"))
|
| 298 |
+
loaded = torch.jit.load(os.path.join(tmp, "traced_model.pt"), map_location=torch_device)
|
| 299 |
+
loaded(inputs_dict["input_ids"].to(torch_device), inputs_dict["attention_mask"].to(torch_device))
|
| 300 |
+
|
| 301 |
+
# Because DistilBertForMultipleChoice requires inputs with different shapes we need to override this test.
|
| 302 |
+
@require_flash_attn
|
| 303 |
+
@require_torch_accelerator
|
| 304 |
+
@pytest.mark.flash_attn_test
|
| 305 |
+
@slow
|
| 306 |
+
def test_flash_attn_2_inference_equivalence(self):
|
| 307 |
+
import torch
|
| 308 |
+
|
| 309 |
+
for model_class in self.all_model_classes:
|
| 310 |
+
dummy_input = torch.LongTensor(
|
| 311 |
+
[
|
| 312 |
+
[1, 2, 3, 4],
|
| 313 |
+
[1, 2, 8, 9],
|
| 314 |
+
[1, 2, 11, 12],
|
| 315 |
+
[1, 2, 13, 14],
|
| 316 |
+
]
|
| 317 |
+
).to(torch_device)
|
| 318 |
+
dummy_attention_mask = torch.LongTensor(
|
| 319 |
+
[
|
| 320 |
+
[0, 1, 1, 1],
|
| 321 |
+
[0, 1, 1, 1],
|
| 322 |
+
[0, 1, 1, 1],
|
| 323 |
+
[0, 1, 1, 1],
|
| 324 |
+
]
|
| 325 |
+
).to(torch_device)
|
| 326 |
+
|
| 327 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 328 |
+
model = model_class(config)
|
| 329 |
+
|
| 330 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 331 |
+
model.save_pretrained(tmpdirname)
|
| 332 |
+
model_fa = model_class.from_pretrained(
|
| 333 |
+
tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
|
| 334 |
+
)
|
| 335 |
+
model_fa.to(torch_device)
|
| 336 |
+
|
| 337 |
+
model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.bfloat16)
|
| 338 |
+
model.to(torch_device)
|
| 339 |
+
|
| 340 |
+
logits = model(dummy_input, output_hidden_states=True).hidden_states[-1]
|
| 341 |
+
logits_fa = model_fa(dummy_input, output_hidden_states=True).hidden_states[-1]
|
| 342 |
+
|
| 343 |
+
self.assertTrue(torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2))
|
| 344 |
+
|
| 345 |
+
output_fa = model_fa(dummy_input, attention_mask=dummy_attention_mask, output_hidden_states=True)
|
| 346 |
+
logits_fa = output_fa.hidden_states[-1]
|
| 347 |
+
|
| 348 |
+
output = model(dummy_input, attention_mask=dummy_attention_mask, output_hidden_states=True)
|
| 349 |
+
logits = output.hidden_states[-1]
|
| 350 |
+
|
| 351 |
+
self.assertTrue(torch.allclose(logits_fa[1:], logits[1:], atol=4e-2, rtol=4e-2))
|
| 352 |
+
|
| 353 |
+
# Because DistilBertForMultipleChoice requires inputs with different shapes we need to override this test.
|
| 354 |
+
@require_flash_attn
|
| 355 |
+
@require_torch_accelerator
|
| 356 |
+
@pytest.mark.flash_attn_test
|
| 357 |
+
@slow
|
| 358 |
+
def test_flash_attn_2_inference_equivalence_right_padding(self):
|
| 359 |
+
import torch
|
| 360 |
+
|
| 361 |
+
for model_class in self.all_model_classes:
|
| 362 |
+
dummy_input = torch.LongTensor(
|
| 363 |
+
[
|
| 364 |
+
[1, 2, 3, 4],
|
| 365 |
+
[1, 2, 8, 9],
|
| 366 |
+
[1, 2, 11, 12],
|
| 367 |
+
[1, 2, 13, 14],
|
| 368 |
+
]
|
| 369 |
+
).to(torch_device)
|
| 370 |
+
dummy_attention_mask = torch.LongTensor(
|
| 371 |
+
[
|
| 372 |
+
[0, 1, 1, 1],
|
| 373 |
+
[0, 1, 1, 1],
|
| 374 |
+
[0, 1, 1, 1],
|
| 375 |
+
[0, 1, 1, 1],
|
| 376 |
+
]
|
| 377 |
+
).to(torch_device)
|
| 378 |
+
|
| 379 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 380 |
+
model = model_class(config)
|
| 381 |
+
|
| 382 |
+
with tempfile.TemporaryDirectory() as tmpdirname:
|
| 383 |
+
model.save_pretrained(tmpdirname)
|
| 384 |
+
model_fa = model_class.from_pretrained(
|
| 385 |
+
tmpdirname, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
|
| 386 |
+
)
|
| 387 |
+
model_fa.to(torch_device)
|
| 388 |
+
|
| 389 |
+
model = model_class.from_pretrained(
|
| 390 |
+
tmpdirname,
|
| 391 |
+
torch_dtype=torch.bfloat16,
|
| 392 |
+
)
|
| 393 |
+
model.to(torch_device)
|
| 394 |
+
|
| 395 |
+
logits = model(dummy_input, output_hidden_states=True).hidden_states[-1]
|
| 396 |
+
logits_fa = model_fa(dummy_input, output_hidden_states=True).hidden_states[-1]
|
| 397 |
+
|
| 398 |
+
self.assertTrue(torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2))
|
| 399 |
+
|
| 400 |
+
output_fa = model_fa(dummy_input, attention_mask=dummy_attention_mask, output_hidden_states=True)
|
| 401 |
+
logits_fa = output_fa.hidden_states[-1]
|
| 402 |
+
|
| 403 |
+
output = model(dummy_input, attention_mask=dummy_attention_mask, output_hidden_states=True)
|
| 404 |
+
logits = output.hidden_states[-1]
|
| 405 |
+
|
| 406 |
+
self.assertTrue(torch.allclose(logits_fa[:-1], logits[:-1], atol=4e-2, rtol=4e-2))
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@require_torch
|
| 410 |
+
class DistilBertModelIntergrationTest(unittest.TestCase):
|
| 411 |
+
@slow
|
| 412 |
+
def test_inference_no_head_absolute_embedding(self):
|
| 413 |
+
model = DistilBertModel.from_pretrained("distilbert-base-uncased")
|
| 414 |
+
input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
|
| 415 |
+
attention_mask = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 416 |
+
with torch.no_grad():
|
| 417 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 418 |
+
expected_shape = torch.Size((1, 11, 768))
|
| 419 |
+
self.assertEqual(output.shape, expected_shape)
|
| 420 |
+
expected_slice = torch.tensor(
|
| 421 |
+
[[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
self.assertTrue(torch.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
|
| 425 |
+
|
| 426 |
+
@slow
|
| 427 |
+
def test_export(self):
|
| 428 |
+
if not is_torch_greater_or_equal_than_2_4:
|
| 429 |
+
self.skipTest(reason="This test requires torch >= 2.4 to run.")
|
| 430 |
+
|
| 431 |
+
distilbert_model = "distilbert-base-uncased"
|
| 432 |
+
device = "cpu"
|
| 433 |
+
attn_implementation = "sdpa"
|
| 434 |
+
max_length = 64
|
| 435 |
+
|
| 436 |
+
tokenizer = AutoTokenizer.from_pretrained(distilbert_model)
|
| 437 |
+
inputs = tokenizer(
|
| 438 |
+
f"Paris is the {tokenizer.mask_token} of France.",
|
| 439 |
+
return_tensors="pt",
|
| 440 |
+
padding="max_length",
|
| 441 |
+
max_length=max_length,
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
model = DistilBertForMaskedLM.from_pretrained(
|
| 445 |
+
distilbert_model,
|
| 446 |
+
device_map=device,
|
| 447 |
+
attn_implementation=attn_implementation,
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
logits = model(**inputs).logits
|
| 451 |
+
eager_predicted_mask = tokenizer.decode(logits[0, 4].topk(5).indices)
|
| 452 |
+
self.assertEqual(
|
| 453 |
+
eager_predicted_mask.split(),
|
| 454 |
+
["capital", "birthplace", "northernmost", "centre", "southernmost"],
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
exported_program = torch.export.export(
|
| 458 |
+
model,
|
| 459 |
+
args=(inputs["input_ids"],),
|
| 460 |
+
kwargs={"attention_mask": inputs["attention_mask"]},
|
| 461 |
+
strict=True,
|
| 462 |
+
)
|
| 463 |
+
|
| 464 |
+
result = exported_program.module().forward(inputs["input_ids"], inputs["attention_mask"])
|
| 465 |
+
exported_predicted_mask = tokenizer.decode(result.logits[0, 4].topk(5).indices)
|
| 466 |
+
self.assertEqual(eager_predicted_mask, exported_predicted_mask)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_flax_distilbert.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from transformers import DistilBertConfig, is_flax_available
|
| 20 |
+
from transformers.testing_utils import require_flax, slow
|
| 21 |
+
|
| 22 |
+
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
if is_flax_available():
|
| 26 |
+
import jax.numpy as jnp
|
| 27 |
+
|
| 28 |
+
from transformers.models.distilbert.modeling_flax_distilbert import (
|
| 29 |
+
FlaxDistilBertForMaskedLM,
|
| 30 |
+
FlaxDistilBertForMultipleChoice,
|
| 31 |
+
FlaxDistilBertForQuestionAnswering,
|
| 32 |
+
FlaxDistilBertForSequenceClassification,
|
| 33 |
+
FlaxDistilBertForTokenClassification,
|
| 34 |
+
FlaxDistilBertModel,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FlaxDistilBertModelTester(unittest.TestCase):
|
| 39 |
+
def __init__(
|
| 40 |
+
self,
|
| 41 |
+
parent,
|
| 42 |
+
batch_size=13,
|
| 43 |
+
seq_length=7,
|
| 44 |
+
is_training=True,
|
| 45 |
+
use_attention_mask=True,
|
| 46 |
+
use_token_type_ids=True,
|
| 47 |
+
use_labels=True,
|
| 48 |
+
vocab_size=99,
|
| 49 |
+
hidden_size=32,
|
| 50 |
+
num_hidden_layers=2,
|
| 51 |
+
num_attention_heads=4,
|
| 52 |
+
intermediate_size=37,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
hidden_dropout_prob=0.1,
|
| 55 |
+
attention_probs_dropout_prob=0.1,
|
| 56 |
+
max_position_embeddings=512,
|
| 57 |
+
type_vocab_size=16,
|
| 58 |
+
type_sequence_label_size=2,
|
| 59 |
+
initializer_range=0.02,
|
| 60 |
+
num_choices=4,
|
| 61 |
+
):
|
| 62 |
+
self.parent = parent
|
| 63 |
+
self.batch_size = batch_size
|
| 64 |
+
self.seq_length = seq_length
|
| 65 |
+
self.is_training = is_training
|
| 66 |
+
self.use_attention_mask = use_attention_mask
|
| 67 |
+
self.use_token_type_ids = use_token_type_ids
|
| 68 |
+
self.use_labels = use_labels
|
| 69 |
+
self.vocab_size = vocab_size
|
| 70 |
+
self.hidden_size = hidden_size
|
| 71 |
+
self.num_hidden_layers = num_hidden_layers
|
| 72 |
+
self.num_attention_heads = num_attention_heads
|
| 73 |
+
self.intermediate_size = intermediate_size
|
| 74 |
+
self.hidden_act = hidden_act
|
| 75 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 76 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 77 |
+
self.max_position_embeddings = max_position_embeddings
|
| 78 |
+
self.type_vocab_size = type_vocab_size
|
| 79 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 80 |
+
self.initializer_range = initializer_range
|
| 81 |
+
self.num_choices = num_choices
|
| 82 |
+
super().__init__()
|
| 83 |
+
|
| 84 |
+
def prepare_config_and_inputs(self):
|
| 85 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 86 |
+
|
| 87 |
+
attention_mask = None
|
| 88 |
+
if self.use_attention_mask:
|
| 89 |
+
attention_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 90 |
+
|
| 91 |
+
config = DistilBertConfig(
|
| 92 |
+
vocab_size=self.vocab_size,
|
| 93 |
+
dim=self.hidden_size,
|
| 94 |
+
n_layers=self.num_hidden_layers,
|
| 95 |
+
n_heads=self.num_attention_heads,
|
| 96 |
+
hidden_dim=self.intermediate_size,
|
| 97 |
+
hidden_act=self.hidden_act,
|
| 98 |
+
dropout=self.hidden_dropout_prob,
|
| 99 |
+
attention_dropout=self.attention_probs_dropout_prob,
|
| 100 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 101 |
+
initializer_range=self.initializer_range,
|
| 102 |
+
tie_weights_=True,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
return config, input_ids, attention_mask
|
| 106 |
+
|
| 107 |
+
def prepare_config_and_inputs_for_common(self):
|
| 108 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 109 |
+
config, input_ids, attention_mask = config_and_inputs
|
| 110 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 111 |
+
return config, inputs_dict
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
@require_flax
|
| 115 |
+
class FlaxDistilBertModelTest(FlaxModelTesterMixin, unittest.TestCase):
|
| 116 |
+
all_model_classes = (
|
| 117 |
+
(
|
| 118 |
+
FlaxDistilBertModel,
|
| 119 |
+
FlaxDistilBertForMaskedLM,
|
| 120 |
+
FlaxDistilBertForMultipleChoice,
|
| 121 |
+
FlaxDistilBertForQuestionAnswering,
|
| 122 |
+
FlaxDistilBertForSequenceClassification,
|
| 123 |
+
FlaxDistilBertForTokenClassification,
|
| 124 |
+
FlaxDistilBertForQuestionAnswering,
|
| 125 |
+
)
|
| 126 |
+
if is_flax_available()
|
| 127 |
+
else ()
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
def setUp(self):
|
| 131 |
+
self.model_tester = FlaxDistilBertModelTester(self)
|
| 132 |
+
|
| 133 |
+
@slow
|
| 134 |
+
def test_model_from_pretrained(self):
|
| 135 |
+
for model_class_name in self.all_model_classes:
|
| 136 |
+
model = model_class_name.from_pretrained("distilbert-base-uncased")
|
| 137 |
+
outputs = model(np.ones((1, 1)))
|
| 138 |
+
self.assertIsNotNone(outputs)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
@require_flax
|
| 142 |
+
class FlaxDistilBertModelIntegrationTest(unittest.TestCase):
|
| 143 |
+
@slow
|
| 144 |
+
def test_inference_no_head_absolute_embedding(self):
|
| 145 |
+
model = FlaxDistilBertModel.from_pretrained("distilbert-base-uncased")
|
| 146 |
+
input_ids = np.array([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]])
|
| 147 |
+
attention_mask = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
|
| 148 |
+
output = model(input_ids, attention_mask=attention_mask)[0]
|
| 149 |
+
expected_shape = (1, 11, 768)
|
| 150 |
+
self.assertEqual(output.shape, expected_shape)
|
| 151 |
+
expected_slice = np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]])
|
| 152 |
+
|
| 153 |
+
self.assertTrue(jnp.allclose(output[:, 1:4, 1:4], expected_slice, atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_modeling_tf_distilbert.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
from transformers import DistilBertConfig, is_tf_available
|
| 22 |
+
from transformers.testing_utils import require_tf, slow
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_tf_available():
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
from transformers.models.distilbert.modeling_tf_distilbert import (
|
| 33 |
+
TFDistilBertForMaskedLM,
|
| 34 |
+
TFDistilBertForMultipleChoice,
|
| 35 |
+
TFDistilBertForQuestionAnswering,
|
| 36 |
+
TFDistilBertForSequenceClassification,
|
| 37 |
+
TFDistilBertForTokenClassification,
|
| 38 |
+
TFDistilBertModel,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class TFDistilBertModelTester:
|
| 43 |
+
def __init__(
|
| 44 |
+
self,
|
| 45 |
+
parent,
|
| 46 |
+
):
|
| 47 |
+
self.parent = parent
|
| 48 |
+
self.batch_size = 13
|
| 49 |
+
self.seq_length = 7
|
| 50 |
+
self.is_training = True
|
| 51 |
+
self.use_input_mask = True
|
| 52 |
+
self.use_token_type_ids = False
|
| 53 |
+
self.use_labels = True
|
| 54 |
+
self.vocab_size = 99
|
| 55 |
+
self.hidden_size = 32
|
| 56 |
+
self.num_hidden_layers = 2
|
| 57 |
+
self.num_attention_heads = 4
|
| 58 |
+
self.intermediate_size = 37
|
| 59 |
+
self.hidden_act = "gelu"
|
| 60 |
+
self.hidden_dropout_prob = 0.1
|
| 61 |
+
self.attention_probs_dropout_prob = 0.1
|
| 62 |
+
self.max_position_embeddings = 512
|
| 63 |
+
self.type_vocab_size = 16
|
| 64 |
+
self.type_sequence_label_size = 2
|
| 65 |
+
self.initializer_range = 0.02
|
| 66 |
+
self.num_labels = 3
|
| 67 |
+
self.num_choices = 4
|
| 68 |
+
self.scope = None
|
| 69 |
+
|
| 70 |
+
def prepare_config_and_inputs(self):
|
| 71 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 72 |
+
|
| 73 |
+
input_mask = None
|
| 74 |
+
if self.use_input_mask:
|
| 75 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 76 |
+
|
| 77 |
+
sequence_labels = None
|
| 78 |
+
token_labels = None
|
| 79 |
+
choice_labels = None
|
| 80 |
+
if self.use_labels:
|
| 81 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 82 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 83 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 84 |
+
|
| 85 |
+
config = DistilBertConfig(
|
| 86 |
+
vocab_size=self.vocab_size,
|
| 87 |
+
dim=self.hidden_size,
|
| 88 |
+
n_layers=self.num_hidden_layers,
|
| 89 |
+
n_heads=self.num_attention_heads,
|
| 90 |
+
hidden_dim=self.intermediate_size,
|
| 91 |
+
hidden_act=self.hidden_act,
|
| 92 |
+
dropout=self.hidden_dropout_prob,
|
| 93 |
+
attention_dropout=self.attention_probs_dropout_prob,
|
| 94 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 95 |
+
initializer_range=self.initializer_range,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 99 |
+
|
| 100 |
+
def create_and_check_distilbert_model(
|
| 101 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 102 |
+
):
|
| 103 |
+
model = TFDistilBertModel(config=config)
|
| 104 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 105 |
+
|
| 106 |
+
result = model(inputs)
|
| 107 |
+
|
| 108 |
+
inputs = [input_ids, input_mask]
|
| 109 |
+
|
| 110 |
+
result = model(inputs)
|
| 111 |
+
|
| 112 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
|
| 113 |
+
|
| 114 |
+
def create_and_check_distilbert_for_masked_lm(
|
| 115 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 116 |
+
):
|
| 117 |
+
model = TFDistilBertForMaskedLM(config=config)
|
| 118 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 119 |
+
result = model(inputs)
|
| 120 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
|
| 121 |
+
|
| 122 |
+
def create_and_check_distilbert_for_question_answering(
|
| 123 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 124 |
+
):
|
| 125 |
+
model = TFDistilBertForQuestionAnswering(config=config)
|
| 126 |
+
inputs = {
|
| 127 |
+
"input_ids": input_ids,
|
| 128 |
+
"attention_mask": input_mask,
|
| 129 |
+
}
|
| 130 |
+
result = model(inputs)
|
| 131 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 132 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 133 |
+
|
| 134 |
+
def create_and_check_distilbert_for_sequence_classification(
|
| 135 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 136 |
+
):
|
| 137 |
+
config.num_labels = self.num_labels
|
| 138 |
+
model = TFDistilBertForSequenceClassification(config)
|
| 139 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 140 |
+
result = model(inputs)
|
| 141 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
|
| 142 |
+
|
| 143 |
+
def create_and_check_distilbert_for_multiple_choice(
|
| 144 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 145 |
+
):
|
| 146 |
+
config.num_choices = self.num_choices
|
| 147 |
+
model = TFDistilBertForMultipleChoice(config)
|
| 148 |
+
multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
|
| 149 |
+
multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
|
| 150 |
+
inputs = {
|
| 151 |
+
"input_ids": multiple_choice_inputs_ids,
|
| 152 |
+
"attention_mask": multiple_choice_input_mask,
|
| 153 |
+
}
|
| 154 |
+
result = model(inputs)
|
| 155 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
|
| 156 |
+
|
| 157 |
+
def create_and_check_distilbert_for_token_classification(
|
| 158 |
+
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 159 |
+
):
|
| 160 |
+
config.num_labels = self.num_labels
|
| 161 |
+
model = TFDistilBertForTokenClassification(config)
|
| 162 |
+
inputs = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 163 |
+
result = model(inputs)
|
| 164 |
+
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
|
| 165 |
+
|
| 166 |
+
def prepare_config_and_inputs_for_common(self):
|
| 167 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 168 |
+
(config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
|
| 169 |
+
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
|
| 170 |
+
return config, inputs_dict
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@require_tf
|
| 174 |
+
class TFDistilBertModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 175 |
+
all_model_classes = (
|
| 176 |
+
(
|
| 177 |
+
TFDistilBertModel,
|
| 178 |
+
TFDistilBertForMaskedLM,
|
| 179 |
+
TFDistilBertForQuestionAnswering,
|
| 180 |
+
TFDistilBertForSequenceClassification,
|
| 181 |
+
TFDistilBertForTokenClassification,
|
| 182 |
+
TFDistilBertForMultipleChoice,
|
| 183 |
+
)
|
| 184 |
+
if is_tf_available()
|
| 185 |
+
else None
|
| 186 |
+
)
|
| 187 |
+
pipeline_model_mapping = (
|
| 188 |
+
{
|
| 189 |
+
"feature-extraction": TFDistilBertModel,
|
| 190 |
+
"fill-mask": TFDistilBertForMaskedLM,
|
| 191 |
+
"question-answering": TFDistilBertForQuestionAnswering,
|
| 192 |
+
"text-classification": TFDistilBertForSequenceClassification,
|
| 193 |
+
"token-classification": TFDistilBertForTokenClassification,
|
| 194 |
+
"zero-shot": TFDistilBertForSequenceClassification,
|
| 195 |
+
}
|
| 196 |
+
if is_tf_available()
|
| 197 |
+
else {}
|
| 198 |
+
)
|
| 199 |
+
test_head_masking = False
|
| 200 |
+
test_onnx = False
|
| 201 |
+
|
| 202 |
+
def setUp(self):
|
| 203 |
+
self.model_tester = TFDistilBertModelTester(self)
|
| 204 |
+
self.config_tester = ConfigTester(self, config_class=DistilBertConfig, dim=37)
|
| 205 |
+
|
| 206 |
+
def test_config(self):
|
| 207 |
+
self.config_tester.run_common_tests()
|
| 208 |
+
|
| 209 |
+
def test_distilbert_model(self):
|
| 210 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 211 |
+
self.model_tester.create_and_check_distilbert_model(*config_and_inputs)
|
| 212 |
+
|
| 213 |
+
def test_for_masked_lm(self):
|
| 214 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 215 |
+
self.model_tester.create_and_check_distilbert_for_masked_lm(*config_and_inputs)
|
| 216 |
+
|
| 217 |
+
def test_for_question_answering(self):
|
| 218 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 219 |
+
self.model_tester.create_and_check_distilbert_for_question_answering(*config_and_inputs)
|
| 220 |
+
|
| 221 |
+
def test_for_sequence_classification(self):
|
| 222 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 223 |
+
self.model_tester.create_and_check_distilbert_for_sequence_classification(*config_and_inputs)
|
| 224 |
+
|
| 225 |
+
def test_for_multiple_choice(self):
|
| 226 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 227 |
+
self.model_tester.create_and_check_distilbert_for_multiple_choice(*config_and_inputs)
|
| 228 |
+
|
| 229 |
+
def test_for_token_classification(self):
|
| 230 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 231 |
+
self.model_tester.create_and_check_distilbert_for_token_classification(*config_and_inputs)
|
| 232 |
+
|
| 233 |
+
@slow
|
| 234 |
+
def test_model_from_pretrained(self):
|
| 235 |
+
model_name = "distilbert/distilbert-base-cased"
|
| 236 |
+
model = TFDistilBertModel.from_pretrained(model_name)
|
| 237 |
+
self.assertIsNotNone(model)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@require_tf
|
| 241 |
+
class TFDistilBertModelIntegrationTest(unittest.TestCase):
|
| 242 |
+
@slow
|
| 243 |
+
def test_inference_masked_lm(self):
|
| 244 |
+
model = TFDistilBertModel.from_pretrained("distilbert-base-uncased")
|
| 245 |
+
input_ids = tf.constant([[0, 1, 2, 3, 4, 5]])
|
| 246 |
+
output = model(input_ids)[0]
|
| 247 |
+
|
| 248 |
+
expected_shape = [1, 6, 768]
|
| 249 |
+
self.assertEqual(output.shape, expected_shape)
|
| 250 |
+
|
| 251 |
+
expected_slice = tf.constant(
|
| 252 |
+
[
|
| 253 |
+
[
|
| 254 |
+
[0.19261885, -0.13732955, 0.4119799],
|
| 255 |
+
[0.22150156, -0.07422661, 0.39037204],
|
| 256 |
+
[0.22756018, -0.0896414, 0.3701467],
|
| 257 |
+
]
|
| 258 |
+
]
|
| 259 |
+
)
|
| 260 |
+
tf.debugging.assert_near(output[:, :3, :3], expected_slice, atol=1e-4)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/distilbert/test_tokenization_distilbert.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
from transformers import DistilBertTokenizer, DistilBertTokenizerFast
|
| 18 |
+
from transformers.testing_utils import require_tokenizers, slow
|
| 19 |
+
|
| 20 |
+
from ..bert.test_tokenization_bert import BertTokenizationTest
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
@require_tokenizers
|
| 24 |
+
class DistilBertTokenizationTest(BertTokenizationTest):
|
| 25 |
+
tokenizer_class = DistilBertTokenizer
|
| 26 |
+
rust_tokenizer_class = DistilBertTokenizerFast
|
| 27 |
+
test_rust_tokenizer = True
|
| 28 |
+
from_pretrained_id = "distilbert/distilbert-base-uncased"
|
| 29 |
+
|
| 30 |
+
@slow
|
| 31 |
+
def test_sequence_builders(self):
|
| 32 |
+
tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased")
|
| 33 |
+
|
| 34 |
+
text = tokenizer.encode("sequence builders", add_special_tokens=False)
|
| 35 |
+
text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
|
| 36 |
+
|
| 37 |
+
encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
|
| 38 |
+
encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
|
| 39 |
+
|
| 40 |
+
assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
|
| 41 |
+
assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [
|
| 42 |
+
tokenizer.sep_token_id
|
| 43 |
+
]
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dit/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dit/test_modeling_dit.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
from transformers import is_torch_available, is_vision_available
|
| 19 |
+
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if is_torch_available():
|
| 23 |
+
import torch
|
| 24 |
+
|
| 25 |
+
from transformers import AutoModelForImageClassification
|
| 26 |
+
|
| 27 |
+
if is_vision_available():
|
| 28 |
+
from transformers import AutoImageProcessor
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@require_torch
|
| 32 |
+
@require_vision
|
| 33 |
+
class DiTIntegrationTest(unittest.TestCase):
|
| 34 |
+
@slow
|
| 35 |
+
def test_for_image_classification(self):
|
| 36 |
+
image_processor = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip")
|
| 37 |
+
model = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip")
|
| 38 |
+
model.to(torch_device)
|
| 39 |
+
|
| 40 |
+
from datasets import load_dataset
|
| 41 |
+
|
| 42 |
+
dataset = load_dataset("nielsr/rvlcdip-demo")
|
| 43 |
+
|
| 44 |
+
image = dataset["train"][0]["image"].convert("RGB")
|
| 45 |
+
|
| 46 |
+
inputs = image_processor(image, return_tensors="pt").to(torch_device)
|
| 47 |
+
|
| 48 |
+
# forward pass
|
| 49 |
+
with torch.no_grad():
|
| 50 |
+
outputs = model(**inputs)
|
| 51 |
+
logits = outputs.logits
|
| 52 |
+
|
| 53 |
+
expected_shape = torch.Size((1, 16))
|
| 54 |
+
self.assertEqual(logits.shape, expected_shape)
|
| 55 |
+
|
| 56 |
+
expected_slice = torch.tensor(
|
| 57 |
+
[-0.4158, -0.4092, -0.4347],
|
| 58 |
+
device=torch_device,
|
| 59 |
+
dtype=torch.float,
|
| 60 |
+
)
|
| 61 |
+
self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_image_processing_donut.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
|
| 21 |
+
from transformers.testing_utils import is_flaky, require_torch, require_vision
|
| 22 |
+
from transformers.utils import is_torch_available, is_vision_available
|
| 23 |
+
|
| 24 |
+
from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_torch_available():
|
| 28 |
+
import torch
|
| 29 |
+
|
| 30 |
+
if is_vision_available():
|
| 31 |
+
from PIL import Image
|
| 32 |
+
|
| 33 |
+
from transformers import DonutImageProcessor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class DonutImageProcessingTester(unittest.TestCase):
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
parent,
|
| 40 |
+
batch_size=7,
|
| 41 |
+
num_channels=3,
|
| 42 |
+
image_size=18,
|
| 43 |
+
min_resolution=30,
|
| 44 |
+
max_resolution=400,
|
| 45 |
+
do_resize=True,
|
| 46 |
+
size=None,
|
| 47 |
+
do_thumbnail=True,
|
| 48 |
+
do_align_axis=False,
|
| 49 |
+
do_pad=True,
|
| 50 |
+
do_normalize=True,
|
| 51 |
+
image_mean=[0.5, 0.5, 0.5],
|
| 52 |
+
image_std=[0.5, 0.5, 0.5],
|
| 53 |
+
):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.parent = parent
|
| 56 |
+
self.batch_size = batch_size
|
| 57 |
+
self.num_channels = num_channels
|
| 58 |
+
self.image_size = image_size
|
| 59 |
+
self.min_resolution = min_resolution
|
| 60 |
+
self.max_resolution = max_resolution
|
| 61 |
+
self.do_resize = do_resize
|
| 62 |
+
self.size = size if size is not None else {"height": 18, "width": 20}
|
| 63 |
+
self.do_thumbnail = do_thumbnail
|
| 64 |
+
self.do_align_axis = do_align_axis
|
| 65 |
+
self.do_pad = do_pad
|
| 66 |
+
self.do_normalize = do_normalize
|
| 67 |
+
self.image_mean = image_mean
|
| 68 |
+
self.image_std = image_std
|
| 69 |
+
|
| 70 |
+
def prepare_image_processor_dict(self):
|
| 71 |
+
return {
|
| 72 |
+
"do_resize": self.do_resize,
|
| 73 |
+
"size": self.size,
|
| 74 |
+
"do_thumbnail": self.do_thumbnail,
|
| 75 |
+
"do_align_long_axis": self.do_align_axis,
|
| 76 |
+
"do_pad": self.do_pad,
|
| 77 |
+
"do_normalize": self.do_normalize,
|
| 78 |
+
"image_mean": self.image_mean,
|
| 79 |
+
"image_std": self.image_std,
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
def expected_output_image_shape(self, images):
|
| 83 |
+
return self.num_channels, self.size["height"], self.size["width"]
|
| 84 |
+
|
| 85 |
+
def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
|
| 86 |
+
return prepare_image_inputs(
|
| 87 |
+
batch_size=self.batch_size,
|
| 88 |
+
num_channels=self.num_channels,
|
| 89 |
+
min_resolution=self.min_resolution,
|
| 90 |
+
max_resolution=self.max_resolution,
|
| 91 |
+
equal_resolution=equal_resolution,
|
| 92 |
+
numpify=numpify,
|
| 93 |
+
torchify=torchify,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@require_torch
|
| 98 |
+
@require_vision
|
| 99 |
+
class DonutImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
|
| 100 |
+
image_processing_class = DonutImageProcessor if is_vision_available() else None
|
| 101 |
+
|
| 102 |
+
def setUp(self):
|
| 103 |
+
super().setUp()
|
| 104 |
+
self.image_processor_tester = DonutImageProcessingTester(self)
|
| 105 |
+
|
| 106 |
+
@property
|
| 107 |
+
def image_processor_dict(self):
|
| 108 |
+
return self.image_processor_tester.prepare_image_processor_dict()
|
| 109 |
+
|
| 110 |
+
def test_image_processor_properties(self):
|
| 111 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 112 |
+
self.assertTrue(hasattr(image_processing, "do_resize"))
|
| 113 |
+
self.assertTrue(hasattr(image_processing, "size"))
|
| 114 |
+
self.assertTrue(hasattr(image_processing, "do_thumbnail"))
|
| 115 |
+
self.assertTrue(hasattr(image_processing, "do_align_long_axis"))
|
| 116 |
+
self.assertTrue(hasattr(image_processing, "do_pad"))
|
| 117 |
+
self.assertTrue(hasattr(image_processing, "do_normalize"))
|
| 118 |
+
self.assertTrue(hasattr(image_processing, "image_mean"))
|
| 119 |
+
self.assertTrue(hasattr(image_processing, "image_std"))
|
| 120 |
+
|
| 121 |
+
def test_image_processor_from_dict_with_kwargs(self):
|
| 122 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
|
| 123 |
+
self.assertEqual(image_processor.size, {"height": 18, "width": 20})
|
| 124 |
+
|
| 125 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42)
|
| 126 |
+
self.assertEqual(image_processor.size, {"height": 42, "width": 42})
|
| 127 |
+
|
| 128 |
+
# Previous config had dimensions in (width, height) order
|
| 129 |
+
image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=(42, 84))
|
| 130 |
+
self.assertEqual(image_processor.size, {"height": 84, "width": 42})
|
| 131 |
+
|
| 132 |
+
@is_flaky()
|
| 133 |
+
def test_call_pil(self):
|
| 134 |
+
# Initialize image_processing
|
| 135 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 136 |
+
# create random PIL images
|
| 137 |
+
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
|
| 138 |
+
for image in image_inputs:
|
| 139 |
+
self.assertIsInstance(image, Image.Image)
|
| 140 |
+
|
| 141 |
+
# Test not batched input
|
| 142 |
+
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
| 143 |
+
self.assertEqual(
|
| 144 |
+
encoded_images.shape,
|
| 145 |
+
(
|
| 146 |
+
1,
|
| 147 |
+
self.image_processor_tester.num_channels,
|
| 148 |
+
self.image_processor_tester.size["height"],
|
| 149 |
+
self.image_processor_tester.size["width"],
|
| 150 |
+
),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Test batched
|
| 154 |
+
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
| 155 |
+
self.assertEqual(
|
| 156 |
+
encoded_images.shape,
|
| 157 |
+
(
|
| 158 |
+
self.image_processor_tester.batch_size,
|
| 159 |
+
self.image_processor_tester.num_channels,
|
| 160 |
+
self.image_processor_tester.size["height"],
|
| 161 |
+
self.image_processor_tester.size["width"],
|
| 162 |
+
),
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
@is_flaky()
|
| 166 |
+
def test_call_numpy(self):
|
| 167 |
+
# Initialize image_processing
|
| 168 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 169 |
+
# create random numpy tensors
|
| 170 |
+
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
|
| 171 |
+
for image in image_inputs:
|
| 172 |
+
self.assertIsInstance(image, np.ndarray)
|
| 173 |
+
|
| 174 |
+
# Test not batched input
|
| 175 |
+
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
| 176 |
+
self.assertEqual(
|
| 177 |
+
encoded_images.shape,
|
| 178 |
+
(
|
| 179 |
+
1,
|
| 180 |
+
self.image_processor_tester.num_channels,
|
| 181 |
+
self.image_processor_tester.size["height"],
|
| 182 |
+
self.image_processor_tester.size["width"],
|
| 183 |
+
),
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# Test batched
|
| 187 |
+
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
| 188 |
+
self.assertEqual(
|
| 189 |
+
encoded_images.shape,
|
| 190 |
+
(
|
| 191 |
+
self.image_processor_tester.batch_size,
|
| 192 |
+
self.image_processor_tester.num_channels,
|
| 193 |
+
self.image_processor_tester.size["height"],
|
| 194 |
+
self.image_processor_tester.size["width"],
|
| 195 |
+
),
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
@is_flaky()
|
| 199 |
+
def test_call_pytorch(self):
|
| 200 |
+
# Initialize image_processing
|
| 201 |
+
image_processing = self.image_processing_class(**self.image_processor_dict)
|
| 202 |
+
# create random PyTorch tensors
|
| 203 |
+
image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
|
| 204 |
+
for image in image_inputs:
|
| 205 |
+
self.assertIsInstance(image, torch.Tensor)
|
| 206 |
+
|
| 207 |
+
# Test not batched input
|
| 208 |
+
encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
|
| 209 |
+
self.assertEqual(
|
| 210 |
+
encoded_images.shape,
|
| 211 |
+
(
|
| 212 |
+
1,
|
| 213 |
+
self.image_processor_tester.num_channels,
|
| 214 |
+
self.image_processor_tester.size["height"],
|
| 215 |
+
self.image_processor_tester.size["width"],
|
| 216 |
+
),
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
# Test batched
|
| 220 |
+
encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
|
| 221 |
+
self.assertEqual(
|
| 222 |
+
encoded_images.shape,
|
| 223 |
+
(
|
| 224 |
+
self.image_processor_tester.batch_size,
|
| 225 |
+
self.image_processor_tester.num_channels,
|
| 226 |
+
self.image_processor_tester.size["height"],
|
| 227 |
+
self.image_processor_tester.size["width"],
|
| 228 |
+
),
|
| 229 |
+
)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_modeling_donut_swin.py
ADDED
|
@@ -0,0 +1,349 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
"""Testing suite for the PyTorch Donut Swin model."""
|
| 16 |
+
|
| 17 |
+
import collections
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import DonutSwinConfig
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
from transformers.utils import is_torch_available
|
| 23 |
+
|
| 24 |
+
from ...test_configuration_common import ConfigTester
|
| 25 |
+
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
|
| 26 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_torch_available():
|
| 30 |
+
import torch
|
| 31 |
+
from torch import nn
|
| 32 |
+
|
| 33 |
+
from transformers import DonutSwinModel
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class DonutSwinModelTester:
|
| 37 |
+
def __init__(
|
| 38 |
+
self,
|
| 39 |
+
parent,
|
| 40 |
+
batch_size=13,
|
| 41 |
+
image_size=32,
|
| 42 |
+
patch_size=2,
|
| 43 |
+
num_channels=3,
|
| 44 |
+
embed_dim=16,
|
| 45 |
+
depths=[1, 2, 1],
|
| 46 |
+
num_heads=[2, 2, 4],
|
| 47 |
+
window_size=2,
|
| 48 |
+
mlp_ratio=2.0,
|
| 49 |
+
qkv_bias=True,
|
| 50 |
+
hidden_dropout_prob=0.0,
|
| 51 |
+
attention_probs_dropout_prob=0.0,
|
| 52 |
+
drop_path_rate=0.1,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
use_absolute_embeddings=False,
|
| 55 |
+
patch_norm=True,
|
| 56 |
+
initializer_range=0.02,
|
| 57 |
+
layer_norm_eps=1e-5,
|
| 58 |
+
is_training=True,
|
| 59 |
+
scope=None,
|
| 60 |
+
use_labels=True,
|
| 61 |
+
type_sequence_label_size=10,
|
| 62 |
+
encoder_stride=8,
|
| 63 |
+
):
|
| 64 |
+
self.parent = parent
|
| 65 |
+
self.batch_size = batch_size
|
| 66 |
+
self.image_size = image_size
|
| 67 |
+
self.patch_size = patch_size
|
| 68 |
+
self.num_channels = num_channels
|
| 69 |
+
self.embed_dim = embed_dim
|
| 70 |
+
self.depths = depths
|
| 71 |
+
self.num_heads = num_heads
|
| 72 |
+
self.window_size = window_size
|
| 73 |
+
self.mlp_ratio = mlp_ratio
|
| 74 |
+
self.qkv_bias = qkv_bias
|
| 75 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 76 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 77 |
+
self.drop_path_rate = drop_path_rate
|
| 78 |
+
self.hidden_act = hidden_act
|
| 79 |
+
self.use_absolute_embeddings = use_absolute_embeddings
|
| 80 |
+
self.patch_norm = patch_norm
|
| 81 |
+
self.layer_norm_eps = layer_norm_eps
|
| 82 |
+
self.initializer_range = initializer_range
|
| 83 |
+
self.is_training = is_training
|
| 84 |
+
self.scope = scope
|
| 85 |
+
self.use_labels = use_labels
|
| 86 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 87 |
+
self.encoder_stride = encoder_stride
|
| 88 |
+
|
| 89 |
+
def prepare_config_and_inputs(self):
|
| 90 |
+
pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
|
| 91 |
+
|
| 92 |
+
labels = None
|
| 93 |
+
if self.use_labels:
|
| 94 |
+
labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 95 |
+
|
| 96 |
+
config = self.get_config()
|
| 97 |
+
|
| 98 |
+
return config, pixel_values, labels
|
| 99 |
+
|
| 100 |
+
def get_config(self):
|
| 101 |
+
return DonutSwinConfig(
|
| 102 |
+
image_size=self.image_size,
|
| 103 |
+
patch_size=self.patch_size,
|
| 104 |
+
num_channels=self.num_channels,
|
| 105 |
+
embed_dim=self.embed_dim,
|
| 106 |
+
depths=self.depths,
|
| 107 |
+
num_heads=self.num_heads,
|
| 108 |
+
window_size=self.window_size,
|
| 109 |
+
mlp_ratio=self.mlp_ratio,
|
| 110 |
+
qkv_bias=self.qkv_bias,
|
| 111 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 112 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 113 |
+
drop_path_rate=self.drop_path_rate,
|
| 114 |
+
hidden_act=self.hidden_act,
|
| 115 |
+
use_absolute_embeddings=self.use_absolute_embeddings,
|
| 116 |
+
path_norm=self.patch_norm,
|
| 117 |
+
layer_norm_eps=self.layer_norm_eps,
|
| 118 |
+
initializer_range=self.initializer_range,
|
| 119 |
+
encoder_stride=self.encoder_stride,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
def create_and_check_model(self, config, pixel_values, labels):
|
| 123 |
+
model = DonutSwinModel(config=config)
|
| 124 |
+
model.to(torch_device)
|
| 125 |
+
model.eval()
|
| 126 |
+
result = model(pixel_values)
|
| 127 |
+
|
| 128 |
+
expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1))
|
| 129 |
+
expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1))
|
| 130 |
+
|
| 131 |
+
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim))
|
| 132 |
+
|
| 133 |
+
def prepare_config_and_inputs_for_common(self):
|
| 134 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 135 |
+
(
|
| 136 |
+
config,
|
| 137 |
+
pixel_values,
|
| 138 |
+
labels,
|
| 139 |
+
) = config_and_inputs
|
| 140 |
+
inputs_dict = {"pixel_values": pixel_values}
|
| 141 |
+
return config, inputs_dict
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@require_torch
|
| 145 |
+
class DonutSwinModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 146 |
+
all_model_classes = (DonutSwinModel,) if is_torch_available() else ()
|
| 147 |
+
pipeline_model_mapping = {"image-feature-extraction": DonutSwinModel} if is_torch_available() else {}
|
| 148 |
+
fx_compatible = True
|
| 149 |
+
|
| 150 |
+
test_pruning = False
|
| 151 |
+
test_resize_embeddings = False
|
| 152 |
+
test_head_masking = False
|
| 153 |
+
|
| 154 |
+
def setUp(self):
|
| 155 |
+
self.model_tester = DonutSwinModelTester(self)
|
| 156 |
+
self.config_tester = ConfigTester(
|
| 157 |
+
self,
|
| 158 |
+
config_class=DonutSwinConfig,
|
| 159 |
+
has_text_modality=False,
|
| 160 |
+
embed_dim=37,
|
| 161 |
+
common_properties=["image_size", "patch_size", "num_channels"],
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def test_config(self):
|
| 165 |
+
self.config_tester.run_common_tests()
|
| 166 |
+
|
| 167 |
+
def test_model(self):
|
| 168 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 169 |
+
self.model_tester.create_and_check_model(*config_and_inputs)
|
| 170 |
+
|
| 171 |
+
@unittest.skip(reason="DonutSwin does not use inputs_embeds")
|
| 172 |
+
def test_inputs_embeds(self):
|
| 173 |
+
pass
|
| 174 |
+
|
| 175 |
+
def test_model_get_set_embeddings(self):
|
| 176 |
+
config, _ = self.model_tester.prepare_config_and_inputs_for_common()
|
| 177 |
+
|
| 178 |
+
for model_class in self.all_model_classes:
|
| 179 |
+
model = model_class(config)
|
| 180 |
+
self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
|
| 181 |
+
x = model.get_output_embeddings()
|
| 182 |
+
self.assertTrue(x is None or isinstance(x, nn.Linear))
|
| 183 |
+
|
| 184 |
+
def test_attention_outputs(self):
|
| 185 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 186 |
+
config.return_dict = True
|
| 187 |
+
|
| 188 |
+
for model_class in self.all_model_classes:
|
| 189 |
+
inputs_dict["output_attentions"] = True
|
| 190 |
+
inputs_dict["output_hidden_states"] = False
|
| 191 |
+
config.return_dict = True
|
| 192 |
+
model = model_class(config)
|
| 193 |
+
model.to(torch_device)
|
| 194 |
+
model.eval()
|
| 195 |
+
with torch.no_grad():
|
| 196 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 197 |
+
attentions = outputs.attentions
|
| 198 |
+
expected_num_attentions = len(self.model_tester.depths)
|
| 199 |
+
self.assertEqual(len(attentions), expected_num_attentions)
|
| 200 |
+
|
| 201 |
+
# check that output_attentions also work using config
|
| 202 |
+
del inputs_dict["output_attentions"]
|
| 203 |
+
config.output_attentions = True
|
| 204 |
+
window_size_squared = config.window_size**2
|
| 205 |
+
model = model_class(config)
|
| 206 |
+
model.to(torch_device)
|
| 207 |
+
model.eval()
|
| 208 |
+
with torch.no_grad():
|
| 209 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 210 |
+
attentions = outputs.attentions
|
| 211 |
+
self.assertEqual(len(attentions), expected_num_attentions)
|
| 212 |
+
|
| 213 |
+
self.assertListEqual(
|
| 214 |
+
list(attentions[0].shape[-3:]),
|
| 215 |
+
[self.model_tester.num_heads[0], window_size_squared, window_size_squared],
|
| 216 |
+
)
|
| 217 |
+
out_len = len(outputs)
|
| 218 |
+
|
| 219 |
+
# Check attention is always last and order is fine
|
| 220 |
+
inputs_dict["output_attentions"] = True
|
| 221 |
+
inputs_dict["output_hidden_states"] = True
|
| 222 |
+
model = model_class(config)
|
| 223 |
+
model.to(torch_device)
|
| 224 |
+
model.eval()
|
| 225 |
+
with torch.no_grad():
|
| 226 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 227 |
+
|
| 228 |
+
if hasattr(self.model_tester, "num_hidden_states_types"):
|
| 229 |
+
added_hidden_states = self.model_tester.num_hidden_states_types
|
| 230 |
+
else:
|
| 231 |
+
# also another +1 for reshaped_hidden_states
|
| 232 |
+
added_hidden_states = 2
|
| 233 |
+
self.assertEqual(out_len + added_hidden_states, len(outputs))
|
| 234 |
+
|
| 235 |
+
self_attentions = outputs.attentions
|
| 236 |
+
|
| 237 |
+
self.assertEqual(len(self_attentions), expected_num_attentions)
|
| 238 |
+
|
| 239 |
+
self.assertListEqual(
|
| 240 |
+
list(self_attentions[0].shape[-3:]),
|
| 241 |
+
[self.model_tester.num_heads[0], window_size_squared, window_size_squared],
|
| 242 |
+
)
|
| 243 |
+
|
| 244 |
+
def check_hidden_states_output(self, inputs_dict, config, model_class, image_size):
|
| 245 |
+
model = model_class(config)
|
| 246 |
+
model.to(torch_device)
|
| 247 |
+
model.eval()
|
| 248 |
+
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
outputs = model(**self._prepare_for_class(inputs_dict, model_class))
|
| 251 |
+
|
| 252 |
+
hidden_states = outputs.hidden_states
|
| 253 |
+
|
| 254 |
+
expected_num_layers = getattr(
|
| 255 |
+
self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1
|
| 256 |
+
)
|
| 257 |
+
self.assertEqual(len(hidden_states), expected_num_layers)
|
| 258 |
+
|
| 259 |
+
# DonutSwin has a different seq_length
|
| 260 |
+
patch_size = (
|
| 261 |
+
config.patch_size
|
| 262 |
+
if isinstance(config.patch_size, collections.abc.Iterable)
|
| 263 |
+
else (config.patch_size, config.patch_size)
|
| 264 |
+
)
|
| 265 |
+
|
| 266 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
| 267 |
+
|
| 268 |
+
self.assertListEqual(
|
| 269 |
+
list(hidden_states[0].shape[-2:]),
|
| 270 |
+
[num_patches, self.model_tester.embed_dim],
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
reshaped_hidden_states = outputs.reshaped_hidden_states
|
| 274 |
+
self.assertEqual(len(reshaped_hidden_states), expected_num_layers)
|
| 275 |
+
|
| 276 |
+
batch_size, num_channels, height, width = reshaped_hidden_states[0].shape
|
| 277 |
+
reshaped_hidden_states = (
|
| 278 |
+
reshaped_hidden_states[0].view(batch_size, num_channels, height * width).permute(0, 2, 1)
|
| 279 |
+
)
|
| 280 |
+
self.assertListEqual(
|
| 281 |
+
list(reshaped_hidden_states.shape[-2:]),
|
| 282 |
+
[num_patches, self.model_tester.embed_dim],
|
| 283 |
+
)
|
| 284 |
+
|
| 285 |
+
def test_hidden_states_output(self):
|
| 286 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 287 |
+
|
| 288 |
+
image_size = (
|
| 289 |
+
self.model_tester.image_size
|
| 290 |
+
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
|
| 291 |
+
else (self.model_tester.image_size, self.model_tester.image_size)
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
for model_class in self.all_model_classes:
|
| 295 |
+
inputs_dict["output_hidden_states"] = True
|
| 296 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
|
| 297 |
+
|
| 298 |
+
# check that output_hidden_states also work using config
|
| 299 |
+
del inputs_dict["output_hidden_states"]
|
| 300 |
+
config.output_hidden_states = True
|
| 301 |
+
|
| 302 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, image_size)
|
| 303 |
+
|
| 304 |
+
def test_hidden_states_output_with_padding(self):
|
| 305 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 306 |
+
config.patch_size = 3
|
| 307 |
+
|
| 308 |
+
image_size = (
|
| 309 |
+
self.model_tester.image_size
|
| 310 |
+
if isinstance(self.model_tester.image_size, collections.abc.Iterable)
|
| 311 |
+
else (self.model_tester.image_size, self.model_tester.image_size)
|
| 312 |
+
)
|
| 313 |
+
patch_size = (
|
| 314 |
+
config.patch_size
|
| 315 |
+
if isinstance(config.patch_size, collections.abc.Iterable)
|
| 316 |
+
else (config.patch_size, config.patch_size)
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
|
| 320 |
+
padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
|
| 321 |
+
|
| 322 |
+
for model_class in self.all_model_classes:
|
| 323 |
+
inputs_dict["output_hidden_states"] = True
|
| 324 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
|
| 325 |
+
|
| 326 |
+
# check that output_hidden_states also work using config
|
| 327 |
+
del inputs_dict["output_hidden_states"]
|
| 328 |
+
config.output_hidden_states = True
|
| 329 |
+
self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width))
|
| 330 |
+
|
| 331 |
+
@slow
|
| 332 |
+
def test_model_from_pretrained(self):
|
| 333 |
+
model_name = "naver-clova-ix/donut-base"
|
| 334 |
+
model = DonutSwinModel.from_pretrained(model_name)
|
| 335 |
+
self.assertIsNotNone(model)
|
| 336 |
+
|
| 337 |
+
def test_initialization(self):
|
| 338 |
+
config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
|
| 339 |
+
|
| 340 |
+
configs_no_init = _config_zero_init(config)
|
| 341 |
+
for model_class in self.all_model_classes:
|
| 342 |
+
model = model_class(config=configs_no_init)
|
| 343 |
+
for name, param in model.named_parameters():
|
| 344 |
+
if "embeddings" not in name and param.requires_grad:
|
| 345 |
+
self.assertIn(
|
| 346 |
+
((param.data.mean() * 1e9).round() / 1e9).item(),
|
| 347 |
+
[0.0, 1.0],
|
| 348 |
+
msg=f"Parameter {name} of model {model_class} seems not properly initialized",
|
| 349 |
+
)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/donut/test_processor_donut.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2022 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import DonutImageProcessor, DonutProcessor, XLMRobertaTokenizerFast
|
| 21 |
+
|
| 22 |
+
from ...test_processing_common import ProcessorTesterMixin
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class DonutProcessorTest(ProcessorTesterMixin, unittest.TestCase):
|
| 26 |
+
from_pretrained_id = "naver-clova-ix/donut-base"
|
| 27 |
+
processor_class = DonutProcessor
|
| 28 |
+
|
| 29 |
+
def setUp(self):
|
| 30 |
+
self.processor = DonutProcessor.from_pretrained(self.from_pretrained_id)
|
| 31 |
+
self.tmpdirname = tempfile.mkdtemp()
|
| 32 |
+
|
| 33 |
+
image_processor = DonutImageProcessor()
|
| 34 |
+
tokenizer = XLMRobertaTokenizerFast.from_pretrained(self.from_pretrained_id)
|
| 35 |
+
|
| 36 |
+
processor = DonutProcessor(image_processor, tokenizer)
|
| 37 |
+
|
| 38 |
+
processor.save_pretrained(self.tmpdirname)
|
| 39 |
+
|
| 40 |
+
def test_token2json(self):
|
| 41 |
+
expected_json = {
|
| 42 |
+
"name": "John Doe",
|
| 43 |
+
"age": "99",
|
| 44 |
+
"city": "Atlanta",
|
| 45 |
+
"state": "GA",
|
| 46 |
+
"zip": "30301",
|
| 47 |
+
"phone": "123-4567",
|
| 48 |
+
"nicknames": [{"nickname": "Johnny"}, {"nickname": "JD"}],
|
| 49 |
+
"multiline": "text\nwith\nnewlines",
|
| 50 |
+
"empty": "",
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
sequence = (
|
| 54 |
+
"<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>"
|
| 55 |
+
"<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>"
|
| 56 |
+
"<s_nicknames><s_nickname>Johnny</s_nickname>"
|
| 57 |
+
"<sep/><s_nickname>JD</s_nickname></s_nicknames>"
|
| 58 |
+
"<s_multiline>text\nwith\nnewlines</s_multiline>"
|
| 59 |
+
"<s_empty></s_empty>"
|
| 60 |
+
)
|
| 61 |
+
actual_json = self.processor.token2json(sequence)
|
| 62 |
+
|
| 63 |
+
self.assertDictEqual(actual_json, expected_json)
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_modeling_dpr.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 Huggingface
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import DPRConfig, is_torch_available
|
| 21 |
+
from transformers.testing_utils import require_torch, slow, torch_device
|
| 22 |
+
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_torch_available():
|
| 29 |
+
import torch
|
| 30 |
+
|
| 31 |
+
from transformers import DPRContextEncoder, DPRQuestionEncoder, DPRReader, DPRReaderTokenizer
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DPRModelTester:
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
parent,
|
| 38 |
+
batch_size=13,
|
| 39 |
+
seq_length=7,
|
| 40 |
+
is_training=False,
|
| 41 |
+
use_input_mask=True,
|
| 42 |
+
use_token_type_ids=True,
|
| 43 |
+
use_labels=True,
|
| 44 |
+
vocab_size=99,
|
| 45 |
+
hidden_size=32,
|
| 46 |
+
num_hidden_layers=2,
|
| 47 |
+
num_attention_heads=4,
|
| 48 |
+
intermediate_size=37,
|
| 49 |
+
hidden_act="gelu",
|
| 50 |
+
hidden_dropout_prob=0.1,
|
| 51 |
+
attention_probs_dropout_prob=0.1,
|
| 52 |
+
max_position_embeddings=512,
|
| 53 |
+
type_vocab_size=16,
|
| 54 |
+
type_sequence_label_size=2,
|
| 55 |
+
initializer_range=0.02,
|
| 56 |
+
num_labels=3,
|
| 57 |
+
num_choices=4,
|
| 58 |
+
scope=None,
|
| 59 |
+
projection_dim=0,
|
| 60 |
+
):
|
| 61 |
+
self.parent = parent
|
| 62 |
+
self.batch_size = batch_size
|
| 63 |
+
self.seq_length = seq_length
|
| 64 |
+
self.is_training = is_training
|
| 65 |
+
self.use_input_mask = use_input_mask
|
| 66 |
+
self.use_token_type_ids = use_token_type_ids
|
| 67 |
+
self.use_labels = use_labels
|
| 68 |
+
self.vocab_size = vocab_size
|
| 69 |
+
self.hidden_size = hidden_size
|
| 70 |
+
self.num_hidden_layers = num_hidden_layers
|
| 71 |
+
self.num_attention_heads = num_attention_heads
|
| 72 |
+
self.intermediate_size = intermediate_size
|
| 73 |
+
self.hidden_act = hidden_act
|
| 74 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 75 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 76 |
+
self.max_position_embeddings = max_position_embeddings
|
| 77 |
+
self.type_vocab_size = type_vocab_size
|
| 78 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 79 |
+
self.initializer_range = initializer_range
|
| 80 |
+
self.num_labels = num_labels
|
| 81 |
+
self.num_choices = num_choices
|
| 82 |
+
self.scope = scope
|
| 83 |
+
self.projection_dim = projection_dim
|
| 84 |
+
|
| 85 |
+
def prepare_config_and_inputs(self):
|
| 86 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 87 |
+
|
| 88 |
+
input_mask = None
|
| 89 |
+
if self.use_input_mask:
|
| 90 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 91 |
+
|
| 92 |
+
token_type_ids = None
|
| 93 |
+
if self.use_token_type_ids:
|
| 94 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 95 |
+
|
| 96 |
+
sequence_labels = None
|
| 97 |
+
token_labels = None
|
| 98 |
+
choice_labels = None
|
| 99 |
+
if self.use_labels:
|
| 100 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 101 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 102 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 103 |
+
|
| 104 |
+
config = self.get_config()
|
| 105 |
+
|
| 106 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 107 |
+
|
| 108 |
+
def get_config(self):
|
| 109 |
+
return DPRConfig(
|
| 110 |
+
projection_dim=self.projection_dim,
|
| 111 |
+
vocab_size=self.vocab_size,
|
| 112 |
+
hidden_size=self.hidden_size,
|
| 113 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 114 |
+
num_attention_heads=self.num_attention_heads,
|
| 115 |
+
intermediate_size=self.intermediate_size,
|
| 116 |
+
hidden_act=self.hidden_act,
|
| 117 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 118 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 119 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 120 |
+
type_vocab_size=self.type_vocab_size,
|
| 121 |
+
initializer_range=self.initializer_range,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
def create_and_check_context_encoder(
|
| 125 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 126 |
+
):
|
| 127 |
+
model = DPRContextEncoder(config=config)
|
| 128 |
+
model.to(torch_device)
|
| 129 |
+
model.eval()
|
| 130 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 131 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 132 |
+
result = model(input_ids)
|
| 133 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))
|
| 134 |
+
|
| 135 |
+
def create_and_check_question_encoder(
|
| 136 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 137 |
+
):
|
| 138 |
+
model = DPRQuestionEncoder(config=config)
|
| 139 |
+
model.to(torch_device)
|
| 140 |
+
model.eval()
|
| 141 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 142 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 143 |
+
result = model(input_ids)
|
| 144 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))
|
| 145 |
+
|
| 146 |
+
def create_and_check_reader(
|
| 147 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 148 |
+
):
|
| 149 |
+
model = DPRReader(config=config)
|
| 150 |
+
model.to(torch_device)
|
| 151 |
+
model.eval()
|
| 152 |
+
result = model(
|
| 153 |
+
input_ids,
|
| 154 |
+
attention_mask=input_mask,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 158 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 159 |
+
self.parent.assertEqual(result.relevance_logits.shape, (self.batch_size,))
|
| 160 |
+
|
| 161 |
+
def prepare_config_and_inputs_for_common(self):
|
| 162 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 163 |
+
(
|
| 164 |
+
config,
|
| 165 |
+
input_ids,
|
| 166 |
+
token_type_ids,
|
| 167 |
+
input_mask,
|
| 168 |
+
sequence_labels,
|
| 169 |
+
token_labels,
|
| 170 |
+
choice_labels,
|
| 171 |
+
) = config_and_inputs
|
| 172 |
+
inputs_dict = {"input_ids": input_ids}
|
| 173 |
+
return config, inputs_dict
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
@require_torch
|
| 177 |
+
class DPRModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 178 |
+
all_model_classes = (
|
| 179 |
+
(
|
| 180 |
+
DPRContextEncoder,
|
| 181 |
+
DPRQuestionEncoder,
|
| 182 |
+
DPRReader,
|
| 183 |
+
)
|
| 184 |
+
if is_torch_available()
|
| 185 |
+
else ()
|
| 186 |
+
)
|
| 187 |
+
pipeline_model_mapping = {"feature-extraction": DPRQuestionEncoder} if is_torch_available() else {}
|
| 188 |
+
|
| 189 |
+
test_resize_embeddings = False
|
| 190 |
+
test_missing_keys = False # why?
|
| 191 |
+
test_pruning = False
|
| 192 |
+
test_head_masking = False
|
| 193 |
+
|
| 194 |
+
def setUp(self):
|
| 195 |
+
self.model_tester = DPRModelTester(self)
|
| 196 |
+
self.config_tester = ConfigTester(self, config_class=DPRConfig, hidden_size=37)
|
| 197 |
+
|
| 198 |
+
def test_config(self):
|
| 199 |
+
self.config_tester.run_common_tests()
|
| 200 |
+
|
| 201 |
+
def test_context_encoder_model(self):
|
| 202 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 203 |
+
self.model_tester.create_and_check_context_encoder(*config_and_inputs)
|
| 204 |
+
|
| 205 |
+
def test_question_encoder_model(self):
|
| 206 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 207 |
+
self.model_tester.create_and_check_question_encoder(*config_and_inputs)
|
| 208 |
+
|
| 209 |
+
def test_reader_model(self):
|
| 210 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 211 |
+
self.model_tester.create_and_check_reader(*config_and_inputs)
|
| 212 |
+
|
| 213 |
+
def test_init_changed_config(self):
|
| 214 |
+
config = self.model_tester.prepare_config_and_inputs()[0]
|
| 215 |
+
|
| 216 |
+
model = DPRQuestionEncoder(config=config)
|
| 217 |
+
model.to(torch_device)
|
| 218 |
+
model.eval()
|
| 219 |
+
|
| 220 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 221 |
+
model.save_pretrained(tmp_dirname)
|
| 222 |
+
model = DPRQuestionEncoder.from_pretrained(tmp_dirname, projection_dim=512)
|
| 223 |
+
|
| 224 |
+
self.assertIsNotNone(model)
|
| 225 |
+
|
| 226 |
+
@slow
|
| 227 |
+
def test_model_from_pretrained(self):
|
| 228 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 229 |
+
model = DPRContextEncoder.from_pretrained(model_name)
|
| 230 |
+
self.assertIsNotNone(model)
|
| 231 |
+
|
| 232 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 233 |
+
model = DPRContextEncoder.from_pretrained(model_name)
|
| 234 |
+
self.assertIsNotNone(model)
|
| 235 |
+
|
| 236 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 237 |
+
model = DPRQuestionEncoder.from_pretrained(model_name)
|
| 238 |
+
self.assertIsNotNone(model)
|
| 239 |
+
|
| 240 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 241 |
+
model = DPRReader.from_pretrained(model_name)
|
| 242 |
+
self.assertIsNotNone(model)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
@require_torch
|
| 246 |
+
class DPRModelIntegrationTest(unittest.TestCase):
|
| 247 |
+
@slow
|
| 248 |
+
def test_inference_no_head(self):
|
| 249 |
+
model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base", return_dict=False)
|
| 250 |
+
model.to(torch_device)
|
| 251 |
+
|
| 252 |
+
input_ids = torch.tensor(
|
| 253 |
+
[[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]], dtype=torch.long, device=torch_device
|
| 254 |
+
) # [CLS] hello, is my dog cute? [SEP]
|
| 255 |
+
output = model(input_ids)[0] # embedding shape = (1, 768)
|
| 256 |
+
# compare the actual values for a slice.
|
| 257 |
+
expected_slice = torch.tensor(
|
| 258 |
+
[
|
| 259 |
+
[
|
| 260 |
+
0.03236253,
|
| 261 |
+
0.12753335,
|
| 262 |
+
0.16818509,
|
| 263 |
+
0.00279786,
|
| 264 |
+
0.3896933,
|
| 265 |
+
0.24264945,
|
| 266 |
+
0.2178971,
|
| 267 |
+
-0.02335227,
|
| 268 |
+
-0.08481959,
|
| 269 |
+
-0.14324117,
|
| 270 |
+
]
|
| 271 |
+
],
|
| 272 |
+
dtype=torch.float,
|
| 273 |
+
device=torch_device,
|
| 274 |
+
)
|
| 275 |
+
self.assertTrue(torch.allclose(output[:, :10], expected_slice, atol=1e-4))
|
| 276 |
+
|
| 277 |
+
@slow
|
| 278 |
+
def test_reader_inference(self):
|
| 279 |
+
tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 280 |
+
model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
|
| 281 |
+
model.to(torch_device)
|
| 282 |
+
|
| 283 |
+
encoded_inputs = tokenizer(
|
| 284 |
+
questions="What is love ?",
|
| 285 |
+
titles="Haddaway",
|
| 286 |
+
texts="What Is Love is a song recorded by the artist Haddaway",
|
| 287 |
+
padding=True,
|
| 288 |
+
return_tensors="pt",
|
| 289 |
+
)
|
| 290 |
+
encoded_inputs.to(torch_device)
|
| 291 |
+
|
| 292 |
+
outputs = model(**encoded_inputs)
|
| 293 |
+
|
| 294 |
+
# compare the actual values for a slice.
|
| 295 |
+
expected_start_logits = torch.tensor(
|
| 296 |
+
[[-10.3005, -10.7765, -11.4872, -11.6841, -11.9312, -10.3002, -9.8544, -11.7378, -12.0821, -10.2975]],
|
| 297 |
+
dtype=torch.float,
|
| 298 |
+
device=torch_device,
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
expected_end_logits = torch.tensor(
|
| 302 |
+
[[-11.0684, -11.7041, -11.5397, -10.3465, -10.8791, -6.8443, -11.9959, -11.0364, -10.0096, -6.8405]],
|
| 303 |
+
dtype=torch.float,
|
| 304 |
+
device=torch_device,
|
| 305 |
+
)
|
| 306 |
+
self.assertTrue(torch.allclose(outputs.start_logits[:, :10], expected_start_logits, atol=1e-4))
|
| 307 |
+
self.assertTrue(torch.allclose(outputs.end_logits[:, :10], expected_end_logits, atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_modeling_tf_dpr.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 Huggingface
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
from transformers import is_tf_available
|
| 21 |
+
from transformers.testing_utils import require_tf, slow
|
| 22 |
+
|
| 23 |
+
from ...test_configuration_common import ConfigTester
|
| 24 |
+
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
|
| 25 |
+
from ...test_pipeline_mixin import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
if is_tf_available():
|
| 29 |
+
import numpy
|
| 30 |
+
import tensorflow as tf
|
| 31 |
+
|
| 32 |
+
from transformers import (
|
| 33 |
+
BertConfig,
|
| 34 |
+
DPRConfig,
|
| 35 |
+
TFDPRContextEncoder,
|
| 36 |
+
TFDPRQuestionEncoder,
|
| 37 |
+
TFDPRReader,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class TFDPRModelTester:
|
| 42 |
+
def __init__(
|
| 43 |
+
self,
|
| 44 |
+
parent,
|
| 45 |
+
batch_size=13,
|
| 46 |
+
seq_length=7,
|
| 47 |
+
is_training=True,
|
| 48 |
+
use_input_mask=True,
|
| 49 |
+
use_token_type_ids=True,
|
| 50 |
+
use_labels=True,
|
| 51 |
+
vocab_size=99,
|
| 52 |
+
hidden_size=32,
|
| 53 |
+
num_hidden_layers=2,
|
| 54 |
+
num_attention_heads=4,
|
| 55 |
+
intermediate_size=37,
|
| 56 |
+
hidden_act="gelu",
|
| 57 |
+
hidden_dropout_prob=0.1,
|
| 58 |
+
attention_probs_dropout_prob=0.1,
|
| 59 |
+
max_position_embeddings=512,
|
| 60 |
+
type_vocab_size=16,
|
| 61 |
+
type_sequence_label_size=2,
|
| 62 |
+
initializer_range=0.02,
|
| 63 |
+
num_labels=3,
|
| 64 |
+
num_choices=4,
|
| 65 |
+
scope=None,
|
| 66 |
+
projection_dim=0,
|
| 67 |
+
):
|
| 68 |
+
self.parent = parent
|
| 69 |
+
self.batch_size = batch_size
|
| 70 |
+
self.seq_length = seq_length
|
| 71 |
+
self.is_training = is_training
|
| 72 |
+
self.use_input_mask = use_input_mask
|
| 73 |
+
self.use_token_type_ids = use_token_type_ids
|
| 74 |
+
self.use_labels = use_labels
|
| 75 |
+
self.vocab_size = vocab_size
|
| 76 |
+
self.hidden_size = hidden_size
|
| 77 |
+
self.num_hidden_layers = num_hidden_layers
|
| 78 |
+
self.num_attention_heads = num_attention_heads
|
| 79 |
+
self.intermediate_size = intermediate_size
|
| 80 |
+
self.hidden_act = hidden_act
|
| 81 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
| 82 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
| 83 |
+
self.max_position_embeddings = max_position_embeddings
|
| 84 |
+
self.type_vocab_size = type_vocab_size
|
| 85 |
+
self.type_sequence_label_size = type_sequence_label_size
|
| 86 |
+
self.initializer_range = initializer_range
|
| 87 |
+
self.num_labels = num_labels
|
| 88 |
+
self.num_choices = num_choices
|
| 89 |
+
self.scope = scope
|
| 90 |
+
self.projection_dim = projection_dim
|
| 91 |
+
|
| 92 |
+
def prepare_config_and_inputs(self):
|
| 93 |
+
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
|
| 94 |
+
|
| 95 |
+
input_mask = None
|
| 96 |
+
if self.use_input_mask:
|
| 97 |
+
# follow test_modeling_tf_ctrl.py
|
| 98 |
+
input_mask = random_attention_mask([self.batch_size, self.seq_length])
|
| 99 |
+
|
| 100 |
+
token_type_ids = None
|
| 101 |
+
if self.use_token_type_ids:
|
| 102 |
+
token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
|
| 103 |
+
|
| 104 |
+
sequence_labels = None
|
| 105 |
+
token_labels = None
|
| 106 |
+
choice_labels = None
|
| 107 |
+
if self.use_labels:
|
| 108 |
+
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
|
| 109 |
+
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
|
| 110 |
+
choice_labels = ids_tensor([self.batch_size], self.num_choices)
|
| 111 |
+
|
| 112 |
+
config = BertConfig(
|
| 113 |
+
vocab_size=self.vocab_size,
|
| 114 |
+
hidden_size=self.hidden_size,
|
| 115 |
+
num_hidden_layers=self.num_hidden_layers,
|
| 116 |
+
num_attention_heads=self.num_attention_heads,
|
| 117 |
+
intermediate_size=self.intermediate_size,
|
| 118 |
+
hidden_act=self.hidden_act,
|
| 119 |
+
hidden_dropout_prob=self.hidden_dropout_prob,
|
| 120 |
+
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
|
| 121 |
+
max_position_embeddings=self.max_position_embeddings,
|
| 122 |
+
type_vocab_size=self.type_vocab_size,
|
| 123 |
+
is_decoder=False,
|
| 124 |
+
initializer_range=self.initializer_range,
|
| 125 |
+
)
|
| 126 |
+
config = DPRConfig(projection_dim=self.projection_dim, **config.to_dict())
|
| 127 |
+
|
| 128 |
+
return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 129 |
+
|
| 130 |
+
def create_and_check_dpr_context_encoder(
|
| 131 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 132 |
+
):
|
| 133 |
+
model = TFDPRContextEncoder(config=config)
|
| 134 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 135 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 136 |
+
result = model(input_ids)
|
| 137 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))
|
| 138 |
+
|
| 139 |
+
def create_and_check_dpr_question_encoder(
|
| 140 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 141 |
+
):
|
| 142 |
+
model = TFDPRQuestionEncoder(config=config)
|
| 143 |
+
result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
|
| 144 |
+
result = model(input_ids, token_type_ids=token_type_ids)
|
| 145 |
+
result = model(input_ids)
|
| 146 |
+
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.projection_dim or self.hidden_size))
|
| 147 |
+
|
| 148 |
+
def create_and_check_dpr_reader(
|
| 149 |
+
self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
|
| 150 |
+
):
|
| 151 |
+
model = TFDPRReader(config=config)
|
| 152 |
+
result = model(input_ids, attention_mask=input_mask)
|
| 153 |
+
|
| 154 |
+
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
|
| 155 |
+
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
|
| 156 |
+
self.parent.assertEqual(result.relevance_logits.shape, (self.batch_size,))
|
| 157 |
+
|
| 158 |
+
def prepare_config_and_inputs_for_common(self):
|
| 159 |
+
config_and_inputs = self.prepare_config_and_inputs()
|
| 160 |
+
(
|
| 161 |
+
config,
|
| 162 |
+
input_ids,
|
| 163 |
+
token_type_ids,
|
| 164 |
+
input_mask,
|
| 165 |
+
sequence_labels,
|
| 166 |
+
token_labels,
|
| 167 |
+
choice_labels,
|
| 168 |
+
) = config_and_inputs
|
| 169 |
+
inputs_dict = {"input_ids": input_ids}
|
| 170 |
+
return config, inputs_dict
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
@require_tf
|
| 174 |
+
class TFDPRModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
|
| 175 |
+
all_model_classes = (
|
| 176 |
+
(
|
| 177 |
+
TFDPRContextEncoder,
|
| 178 |
+
TFDPRQuestionEncoder,
|
| 179 |
+
TFDPRReader,
|
| 180 |
+
)
|
| 181 |
+
if is_tf_available()
|
| 182 |
+
else ()
|
| 183 |
+
)
|
| 184 |
+
pipeline_model_mapping = {"feature-extraction": TFDPRQuestionEncoder} if is_tf_available() else {}
|
| 185 |
+
|
| 186 |
+
test_resize_embeddings = False
|
| 187 |
+
test_missing_keys = False
|
| 188 |
+
test_pruning = False
|
| 189 |
+
test_head_masking = False
|
| 190 |
+
test_onnx = False
|
| 191 |
+
|
| 192 |
+
def setUp(self):
|
| 193 |
+
self.model_tester = TFDPRModelTester(self)
|
| 194 |
+
self.config_tester = ConfigTester(self, config_class=DPRConfig, hidden_size=37)
|
| 195 |
+
|
| 196 |
+
def test_config(self):
|
| 197 |
+
self.config_tester.run_common_tests()
|
| 198 |
+
|
| 199 |
+
def test_dpr_context_encoder_model(self):
|
| 200 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 201 |
+
self.model_tester.create_and_check_dpr_context_encoder(*config_and_inputs)
|
| 202 |
+
|
| 203 |
+
def test_dpr_question_encoder_model(self):
|
| 204 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 205 |
+
self.model_tester.create_and_check_dpr_question_encoder(*config_and_inputs)
|
| 206 |
+
|
| 207 |
+
def test_dpr_reader_model(self):
|
| 208 |
+
config_and_inputs = self.model_tester.prepare_config_and_inputs()
|
| 209 |
+
self.model_tester.create_and_check_dpr_reader(*config_and_inputs)
|
| 210 |
+
|
| 211 |
+
@slow
|
| 212 |
+
def test_model_from_pretrained(self):
|
| 213 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 214 |
+
model = TFDPRContextEncoder.from_pretrained(model_name)
|
| 215 |
+
self.assertIsNotNone(model)
|
| 216 |
+
|
| 217 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 218 |
+
model = TFDPRContextEncoder.from_pretrained(model_name)
|
| 219 |
+
self.assertIsNotNone(model)
|
| 220 |
+
|
| 221 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 222 |
+
model = TFDPRQuestionEncoder.from_pretrained(model_name)
|
| 223 |
+
self.assertIsNotNone(model)
|
| 224 |
+
|
| 225 |
+
model_name = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 226 |
+
model = TFDPRReader.from_pretrained(model_name)
|
| 227 |
+
self.assertIsNotNone(model)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@require_tf
|
| 231 |
+
class TFDPRModelIntegrationTest(unittest.TestCase):
|
| 232 |
+
@slow
|
| 233 |
+
def test_inference_no_head(self):
|
| 234 |
+
model = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
|
| 235 |
+
|
| 236 |
+
input_ids = tf.constant(
|
| 237 |
+
[[101, 7592, 1010, 2003, 2026, 3899, 10140, 1029, 102]]
|
| 238 |
+
) # [CLS] hello, is my dog cute? [SEP]
|
| 239 |
+
output = model(input_ids)[0] # embedding shape = (1, 768)
|
| 240 |
+
# compare the actual values for a slice.
|
| 241 |
+
expected_slice = tf.constant(
|
| 242 |
+
[
|
| 243 |
+
[
|
| 244 |
+
0.03236253,
|
| 245 |
+
0.12753335,
|
| 246 |
+
0.16818509,
|
| 247 |
+
0.00279786,
|
| 248 |
+
0.3896933,
|
| 249 |
+
0.24264945,
|
| 250 |
+
0.2178971,
|
| 251 |
+
-0.02335227,
|
| 252 |
+
-0.08481959,
|
| 253 |
+
-0.14324117,
|
| 254 |
+
]
|
| 255 |
+
]
|
| 256 |
+
)
|
| 257 |
+
self.assertTrue(numpy.allclose(output[:, :10].numpy(), expected_slice.numpy(), atol=1e-4))
|
tasks/tasksmith-333d8be2d5aa/tests/source/tests/models/dpr/test_tokenization_dpr.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2020 Huggingface
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
from transformers import (
|
| 17 |
+
DPRContextEncoderTokenizer,
|
| 18 |
+
DPRContextEncoderTokenizerFast,
|
| 19 |
+
DPRQuestionEncoderTokenizer,
|
| 20 |
+
DPRQuestionEncoderTokenizerFast,
|
| 21 |
+
DPRReaderOutput,
|
| 22 |
+
DPRReaderTokenizer,
|
| 23 |
+
DPRReaderTokenizerFast,
|
| 24 |
+
)
|
| 25 |
+
from transformers.testing_utils import require_tokenizers, slow
|
| 26 |
+
from transformers.tokenization_utils_base import BatchEncoding
|
| 27 |
+
|
| 28 |
+
from ..bert.test_tokenization_bert import BertTokenizationTest
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@require_tokenizers
|
| 32 |
+
class DPRContextEncoderTokenizationTest(BertTokenizationTest):
|
| 33 |
+
tokenizer_class = DPRContextEncoderTokenizer
|
| 34 |
+
rust_tokenizer_class = DPRContextEncoderTokenizerFast
|
| 35 |
+
test_rust_tokenizer = True
|
| 36 |
+
from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@require_tokenizers
|
| 40 |
+
class DPRQuestionEncoderTokenizationTest(BertTokenizationTest):
|
| 41 |
+
tokenizer_class = DPRQuestionEncoderTokenizer
|
| 42 |
+
rust_tokenizer_class = DPRQuestionEncoderTokenizerFast
|
| 43 |
+
test_rust_tokenizer = True
|
| 44 |
+
from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@require_tokenizers
|
| 48 |
+
class DPRReaderTokenizationTest(BertTokenizationTest):
|
| 49 |
+
tokenizer_class = DPRReaderTokenizer
|
| 50 |
+
rust_tokenizer_class = DPRReaderTokenizerFast
|
| 51 |
+
test_rust_tokenizer = True
|
| 52 |
+
from_pretrained_id = "facebook/dpr-ctx_encoder-single-nq-base"
|
| 53 |
+
|
| 54 |
+
@slow
|
| 55 |
+
def test_decode_best_spans(self):
|
| 56 |
+
tokenizer = self.tokenizer_class.from_pretrained("google-bert/bert-base-uncased")
|
| 57 |
+
|
| 58 |
+
text_1 = tokenizer.encode("question sequence", add_special_tokens=False)
|
| 59 |
+
text_2 = tokenizer.encode("title sequence", add_special_tokens=False)
|
| 60 |
+
text_3 = tokenizer.encode("text sequence " * 4, add_special_tokens=False)
|
| 61 |
+
input_ids = [[101] + text_1 + [102] + text_2 + [102] + text_3]
|
| 62 |
+
reader_input = BatchEncoding({"input_ids": input_ids})
|
| 63 |
+
|
| 64 |
+
start_logits = [[0] * len(input_ids[0])]
|
| 65 |
+
end_logits = [[0] * len(input_ids[0])]
|
| 66 |
+
relevance_logits = [0]
|
| 67 |
+
reader_output = DPRReaderOutput(start_logits, end_logits, relevance_logits)
|
| 68 |
+
|
| 69 |
+
start_index, end_index = 8, 9
|
| 70 |
+
start_logits[0][start_index] = 10
|
| 71 |
+
end_logits[0][end_index] = 10
|
| 72 |
+
predicted_spans = tokenizer.decode_best_spans(reader_input, reader_output)
|
| 73 |
+
self.assertEqual(predicted_spans[0].start_index, start_index)
|
| 74 |
+
self.assertEqual(predicted_spans[0].end_index, end_index)
|
| 75 |
+
self.assertEqual(predicted_spans[0].doc_id, 0)
|
| 76 |
+
|
| 77 |
+
@slow
|
| 78 |
+
def test_call(self):
|
| 79 |
+
tokenizer = self.tokenizer_class.from_pretrained("google-bert/bert-base-uncased")
|
| 80 |
+
|
| 81 |
+
text_1 = tokenizer.encode("question sequence", add_special_tokens=False)
|
| 82 |
+
text_2 = tokenizer.encode("title sequence", add_special_tokens=False)
|
| 83 |
+
text_3 = tokenizer.encode("text sequence", add_special_tokens=False)
|
| 84 |
+
expected_input_ids = [101] + text_1 + [102] + text_2 + [102] + text_3
|
| 85 |
+
encoded_input = tokenizer(questions=["question sequence"], titles=["title sequence"], texts=["text sequence"])
|
| 86 |
+
self.assertIn("input_ids", encoded_input)
|
| 87 |
+
self.assertIn("attention_mask", encoded_input)
|
| 88 |
+
self.assertListEqual(encoded_input["input_ids"][0], expected_input_ids)
|