transformers

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

16

17
from __future__ import annotations
18

19
import unittest
20

21
from transformers import EsmConfig, is_tf_available
22
from transformers.testing_utils import require_tf, slow
23

24
from ...test_configuration_common import ConfigTester
25
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
26
from ...test_pipeline_mixin import PipelineTesterMixin
27

28

29
if is_tf_available():
30
    import numpy
31
    import tensorflow as tf
32

33
    from transformers.modeling_tf_utils import keras
34
    from transformers.models.esm.modeling_tf_esm import (
35
        TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
36
        TFEsmForMaskedLM,
37
        TFEsmForSequenceClassification,
38
        TFEsmForTokenClassification,
39
        TFEsmModel,
40
    )
41

42

43
# copied from tests.test_modeling_tf_roberta
44
class TFEsmModelTester:
45
    def __init__(
46
        self,
47
        parent,
48
    ):
49
        self.parent = parent
50
        self.batch_size = 13
51
        self.seq_length = 7
52
        self.is_training = True
53
        self.use_input_mask = True
54
        self.use_labels = True
55
        self.vocab_size = 99
56
        self.hidden_size = 32
57
        self.num_hidden_layers = 2
58
        self.num_attention_heads = 4
59
        self.intermediate_size = 37
60
        self.hidden_act = "gelu"
61
        self.hidden_dropout_prob = 0.1
62
        self.attention_probs_dropout_prob = 0.1
63
        self.max_position_embeddings = 512
64
        self.type_vocab_size = 16
65
        self.type_sequence_label_size = 2
66
        self.initializer_range = 0.02
67
        self.num_labels = 3
68
        self.num_choices = 4
69
        self.scope = None
70

71
    def prepare_config_and_inputs(self):
72
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
73

74
        input_mask = None
75
        if self.use_input_mask:
76
            input_mask = random_attention_mask([self.batch_size, self.seq_length])
77

78
        sequence_labels = None
79
        token_labels = None
80
        choice_labels = None
81
        if self.use_labels:
82
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
83
            token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
84
            choice_labels = ids_tensor([self.batch_size], self.num_choices)
85

86
        config = EsmConfig(
87
            vocab_size=self.vocab_size,
88
            hidden_size=self.hidden_size,
89
            num_hidden_layers=self.num_hidden_layers,
90
            pad_token_id=1,
91
            num_attention_heads=self.num_attention_heads,
92
            intermediate_size=self.intermediate_size,
93
            hidden_act=self.hidden_act,
94
            hidden_dropout_prob=self.hidden_dropout_prob,
95
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
96
            max_position_embeddings=self.max_position_embeddings,
97
            type_vocab_size=self.type_vocab_size,
98
            initializer_range=self.initializer_range,
99
        )
100

101
        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
102

103
    def prepare_config_and_inputs_for_decoder(self):
104
        (
105
            config,
106
            input_ids,
107
            input_mask,
108
            sequence_labels,
109
            token_labels,
110
            choice_labels,
111
        ) = self.prepare_config_and_inputs()
112

113
        config.is_decoder = True
114
        encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
115
        encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
116

117
        return (
118
            config,
119
            input_ids,
120
            input_mask,
121
            sequence_labels,
122
            token_labels,
123
            choice_labels,
124
            encoder_hidden_states,
125
            encoder_attention_mask,
126
        )
127

128
    def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels):
129
        model = TFEsmModel(config=config)
130
        inputs = {"input_ids": input_ids, "attention_mask": input_mask}
131
        result = model(inputs)
132

133
        inputs = [input_ids, input_mask]
134
        result = model(inputs)
135

136
        result = model(input_ids)
137

138
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
139

140
    def create_and_check_model_as_decoder(
141
        self,
142
        config,
143
        input_ids,
144
        input_mask,
145
        sequence_labels,
146
        token_labels,
147
        choice_labels,
148
        encoder_hidden_states,
149
        encoder_attention_mask,
150
    ):
151
        config.add_cross_attention = True
152

153
        model = TFEsmModel(config=config)
154
        inputs = {
155
            "input_ids": input_ids,
156
            "attention_mask": input_mask,
157
            "encoder_hidden_states": encoder_hidden_states,
158
            "encoder_attention_mask": encoder_attention_mask,
159
        }
160
        result = model(inputs)
161

162
        inputs = [input_ids, input_mask]
163
        result = model(inputs, encoder_hidden_states=encoder_hidden_states)
164

165
        # Also check the case where encoder outputs are not passed
166
        result = model(input_ids, attention_mask=input_mask)
167

168
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
169

170
    def create_and_check_for_masked_lm(
171
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
172
    ):
173
        model = TFEsmForMaskedLM(config=config)
174
        result = model([input_ids, input_mask])
175
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
176

177
    def create_and_check_for_token_classification(
178
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
179
    ):
