This is a paragraph.
+ + + + """ + + return html_string + + +@require_torch +class MarkupLMModelIntegrationTest(unittest.TestCase): + @cached_property + def default_processor(self): + # TODO use from_pretrained here + feature_extractor = MarkupLMFeatureExtractor() + tokenizer = MarkupLMTokenizer.from_pretrained("microsoft/markuplm-base") + + return MarkupLMProcessor(feature_extractor, tokenizer) + + @slow + def test_forward_pass_no_head(self): + model = MarkupLMModel.from_pretrained("microsoft/markuplm-base").to(torch_device) + + processor = self.default_processor + + inputs = processor(prepare_html_string(), return_tensors="pt") + inputs = inputs.to(torch_device) + + # forward pass + with torch.no_grad(): + outputs = model(**inputs) + + # verify the last hidden states + expected_shape = torch.Size([1, 14, 768]) + self.assertEqual(outputs.last_hidden_state.shape, expected_shape) + + expected_slice = torch.tensor( + [[0.0675, -0.0052, 0.5001], [-0.2281, 0.0802, 0.2192], [-0.0583, -0.3311, 0.1185]] + ).to(torch_device) + + self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4)) diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mask2former/__init__.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mask2former/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mask2former/test_image_processing_mask2former.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mask2former/test_image_processing_mask2former.py new file mode 100644 index 0000000000000000000000000000000000000000..9f76f678f32e820ad33ac480942a480ec058ca19 --- /dev/null +++ b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mask2former/test_image_processing_mask2former.py @@ -0,0 +1,608 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import unittest + +import numpy as np +from datasets import load_dataset +from huggingface_hub import hf_hub_download + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + + if is_vision_available(): + from transformers import Mask2FormerImageProcessor + from transformers.models.mask2former.image_processing_mask2former import binary_mask_to_rle + from transformers.models.mask2former.modeling_mask2former import Mask2FormerForUniversalSegmentationOutput + +if is_vision_available(): + from PIL import Image + + +class Mask2FormerImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + min_resolution=30, + max_resolution=400, + size=None, + do_resize=True, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + num_labels=10, + do_reduce_labels=True, + ignore_index=255, + ): + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = {"shortest_edge": 32, "longest_edge": 1333} if size is None else size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.size_divisor = 0 + # for the post_process_functions + self.batch_size = 2 + self.num_queries = 3 + self.num_classes = 2 + self.height = 3 + self.width = 4 + self.num_labels = num_labels + self.do_reduce_labels = do_reduce_labels + self.ignore_index = ignore_index + + def prepare_image_processor_dict(self): + return { + "do_resize": self.do_resize, + "size": self.size, + "do_normalize": self.do_normalize, + "image_mean": self.image_mean, + "image_std": self.image_std, + "size_divisor": self.size_divisor, + "num_labels": self.num_labels, + "do_reduce_labels": self.do_reduce_labels, + "ignore_index": self.ignore_index, + } + + def get_expected_values(self, image_inputs, batched=False): + """ + This function computes the expected height and width when providing images to Mask2FormerImageProcessor, + assuming do_resize is set to True with a scalar size. + """ + if not batched: + image = image_inputs[0] + if isinstance(image, Image.Image): + w, h = image.size + else: + h, w = image.shape[1], image.shape[2] + if w < h: + expected_height = int(self.size["shortest_edge"] * h / w) + expected_width = self.size["shortest_edge"] + elif w > h: + expected_height = self.size["shortest_edge"] + expected_width = int(self.size["shortest_edge"] * w / h) + else: + expected_height = self.size["shortest_edge"] + expected_width = self.size["shortest_edge"] + + else: + expected_values = [] + for image in image_inputs: + expected_height, expected_width = self.get_expected_values([image]) + expected_values.append((expected_height, expected_width)) + expected_height = max(expected_values, key=lambda item: item[0])[0] + expected_width = max(expected_values, key=lambda item: item[1])[1] + + return expected_height, expected_width + + def get_fake_mask2former_outputs(self): + return Mask2FormerForUniversalSegmentationOutput( + # +1 for null class + class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1)), + masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width)), + ) + + +@require_torch +@require_vision +class Mask2FormerImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): + image_processing_class = Mask2FormerImageProcessor if (is_vision_available() and is_torch_available()) else None + + def setUp(self): + self.image_processor_tester = Mask2FormerImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + self.assertTrue(hasattr(image_processing, "max_size")) + self.assertTrue(hasattr(image_processing, "ignore_index")) + self.assertTrue(hasattr(image_processing, "num_labels")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 32, "longest_edge": 1333}) + self.assertEqual(image_processor.size_divisor, 0) + + image_processor = self.image_processing_class.from_dict( + self.image_processor_dict, size=42, max_size=84, size_divisibility=8 + ) + self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84}) + self.assertEqual(image_processor.size_divisor, 8) + + def test_batch_feature(self): + pass + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, torchify=True) + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_equivalence_pad_and_create_pixel_mask(self): + # Initialize image_processings + image_processing_1 = self.image_processing_class(**self.image_processor_dict) + image_processing_2 = self.image_processing_class( + do_resize=False, do_normalize=False, do_rescale=False, num_labels=self.image_processor_tester.num_classes + ) + # create random PyTorch tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, torchify=True) + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test whether the method "pad_and_return_pixel_mask" and calling the image processor return the same tensors + encoded_images_with_method = image_processing_1.encode_inputs(image_inputs, return_tensors="pt") + encoded_images = image_processing_2(image_inputs, return_tensors="pt") + + self.assertTrue( + torch.allclose(encoded_images_with_method["pixel_values"], encoded_images["pixel_values"], atol=1e-4) + ) + self.assertTrue( + torch.allclose(encoded_images_with_method["pixel_mask"], encoded_images["pixel_mask"], atol=1e-4) + ) + + def comm_get_image_processing_inputs( + self, with_segmentation_maps=False, is_instance_map=False, segmentation_type="np" + ): + image_processing = self.image_processing_class(**self.image_processor_dict) + # prepare image and target + num_labels = self.image_processor_tester.num_labels + annotations = None + instance_id_to_semantic_id = None + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False) + if with_segmentation_maps: + high = num_labels + if is_instance_map: + labels_expanded = list(range(num_labels)) * 2 + instance_id_to_semantic_id = dict(enumerate(labels_expanded)) + annotations = [ + np.random.randint(0, high * 2, (img.size[1], img.size[0])).astype(np.uint8) for img in image_inputs + ] + if segmentation_type == "pil": + annotations = [Image.fromarray(annotation) for annotation in annotations] + + inputs = image_processing( + image_inputs, + annotations, + return_tensors="pt", + instance_id_to_semantic_id=instance_id_to_semantic_id, + pad_and_return_pixel_mask=True, + ) + + return inputs + + def test_init_without_params(self): + pass + + def test_with_size_divisor(self): + size_divisors = [8, 16, 32] + weird_input_sizes = [(407, 802), (582, 1094)] + for size_divisor in size_divisors: + image_processor_dict = {**self.image_processor_dict, **{"size_divisor": size_divisor}} + image_processing = self.image_processing_class(**image_processor_dict) + for weird_input_size in weird_input_sizes: + inputs = image_processing([np.ones((3, *weird_input_size))], return_tensors="pt") + pixel_values = inputs["pixel_values"] + # check if divisible + self.assertTrue((pixel_values.shape[-1] % size_divisor) == 0) + self.assertTrue((pixel_values.shape[-2] % size_divisor) == 0) + + def test_call_with_segmentation_maps(self): + def common(is_instance_map=False, segmentation_type=None): + inputs = self.comm_get_image_processing_inputs( + with_segmentation_maps=True, is_instance_map=is_instance_map, segmentation_type=segmentation_type + ) + + mask_labels = inputs["mask_labels"] + class_labels = inputs["class_labels"] + pixel_values = inputs["pixel_values"] + + # check the batch_size + for mask_label, class_label in zip(mask_labels, class_labels): + self.assertEqual(mask_label.shape[0], class_label.shape[0]) + # this ensure padding has happened + self.assertEqual(mask_label.shape[1:], pixel_values.shape[2:]) + + common() + common(is_instance_map=True) + common(is_instance_map=False, segmentation_type="pil") + common(is_instance_map=True, segmentation_type="pil") + + def test_integration_instance_segmentation(self): + # load 2 images and corresponding annotations from the hub + repo_id = "nielsr/image-segmentation-toy-data" + image1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_image_1.png", repo_type="dataset") + ) + image2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_image_2.png", repo_type="dataset") + ) + annotation1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_annotation_1.png", repo_type="dataset") + ) + annotation2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_annotation_2.png", repo_type="dataset") + ) + + # get instance segmentations and instance-to-segmentation mappings + def get_instance_segmentation_and_mapping(annotation): + instance_seg = np.array(annotation)[:, :, 1] + class_id_map = np.array(annotation)[:, :, 0] + class_labels = np.unique(class_id_map) + + # create mapping between instance IDs and semantic category IDs + inst2class = {} + for label in class_labels: + instance_ids = np.unique(instance_seg[class_id_map == label]) + inst2class.update({i: label for i in instance_ids}) + + return instance_seg, inst2class + + instance_seg1, inst2class1 = get_instance_segmentation_and_mapping(annotation1) + instance_seg2, inst2class2 = get_instance_segmentation_and_mapping(annotation2) + + # create a image processor + image_processing = Mask2FormerImageProcessor(reduce_labels=True, ignore_index=255, size=(512, 512)) + + # prepare the images and annotations + inputs = image_processing( + [image1, image2], + [instance_seg1, instance_seg2], + instance_id_to_semantic_id=[inst2class1, inst2class2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 512)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 512)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor([30, 55]))) + self.assertTrue(torch.allclose(inputs["class_labels"][1], torch.tensor([4, 4, 23, 55]))) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (2, 512, 512)) + self.assertEqual(inputs["mask_labels"][1].shape, (4, 512, 512)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 41527.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 26259.0) + + def test_integration_semantic_segmentation(self): + # load 2 images and corresponding semantic annotations from the hub + repo_id = "nielsr/image-segmentation-toy-data" + image1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_image_1.png", repo_type="dataset") + ) + image2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_image_2.png", repo_type="dataset") + ) + annotation1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_annotation_1.png", repo_type="dataset") + ) + annotation2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_annotation_2.png", repo_type="dataset") + ) + + # create a image processor + image_processing = Mask2FormerImageProcessor(reduce_labels=True, ignore_index=255, size=(512, 512)) + + # prepare the images and annotations + inputs = image_processing( + [image1, image2], + [annotation1, annotation2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 512)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 512)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor([2, 4, 60]))) + self.assertTrue(torch.allclose(inputs["class_labels"][1], torch.tensor([0, 3, 7, 8, 15, 28, 30, 143]))) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (3, 512, 512)) + self.assertEqual(inputs["mask_labels"][1].shape, (8, 512, 512)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 170200.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 257036.0) + + def test_integration_panoptic_segmentation(self): + # load 2 images and corresponding panoptic annotations from the hub + dataset = load_dataset("nielsr/ade20k-panoptic-demo") + image1 = dataset["train"][0]["image"] + image2 = dataset["train"][1]["image"] + segments_info1 = dataset["train"][0]["segments_info"] + segments_info2 = dataset["train"][1]["segments_info"] + annotation1 = dataset["train"][0]["label"] + annotation2 = dataset["train"][1]["label"] + + def rgb_to_id(color): + if isinstance(color, np.ndarray) and len(color.shape) == 3: + if color.dtype == np.uint8: + color = color.astype(np.int32) + return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] + return int(color[0] + 256 * color[1] + 256 * 256 * color[2]) + + def create_panoptic_map(annotation, segments_info): + annotation = np.array(annotation) + # convert RGB to segment IDs per pixel + # 0 is the "ignore" label, for which we don't need to make binary masks + panoptic_map = rgb_to_id(annotation) + + # create mapping between segment IDs and semantic classes + inst2class = {segment["id"]: segment["category_id"] for segment in segments_info} + + return panoptic_map, inst2class + + panoptic_map1, inst2class1 = create_panoptic_map(annotation1, segments_info1) + panoptic_map2, inst2class2 = create_panoptic_map(annotation2, segments_info2) + + # create a image processor + image_processing = Mask2FormerImageProcessor(ignore_index=0, do_resize=False) + + # prepare the images and annotations + pixel_values_list = [np.moveaxis(np.array(image1), -1, 0), np.moveaxis(np.array(image2), -1, 0)] + inputs = image_processing.encode_inputs( + pixel_values_list, + [panoptic_map1, panoptic_map2], + instance_id_to_semantic_id=[inst2class1, inst2class2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 711)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 711)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + # fmt: off + expected_class_labels = torch.tensor([4, 17, 32, 42, 42, 42, 42, 42, 42, 42, 32, 12, 12, 12, 12, 12, 42, 42, 12, 12, 12, 42, 12, 12, 12, 12, 12, 3, 12, 12, 12, 12, 42, 42, 42, 12, 42, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 5, 12, 12, 12, 12, 12, 12, 12, 0, 43, 43, 43, 96, 43, 104, 43, 31, 125, 31, 125, 138, 87, 125, 149, 138, 125, 87, 87]) # noqa: E231 + # fmt: on + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor(expected_class_labels))) + # fmt: off + expected_class_labels = torch.tensor([19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 67, 82, 19, 19, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 12, 12, 42, 12, 12, 12, 12, 3, 14, 12, 12, 12, 12, 12, 12, 12, 12, 14, 5, 12, 12, 0, 115, 43, 43, 115, 43, 43, 43, 8, 8, 8, 138, 138, 125, 143]) # noqa: E231 + # fmt: on + self.assertTrue(torch.allclose(inputs["class_labels"][1], expected_class_labels)) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (79, 512, 711)) + self.assertEqual(inputs["mask_labels"][1].shape, (61, 512, 711)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 315193.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 350747.0) + + def test_binary_mask_to_rle(self): + fake_binary_mask = np.zeros((20, 50)) + fake_binary_mask[0, 20:] = 1 + fake_binary_mask[1, :15] = 1 + fake_binary_mask[5, :10] = 1 + + rle = binary_mask_to_rle(fake_binary_mask) + self.assertEqual(len(rle), 4) + self.assertEqual(rle[0], 21) + self.assertEqual(rle[1], 45) + + def test_post_process_semantic_segmentation(self): + fature_extractor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_mask2former_outputs() + + segmentation = fature_extractor.post_process_semantic_segmentation(outputs) + + self.assertEqual(len(segmentation), self.image_processor_tester.batch_size) + self.assertEqual(segmentation[0].shape, (384, 384)) + + target_sizes = [(1, 4) for i in range(self.image_processor_tester.batch_size)] + segmentation = fature_extractor.post_process_semantic_segmentation(outputs, target_sizes=target_sizes) + + self.assertEqual(segmentation[0].shape, target_sizes[0]) + + def test_post_process_instance_segmentation(self): + feature_extractor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_mask2former_outputs() + segmentation = feature_extractor.post_process_instance_segmentation(outputs, threshold=0) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual(el["segmentation"].shape, (384, 384)) + + segmentation = feature_extractor.post_process_instance_segmentation( + outputs, threshold=0, return_binary_maps=True + ) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual(len(el["segmentation"].shape), 3) + self.assertEqual(el["segmentation"].shape[1:], (384, 384)) + + def test_post_process_panoptic_segmentation(self): + image_processing = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_mask2former_outputs() + segmentation = image_processing.post_process_panoptic_segmentation(outputs, threshold=0) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual(el["segmentation"].shape, (384, 384)) + + def test_post_process_label_fusing(self): + image_processor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_mask2former_outputs() + + segmentation = image_processor.post_process_panoptic_segmentation( + outputs, threshold=0, mask_threshold=0, overlap_mask_area_threshold=0 + ) + unfused_segments = [el["segments_info"] for el in segmentation] + + fused_segmentation = image_processor.post_process_panoptic_segmentation( + outputs, threshold=0, mask_threshold=0, overlap_mask_area_threshold=0, label_ids_to_fuse={1} + ) + fused_segments = [el["segments_info"] for el in fused_segmentation] + + for el_unfused, el_fused in zip(unfused_segments, fused_segments): + if len(el_unfused) == 0: + self.assertEqual(len(el_unfused), len(el_fused)) + continue + + # Get number of segments to be fused + fuse_targets = [1 for el in el_unfused if el["label_id"] in {1}] + num_to_fuse = 0 if len(fuse_targets) == 0 else sum(fuse_targets) - 1 + # Expected number of segments after fusing + expected_num_segments = max([el["id"] for el in el_unfused]) - num_to_fuse + num_segments_fused = max([el["id"] for el in el_fused]) + self.assertEqual(num_segments_fused, expected_num_segments) diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_image_processing_maskformer.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_image_processing_maskformer.py new file mode 100644 index 0000000000000000000000000000000000000000..128d232d4cf893f6075245a5de6c9b5ffe97ccf2 --- /dev/null +++ b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_image_processing_maskformer.py @@ -0,0 +1,643 @@ +# coding=utf-8 +# Copyright 2022 HuggingFace Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import unittest + +import numpy as np +from datasets import load_dataset +from huggingface_hub import hf_hub_download + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils import is_torch_available, is_vision_available + +from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs + + +if is_torch_available(): + import torch + + if is_vision_available(): + from transformers import MaskFormerImageProcessor + from transformers.models.maskformer.image_processing_maskformer import binary_mask_to_rle + from transformers.models.maskformer.modeling_maskformer import MaskFormerForInstanceSegmentationOutput + +if is_vision_available(): + from PIL import Image + + +class MaskFormerImageProcessingTester(unittest.TestCase): + def __init__( + self, + parent, + batch_size=7, + num_channels=3, + min_resolution=30, + max_resolution=400, + size=None, + do_resize=True, + do_normalize=True, + image_mean=[0.5, 0.5, 0.5], + image_std=[0.5, 0.5, 0.5], + num_labels=10, + do_reduce_labels=True, + ignore_index=255, + ): + self.parent = parent + self.batch_size = batch_size + self.num_channels = num_channels + self.min_resolution = min_resolution + self.max_resolution = max_resolution + self.do_resize = do_resize + self.size = {"shortest_edge": 32, "longest_edge": 1333} if size is None else size + self.do_normalize = do_normalize + self.image_mean = image_mean + self.image_std = image_std + self.size_divisor = 0 + # for the post_process_functions + self.batch_size = 2 + self.num_queries = 3 + self.num_classes = 2 + self.height = 3 + self.width = 4 + self.num_labels = num_labels + self.do_reduce_labels = do_reduce_labels + self.ignore_index = ignore_index + + def prepare_image_processor_dict(self): + return { + "do_resize": self.do_resize, + "size": self.size, + "do_normalize": self.do_normalize, + "image_mean": self.image_mean, + "image_std": self.image_std, + "size_divisor": self.size_divisor, + "num_labels": self.num_labels, + "do_reduce_labels": self.do_reduce_labels, + "ignore_index": self.ignore_index, + } + + def get_expected_values(self, image_inputs, batched=False): + """ + This function computes the expected height and width when providing images to MaskFormerImageProcessor, + assuming do_resize is set to True with a scalar size. + """ + if not batched: + image = image_inputs[0] + if isinstance(image, Image.Image): + w, h = image.size + else: + h, w = image.shape[1], image.shape[2] + if w < h: + expected_height = int(self.size["shortest_edge"] * h / w) + expected_width = self.size["shortest_edge"] + elif w > h: + expected_height = self.size["shortest_edge"] + expected_width = int(self.size["shortest_edge"] * w / h) + else: + expected_height = self.size["shortest_edge"] + expected_width = self.size["shortest_edge"] + + else: + expected_values = [] + for image in image_inputs: + expected_height, expected_width = self.get_expected_values([image]) + expected_values.append((expected_height, expected_width)) + expected_height = max(expected_values, key=lambda item: item[0])[0] + expected_width = max(expected_values, key=lambda item: item[1])[1] + + return expected_height, expected_width + + def get_fake_maskformer_outputs(self): + return MaskFormerForInstanceSegmentationOutput( + # +1 for null class + class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1)), + masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width)), + ) + + +@require_torch +@require_vision +class MaskFormerImageProcessingTest(ImageProcessingSavingTestMixin, unittest.TestCase): + image_processing_class = MaskFormerImageProcessor if (is_vision_available() and is_torch_available()) else None + + def setUp(self): + self.image_processor_tester = MaskFormerImageProcessingTester(self) + + @property + def image_processor_dict(self): + return self.image_processor_tester.prepare_image_processor_dict() + + def test_image_processor_properties(self): + image_processing = self.image_processing_class(**self.image_processor_dict) + self.assertTrue(hasattr(image_processing, "image_mean")) + self.assertTrue(hasattr(image_processing, "image_std")) + self.assertTrue(hasattr(image_processing, "do_normalize")) + self.assertTrue(hasattr(image_processing, "do_resize")) + self.assertTrue(hasattr(image_processing, "size")) + self.assertTrue(hasattr(image_processing, "max_size")) + self.assertTrue(hasattr(image_processing, "ignore_index")) + self.assertTrue(hasattr(image_processing, "num_labels")) + + def test_image_processor_from_dict_with_kwargs(self): + image_processor = self.image_processing_class.from_dict(self.image_processor_dict) + self.assertEqual(image_processor.size, {"shortest_edge": 32, "longest_edge": 1333}) + self.assertEqual(image_processor.size_divisor, 0) + + image_processor = self.image_processing_class.from_dict( + self.image_processor_dict, size=42, max_size=84, size_divisibility=8 + ) + self.assertEqual(image_processor.size, {"shortest_edge": 42, "longest_edge": 84}) + self.assertEqual(image_processor.size_divisor, 8) + + def test_batch_feature(self): + pass + + def test_call_pil(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_numpy(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_call_pytorch(self): + # Initialize image_processing + image_processing = self.image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, torchify=True) + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs) + + self.assertEqual( + encoded_images.shape, + (1, self.image_processor_tester.num_channels, expected_height, expected_width), + ) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + + expected_height, expected_width = self.image_processor_tester.get_expected_values(image_inputs, batched=True) + + self.assertEqual( + encoded_images.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_channels, + expected_height, + expected_width, + ), + ) + + def test_equivalence_pad_and_create_pixel_mask(self): + # Initialize image_processings + image_processing_1 = self.image_processing_class(**self.image_processor_dict) + image_processing_2 = self.image_processing_class( + do_resize=False, do_normalize=False, do_rescale=False, num_labels=self.image_processor_tester.num_classes + ) + # create random PyTorch tensors + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False, torchify=True) + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test whether the method "pad_and_return_pixel_mask" and calling the image processor return the same tensors + encoded_images_with_method = image_processing_1.encode_inputs(image_inputs, return_tensors="pt") + encoded_images = image_processing_2(image_inputs, return_tensors="pt") + + self.assertTrue( + torch.allclose(encoded_images_with_method["pixel_values"], encoded_images["pixel_values"], atol=1e-4) + ) + self.assertTrue( + torch.allclose(encoded_images_with_method["pixel_mask"], encoded_images["pixel_mask"], atol=1e-4) + ) + + def comm_get_image_processing_inputs( + self, with_segmentation_maps=False, is_instance_map=False, segmentation_type="np" + ): + image_processing = self.image_processing_class(**self.image_processor_dict) + # prepare image and target + num_labels = self.image_processor_tester.num_labels + annotations = None + instance_id_to_semantic_id = None + image_inputs = prepare_image_inputs(self.image_processor_tester, equal_resolution=False) + if with_segmentation_maps: + high = num_labels + if is_instance_map: + labels_expanded = list(range(num_labels)) * 2 + instance_id_to_semantic_id = dict(enumerate(labels_expanded)) + annotations = [ + np.random.randint(0, high * 2, (img.size[1], img.size[0])).astype(np.uint8) for img in image_inputs + ] + if segmentation_type == "pil": + annotations = [Image.fromarray(annotation) for annotation in annotations] + + inputs = image_processing( + image_inputs, + annotations, + return_tensors="pt", + instance_id_to_semantic_id=instance_id_to_semantic_id, + pad_and_return_pixel_mask=True, + ) + + return inputs + + def test_init_without_params(self): + pass + + def test_with_size_divisor(self): + size_divisors = [8, 16, 32] + weird_input_sizes = [(407, 802), (582, 1094)] + for size_divisor in size_divisors: + image_processor_dict = {**self.image_processor_dict, **{"size_divisor": size_divisor}} + image_processing = self.image_processing_class(**image_processor_dict) + for weird_input_size in weird_input_sizes: + inputs = image_processing([np.ones((3, *weird_input_size))], return_tensors="pt") + pixel_values = inputs["pixel_values"] + # check if divisible + self.assertTrue((pixel_values.shape[-1] % size_divisor) == 0) + self.assertTrue((pixel_values.shape[-2] % size_divisor) == 0) + + def test_call_with_segmentation_maps(self): + def common(is_instance_map=False, segmentation_type=None): + inputs = self.comm_get_image_processing_inputs( + with_segmentation_maps=True, is_instance_map=is_instance_map, segmentation_type=segmentation_type + ) + + mask_labels = inputs["mask_labels"] + class_labels = inputs["class_labels"] + pixel_values = inputs["pixel_values"] + + # check the batch_size + for mask_label, class_label in zip(mask_labels, class_labels): + self.assertEqual(mask_label.shape[0], class_label.shape[0]) + # this ensure padding has happened + self.assertEqual(mask_label.shape[1:], pixel_values.shape[2:]) + + common() + common(is_instance_map=True) + common(is_instance_map=False, segmentation_type="pil") + common(is_instance_map=True, segmentation_type="pil") + + def test_integration_instance_segmentation(self): + # load 2 images and corresponding annotations from the hub + repo_id = "nielsr/image-segmentation-toy-data" + image1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_image_1.png", repo_type="dataset") + ) + image2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_image_2.png", repo_type="dataset") + ) + annotation1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_annotation_1.png", repo_type="dataset") + ) + annotation2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="instance_segmentation_annotation_2.png", repo_type="dataset") + ) + + # get instance segmentations and instance-to-segmentation mappings + def get_instance_segmentation_and_mapping(annotation): + instance_seg = np.array(annotation)[:, :, 1] + class_id_map = np.array(annotation)[:, :, 0] + class_labels = np.unique(class_id_map) + + # create mapping between instance IDs and semantic category IDs + inst2class = {} + for label in class_labels: + instance_ids = np.unique(instance_seg[class_id_map == label]) + inst2class.update({i: label for i in instance_ids}) + + return instance_seg, inst2class + + instance_seg1, inst2class1 = get_instance_segmentation_and_mapping(annotation1) + instance_seg2, inst2class2 = get_instance_segmentation_and_mapping(annotation2) + + # create a image processor + image_processing = MaskFormerImageProcessor(reduce_labels=True, ignore_index=255, size=(512, 512)) + + # prepare the images and annotations + inputs = image_processing( + [image1, image2], + [instance_seg1, instance_seg2], + instance_id_to_semantic_id=[inst2class1, inst2class2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 512)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 512)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor([30, 55]))) + self.assertTrue(torch.allclose(inputs["class_labels"][1], torch.tensor([4, 4, 23, 55]))) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (2, 512, 512)) + self.assertEqual(inputs["mask_labels"][1].shape, (4, 512, 512)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 41527.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 26259.0) + + def test_integration_semantic_segmentation(self): + # load 2 images and corresponding semantic annotations from the hub + repo_id = "nielsr/image-segmentation-toy-data" + image1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_image_1.png", repo_type="dataset") + ) + image2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_image_2.png", repo_type="dataset") + ) + annotation1 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_annotation_1.png", repo_type="dataset") + ) + annotation2 = Image.open( + hf_hub_download(repo_id=repo_id, filename="semantic_segmentation_annotation_2.png", repo_type="dataset") + ) + + # create a image processor + image_processing = MaskFormerImageProcessor(reduce_labels=True, ignore_index=255, size=(512, 512)) + + # prepare the images and annotations + inputs = image_processing( + [image1, image2], + [annotation1, annotation2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 512)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 512)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor([2, 4, 60]))) + self.assertTrue(torch.allclose(inputs["class_labels"][1], torch.tensor([0, 3, 7, 8, 15, 28, 30, 143]))) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (3, 512, 512)) + self.assertEqual(inputs["mask_labels"][1].shape, (8, 512, 512)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 170200.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 257036.0) + + def test_integration_panoptic_segmentation(self): + # load 2 images and corresponding panoptic annotations from the hub + dataset = load_dataset("nielsr/ade20k-panoptic-demo") + image1 = dataset["train"][0]["image"] + image2 = dataset["train"][1]["image"] + segments_info1 = dataset["train"][0]["segments_info"] + segments_info2 = dataset["train"][1]["segments_info"] + annotation1 = dataset["train"][0]["label"] + annotation2 = dataset["train"][1]["label"] + + def rgb_to_id(color): + if isinstance(color, np.ndarray) and len(color.shape) == 3: + if color.dtype == np.uint8: + color = color.astype(np.int32) + return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2] + return int(color[0] + 256 * color[1] + 256 * 256 * color[2]) + + def create_panoptic_map(annotation, segments_info): + annotation = np.array(annotation) + # convert RGB to segment IDs per pixel + # 0 is the "ignore" label, for which we don't need to make binary masks + panoptic_map = rgb_to_id(annotation) + + # create mapping between segment IDs and semantic classes + inst2class = {segment["id"]: segment["category_id"] for segment in segments_info} + + return panoptic_map, inst2class + + panoptic_map1, inst2class1 = create_panoptic_map(annotation1, segments_info1) + panoptic_map2, inst2class2 = create_panoptic_map(annotation2, segments_info2) + + # create a image processor + image_processing = MaskFormerImageProcessor(ignore_index=0, do_resize=False) + + # prepare the images and annotations + pixel_values_list = [np.moveaxis(np.array(image1), -1, 0), np.moveaxis(np.array(image2), -1, 0)] + inputs = image_processing.encode_inputs( + pixel_values_list, + [panoptic_map1, panoptic_map2], + instance_id_to_semantic_id=[inst2class1, inst2class2], + return_tensors="pt", + ) + + # verify the pixel values and pixel mask + self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 711)) + self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 711)) + + # verify the class labels + self.assertEqual(len(inputs["class_labels"]), 2) + # fmt: off + expected_class_labels = torch.tensor([4, 17, 32, 42, 42, 42, 42, 42, 42, 42, 32, 12, 12, 12, 12, 12, 42, 42, 12, 12, 12, 42, 12, 12, 12, 12, 12, 3, 12, 12, 12, 12, 42, 42, 42, 12, 42, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 5, 12, 12, 12, 12, 12, 12, 12, 0, 43, 43, 43, 96, 43, 104, 43, 31, 125, 31, 125, 138, 87, 125, 149, 138, 125, 87, 87]) # noqa: E231 + # fmt: on + self.assertTrue(torch.allclose(inputs["class_labels"][0], torch.tensor(expected_class_labels))) + # fmt: off + expected_class_labels = torch.tensor([19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 67, 82, 19, 19, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 12, 12, 42, 12, 12, 12, 12, 3, 14, 12, 12, 12, 12, 12, 12, 12, 12, 14, 5, 12, 12, 0, 115, 43, 43, 115, 43, 43, 43, 8, 8, 8, 138, 138, 125, 143]) # noqa: E231 + # fmt: on + self.assertTrue(torch.allclose(inputs["class_labels"][1], expected_class_labels)) + + # verify the mask labels + self.assertEqual(len(inputs["mask_labels"]), 2) + self.assertEqual(inputs["mask_labels"][0].shape, (79, 512, 711)) + self.assertEqual(inputs["mask_labels"][1].shape, (61, 512, 711)) + self.assertEquals(inputs["mask_labels"][0].sum().item(), 315193.0) + self.assertEquals(inputs["mask_labels"][1].sum().item(), 350747.0) + + def test_binary_mask_to_rle(self): + fake_binary_mask = np.zeros((20, 50)) + fake_binary_mask[0, 20:] = 1 + fake_binary_mask[1, :15] = 1 + fake_binary_mask[5, :10] = 1 + + rle = binary_mask_to_rle(fake_binary_mask) + self.assertEqual(len(rle), 4) + self.assertEqual(rle[0], 21) + self.assertEqual(rle[1], 45) + + def test_post_process_segmentation(self): + fature_extractor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_maskformer_outputs() + segmentation = fature_extractor.post_process_segmentation(outputs) + + self.assertEqual( + segmentation.shape, + ( + self.image_processor_tester.batch_size, + self.image_processor_tester.num_classes, + self.image_processor_tester.height, + self.image_processor_tester.width, + ), + ) + + target_size = (1, 4) + segmentation = fature_extractor.post_process_segmentation(outputs, target_size=target_size) + + self.assertEqual( + segmentation.shape, + (self.image_processor_tester.batch_size, self.image_processor_tester.num_classes, *target_size), + ) + + def test_post_process_semantic_segmentation(self): + fature_extractor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_maskformer_outputs() + + segmentation = fature_extractor.post_process_semantic_segmentation(outputs) + + self.assertEqual(len(segmentation), self.image_processor_tester.batch_size) + self.assertEqual( + segmentation[0].shape, + ( + self.image_processor_tester.height, + self.image_processor_tester.width, + ), + ) + + target_sizes = [(1, 4) for i in range(self.image_processor_tester.batch_size)] + segmentation = fature_extractor.post_process_semantic_segmentation(outputs, target_sizes=target_sizes) + + self.assertEqual(segmentation[0].shape, target_sizes[0]) + + def test_post_process_instance_segmentation(self): + feature_extractor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_maskformer_outputs() + segmentation = feature_extractor.post_process_instance_segmentation(outputs, threshold=0) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual( + el["segmentation"].shape, (self.image_processor_tester.height, self.image_processor_tester.width) + ) + + segmentation = feature_extractor.post_process_instance_segmentation( + outputs, threshold=0, return_binary_maps=True + ) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual(len(el["segmentation"].shape), 3) + self.assertEqual( + el["segmentation"].shape[1:], (self.image_processor_tester.height, self.image_processor_tester.width) + ) + + def test_post_process_panoptic_segmentation(self): + image_processing = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_maskformer_outputs() + segmentation = image_processing.post_process_panoptic_segmentation(outputs, threshold=0) + + self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size) + for el in segmentation: + self.assertTrue("segmentation" in el) + self.assertTrue("segments_info" in el) + self.assertEqual(type(el["segments_info"]), list) + self.assertEqual( + el["segmentation"].shape, (self.image_processor_tester.height, self.image_processor_tester.width) + ) + + def test_post_process_label_fusing(self): + image_processor = self.image_processing_class(num_labels=self.image_processor_tester.num_classes) + outputs = self.image_processor_tester.get_fake_maskformer_outputs() + + segmentation = image_processor.post_process_panoptic_segmentation( + outputs, threshold=0, mask_threshold=0, overlap_mask_area_threshold=0 + ) + unfused_segments = [el["segments_info"] for el in segmentation] + + fused_segmentation = image_processor.post_process_panoptic_segmentation( + outputs, threshold=0, mask_threshold=0, overlap_mask_area_threshold=0, label_ids_to_fuse={1} + ) + fused_segments = [el["segments_info"] for el in fused_segmentation] + + for el_unfused, el_fused in zip(unfused_segments, fused_segments): + if len(el_unfused) == 0: + self.assertEqual(len(el_unfused), len(el_fused)) + continue + + # Get number of segments to be fused + fuse_targets = [1 for el in el_unfused if el["label_id"] in {1}] + num_to_fuse = 0 if len(fuse_targets) == 0 else sum(fuse_targets) - 1 + # Expected number of segments after fusing + expected_num_segments = max([el["id"] for el in el_unfused]) - num_to_fuse + num_segments_fused = max([el["id"] for el in el_fused]) + self.assertEqual(num_segments_fused, expected_num_segments) diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer.py new file mode 100644 index 0000000000000000000000000000000000000000..65ce4aa7f0cae1beab790b8055f154e361e8a483 --- /dev/null +++ b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer.py @@ -0,0 +1,478 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Testing suite for the PyTorch MaskFormer model. """ + +import inspect +import unittest + +import numpy as np + +from tests.test_modeling_common import floats_tensor +from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available +from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device +from transformers.utils import cached_property + +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel + + if is_vision_available(): + from transformers import MaskFormerFeatureExtractor + +if is_vision_available(): + from PIL import Image + + +class MaskFormerModelTester: + def __init__( + self, + parent, + batch_size=2, + is_training=True, + use_auxiliary_loss=False, + num_queries=10, + num_channels=3, + min_size=32 * 4, + max_size=32 * 6, + num_labels=4, + mask_feature_size=32, + ): + self.parent = parent + self.batch_size = batch_size + self.is_training = is_training + self.use_auxiliary_loss = use_auxiliary_loss + self.num_queries = num_queries + self.num_channels = num_channels + self.min_size = min_size + self.max_size = max_size + self.num_labels = num_labels + self.mask_feature_size = mask_feature_size + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to( + torch_device + ) + + pixel_mask = torch.ones([self.batch_size, self.min_size, self.max_size], device=torch_device) + + mask_labels = ( + torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=torch_device) > 0.5 + ).float() + class_labels = (torch.rand((self.batch_size, self.num_labels), device=torch_device) > 0.5).long() + + config = self.get_config() + return config, pixel_values, pixel_mask, mask_labels, class_labels + + def get_config(self): + return MaskFormerConfig.from_backbone_and_decoder_configs( + backbone_config=SwinConfig( + depths=[1, 1, 1, 1], + ), + decoder_config=DetrConfig( + decoder_ffn_dim=128, + num_queries=self.num_queries, + decoder_attention_heads=2, + d_model=self.mask_feature_size, + ), + mask_feature_size=self.mask_feature_size, + fpn_feature_size=self.mask_feature_size, + num_channels=self.num_channels, + num_labels=self.num_labels, + ) + + def prepare_config_and_inputs_for_common(self): + config, pixel_values, pixel_mask, _, _ = self.prepare_config_and_inputs() + inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} + return config, inputs_dict + + def check_output_hidden_state(self, output, config): + encoder_hidden_states = output.encoder_hidden_states + pixel_decoder_hidden_states = output.pixel_decoder_hidden_states + transformer_decoder_hidden_states = output.transformer_decoder_hidden_states + + self.parent.assertTrue(len(encoder_hidden_states), len(config.backbone_config.depths)) + self.parent.assertTrue(len(pixel_decoder_hidden_states), len(config.backbone_config.depths)) + self.parent.assertTrue(len(transformer_decoder_hidden_states), config.decoder_config.decoder_layers) + + def create_and_check_maskformer_model(self, config, pixel_values, pixel_mask, output_hidden_states=False): + with torch.no_grad(): + model = MaskFormerModel(config=config) + model.to(torch_device) + model.eval() + + output = model(pixel_values=pixel_values, pixel_mask=pixel_mask) + output = model(pixel_values, output_hidden_states=True) + # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the + # encoder and pixel decoder + self.parent.assertEqual( + output.transformer_decoder_last_hidden_state.shape, + (self.batch_size, self.num_queries, self.mask_feature_size), + ) + # let's ensure the other two hidden state exists + self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None) + self.parent.assertTrue(output.encoder_last_hidden_state is not None) + + if output_hidden_states: + self.check_output_hidden_state(output, config) + + def create_and_check_maskformer_instance_segmentation_head_model( + self, config, pixel_values, pixel_mask, mask_labels, class_labels + ): + model = MaskFormerForInstanceSegmentation(config=config) + model.to(torch_device) + model.eval() + + def comm_check_on_output(result): + # let's still check that all the required stuff is there + self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None) + self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None) + self.parent.assertTrue(result.encoder_last_hidden_state is not None) + # okay, now we need to check the logits shape + # due to the encoder compression, masks have a //4 spatial size + self.parent.assertEqual( + result.masks_queries_logits.shape, + (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4), + ) + # + 1 for null class + self.parent.assertEqual( + result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1) + ) + + with torch.no_grad(): + result = model(pixel_values=pixel_values, pixel_mask=pixel_mask) + result = model(pixel_values) + + comm_check_on_output(result) + + result = model( + pixel_values=pixel_values, pixel_mask=pixel_mask, mask_labels=mask_labels, class_labels=class_labels + ) + + comm_check_on_output(result) + + self.parent.assertTrue(result.loss is not None) + self.parent.assertEqual(result.loss.shape, torch.Size([1])) + + +@require_torch +class MaskFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () + pipeline_model_mapping = ( + {"feature-extraction": MaskFormerModel, "image-segmentation": MaskFormerForInstanceSegmentation} + if is_torch_available() + else {} + ) + + is_encoder_decoder = False + test_pruning = False + test_head_masking = False + test_missing_keys = False + + def setUp(self): + self.model_tester = MaskFormerModelTester(self) + self.config_tester = ConfigTester(self, config_class=MaskFormerConfig, has_text_modality=False) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_maskformer_model(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + self.model_tester.create_and_check_maskformer_model(config, **inputs, output_hidden_states=False) + + def test_maskformer_instance_segmentation_head_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*config_and_inputs) + + @unittest.skip(reason="MaskFormer does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method") + def test_model_common_attributes(self): + pass + + @unittest.skip(reason="MaskFormer is not a generative model") + def test_generate_without_input_ids(self): + pass + + @unittest.skip(reason="MaskFormer does not use token embeddings") + def test_resize_tokens_embeddings(self): + pass + + @require_torch_multi_gpu + @unittest.skip( + reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" + ) + def test_multi_gpu_data_parallel_forward(self): + pass + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + @slow + def test_model_from_pretrained(self): + for model_name in ["facebook/maskformer-swin-small-coco"]: + model = MaskFormerModel.from_pretrained(model_name) + self.assertIsNotNone(model) + + def test_model_with_labels(self): + size = (self.model_tester.min_size,) * 2 + inputs = { + "pixel_values": torch.randn((2, 3, *size), device=torch_device), + "mask_labels": torch.randn((2, 10, *size), device=torch_device), + "class_labels": torch.zeros(2, 10, device=torch_device).long(), + } + + model = MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(torch_device) + outputs = model(**inputs) + self.assertTrue(outputs.loss is not None) + + def test_hidden_states_output(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + self.model_tester.create_and_check_maskformer_model(config, **inputs, output_hidden_states=True) + + def test_attention_outputs(self): + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config).to(torch_device) + outputs = model(**inputs, output_attentions=True) + self.assertTrue(outputs.attentions is not None) + + def test_training(self): + if not self.model_tester.is_training: + return + # only MaskFormerForInstanceSegmentation has the loss + model_class = self.all_model_classes[1] + config, pixel_values, pixel_mask, mask_labels, class_labels = self.model_tester.prepare_config_and_inputs() + + model = model_class(config) + model.to(torch_device) + model.train() + + loss = model(pixel_values, mask_labels=mask_labels, class_labels=class_labels).loss + loss.backward() + + def test_retain_grad_hidden_states_attentions(self): + # only MaskFormerForInstanceSegmentation has the loss + model_class = self.all_model_classes[1] + config, pixel_values, pixel_mask, mask_labels, class_labels = self.model_tester.prepare_config_and_inputs() + config.output_hidden_states = True + config.output_attentions = True + + model = model_class(config) + model.to(torch_device) + model.train() + + outputs = model(pixel_values, mask_labels=mask_labels, class_labels=class_labels) + + encoder_hidden_states = outputs.encoder_hidden_states[0] + encoder_hidden_states.retain_grad() + + pixel_decoder_hidden_states = outputs.pixel_decoder_hidden_states[0] + pixel_decoder_hidden_states.retain_grad() + # we requires_grad=True in inputs_embeds (line 2152), the original implementation don't + transformer_decoder_hidden_states = outputs.transformer_decoder_hidden_states[0] + transformer_decoder_hidden_states.retain_grad() + + attentions = outputs.attentions[0] + attentions.retain_grad() + + outputs.loss.backward(retain_graph=True) + + self.assertIsNotNone(encoder_hidden_states.grad) + self.assertIsNotNone(pixel_decoder_hidden_states.grad) + self.assertIsNotNone(transformer_decoder_hidden_states.grad) + self.assertIsNotNone(attentions.grad) + + +TOLERANCE = 1e-4 + + +# We will verify our results on an image of cute cats +def prepare_img(): + image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png") + return image + + +@require_vision +@slow +class MaskFormerModelIntegrationTest(unittest.TestCase): + @cached_property + def default_feature_extractor(self): + return ( + MaskFormerFeatureExtractor.from_pretrained("facebook/maskformer-swin-small-coco") + if is_vision_available() + else None + ) + + def test_inference_no_head(self): + model = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco").to(torch_device) + feature_extractor = self.default_feature_extractor + image = prepare_img() + inputs = feature_extractor(image, return_tensors="pt").to(torch_device) + inputs_shape = inputs["pixel_values"].shape + # check size is divisible by 32 + self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) + # check size + self.assertEqual(inputs_shape, (1, 3, 800, 1088)) + + with torch.no_grad(): + outputs = model(**inputs) + + expected_slice_hidden_state = torch.tensor( + [[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]] + ).to(torch_device) + self.assertTrue( + torch.allclose( + outputs.encoder_last_hidden_state[0, 0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE + ) + ) + + expected_slice_hidden_state = torch.tensor( + [[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]] + ).to(torch_device) + self.assertTrue( + torch.allclose( + outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE + ) + ) + + expected_slice_hidden_state = torch.tensor( + [[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]] + ).to(torch_device) + self.assertTrue( + torch.allclose( + outputs.transformer_decoder_last_hidden_state[0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE + ) + ) + + def test_inference_instance_segmentation_head(self): + model = ( + MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco") + .to(torch_device) + .eval() + ) + feature_extractor = self.default_feature_extractor + image = prepare_img() + inputs = feature_extractor(image, return_tensors="pt").to(torch_device) + inputs_shape = inputs["pixel_values"].shape + # check size is divisible by 32 + self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) + # check size + self.assertEqual(inputs_shape, (1, 3, 800, 1088)) + + with torch.no_grad(): + outputs = model(**inputs) + # masks_queries_logits + masks_queries_logits = outputs.masks_queries_logits + self.assertEqual( + masks_queries_logits.shape, + (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4), + ) + expected_slice = [ + [-1.3737124, -1.7724937, -1.9364233], + [-1.5977281, -1.9867939, -2.1523695], + [-1.5795398, -1.9269832, -2.093942], + ] + expected_slice = torch.tensor(expected_slice).to(torch_device) + self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], expected_slice, atol=TOLERANCE)) + # class_queries_logits + class_queries_logits = outputs.class_queries_logits + self.assertEqual( + class_queries_logits.shape, (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) + ) + expected_slice = torch.tensor( + [ + [1.6512e00, -5.2572e00, -3.3519e00], + [3.6169e-02, -5.9025e00, -2.9313e00], + [1.0766e-04, -7.7630e00, -5.1263e00], + ] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], expected_slice, atol=TOLERANCE)) + + def test_inference_instance_segmentation_head_resnet_backbone(self): + model = ( + MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff") + .to(torch_device) + .eval() + ) + feature_extractor = self.default_feature_extractor + image = prepare_img() + inputs = feature_extractor(image, return_tensors="pt").to(torch_device) + inputs_shape = inputs["pixel_values"].shape + # check size is divisible by 32 + self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0) + # check size + self.assertEqual(inputs_shape, (1, 3, 800, 1088)) + + with torch.no_grad(): + outputs = model(**inputs) + # masks_queries_logits + masks_queries_logits = outputs.masks_queries_logits + self.assertEqual( + masks_queries_logits.shape, + (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4), + ) + expected_slice = [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]] + expected_slice = torch.tensor(expected_slice).to(torch_device) + self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3], expected_slice, atol=TOLERANCE)) + # class_queries_logits + class_queries_logits = outputs.class_queries_logits + self.assertEqual( + class_queries_logits.shape, (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) + ) + expected_slice = torch.tensor( + [[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]] + ).to(torch_device) + self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3], expected_slice, atol=TOLERANCE)) + + def test_with_segmentation_maps_and_loss(self): + model = ( + MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco") + .to(torch_device) + .eval() + ) + feature_extractor = self.default_feature_extractor + + inputs = feature_extractor( + [np.zeros((3, 800, 1333)), np.zeros((3, 800, 1333))], + segmentation_maps=[np.zeros((384, 384)).astype(np.float32), np.zeros((384, 384)).astype(np.float32)], + return_tensors="pt", + ) + + inputs["pixel_values"] = inputs["pixel_values"].to(torch_device) + inputs["mask_labels"] = [el.to(torch_device) for el in inputs["mask_labels"]] + inputs["class_labels"] = [el.to(torch_device) for el in inputs["class_labels"]] + + with torch.no_grad(): + outputs = model(**inputs) + + self.assertTrue(outputs.loss is not None) diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer_swin.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer_swin.py new file mode 100644 index 0000000000000000000000000000000000000000..4125f36db798e1df33ab632ed8bd233c89710cdb --- /dev/null +++ b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/maskformer/test_modeling_maskformer_swin.py @@ -0,0 +1,446 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Testing suite for the PyTorch MaskFormer Swin model. """ + +import collections +import inspect +import unittest +from typing import Dict, List, Tuple + +from transformers import MaskFormerSwinConfig +from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device +from transformers.utils import is_torch_available + +from ...test_backbone_common import BackboneTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + from torch import nn + + from transformers import MaskFormerSwinBackbone + from transformers.models.maskformer import MaskFormerSwinModel + + +class MaskFormerSwinModelTester: + def __init__( + self, + parent, + batch_size=13, + image_size=32, + patch_size=2, + num_channels=3, + embed_dim=16, + depths=[1, 2, 1], + num_heads=[2, 2, 4], + window_size=2, + mlp_ratio=2.0, + qkv_bias=True, + hidden_dropout_prob=0.0, + attention_probs_dropout_prob=0.0, + drop_path_rate=0.1, + hidden_act="gelu", + use_absolute_embeddings=False, + patch_norm=True, + initializer_range=0.02, + layer_norm_eps=1e-5, + is_training=True, + scope=None, + use_labels=True, + type_sequence_label_size=10, + encoder_stride=8, + out_features=["stage1", "stage2", "stage3"], + out_indices=[1, 2, 3], + ): + self.parent = parent + self.batch_size = batch_size + self.image_size = image_size + self.patch_size = patch_size + self.num_channels = num_channels + self.embed_dim = embed_dim + self.depths = depths + self.num_heads = num_heads + self.window_size = window_size + self.mlp_ratio = mlp_ratio + self.qkv_bias = qkv_bias + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.drop_path_rate = drop_path_rate + self.hidden_act = hidden_act + self.use_absolute_embeddings = use_absolute_embeddings + self.patch_norm = patch_norm + self.layer_norm_eps = layer_norm_eps + self.initializer_range = initializer_range + self.is_training = is_training + self.scope = scope + self.use_labels = use_labels + self.type_sequence_label_size = type_sequence_label_size + self.encoder_stride = encoder_stride + self.out_features = out_features + self.out_indices = out_indices + + def prepare_config_and_inputs(self): + pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]) + + labels = None + if self.use_labels: + labels = ids_tensor([self.batch_size], self.type_sequence_label_size) + + config = self.get_config() + + return config, pixel_values, labels + + def get_config(self): + return MaskFormerSwinConfig( + image_size=self.image_size, + patch_size=self.patch_size, + num_channels=self.num_channels, + embed_dim=self.embed_dim, + depths=self.depths, + num_heads=self.num_heads, + window_size=self.window_size, + mlp_ratio=self.mlp_ratio, + qkv_bias=self.qkv_bias, + hidden_dropout_prob=self.hidden_dropout_prob, + attention_probs_dropout_prob=self.attention_probs_dropout_prob, + drop_path_rate=self.drop_path_rate, + hidden_act=self.hidden_act, + use_absolute_embeddings=self.use_absolute_embeddings, + path_norm=self.patch_norm, + layer_norm_eps=self.layer_norm_eps, + initializer_range=self.initializer_range, + encoder_stride=self.encoder_stride, + out_features=self.out_features, + out_indices=self.out_indices, + ) + + def create_and_check_model(self, config, pixel_values, labels): + model = MaskFormerSwinModel(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + expected_seq_len = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths) - 1)) + expected_dim = int(config.embed_dim * 2 ** (len(config.depths) - 1)) + + self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, expected_seq_len, expected_dim)) + + def create_and_check_backbone(self, config, pixel_values, labels): + model = MaskFormerSwinBackbone(config=config) + model.to(torch_device) + model.eval() + result = model(pixel_values) + + # verify feature maps + self.parent.assertEqual(len(result.feature_maps), len(config.out_features)) + self.parent.assertListEqual(list(result.feature_maps[0].shape), [13, 16, 16, 16]) + + # verify channels + self.parent.assertEqual(len(model.channels), len(config.out_features)) + self.parent.assertListEqual(model.channels, [16, 32, 64]) + + # verify ValueError + with self.parent.assertRaises(ValueError): + config.out_features = ["stem"] + model = MaskFormerSwinBackbone(config=config) + + def prepare_config_and_inputs_for_common(self): + config_and_inputs = self.prepare_config_and_inputs() + config, pixel_values, labels = config_and_inputs + inputs_dict = {"pixel_values": pixel_values} + return config, inputs_dict + + +@require_torch +class MaskFormerSwinModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + ( + MaskFormerSwinModel, + MaskFormerSwinBackbone, + ) + if is_torch_available() + else () + ) + pipeline_model_mapping = {"feature-extraction": MaskFormerSwinModel} if is_torch_available() else {} + fx_compatible = False + test_torchscript = False + test_pruning = False + test_resize_embeddings = False + test_head_masking = False + + def setUp(self): + self.model_tester = MaskFormerSwinModelTester(self) + self.config_tester = ConfigTester(self, config_class=MaskFormerSwinConfig, embed_dim=37) + + @require_torch_multi_gpu + @unittest.skip( + reason=( + "`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with" + " `nn.DataParallel`" + ) + ) + def test_multi_gpu_data_parallel_forward(self): + pass + + def test_config(self): + self.create_and_test_config_common_properties() + self.config_tester.create_and_test_config_to_json_string() + self.config_tester.create_and_test_config_to_json_file() + self.config_tester.create_and_test_config_from_and_save_pretrained() + self.config_tester.create_and_test_config_with_num_labels() + self.config_tester.check_config_can_be_init_without_params() + self.config_tester.check_config_arguments_init() + + def create_and_test_config_common_properties(self): + return + + def test_model(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_model(*config_and_inputs) + + def test_backbone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_backbone(*config_and_inputs) + + @unittest.skip("Swin does not use inputs_embeds") + def test_inputs_embeds(self): + pass + + @unittest.skip("Swin does not support feedforward chunking") + def test_feed_forward_chunking(self): + pass + + def test_model_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertIsInstance(model.get_input_embeddings(), (nn.Module)) + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + @unittest.skip(reason="MaskFormerSwin is only used as backbone and doesn't support output_attentions") + def test_attention_outputs(self): + pass + + @unittest.skip(reason="MaskFormerSwin is only used as an internal backbone") + def test_save_load_fast_init_to_base(self): + pass + + def check_hidden_states_output(self, inputs_dict, config, model_class, image_size): + model = model_class(config) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", len(self.model_tester.depths) + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + # Swin has a different seq_length + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0]) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [num_patches, self.model_tester.embed_dim], + ) + + def test_hidden_states_output(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + + self.check_hidden_states_output(inputs_dict, config, model_class, image_size) + + def test_hidden_states_output_with_padding(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.patch_size = 3 + + image_size = ( + self.model_tester.image_size + if isinstance(self.model_tester.image_size, collections.abc.Iterable) + else (self.model_tester.image_size, self.model_tester.image_size) + ) + patch_size = ( + config.patch_size + if isinstance(config.patch_size, collections.abc.Iterable) + else (config.patch_size, config.patch_size) + ) + + padded_height = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0]) + padded_width = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1]) + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + self.check_hidden_states_output(inputs_dict, config, model_class, (padded_height, padded_width)) + + @unittest.skip(reason="MaskFormerSwin doesn't have pretrained checkpoints") + def test_model_from_pretrained(self): + pass + + @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin") + def test_initialization(self): + pass + + @unittest.skip(reason="This will be fixed once MaskFormerSwin is replaced by native Swin") + def test_gradient_checkpointing_backward_compatibility(self): + pass + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def set_nan_tensor_to_zero(t): + t[t != t] = 0 + return t + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + with torch.no_grad(): + tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (List, Tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif isinstance(tuple_object, Dict): + for tuple_iterable_value, dict_iterable_value in zip( + tuple_object.values(), dict_object.values() + ): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + else: + self.assertTrue( + torch.allclose( + set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5 + ), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:" + f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has" + f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}." + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + +@require_torch +class MaskFormerSwinBackboneTest(unittest.TestCase, BackboneTesterMixin): + all_model_classes = (MaskFormerSwinBackbone,) if is_torch_available() else () + config_class = MaskFormerSwinConfig + + def setUp(self): + self.model_tester = MaskFormerSwinModelTester(self) + + # Overriding as returned hidden states are tuples of tensors instead of a single tensor + def test_backbone_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + batch_size = inputs_dict["pixel_values"].shape[0] + + for backbone_class in self.all_model_classes: + backbone = backbone_class(config) + backbone.to(torch_device) + backbone.eval() + + outputs = backbone(**inputs_dict) + + # Test default outputs and verify feature maps + self.assertIsInstance(outputs.feature_maps, tuple) + self.assertTrue(len(outputs.feature_maps) == len(backbone.channels)) + for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels): + self.assertTrue(feature_map.shape[:2], (batch_size, n_channels)) + self.assertIsNone(outputs.hidden_states) + self.assertIsNone(outputs.attentions) + + # Test output_hidden_states=True + outputs = backbone(**inputs_dict, output_hidden_states=True) + self.assertIsNotNone(outputs.hidden_states) + self.assertTrue(len(outputs.hidden_states), len(backbone.stage_names)) + # We skip the stem layer + for hidden_states, n_channels in zip(outputs.hidden_states[1:], backbone.channels): + for hidden_state in hidden_states: + # Hidden states are in the format (batch_size, (height * width), n_channels) + h_batch_size, _, h_n_channels = hidden_state.shape + self.assertTrue((h_batch_size, h_n_channels), (batch_size, n_channels)) + + # Test output_attentions=True + if self.has_attentions: + outputs = backbone(**inputs_dict, output_attentions=True) + self.assertIsNotNone(outputs.attentions) diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/__init__.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/test_modeling_flax_mbart.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/test_modeling_flax_mbart.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/test_modeling_mbart.py b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/test_modeling_mbart.py new file mode 100644 index 0000000000000000000000000000000000000000..d7094ca6e4796dd60804b936ed4ecf5d130ebba1 --- /dev/null +++ b/SupplementaryMaterial_Code/OPERA/transformers-4.29.2/tests/models/mbart/test_modeling_mbart.py @@ -0,0 +1,694 @@ +# coding=utf-8 +# Copyright 2021, The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Testing suite for the PyTorch MBART model. """ + + +import copy +import tempfile +import unittest + +from transformers import MBartConfig, is_torch_available +from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device +from transformers.utils import cached_property + +from ...generation.test_utils import GenerationTesterMixin +from ...test_configuration_common import ConfigTester +from ...test_modeling_common import ModelTesterMixin, ids_tensor +from ...test_pipeline_mixin import PipelineTesterMixin + + +if is_torch_available(): + import torch + + from transformers import ( + AutoTokenizer, + BatchEncoding, + MBartForCausalLM, + MBartForConditionalGeneration, + MBartForQuestionAnswering, + MBartForSequenceClassification, + MBartModel, + ) + from transformers.models.mbart.modeling_mbart import MBartDecoder, MBartEncoder + + +def prepare_mbart_inputs_dict( + config, + input_ids, + decoder_input_ids, + attention_mask=None, + decoder_attention_mask=None, + head_mask=None, + decoder_head_mask=None, + cross_attn_head_mask=None, +): + if attention_mask is None: + attention_mask = input_ids.ne(config.pad_token_id) + if decoder_attention_mask is None: + decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id) + if head_mask is None: + head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device) + if decoder_head_mask is None: + decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + if cross_attn_head_mask is None: + cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device) + return { + "input_ids": input_ids, + "decoder_input_ids": decoder_input_ids, + "attention_mask": attention_mask, + "decoder_attention_mask": attention_mask, + "head_mask": head_mask, + "decoder_head_mask": decoder_head_mask, + "cross_attn_head_mask": cross_attn_head_mask, + } + + +class MBartModelTester: + def __init__( + self, + parent, + batch_size=13, + seq_length=7, + is_training=True, + use_labels=False, + vocab_size=99, + hidden_size=16, + num_hidden_layers=2, + num_attention_heads=4, + intermediate_size=4, + hidden_act="gelu", + hidden_dropout_prob=0.1, + attention_probs_dropout_prob=0.1, + max_position_embeddings=100, + eos_token_id=2, + pad_token_id=1, + bos_token_id=0, + ): + self.parent = parent + self.batch_size = batch_size + self.seq_length = seq_length + self.is_training = is_training + self.use_labels = use_labels + self.vocab_size = vocab_size + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.intermediate_size = intermediate_size + self.hidden_act = hidden_act + self.hidden_dropout_prob = hidden_dropout_prob + self.attention_probs_dropout_prob = attention_probs_dropout_prob + self.max_position_embeddings = max_position_embeddings + self.eos_token_id = eos_token_id + self.pad_token_id = pad_token_id + self.bos_token_id = bos_token_id + + # forcing a certain token to be generated, sets all other tokens to -inf + # if however the token to be generated is already at -inf then it can lead token + # `nan` values and thus break generation + self.forced_bos_token_id = None + self.forced_eos_token_id = None + + def prepare_config_and_inputs(self): + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp( + 3, + ) + input_ids[:, -1] = self.eos_token_id # Eos Token + + decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) + + config = self.get_config() + inputs_dict = prepare_mbart_inputs_dict(config, input_ids, decoder_input_ids) + return config, inputs_dict + + def get_config(self): + return MBartConfig( + vocab_size=self.vocab_size, + d_model=self.hidden_size, + encoder_layers=self.num_hidden_layers, + decoder_layers=self.num_hidden_layers, + encoder_attention_heads=self.num_attention_heads, + decoder_attention_heads=self.num_attention_heads, + encoder_ffn_dim=self.intermediate_size, + decoder_ffn_dim=self.intermediate_size, + dropout=self.hidden_dropout_prob, + attention_dropout=self.attention_probs_dropout_prob, + max_position_embeddings=self.max_position_embeddings, + eos_token_id=self.eos_token_id, + bos_token_id=self.bos_token_id, + pad_token_id=self.pad_token_id, + forced_bos_token_id=self.forced_bos_token_id, + forced_eos_token_id=self.forced_eos_token_id, + ) + + def prepare_config_and_inputs_for_common(self): + config, inputs_dict = self.prepare_config_and_inputs() + return config, inputs_dict + + def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict): + model = MBartModel(config=config).get_decoder().to(torch_device).eval() + input_ids = inputs_dict["input_ids"] + attention_mask = inputs_dict["attention_mask"] + head_mask = inputs_dict["head_mask"] + + # first forward pass + outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True) + + output, past_key_values = outputs.to_tuple() + + # create hypothetical multiple next token and extent to next_input_ids + next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size) + next_attn_mask = ids_tensor((self.batch_size, 3), 2) + + # append to next input_ids and + next_input_ids = torch.cat([input_ids, next_tokens], dim=-1) + next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1) + + output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"] + output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[ + "last_hidden_state" + ] + + # select random slice + random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item() + output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach() + output_from_past_slice = output_from_past[:, :, random_slice_idx].detach() + + self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]) + + # test that outputs are equal for slice + self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)) + + def check_encoder_decoder_model_standalone(self, config, inputs_dict): + model = MBartModel(config=config).to(torch_device).eval() + outputs = model(**inputs_dict) + + encoder_last_hidden_state = outputs.encoder_last_hidden_state + last_hidden_state = outputs.last_hidden_state + + with tempfile.TemporaryDirectory() as tmpdirname: + encoder = model.get_encoder() + encoder.save_pretrained(tmpdirname) + encoder = MBartEncoder.from_pretrained(tmpdirname).to(torch_device) + + encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[ + 0 + ] + + self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3) + + with tempfile.TemporaryDirectory() as tmpdirname: + decoder = model.get_decoder() + decoder.save_pretrained(tmpdirname) + decoder = MBartDecoder.from_pretrained(tmpdirname).to(torch_device) + + last_hidden_state_2 = decoder( + input_ids=inputs_dict["decoder_input_ids"], + attention_mask=inputs_dict["decoder_attention_mask"], + encoder_hidden_states=encoder_last_hidden_state, + encoder_attention_mask=inputs_dict["attention_mask"], + )[0] + + self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3) + + +@require_torch +class MBartModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase): + all_model_classes = ( + (MBartModel, MBartForConditionalGeneration, MBartForSequenceClassification, MBartForQuestionAnswering) + if is_torch_available() + else () + ) + all_generative_model_classes = (MBartForConditionalGeneration,) if is_torch_available() else () + pipeline_model_mapping = ( + { + "conversational": MBartForConditionalGeneration, + "feature-extraction": MBartModel, + "fill-mask": MBartForConditionalGeneration, + "question-answering": MBartForQuestionAnswering, + "summarization": MBartForConditionalGeneration, + "text-classification": MBartForSequenceClassification, + "text-generation": MBartForCausalLM, + "text2text-generation": MBartForConditionalGeneration, + "translation": MBartForConditionalGeneration, + "zero-shot": MBartForSequenceClassification, + } + if is_torch_available() + else {} + ) + is_encoder_decoder = True + fx_compatible = False # Fix me Michael + test_pruning = False + test_missing_keys = False + + # TODO: Fix the failed tests + def is_pipeline_test_to_skip( + self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name + ): + if pipeline_test_casse_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"): + return True + + return False + + def setUp(self): + self.model_tester = MBartModelTester(self) + self.config_tester = ConfigTester(self, config_class=MBartConfig) + + def test_config(self): + self.config_tester.run_common_tests() + + def test_save_load_strict(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs() + for model_class in self.all_model_classes: + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True) + self.assertEqual(info["missing_keys"], []) + + def test_decoder_model_past_with_large_inputs(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs() + self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs) + + def test_encoder_decoder_model_standalone(self): + config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common() + self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs) + + # MBartForSequenceClassification does not support inputs_embeds + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in (MBartModel, MBartForConditionalGeneration, MBartForQuestionAnswering): + model = model_class(config) + model.to(torch_device) + model.eval() + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + def test_generate_fp16(self): + config, input_dict = self.model_tester.prepare_config_and_inputs() + input_ids = input_dict["input_ids"] + attention_mask = input_ids.ne(1).to(torch_device) + model = MBartForConditionalGeneration(config).eval().to(torch_device) + if torch_device == "cuda": + model.half() + model.generate(input_ids, attention_mask=attention_mask) + model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3) + + +def assert_tensors_close(a, b, atol=1e-12, prefix=""): + """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error.""" + if a is None and b is None: + return True + try: + if torch.allclose(a, b, atol=atol): + return True + raise + except Exception: + pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item() + if a.numel() > 100: + msg = f"tensor values are {pct_different:.1%} percent different." + else: + msg = f"{a} != {b}" + if prefix: + msg = prefix + ": " + msg + raise AssertionError(msg) + + +def _long_tensor(tok_lst): + return torch.tensor(tok_lst, dtype=torch.long, device=torch_device) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class AbstractSeq2SeqIntegrationTest(unittest.TestCase): + maxDiff = 1000 # longer string compare tracebacks + checkpoint_name = None + + @classmethod + def setUpClass(cls): + cls.tokenizer = AutoTokenizer.from_pretrained(cls.checkpoint_name, use_fast=False) + return cls + + @cached_property + def model(self): + """Only load the model if needed.""" + model = MBartForConditionalGeneration.from_pretrained(self.checkpoint_name).to(torch_device) + if "cuda" in torch_device: + model = model.half() + return model + + +@require_torch +@require_sentencepiece +@require_tokenizers +class MBartEnroIntegrationTest(AbstractSeq2SeqIntegrationTest): + checkpoint_name = "facebook/mbart-large-en-ro" + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", + ] + tgt_text = [ + "Şeful ONU declară că nu există o soluţie militară în Siria", + "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei" + ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor' + " face decât să înrăutăţească violenţa şi mizeria pentru milioane de oameni.", + ] + expected_src_tokens = [8274, 127873, 25916, 7, 8622, 2071, 438, 67485, 53, 187895, 23, 51712, 2, 250004] + + @slow + def test_enro_generate_one(self): + batch: BatchEncoding = self.tokenizer( + ["UN Chief Says There Is No Military Solution in Syria"], return_tensors="pt" + ).to(torch_device) + translated_tokens = self.model.generate(**batch) + decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True) + self.assertEqual(self.tgt_text[0], decoded[0]) + # self.assertEqual(self.tgt_text[1], decoded[1]) + + @slow + def test_enro_generate_batch(self): + batch: BatchEncoding = self.tokenizer(self.src_text, return_tensors="pt", padding=True, truncation=True).to( + torch_device + ) + translated_tokens = self.model.generate(**batch) + decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True) + assert self.tgt_text == decoded + + def test_mbart_enro_config(self): + mbart_models = ["facebook/mbart-large-en-ro"] + expected = {"scale_embedding": True, "output_past": True} + for name in mbart_models: + config = MBartConfig.from_pretrained(name) + for k, v in expected.items(): + try: + self.assertEqual(v, getattr(config, k)) + except AssertionError as e: + e.args += (name, k) + raise + + def test_mbart_fast_forward(self): + config = MBartConfig( + vocab_size=99, + d_model=24, + encoder_layers=2, + decoder_layers=2, + encoder_attention_heads=2, + decoder_attention_heads=2, + encoder_ffn_dim=32, + decoder_ffn_dim=32, + max_position_embeddings=48, + add_final_layer_norm=True, + ) + lm_model = MBartForConditionalGeneration(config).to(torch_device) + context = torch.tensor( + [[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], device=torch_device, dtype=torch.long + ) + summary = torch.tensor([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], device=torch_device, dtype=torch.long) + result = lm_model(input_ids=context, decoder_input_ids=summary, labels=summary) + expected_shape = (*summary.shape, config.vocab_size) + self.assertEqual(result.logits.shape, expected_shape) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class MBartCC25IntegrationTest(AbstractSeq2SeqIntegrationTest): + checkpoint_name = "facebook/mbart-large-cc25" + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + " I ate lunch twice yesterday", + ] + tgt_text = ["Şeful ONU declară că nu există o soluţie militară în Siria", "to be padded"] + + @unittest.skip("This test is broken, still generates english") + def test_cc25_generate(self): + inputs = self.tokenizer([self.src_text[0]], return_tensors="pt").to(torch_device) + translated_tokens = self.model.generate( + input_ids=inputs["input_ids"].to(torch_device), + decoder_start_token_id=self.tokenizer.lang_code_to_id["ro_RO"], + ) + decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True) + self.assertEqual(self.tgt_text[0], decoded[0]) + + @slow + def test_fill_mask(self): + inputs = self.tokenizer(["One of the best
+
+
+
+## Train
+
+*Below is the latest training configuration for LLaVA v1.5. For legacy models, please refer to README of [this](https://github.com/haotian-liu/LLaVA/tree/v1.0.1) version for now. We'll add them in a separate doc later.*
+
+LLaVA training consists of two stages: (1) feature alignment stage: use our 558K subset of the LAION-CC-SBU dataset to connect a *frozen pretrained* vision encoder to a *frozen LLM*; (2) visual instruction tuning stage: use 150K GPT-generated multimodal instruction-following data, plus around 515K VQA data from academic-oriented tasks, to teach the model to follow multimodal instructions.
+
+LLaVA is trained on 8 A100 GPUs with 80GB memory. To train on fewer GPUs, you can reduce the `per_device_train_batch_size` and increase the `gradient_accumulation_steps` accordingly. Always keep the global batch size the same: `per_device_train_batch_size` x `gradient_accumulation_steps` x `num_gpus`.
+
+### Hyperparameters
+We use a similar set of hyperparameters as Vicuna in finetuning. Both hyperparameters used in pretraining and finetuning are provided below.
+
+1. Pretraining
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 256 | 1e-3 | 1 | 2048 | 0 |
+
+2. Finetuning
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 128 | 2e-5 | 1 | 2048 | 0 |
+
+### Download Vicuna checkpoints (automatically)
+
+Our base model Vicuna v1.5, which is an instruction-tuned chatbot, will be downloaded automatically when you run our provided training scripts. No action is needed.
+
+### Pretrain (feature alignment)
+
+Please download the 558K subset of the LAION-CC-SBU dataset with BLIP captions we use in the paper [here](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain).
+
+Pretrain takes around 5.5 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 3.5 hours for LLaVA-v1.5-7B.
+
+Training script with DeepSpeed ZeRO-2: [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/pretrain.sh).
+
+- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
+- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
+
+
+
diff --git a/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/LoRA.md b/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/LoRA.md
new file mode 100644
index 0000000000000000000000000000000000000000..bed25f57d0aaa8c37f63703f6f641999b02b1b3e
--- /dev/null
+++ b/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/LoRA.md
@@ -0,0 +1,46 @@
+# LLaVA (LoRA, Preview)
+
+NOTE: This is a technical preview, and is not yet ready for production use. We are still running hyperparameter search for the LoRA model, and will release the final model soon. If you'd like to contribute to this, please contact us.
+
+You need latest code base for LoRA support (instructions [here](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base))
+
+## Demo (Web UI)
+
+Please execute each of the commands below one by one (after the previous one has finished). The commands are the same as launching other demos except for an additional `--model-base` flag to specify the base model to use. Please make sure the base model corresponds to the LoRA checkpoint that you are using. For this technical preview, you need Vicuna v1.1 (7B) checkpoint (if you do not have that already, follow the instructions [here](https://github.com/lm-sys/FastChat#vicuna-weights)).
+
+#### Launch a controller
+```Shell
+python -m llava.serve.controller --host 0.0.0.0 --port 10000
+```
+
+#### Launch a gradio web server.
+```Shell
+python -m llava.serve.gradio_web_server --controller http://localhost:10000 --model-list-mode reload
+```
+You just launched the Gradio web interface. Now, you can open the web interface with the URL printed on the screen. You may notice that there is no model in the model list. Do not worry, as we have not launched any model worker yet. It will be automatically updated when you launch a model worker.
+
+#### Launch a model worker
+```Shell
+python -m llava.serve.model_worker --host 0.0.0.0 --controller http://localhost:10000 --port 40000 --worker http://localhost:40000 --model-path liuhaotian/llava-vicuna-7b-v1.1-lcs_558k-instruct_80k_3e-lora-preview-alpha --model-base /path/to/vicuna-v1.1
+```
+Wait until the process finishes loading the model and you see "Uvicorn running on ...". Now, refresh your Gradio web UI, and you will see the model you just launched in the model list.
+
+You can launch as many workers as you want, and compare between different model checkpoints in the same Gradio interface. Please keep the `--controller` the same, and modify the `--port` and `--worker` to a different port number for each worker.
+
+
+## Training
+
+Please see sample training scripts for [LoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_lora.sh) and [QLoRA](https://github.com/haotian-liu/LLaVA/blob/main/scripts/finetune_qlora.sh).
+
+We provide sample DeepSpeed configs, [`zero3.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3.json) is more like PyTorch FSDP, and [`zero3_offload.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero3_offload.json) can further save memory consumption by offloading parameters to CPU. `zero3.json` is usually faster than `zero3_offload.json` but requires more GPU memory, therefore, we recommend trying `zero3.json` first, and if you run out of GPU memory, try `zero3_offload.json`. You can also tweak the `per_device_train_batch_size` and `gradient_accumulation_steps` in the config to save memory, and just to make sure that `per_device_train_batch_size` and `gradient_accumulation_steps` remains the same.
+
+If you are having issues with ZeRO-3 configs, and there are enough VRAM, you may try [`zero2.json`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/zero2.json). This consumes slightly more memory than ZeRO-3, and behaves more similar to PyTorch FSDP, while still supporting parameter-efficient tuning.
+
+## Create Merged Checkpoints
+
+```Shell
+python scripts/merge_lora_weights.py \
+ --model-path /path/to/lora_model \
+ --model-base /path/to/base_model \
+ --save-model-path /path/to/merge_model
+```
diff --git a/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/MODEL_ZOO.md b/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/MODEL_ZOO.md
new file mode 100644
index 0000000000000000000000000000000000000000..2d870e6c0b8e97dc08d4e1b6a2d4ca0af9185ee1
--- /dev/null
+++ b/SupplementaryMaterial_Code/VLMEvalKit/LLaVA/docs/MODEL_ZOO.md
@@ -0,0 +1,150 @@
+# Model Zoo
+
+**To Use LLaVA-1.6 checkpoints, your llava package version must be newer than 1.2.0. [Instructions](https://github.com/haotian-liu/LLaVA#upgrade-to-latest-code-base) on how to upgrade.**
+
+If you are interested in including any other details in Model Zoo, please open an issue :)
+
+The model weights below are *merged* weights. You do not need to apply delta. The usage of LLaVA checkpoints should comply with the base LLM's model license.
+
+## LLaVA-v1.6
+
+| Version | LLM | Schedule | Checkpoint | MMMU | MathVista | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED-IMG | LLaVA-Bench-Wild | MM-Vet |
+|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
+| LLaVA-1.6 | Vicuna-7B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-7b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-7b) | 35.8 | 34.6 | 81.8 | 64.2 | 57.6 | 70.1 | 64.9 | 86.5 | 1519/332 | 67.4 | 60.6 | 70.2 | 81.6 | 43.9 |
+| LLaVA-1.6 | Vicuna-13B | full_ft-1e | [liuhaotian/llava-v1.6-vicuna-13b](https://huggingface.co/liuhaotian/llava-v1.6-vicuna-13b) | 36.2 | 35.3 | 82.8 | 65.4 | 60.5 | 73.6 | 67.1 | 86.2 | 1575/326 | 70 | 64.4 | 71.9 | 87.3 | 48.4 |
+| LLaVA-1.6 | Mistral-7B | full_ft-1e | [liuhaotian/llava-v1.6-mistral-7b](https://huggingface.co/liuhaotian/llava-v1.6-mistral-7b) | 35.3 | 37.7 | 82.2 | 64.8 | 60.0 | 72.8 | 65.7 | 86.7 | 1498/321 | 68.7 | 61.2 | 72.2 | 83.2 | 47.3 |
+| LLaVA-1.6 | Hermes-Yi-34B | full_ft-1e | [liuhaotian/llava-v1.6-34b](https://huggingface.co/liuhaotian/llava-v1.6-34b) | 51.1 | 46.5 | 83.7 | 67.1 | 63.8 | 81.8 | 69.5 | 87.7 | 1631/397 | 79.3 | 79 | 75.9 | 89.6 | 57.4 |
+
+*LLaVA-1.6-34B outperforms Gemini Pro on benchmarks like MMMU and MathVista.*
+
+
+## LLaVA-v1.5
+
+| Version | Size | Schedule | Checkpoint | VQAv2 | GQA | VizWiz | SQA | TextVQA | POPE | MME | MM-Bench | MM-Bench-CN | SEED | LLaVA-Bench-Wild | MM-Vet |
+|----------|----------|-----------|-----------|---|---|---|---|---|---|---|---|---|---|---|---|
+| LLaVA-1.5 | 7B | full_ft-1e | [liuhaotian/llava-v1.5-7b](https://huggingface.co/liuhaotian/llava-v1.5-7b) | 78.5 | 62.0 | 50.0 | 66.8 | 58.2 | 85.9 | 1510.7 | 64.3 | 58.3 | 58.6 | 65.4 | 31.1 |
+| LLaVA-1.5 | 13B | full_ft-1e | [liuhaotian/llava-v1.5-13b](https://huggingface.co/liuhaotian/llava-v1.5-13b) | 80.0 | 63.3 | 53.6 | 71.6 | 61.3 | 85.9 | 1531.3 | 67.7 | 63.6 | 61.6 | 72.5 | 36.1 |
+| LLaVA-1.5 | 7B | lora-1e | [liuhaotian/llava-v1.5-7b-lora](https://huggingface.co/liuhaotian/llava-v1.5-7b-lora) | 79.1 | 63.0 | 47.8 | 68.4 | 58.2 | 86.4 | 1476.9 | 66.1 | 58.9 | 60.1 | 67.9 | 30.2 |
+| LLaVA-1.5 | 13B | lora-1e | [liuhaotian/llava-v1.5-13b-lora](https://huggingface.co/liuhaotian/llava-v1.5-13b-lora) | 80.0 | 63.3 | 58.9 | 71.2 | 60.2 | 86.7 | 1541.7 | 68.5 | 61.5 | 61.3 | 69.5 | 38.3 |
+
+Base model: Vicuna v1.5. Training logs: [wandb](https://api.wandb.ai/links/lht/6orh56wc).
+
+
+
+ LLaVA-1.5 achieves SoTA performance across 11 benchmarks.
+
+
+
+
+## Train
+
+*Below is the latest training configuration for LLaVA v1.5. For legacy models, please refer to README of [this](https://github.com/haotian-liu/LLaVA/tree/v1.0.1) version for now. We'll add them in a separate doc later.*
+
+LLaVA training consists of two stages: (1) feature alignment stage: use our 558K subset of the LAION-CC-SBU dataset to connect a *frozen pretrained* vision encoder to a *frozen LLM*; (2) visual instruction tuning stage: use 150K GPT-generated multimodal instruction-following data, plus around 515K VQA data from academic-oriented tasks, to teach the model to follow multimodal instructions.
+
+LLaVA is trained on 8 A100 GPUs with 80GB memory. To train on fewer GPUs, you can reduce the `per_device_train_batch_size` and increase the `gradient_accumulation_steps` accordingly. Always keep the global batch size the same: `per_device_train_batch_size` x `gradient_accumulation_steps` x `num_gpus`.
+
+### Hyperparameters
+We use a similar set of hyperparameters as Vicuna in finetuning. Both hyperparameters used in pretraining and finetuning are provided below.
+
+1. Pretraining
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 256 | 1e-3 | 1 | 2048 | 0 |
+
+2. Finetuning
+
+| Hyperparameter | Global Batch Size | Learning rate | Epochs | Max length | Weight decay |
+| --- | ---: | ---: | ---: | ---: | ---: |
+| LLaVA-v1.5-13B | 128 | 2e-5 | 1 | 2048 | 0 |
+
+### Download Vicuna checkpoints (automatically)
+
+Our base model Vicuna v1.5, which is an instruction-tuned chatbot, will be downloaded automatically when you run our provided training scripts. No action is needed.
+
+### Pretrain (feature alignment)
+
+Please download the 558K subset of the LAION-CC-SBU dataset with BLIP captions we use in the paper [here](https://huggingface.co/datasets/liuhaotian/LLaVA-Pretrain).
+
+Pretrain takes around 5.5 hours for LLaVA-v1.5-13B on 8x A100 (80G), due to the increased resolution to 336px. It takes around 3.5 hours for LLaVA-v1.5-7B.
+
+Training script with DeepSpeed ZeRO-2: [`pretrain.sh`](https://github.com/haotian-liu/LLaVA/blob/main/scripts/v1_5/pretrain.sh).
+
+- `--mm_projector_type mlp2x_gelu`: the two-layer MLP vision-language connector.
+- `--vision_tower openai/clip-vit-large-patch14-336`: CLIP ViT-L/14 336px.
+
+
+