transformers
266 строк · 10.5 Кб
1# coding=utf-8
2# Copyright 2021 HuggingFace Inc.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16
17import json18import os19import tempfile20import unittest21
22import numpy as np23from datasets import load_dataset24
25from transformers.testing_utils import require_torch, require_vision, slow26from transformers.utils import is_torch_available, is_vision_available27
28from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs29
30
31if is_torch_available():32import torch33
34if is_vision_available():35from PIL import Image36
37from transformers import ImageGPTImageProcessor38
39
40class ImageGPTImageProcessingTester(unittest.TestCase):41def __init__(42self,43parent,44batch_size=7,45num_channels=3,46image_size=18,47min_resolution=30,48max_resolution=400,49do_resize=True,50size=None,51do_normalize=True,52):53size = size if size is not None else {"height": 18, "width": 18}54self.parent = parent55self.batch_size = batch_size56self.num_channels = num_channels57self.image_size = image_size58self.min_resolution = min_resolution59self.max_resolution = max_resolution60self.do_resize = do_resize61self.size = size62self.do_normalize = do_normalize63
64def prepare_image_processor_dict(self):65return {66# here we create 2 clusters for the sake of simplicity67"clusters": np.asarray(68[69[0.8866443634033203, 0.6618829369544983, 0.3891746401786804],70[-0.6042559146881104, -0.02295008860528469, 0.5423797369003296],71]72),73"do_resize": self.do_resize,74"size": self.size,75"do_normalize": self.do_normalize,76}77
78def expected_output_image_shape(self, images):79return (self.size["height"] * self.size["width"],)80
81def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):82return prepare_image_inputs(83batch_size=self.batch_size,84num_channels=self.num_channels,85min_resolution=self.min_resolution,86max_resolution=self.max_resolution,87equal_resolution=equal_resolution,88numpify=numpify,89torchify=torchify,90)91
92
93@require_torch
94@require_vision
95class ImageGPTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):96image_processing_class = ImageGPTImageProcessor if is_vision_available() else None97
98def setUp(self):99self.image_processor_tester = ImageGPTImageProcessingTester(self)100
101@property102def image_processor_dict(self):103return self.image_processor_tester.prepare_image_processor_dict()104
105def test_image_processor_properties(self):106image_processing = self.image_processing_class(**self.image_processor_dict)107self.assertTrue(hasattr(image_processing, "clusters"))108self.assertTrue(hasattr(image_processing, "do_resize"))109self.assertTrue(hasattr(image_processing, "size"))110self.assertTrue(hasattr(image_processing, "do_normalize"))111
112def test_image_processor_from_dict_with_kwargs(self):113image_processor = self.image_processing_class.from_dict(self.image_processor_dict)114self.assertEqual(image_processor.size, {"height": 18, "width": 18})115
116image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42)117self.assertEqual(image_processor.size, {"height": 42, "width": 42})118
119def test_image_processor_to_json_string(self):120image_processor = self.image_processing_class(**self.image_processor_dict)121obj = json.loads(image_processor.to_json_string())122for key, value in self.image_processor_dict.items():123if key == "clusters":124self.assertTrue(np.array_equal(value, obj[key]))125else:126self.assertEqual(obj[key], value)127
128def test_image_processor_to_json_file(self):129image_processor_first = self.image_processing_class(**self.image_processor_dict)130
131with tempfile.TemporaryDirectory() as tmpdirname:132json_file_path = os.path.join(tmpdirname, "image_processor.json")133image_processor_first.to_json_file(json_file_path)134image_processor_second = self.image_processing_class.from_json_file(json_file_path).to_dict()135
136image_processor_first = image_processor_first.to_dict()137for key, value in image_processor_first.items():138if key == "clusters":139self.assertTrue(np.array_equal(value, image_processor_second[key]))140else:141self.assertEqual(image_processor_first[key], value)142
143def test_image_processor_from_and_save_pretrained(self):144image_processor_first = self.image_processing_class(**self.image_processor_dict)145
146with tempfile.TemporaryDirectory() as tmpdirname:147image_processor_first.save_pretrained(tmpdirname)148image_processor_second = self.image_processing_class.from_pretrained(tmpdirname).to_dict()149
150image_processor_first = image_processor_first.to_dict()151for key, value in image_processor_first.items():152if key == "clusters":153self.assertTrue(np.array_equal(value, image_processor_second[key]))154else:155self.assertEqual(image_processor_first[key], value)156
157@unittest.skip("ImageGPT requires clusters at initialization")158def test_init_without_params(self):159pass160
161# Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input162def test_call_pil(self):163# Initialize image_processing164image_processing = self.image_processing_class(**self.image_processor_dict)165# create random PIL images166image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)167for image in image_inputs:168self.assertIsInstance(image, Image.Image)169
170# Test not batched input171encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids172expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(encoded_images)173self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))174
175# Test batched176encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids177self.assertEqual(178tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)179)180
181# Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input182def test_call_numpy(self):183# Initialize image_processing184image_processing = self.image_processing_class(**self.image_processor_dict)185# create random numpy tensors186image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)187for image in image_inputs:188self.assertIsInstance(image, np.ndarray)189
190# Test not batched input191encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids192expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(encoded_images)193self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))194
195# Test batched196encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids197self.assertEqual(198tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape)199)200
201@unittest.skip("ImageGPT assumes clusters for 3 channels")202def test_call_numpy_4_channels(self):203pass204
205# Override the test from ImageProcessingTestMixin as ImageGPT model takes input_ids as input206def test_call_pytorch(self):207# Initialize image_processing208image_processing = self.image_processing_class(**self.image_processor_dict)209# create random PyTorch tensors210image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)211expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)212
213for image in image_inputs:214self.assertIsInstance(image, torch.Tensor)215
216# Test not batched input217encoded_images = image_processing(image_inputs[0], return_tensors="pt").input_ids218self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape))219
220# Test batched221encoded_images = image_processing(image_inputs, return_tensors="pt").input_ids222self.assertEqual(223tuple(encoded_images.shape),224(self.image_processor_tester.batch_size, *expected_output_image_shape),225)226
227
228def prepare_images():229# we use revision="refs/pr/1" until the PR is merged230# https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1231dataset = load_dataset("hf-internal-testing/fixtures_image_utils", split="test", revision="refs/pr/1")232
233image1 = dataset[4]["image"]234image2 = dataset[5]["image"]235
236images = [image1, image2]237
238return images239
240
241@require_vision
242@require_torch
243class ImageGPTImageProcessorIntegrationTest(unittest.TestCase):244@slow245def test_image(self):246image_processing = ImageGPTImageProcessor.from_pretrained("openai/imagegpt-small")247
248images = prepare_images()249
250# test non-batched251encoding = image_processing(images[0], return_tensors="pt")252
253self.assertIsInstance(encoding.input_ids, torch.LongTensor)254self.assertEqual(encoding.input_ids.shape, (1, 1024))255
256expected_slice = [306, 191, 191]257self.assertEqual(encoding.input_ids[0, :3].tolist(), expected_slice)258
259# test batched260encoding = image_processing(images, return_tensors="pt")261
262self.assertIsInstance(encoding.input_ids, torch.LongTensor)263self.assertEqual(encoding.input_ids.shape, (2, 1024))264
265expected_slice = [303, 13, 13]266self.assertEqual(encoding.input_ids[1, -3:].tolist(), expected_slice)267