180
        config.num_labels = self.num_labels
181
        model = TFEsmForTokenClassification(config=config)
182
        inputs = {"input_ids": input_ids, "attention_mask": input_mask}
183
        result = model(inputs)
184
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
185

186
    def prepare_config_and_inputs_for_common(self):
187
        config_and_inputs = self.prepare_config_and_inputs()
188
        (
189
            config,
190
            input_ids,
191
            input_mask,
192
            sequence_labels,
193
            token_labels,
194
            choice_labels,
195
        ) = config_and_inputs
196
        inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
197
        return config, inputs_dict
198

199

200
@require_tf
201
class TFEsmModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
202
    all_model_classes = (
203
        (
204
            TFEsmModel,
205
            TFEsmForMaskedLM,
206
            TFEsmForSequenceClassification,
207
            TFEsmForTokenClassification,
208
        )
209
        if is_tf_available()
210
        else ()
211
    )
212
    pipeline_model_mapping = (
213
        {
214
            "feature-extraction": TFEsmModel,
215
            "fill-mask": TFEsmForMaskedLM,
216
            "text-classification": TFEsmForSequenceClassification,
217
            "token-classification": TFEsmForTokenClassification,
218
            "zero-shot": TFEsmForSequenceClassification,
219
        }
220
        if is_tf_available()
221
        else {}
222
    )
223
    test_head_masking = False
224
    test_onnx = False
225

226
    def setUp(self):
227
        self.model_tester = TFEsmModelTester(self)
228
        self.config_tester = ConfigTester(self, config_class=EsmConfig, hidden_size=37)
229

230
    def test_config(self):
231
        self.config_tester.run_common_tests()
232

233
    def test_model(self):
234
        """Test the base model"""
235
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
236
        self.model_tester.create_and_check_model(*config_and_inputs)
237

238
    def test_model_as_decoder(self):
239
        """Test the base model as a decoder (of an encoder-decoder architecture)
240

241
        is_deocder=True + cross_attention + pass encoder outputs
242
        """
243
        config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
244
        self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
245

246
    def test_for_masked_lm(self):
247
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
248
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
249

250
    def test_for_token_classification(self):
251
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
252
        self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
253

254
    @slow
255
    def test_model_from_pretrained(self):
256
        for model_name in TF_ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
257
            model = TFEsmModel.from_pretrained(model_name)
258
            self.assertIsNotNone(model)
259

260
    @unittest.skip("Protein models do not support embedding resizing.")
261
    def test_resize_token_embeddings(self):
262
        pass
263

264
    @unittest.skip("Protein models do not support embedding resizing.")
265
    def test_save_load_after_resize_token_embeddings(self):
266
        pass
267

268
    def test_model_common_attributes(self):
269
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
270

271
        for model_class in self.all_model_classes:
272
            model = model_class(config)
273
            assert isinstance(model.get_input_embeddings(), keras.layers.Layer)
274
            if model_class is TFEsmForMaskedLM:
275
                # Output embedding test differs from the main test because they're a matrix, not a layer
276
                name = model.get_bias()
277
                assert isinstance(name, dict)
278
                for k, v in name.items():
279
                    assert isinstance(v, tf.Variable)
280
            else:
281
                x = model.get_output_embeddings()
282
                assert x is None
283
                name = model.get_bias()
284
                assert name is None
285

286

287
@require_tf
288
class TFEsmModelIntegrationTest(unittest.TestCase):
289
    @slow
290
    def test_inference_masked_lm(self):
291
        model = TFEsmForMaskedLM.from_pretrained("facebook/esm2_t6_8M_UR50D")
292

293
        input_ids = tf.constant([[0, 1, 2, 3, 4, 5]])
294
        output = model(input_ids)[0]
295
        expected_shape = [1, 6, 33]
296
        self.assertEqual(list(output.numpy().shape), expected_shape)
297
        # compare the actual values for a slice.
298
        expected_slice = tf.constant(
299
            [
300
                [
301
                    [8.921518, -10.589814, -6.4671307],
302
                    [-6.3967156, -13.911377, -1.1211915],
303
                    [-7.781247, -13.951557, -3.740592],
304
                ]
305
            ]
306
        )
307
        self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-2))
308

309
    @slow
310
    def test_inference_no_head(self):
311
        model = TFEsmModel.from_pretrained("facebook/esm2_t6_8M_UR50D")
312

313
        input_ids = tf.constant([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
314
        output = model(input_ids)[0]
315
        # compare the actual values for a slice.
316
        expected_slice = tf.constant(
317
            [
318
                [
319
                    [0.14443092, 0.54125327, 0.3247739],
320
                    [0.30340484, 0.00526676, 0.31077722],
321
                    [0.32278043, -0.24987096, 0.3414628],
322
                ]
323
            ]
324
        )
325
        self.assertTrue(numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4))
326

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

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

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

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