transformers
278 строк · 9.7 Кб
1# coding=utf-8
2# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15""" Testing suite for the PyTorch ESM model. """
16
17
18import unittest
19
20from transformers import EsmConfig, is_torch_available
21from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
22
23from ...test_configuration_common import ConfigTester
24from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
25from ...test_pipeline_mixin import PipelineTesterMixin
26
27
28if is_torch_available():
29import torch
30
31from transformers.models.esm.modeling_esmfold import EsmForProteinFolding
32
33
34class EsmFoldModelTester:
35def __init__(
36self,
37parent,
38batch_size=13,
39seq_length=7,
40is_training=False,
41use_input_mask=True,
42use_token_type_ids=False,
43use_labels=False,
44vocab_size=19,
45hidden_size=32,
46num_hidden_layers=2,
47num_attention_heads=4,
48intermediate_size=37,
49hidden_act="gelu",
50hidden_dropout_prob=0.1,
51attention_probs_dropout_prob=0.1,
52max_position_embeddings=512,
53type_vocab_size=16,
54type_sequence_label_size=2,
55initializer_range=0.02,
56num_labels=3,
57num_choices=4,
58scope=None,
59):
60self.parent = parent
61self.batch_size = batch_size
62self.seq_length = seq_length
63self.is_training = is_training
64self.use_input_mask = use_input_mask
65self.use_token_type_ids = use_token_type_ids
66self.use_labels = use_labels
67self.vocab_size = vocab_size
68self.hidden_size = hidden_size
69self.num_hidden_layers = num_hidden_layers
70self.num_attention_heads = num_attention_heads
71self.intermediate_size = intermediate_size
72self.hidden_act = hidden_act
73self.hidden_dropout_prob = hidden_dropout_prob
74self.attention_probs_dropout_prob = attention_probs_dropout_prob
75self.max_position_embeddings = max_position_embeddings
76self.type_vocab_size = type_vocab_size
77self.type_sequence_label_size = type_sequence_label_size
78self.initializer_range = initializer_range
79self.num_labels = num_labels
80self.num_choices = num_choices
81self.scope = scope
82
83def prepare_config_and_inputs(self):
84input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
85
86input_mask = None
87if self.use_input_mask:
88input_mask = random_attention_mask([self.batch_size, self.seq_length])
89
90sequence_labels = None
91token_labels = None
92choice_labels = None
93if self.use_labels:
94sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
95token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
96choice_labels = ids_tensor([self.batch_size], self.num_choices)
97
98config = self.get_config()
99
100return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
101
102def get_config(self):
103esmfold_config = {
104"trunk": {
105"num_blocks": 2,
106"sequence_state_dim": 64,
107"pairwise_state_dim": 16,
108"sequence_head_width": 4,
109"pairwise_head_width": 4,
110"position_bins": 4,
111"chunk_size": 16,
112"structure_module": {
113"ipa_dim": 16,
114"num_angles": 7,
115"num_blocks": 2,
116"num_heads_ipa": 4,
117"pairwise_dim": 16,
118"resnet_dim": 16,
119"sequence_dim": 48,
120},
121},
122"fp16_esm": False,
123"lddt_head_hid_dim": 16,
124}
125config = EsmConfig(
126vocab_size=33,
127hidden_size=self.hidden_size,
128pad_token_id=1,
129num_hidden_layers=self.num_hidden_layers,
130num_attention_heads=self.num_attention_heads,
131intermediate_size=self.intermediate_size,
132hidden_act=self.hidden_act,
133hidden_dropout_prob=self.hidden_dropout_prob,
134attention_probs_dropout_prob=self.attention_probs_dropout_prob,
135max_position_embeddings=self.max_position_embeddings,
136type_vocab_size=self.type_vocab_size,
137initializer_range=self.initializer_range,
138is_folding_model=True,
139esmfold_config=esmfold_config,
140)
141return config
142
143def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels):
144model = EsmForProteinFolding(config=config).float()
145model.to(torch_device)
146model.eval()
147result = model(input_ids, attention_mask=input_mask)
148result = model(input_ids)
149result = model(input_ids)
150
151self.parent.assertEqual(result.positions.shape, (2, self.batch_size, self.seq_length, 14, 3))
152self.parent.assertEqual(result.angles.shape, (2, self.batch_size, self.seq_length, 7, 2))
153
154def prepare_config_and_inputs_for_common(self):
155config_and_inputs = self.prepare_config_and_inputs()
156(
157config,
158input_ids,
159input_mask,
160sequence_labels,
161token_labels,
162choice_labels,
163) = config_and_inputs
164inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
165return config, inputs_dict
166
167
168@require_torch
169class EsmFoldModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
170test_mismatched_shapes = False
171
172all_model_classes = (EsmForProteinFolding,) if is_torch_available() else ()
173all_generative_model_classes = ()
174pipeline_model_mapping = {} if is_torch_available() else {}
175test_sequence_classification_problem_types = False
176
177def setUp(self):
178self.model_tester = EsmFoldModelTester(self)
179self.config_tester = ConfigTester(self, config_class=EsmConfig, hidden_size=37)
180
181def test_config(self):
182self.config_tester.run_common_tests()
183
184def test_model(self):
185config_and_inputs = self.model_tester.prepare_config_and_inputs()
186self.model_tester.create_and_check_model(*config_and_inputs)
187
188@unittest.skip("Does not support attention outputs")
189def test_attention_outputs(self):
190pass
191
192@unittest.skip
193def test_correct_missing_keys(self):
194pass
195
196@unittest.skip("Esm does not support embedding resizing")
197def test_resize_embeddings_untied(self):
198pass
199
200@unittest.skip("Esm does not support embedding resizing")
201def test_resize_tokens_embeddings(self):
202pass
203
204@unittest.skip("ESMFold does not support passing input embeds!")
205def test_inputs_embeds(self):
206pass
207
208@unittest.skip("ESMFold does not support head pruning.")
209def test_head_pruning(self):
210pass
211
212@unittest.skip("ESMFold does not support head pruning.")
213def test_head_pruning_integration(self):
214pass
215
216@unittest.skip("ESMFold does not support head pruning.")
217def test_head_pruning_save_load_from_config_init(self):
218pass
219
220@unittest.skip("ESMFold does not support head pruning.")
221def test_head_pruning_save_load_from_pretrained(self):
222pass
223
224@unittest.skip("ESMFold does not support head pruning.")
225def test_headmasking(self):
226pass
227
228@unittest.skip("ESMFold does not output hidden states in the normal way.")
229def test_hidden_states_output(self):
230pass
231
232@unittest.skip("ESMfold does not output hidden states in the normal way.")
233def test_retain_grad_hidden_states_attentions(self):
234pass
235
236@unittest.skip("ESMFold only has one output format.")
237def test_model_outputs_equivalence(self):
238pass
239
240@unittest.skip("This test doesn't work for ESMFold and doesn't test core functionality")
241def test_save_load_fast_init_from_base(self):
242pass
243
244@unittest.skip("ESMFold does not support input chunking.")
245def test_feed_forward_chunking(self):
246pass
247
248@unittest.skip("ESMFold doesn't respect you and it certainly doesn't respect your initialization arguments.")
249def test_initialization(self):
250pass
251
252@unittest.skip("ESMFold doesn't support torchscript compilation.")
253def test_torchscript_output_attentions(self):
254pass
255
256@unittest.skip("ESMFold doesn't support torchscript compilation.")
257def test_torchscript_output_hidden_state(self):
258pass
259
260@unittest.skip("ESMFold doesn't support torchscript compilation.")
261def test_torchscript_simple(self):
262pass
263
264@unittest.skip("ESMFold doesn't support data parallel.")
265def test_multi_gpu_data_parallel_forward(self):
266pass
267
268
269@require_torch
270class EsmModelIntegrationTest(TestCasePlus):
271@slow
272def test_inference_protein_folding(self):
273model = EsmForProteinFolding.from_pretrained("facebook/esmfold_v1").float()
274model.eval()
275input_ids = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]])
276position_outputs = model(input_ids)["positions"]
277expected_slice = torch.tensor([2.5828, 0.7993, -10.9334], dtype=torch.float32)
278self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0], expected_slice, atol=1e-4))
279