test_modeling_luke.py 26.7 KB
Newer Older
NielsRogge's avatar
NielsRogge committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 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 LUKE model. """
import unittest

18
from transformers import LukeConfig, is_torch_available
NielsRogge's avatar
NielsRogge committed
19
20
from transformers.testing_utils import require_torch, slow, torch_device

Yih-Dar's avatar
Yih-Dar committed
21
22
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
NielsRogge's avatar
NielsRogge committed
23
24
25
26
27
28
29
30
31


if is_torch_available():
    import torch

    from transformers import (
        LukeForEntityClassification,
        LukeForEntityPairClassification,
        LukeForEntitySpanClassification,
Ryokan RI's avatar
Ryokan RI committed
32
        LukeForMaskedLM,
NielsRogge's avatar
NielsRogge committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
        LukeModel,
        LukeTokenizer,
    )
    from transformers.models.luke.modeling_luke import LUKE_PRETRAINED_MODEL_ARCHIVE_LIST


class LukeModelTester:
    def __init__(
        self,
        parent,
        batch_size=13,
        seq_length=7,
        is_training=True,
        entity_length=3,
        mention_length=5,
        use_attention_mask=True,
        use_token_type_ids=True,
        use_entity_ids=True,
        use_entity_attention_mask=True,
        use_entity_token_type_ids=True,
        use_entity_position_ids=True,
        use_labels=True,
        vocab_size=99,
        entity_vocab_size=10,
        entity_emb_size=6,
        hidden_size=32,
        num_hidden_layers=5,
        num_attention_heads=4,
        intermediate_size=37,
        hidden_act="gelu",
        hidden_dropout_prob=0.1,
        attention_probs_dropout_prob=0.1,
        max_position_embeddings=512,
        type_vocab_size=16,
        type_sequence_label_size=2,
        initializer_range=0.02,
        num_entity_classification_labels=9,
        num_entity_pair_classification_labels=6,
        num_entity_span_classification_labels=4,
        use_entity_aware_attention=True,
        scope=None,
    ):
        self.parent = parent
        self.batch_size = batch_size
        self.seq_length = seq_length
        self.is_training = is_training
        self.entity_length = entity_length
        self.mention_length = mention_length
        self.use_attention_mask = use_attention_mask
        self.use_token_type_ids = use_token_type_ids
        self.use_entity_ids = use_entity_ids
        self.use_entity_attention_mask = use_entity_attention_mask
        self.use_entity_token_type_ids = use_entity_token_type_ids
        self.use_entity_position_ids = use_entity_position_ids
        self.use_labels = use_labels
        self.vocab_size = vocab_size
        self.entity_vocab_size = entity_vocab_size
        self.entity_emb_size = entity_emb_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.type_vocab_size = type_vocab_size
        self.type_sequence_label_size = type_sequence_label_size
        self.initializer_range = initializer_range
        self.num_entity_classification_labels = num_entity_classification_labels
        self.num_entity_pair_classification_labels = num_entity_pair_classification_labels
        self.num_entity_span_classification_labels = num_entity_span_classification_labels
        self.scope = scope
        self.use_entity_aware_attention = use_entity_aware_attention

        self.encoder_seq_length = seq_length
        self.key_length = seq_length
        self.num_hidden_states_types = 2  # hidden_states and entity_hidden_states

    def prepare_config_and_inputs(self):
        # prepare words
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)

        attention_mask = None
        if self.use_attention_mask:
            attention_mask = random_attention_mask([self.batch_size, self.seq_length])

        token_type_ids = None
        if self.use_token_type_ids:
            token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)

        # prepare entities
        entity_ids = ids_tensor([self.batch_size, self.entity_length], self.entity_vocab_size)

        entity_attention_mask = None
        if self.use_entity_attention_mask:
            entity_attention_mask = random_attention_mask([self.batch_size, self.entity_length])

        entity_token_type_ids = None
        if self.use_token_type_ids:
            entity_token_type_ids = ids_tensor([self.batch_size, self.entity_length], self.type_vocab_size)

        entity_position_ids = None
        if self.use_entity_position_ids:
            entity_position_ids = ids_tensor(
                [self.batch_size, self.entity_length, self.mention_length], self.mention_length
            )

        sequence_labels = None
Ryokan RI's avatar
Ryokan RI committed
142
143
        labels = None
        entity_labels = None
NielsRogge's avatar
NielsRogge committed
144
145
146
147
148
149
        entity_classification_labels = None
        entity_pair_classification_labels = None
        entity_span_classification_labels = None

        if self.use_labels:
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
Ryokan RI's avatar
Ryokan RI committed
150
151
152
            labels = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
            entity_labels = ids_tensor([self.batch_size, self.entity_length], self.entity_vocab_size)

NielsRogge's avatar
NielsRogge committed
153
154
155
156
157
158
159
160
            entity_classification_labels = ids_tensor([self.batch_size], self.num_entity_classification_labels)
            entity_pair_classification_labels = ids_tensor(
                [self.batch_size], self.num_entity_pair_classification_labels
            )
            entity_span_classification_labels = ids_tensor(
                [self.batch_size, self.entity_length], self.num_entity_span_classification_labels
            )

161
162
163
164
165
166
167
168
169
170
171
172
        config = self.get_config()

        return (
            config,
            input_ids,
            attention_mask,
            token_type_ids,
            entity_ids,
            entity_attention_mask,
            entity_token_type_ids,
            entity_position_ids,
            sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
173
174
            labels,
            entity_labels,
175
176
177
178
179
180
181
            entity_classification_labels,
            entity_pair_classification_labels,
            entity_span_classification_labels,
        )

    def get_config(self):
        return LukeConfig(
NielsRogge's avatar
NielsRogge committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
            vocab_size=self.vocab_size,
            entity_vocab_size=self.entity_vocab_size,
            entity_emb_size=self.entity_emb_size,
            hidden_size=self.hidden_size,
            num_hidden_layers=self.num_hidden_layers,
            num_attention_heads=self.num_attention_heads,
            intermediate_size=self.intermediate_size,
            hidden_act=self.hidden_act,
            hidden_dropout_prob=self.hidden_dropout_prob,
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
            max_position_embeddings=self.max_position_embeddings,
            type_vocab_size=self.type_vocab_size,
            is_decoder=False,
            initializer_range=self.initializer_range,
            use_entity_aware_attention=self.use_entity_aware_attention,
        )

    def create_and_check_model(
        self,
        config,
        input_ids,
        attention_mask,
        token_type_ids,
        entity_ids,
        entity_attention_mask,
        entity_token_type_ids,
        entity_position_ids,
        sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
210
211
        labels,
        entity_labels,
NielsRogge's avatar
NielsRogge committed
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
        entity_classification_labels,
        entity_pair_classification_labels,
        entity_span_classification_labels,
    ):
        model = LukeModel(config=config)
        model.to(torch_device)
        model.eval()
        # test with words + entities
        result = model(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
        )
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
        self.parent.assertEqual(
            result.entity_last_hidden_state.shape, (self.batch_size, self.entity_length, self.hidden_size)
        )

        # test with words only
        result = model(input_ids, token_type_ids=token_type_ids)
        result = model(input_ids)
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))

Ryokan RI's avatar
Ryokan RI committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
    def create_and_check_for_masked_lm(
        self,
        config,
        input_ids,
        attention_mask,
        token_type_ids,
        entity_ids,
        entity_attention_mask,
        entity_token_type_ids,
        entity_position_ids,
        sequence_labels,
        labels,
        entity_labels,
        entity_classification_labels,
        entity_pair_classification_labels,
        entity_span_classification_labels,
    ):
        config.num_labels = self.num_entity_classification_labels
        model = LukeForMaskedLM(config)
        model.to(torch_device)
        model.eval()

        result = model(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            labels=labels,
            entity_labels=entity_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
Ryokan RI's avatar
Ryokan RI committed
273
274
275
276
277
278
        if entity_ids is not None:
            self.parent.assertEqual(
                result.entity_logits.shape, (self.batch_size, self.entity_length, self.entity_vocab_size)
            )
        else:
            self.parent.assertIsNone(result.entity_logits)
Ryokan RI's avatar
Ryokan RI committed
279

NielsRogge's avatar
NielsRogge committed
280
281
282
283
284
285
286
287
288
289
290
    def create_and_check_for_entity_classification(
        self,
        config,
        input_ids,
        attention_mask,
        token_type_ids,
        entity_ids,
        entity_attention_mask,
        entity_token_type_ids,
        entity_position_ids,
        sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
291
292
        labels,
        entity_labels,
NielsRogge's avatar
NielsRogge committed
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
        entity_classification_labels,
        entity_pair_classification_labels,
        entity_span_classification_labels,
    ):
        config.num_labels = self.num_entity_classification_labels
        model = LukeForEntityClassification(config)
        model.to(torch_device)
        model.eval()

        result = model(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            labels=entity_classification_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_classification_labels))

    def create_and_check_for_entity_pair_classification(
        self,
        config,
        input_ids,
        attention_mask,
        token_type_ids,
        entity_ids,
        entity_attention_mask,
        entity_token_type_ids,
        entity_position_ids,
        sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
325
326
        labels,
        entity_labels,
NielsRogge's avatar
NielsRogge committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
        entity_classification_labels,
        entity_pair_classification_labels,
        entity_span_classification_labels,
    ):
        config.num_labels = self.num_entity_pair_classification_labels
        model = LukeForEntityClassification(config)
        model.to(torch_device)
        model.eval()

        result = model(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            labels=entity_pair_classification_labels,
        )
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_entity_pair_classification_labels))

    def create_and_check_for_entity_span_classification(
        self,
        config,
        input_ids,
        attention_mask,
        token_type_ids,
        entity_ids,
        entity_attention_mask,
        entity_token_type_ids,
        entity_position_ids,
        sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
359
360
        labels,
        entity_labels,
NielsRogge's avatar
NielsRogge committed
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
        entity_classification_labels,
        entity_pair_classification_labels,
        entity_span_classification_labels,
    ):
        config.num_labels = self.num_entity_span_classification_labels
        model = LukeForEntitySpanClassification(config)
        model.to(torch_device)
        model.eval()

        entity_start_positions = ids_tensor([self.batch_size, self.entity_length], self.seq_length)
        entity_end_positions = ids_tensor([self.batch_size, self.entity_length], self.seq_length)

        result = model(
            input_ids,
            attention_mask=attention_mask,
            token_type_ids=token_type_ids,
            entity_ids=entity_ids,
            entity_attention_mask=entity_attention_mask,
            entity_token_type_ids=entity_token_type_ids,
            entity_position_ids=entity_position_ids,
            entity_start_positions=entity_start_positions,
            entity_end_positions=entity_end_positions,
            labels=entity_span_classification_labels,
        )
        self.parent.assertEqual(
            result.logits.shape, (self.batch_size, self.entity_length, self.num_entity_span_classification_labels)
        )

    def prepare_config_and_inputs_for_common(self):
        config_and_inputs = self.prepare_config_and_inputs()
        (
            config,
            input_ids,
            attention_mask,
            token_type_ids,
            entity_ids,
            entity_attention_mask,
            entity_token_type_ids,
            entity_position_ids,
            sequence_labels,
Ryokan RI's avatar
Ryokan RI committed
401
402
            labels,
            entity_labels,
NielsRogge's avatar
NielsRogge committed
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
            entity_classification_labels,
            entity_pair_classification_labels,
            entity_span_classification_labels,
        ) = config_and_inputs
        inputs_dict = {
            "input_ids": input_ids,
            "token_type_ids": token_type_ids,
            "attention_mask": attention_mask,
            "entity_ids": entity_ids,
            "entity_token_type_ids": entity_token_type_ids,
            "entity_attention_mask": entity_attention_mask,
            "entity_position_ids": entity_position_ids,
        }
        return config, inputs_dict


@require_torch
class LukeModelTest(ModelTesterMixin, unittest.TestCase):

    all_model_classes = (
        (
            LukeModel,
Ryokan RI's avatar
Ryokan RI committed
425
            LukeForMaskedLM,
NielsRogge's avatar
NielsRogge committed
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
            LukeForEntityClassification,
            LukeForEntityPairClassification,
            LukeForEntitySpanClassification,
        )
        if is_torch_available()
        else ()
    )
    test_pruning = False
    test_torchscript = False
    test_resize_embeddings = True
    test_head_masking = True

    def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
        inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
        if model_class == LukeForEntitySpanClassification:
            inputs_dict["entity_start_positions"] = torch.zeros(
                (self.model_tester.batch_size, self.model_tester.entity_length), dtype=torch.long, device=torch_device
            )
            inputs_dict["entity_end_positions"] = torch.ones(
                (self.model_tester.batch_size, self.model_tester.entity_length), dtype=torch.long, device=torch_device
            )

        if return_labels:
            if model_class in (LukeForEntityClassification, LukeForEntityPairClassification):
                inputs_dict["labels"] = torch.zeros(
                    self.model_tester.batch_size, dtype=torch.long, device=torch_device
                )
            elif model_class == LukeForEntitySpanClassification:
                inputs_dict["labels"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.entity_length),
                    dtype=torch.long,
                    device=torch_device,
                )
Ryokan RI's avatar
Ryokan RI committed
459
460
461
462
463
464
465
466
467
468
469
470
            elif model_class == LukeForMaskedLM:
                inputs_dict["labels"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.seq_length),
                    dtype=torch.long,
                    device=torch_device,
                )
                inputs_dict["entity_labels"] = torch.zeros(
                    (self.model_tester.batch_size, self.model_tester.entity_length),
                    dtype=torch.long,
                    device=torch_device,
                )

NielsRogge's avatar
NielsRogge committed
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
        return inputs_dict

    def setUp(self):
        self.model_tester = LukeModelTester(self)
        self.config_tester = ConfigTester(self, config_class=LukeConfig, hidden_size=37)

    def test_config(self):
        self.config_tester.run_common_tests()

    def test_model(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*config_and_inputs)

    @slow
    def test_model_from_pretrained(self):
        for model_name in LUKE_PRETRAINED_MODEL_ARCHIVE_LIST:
            model = LukeModel.from_pretrained(model_name)
            self.assertIsNotNone(model)

Ryokan RI's avatar
Ryokan RI committed
490
491
492
493
    def test_for_masked_lm(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)

Ryokan RI's avatar
Ryokan RI committed
494
495
496
497
498
    def test_for_masked_lm_with_word_only(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        config_and_inputs = (*config_and_inputs[:4], *((None,) * len(config_and_inputs[4:])))
        self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)

NielsRogge's avatar
NielsRogge committed
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
    def test_for_entity_classification(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_entity_classification(*config_and_inputs)

    def test_for_entity_pair_classification(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_entity_pair_classification(*config_and_inputs)

    def test_for_entity_span_classification(self):
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_entity_span_classification(*config_and_inputs)

    def test_attention_outputs(self):
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
        config.return_dict = True

        seq_length = self.model_tester.seq_length
        entity_length = self.model_tester.entity_length
        key_length = seq_length + entity_length

        for model_class in self.all_model_classes:
            inputs_dict["output_attentions"] = True
            inputs_dict["output_hidden_states"] = False
            config.return_dict = True
            model = model_class(config)
            model.to(torch_device)
            model.eval()
            with torch.no_grad():
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))
            attentions = outputs.attentions
            self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)

            # check that output_attentions also work using config
            del inputs_dict["output_attentions"]
            config.output_attentions = True
            model = model_class(config)
            model.to(torch_device)
            model.eval()
            with torch.no_grad():
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))
            attentions = outputs.attentions
            self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)

            self.assertListEqual(
                list(attentions[0].shape[-3:]),
                [self.model_tester.num_attention_heads, seq_length + entity_length, key_length],
            )
            out_len = len(outputs)

            # Check attention is always last and order is fine
            inputs_dict["output_attentions"] = True
            inputs_dict["output_hidden_states"] = True
            model = model_class(config)
            model.to(torch_device)
            model.eval()
            with torch.no_grad():
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))

            added_hidden_states = self.model_tester.num_hidden_states_types
            self.assertEqual(out_len + added_hidden_states, len(outputs))

            self_attentions = outputs.attentions

            self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
            self.assertListEqual(
                list(self_attentions[0].shape[-3:]),
                [self.model_tester.num_attention_heads, seq_length + entity_length, key_length],
            )

    def test_entity_hidden_states_output(self):
        def check_hidden_states_output(inputs_dict, config, model_class):
            model = model_class(config)
            model.to(torch_device)
            model.eval()

            with torch.no_grad():
                outputs = model(**self._prepare_for_class(inputs_dict, model_class))

            entity_hidden_states = outputs.entity_hidden_states

            expected_num_layers = getattr(
                self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
            )
            self.assertEqual(len(entity_hidden_states), expected_num_layers)

            entity_length = self.model_tester.entity_length

            self.assertListEqual(
                list(entity_hidden_states[0].shape[-2:]),
                [entity_length, self.model_tester.hidden_size],
            )

        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
            inputs_dict["output_hidden_states"] = True
            check_hidden_states_output(inputs_dict, config, model_class)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            config.output_hidden_states = True

            check_hidden_states_output(inputs_dict, config, model_class)

    def test_retain_grad_entity_hidden_states(self):
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
        config.output_hidden_states = True
        config.output_attentions = True

        # no need to test all models as different heads yield the same functionality
        model_class = self.all_model_classes[0]
        model = model_class(config)
        model.to(torch_device)

        inputs = self._prepare_for_class(inputs_dict, model_class)

        outputs = model(**inputs)

        output = outputs[0]

        entity_hidden_states = outputs.entity_hidden_states[0]
        entity_hidden_states.retain_grad()

        output.flatten()[0].backward(retain_graph=True)

        self.assertIsNotNone(entity_hidden_states.grad)


@require_torch
class LukeModelIntegrationTests(unittest.TestCase):
    @slow
    def test_inference_base_model(self):
        model = LukeModel.from_pretrained("studio-ousia/luke-base").eval()
        model.to(torch_device)

        tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-base", task="entity_classification")
Sylvain Gugger's avatar
Sylvain Gugger committed
635
636
637
638
        text = (
            "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
            " the new world number one avoid a humiliating second- round exit at Wimbledon ."
        )
NielsRogge's avatar
NielsRogge committed
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
        span = (39, 42)
        encoding = tokenizer(text, entity_spans=[span], add_prefix_space=True, return_tensors="pt")

        # move all values to device
        for key, value in encoding.items():
            encoding[key] = encoding[key].to(torch_device)

        outputs = model(**encoding)

        # Verify word hidden states
        expected_shape = torch.Size((1, 42, 768))
        self.assertEqual(outputs.last_hidden_state.shape, expected_shape)

        expected_slice = torch.tensor(
            [[0.0037, 0.1368, -0.0091], [0.1099, 0.3329, -0.1095], [0.0765, 0.5335, 0.1179]]
        ).to(torch_device)
        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))

        # Verify entity hidden states
        expected_shape = torch.Size((1, 1, 768))
        self.assertEqual(outputs.entity_last_hidden_state.shape, expected_shape)

NielsRogge's avatar
NielsRogge committed
661
        expected_slice = torch.tensor([[0.1457, 0.1044, 0.0174]]).to(torch_device)
NielsRogge's avatar
NielsRogge committed
662
663
664
665
666
667
668
669
        self.assertTrue(torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))

    @slow
    def test_inference_large_model(self):
        model = LukeModel.from_pretrained("studio-ousia/luke-large").eval()
        model.to(torch_device)

        tokenizer = LukeTokenizer.from_pretrained("studio-ousia/luke-large", task="entity_classification")
Sylvain Gugger's avatar
Sylvain Gugger committed
670
671
672
673
        text = (
            "Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped"
            " the new world number one avoid a humiliating second- round exit at Wimbledon ."
        )
NielsRogge's avatar
NielsRogge committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
        span = (39, 42)
        encoding = tokenizer(text, entity_spans=[span], add_prefix_space=True, return_tensors="pt")

        # move all values to device
        for key, value in encoding.items():
            encoding[key] = encoding[key].to(torch_device)

        outputs = model(**encoding)

        # Verify word hidden states
        expected_shape = torch.Size((1, 42, 1024))
        self.assertEqual(outputs.last_hidden_state.shape, expected_shape)

        expected_slice = torch.tensor(
            [[0.0133, 0.0865, 0.0095], [0.3093, -0.2576, -0.7418], [-0.1720, -0.2117, -0.2869]]
        ).to(torch_device)
        self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))

        # Verify entity hidden states
        expected_shape = torch.Size((1, 1, 1024))
        self.assertEqual(outputs.entity_last_hidden_state.shape, expected_shape)

NielsRogge's avatar
NielsRogge committed
696
        expected_slice = torch.tensor([[0.0466, -0.0106, -0.0179]]).to(torch_device)
NielsRogge's avatar
NielsRogge committed
697
        self.assertTrue(torch.allclose(outputs.entity_last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))