transformers

Форк
0
/
test_processor_pix2struct.py 
192 строки · 7.2 Кб
1
# Copyright 2023 The HuggingFace Team. All rights reserved.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14
import shutil
15
import tempfile
16
import unittest
17

18
import numpy as np
19
import pytest
20

21
from transformers.testing_utils import require_torch, require_vision
22
from transformers.utils import is_vision_available
23

24

25
if is_vision_available():
26
    from PIL import Image
27

28
    from transformers import (
29
        AutoProcessor,
30
        Pix2StructImageProcessor,
31
        Pix2StructProcessor,
32
        PreTrainedTokenizerFast,
33
        T5Tokenizer,
34
    )
35

36

37
@require_vision
38
@require_torch
39
class Pix2StructProcessorTest(unittest.TestCase):
40
    def setUp(self):
41
        self.tmpdirname = tempfile.mkdtemp()
42

43
        image_processor = Pix2StructImageProcessor()
44
        tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
45

46
        processor = Pix2StructProcessor(image_processor, tokenizer)
47

48
        processor.save_pretrained(self.tmpdirname)
49

50
    def get_tokenizer(self, **kwargs):
51
        return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
52

53
    def get_image_processor(self, **kwargs):
54
        return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
55

56
    def tearDown(self):
57
        shutil.rmtree(self.tmpdirname)
58

59
    def prepare_image_inputs(self):
60
        """
61
        This function prepares a list of random PIL images of the same fixed size.
62
        """
63

64
        image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)]
65

66
        image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs]
67

68
        return image_inputs
69

70
    def test_save_load_pretrained_additional_features(self):
71
        processor = Pix2StructProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
72
        processor.save_pretrained(self.tmpdirname)
73

74
        tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
75
        image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
76

77
        processor = Pix2StructProcessor.from_pretrained(
78
            self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
79
        )
80

81
        self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
82
        self.assertIsInstance(processor.tokenizer, PreTrainedTokenizerFast)
83

84
        self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
85
        self.assertIsInstance(processor.image_processor, Pix2StructImageProcessor)
86

87
    def test_image_processor(self):
88
        image_processor = self.get_image_processor()
89
        tokenizer = self.get_tokenizer()
90

91
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
92

93
        image_input = self.prepare_image_inputs()
94

95
        input_feat_extract = image_processor(image_input, return_tensors="np")
96
        input_processor = processor(images=image_input, return_tensors="np")
97

98
        for key in input_feat_extract.keys():
99
            self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
100

101
    def test_tokenizer(self):
102
        image_processor = self.get_image_processor()
103
        tokenizer = self.get_tokenizer()
104

105
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
106

107
        input_str = "lower newer"
108

109
        encoded_processor = processor(text=input_str)
110

111
        encoded_tok = tokenizer(input_str, return_token_type_ids=False, add_special_tokens=True)
112

113
        for key in encoded_tok.keys():
114
            self.assertListEqual(encoded_tok[key], encoded_processor[key])
115

116
    def test_processor(self):
117
        image_processor = self.get_image_processor()
118
        tokenizer = self.get_tokenizer()
119

120
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
121

122
        input_str = "lower newer"
123
        image_input = self.prepare_image_inputs()
124

125
        inputs = processor(text=input_str, images=image_input)
126

127
        self.assertListEqual(
128
            list(inputs.keys()), ["flattened_patches", "attention_mask", "decoder_attention_mask", "decoder_input_ids"]
129
        )
130

131
        # test if it raises when no input is passed
132
        with pytest.raises(ValueError):
133
            processor()
134

135
    def test_processor_max_patches(self):
136
        image_processor = self.get_image_processor()
137
        tokenizer = self.get_tokenizer()
138

139
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
140

141
        input_str = "lower newer"
142
        image_input = self.prepare_image_inputs()
143

144
        inputs = processor(text=input_str, images=image_input)
145

146
        max_patches = [512, 1024, 2048, 4096]
147
        expected_hidden_size = [770, 770, 770, 770]
148
        # with text
149
        for i, max_patch in enumerate(max_patches):
150
            inputs = processor(text=input_str, images=image_input, max_patches=max_patch)
151
            self.assertEqual(inputs["flattened_patches"][0].shape[0], max_patch)
152
            self.assertEqual(inputs["flattened_patches"][0].shape[1], expected_hidden_size[i])
153

154
        # without text input
155
        for i, max_patch in enumerate(max_patches):
156
            inputs = processor(images=image_input, max_patches=max_patch)
157
            self.assertEqual(inputs["flattened_patches"][0].shape[0], max_patch)
158
            self.assertEqual(inputs["flattened_patches"][0].shape[1], expected_hidden_size[i])
159

160
    def test_tokenizer_decode(self):
161
        image_processor = self.get_image_processor()
162
        tokenizer = self.get_tokenizer()
163

164
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
165

166
        predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
167

168
        decoded_processor = processor.batch_decode(predicted_ids)
169
        decoded_tok = tokenizer.batch_decode(predicted_ids)
170

171
        self.assertListEqual(decoded_tok, decoded_processor)
172

173
    def test_model_input_names(self):
174
        image_processor = self.get_image_processor()
175
        tokenizer = self.get_tokenizer()
176

177
        processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
178

179
        input_str = "lower newer"
180
        image_input = self.prepare_image_inputs()
181

182
        inputs = processor(text=input_str, images=image_input)
183

184
        # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
185
        self.assertListEqual(
186
            list(inputs.keys()), ["flattened_patches", "attention_mask", "decoder_attention_mask", "decoder_input_ids"]
187
        )
188

189
        inputs = processor(text=input_str)
190

191
        # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
192
        self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask"])
193

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.