modeling_openai_test.py 9.25 KB
Newer Older
thomwolf's avatar
thomwolf committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

19
import os
thomwolf's avatar
thomwolf committed
20
21
22
23
24
25
import unittest
import json
import random

import torch

thomwolf's avatar
thomwolf committed
26
27
from pytorch_pretrained_bert import (OpenAIGPTConfig, OpenAIGPTModel,
                                     OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel)
thomwolf's avatar
thomwolf committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42


class OpenAIGPTModelTest(unittest.TestCase):
    class OpenAIGPTModelTester(object):

        def __init__(self,
                     parent,
                     batch_size=13,
                     seq_length=7,
                     is_training=True,
                     use_position_ids=True,
                     use_token_type_ids=True,
                     use_labels=True,
                     vocab_size=99,
                     n_special=1,
43
                     n_positions=33,
thomwolf's avatar
thomwolf committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
                     n_embd=32,
                     n_layer=5,
                     n_head=4,
                     n_choices=3,
                     afn="gelu",
                     resid_pdrop=0.1,
                     attn_pdrop=0.1,
                     embd_pdrop=0.1,
                     type_sequence_label_size=2,
                     initializer_range=0.02,
                     num_labels=3,
                     scope=None):
            self.parent = parent
            self.batch_size = batch_size
            self.seq_length = seq_length
            self.is_training = is_training
            self.use_position_ids = use_position_ids
            self.use_token_type_ids = use_token_type_ids
            self.use_labels = use_labels
            self.vocab_size = vocab_size
            self.n_special = n_special
65
            self.n_positions = n_positions
thomwolf's avatar
thomwolf committed
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
            self.n_embd = n_embd
            self.n_layer = n_layer
            self.n_head = n_head
            self.afn = afn
            self.n_choices = n_choices
            self.resid_pdrop = resid_pdrop
            self.attn_pdrop = attn_pdrop
            self.embd_pdrop = embd_pdrop
            self.type_sequence_label_size = type_sequence_label_size
            self.initializer_range = initializer_range
            self.num_labels = num_labels
            self.scope = scope

        def prepare_config_and_inputs(self):
            input_ids = OpenAIGPTModelTest.ids_tensor([self.batch_size, self.n_choices, self.seq_length], self.vocab_size)

            position_ids = None
            if self.use_position_ids:
84
                position_ids = OpenAIGPTModelTest.ids_tensor([self.batch_size, self.n_choices, self.seq_length], self.n_positions)
thomwolf's avatar
thomwolf committed
85
86
87

            token_type_ids = None
            if self.use_token_type_ids:
88
                total_voc = self.vocab_size + self.n_special
thomwolf's avatar
thomwolf committed
89
90
                token_type_ids = OpenAIGPTModelTest.ids_tensor([self.batch_size, self.n_choices, self.seq_length], total_voc)

thomwolf's avatar
thomwolf committed
91
            mc_labels = None
thomwolf's avatar
thomwolf committed
92
            lm_labels = None
thomwolf's avatar
thomwolf committed
93
            mc_token_ids = None
thomwolf's avatar
thomwolf committed
94
            if self.use_labels:
thomwolf's avatar
thomwolf committed
95
                mc_labels = OpenAIGPTModelTest.ids_tensor([self.batch_size], self.type_sequence_label_size)
thomwolf's avatar
thomwolf committed
96
                lm_labels = OpenAIGPTModelTest.ids_tensor([self.batch_size, self.n_choices, self.seq_length], self.num_labels)
thomwolf's avatar
thomwolf committed
97
                mc_token_ids = OpenAIGPTModelTest.ids_tensor([self.batch_size, self.n_choices], self.seq_length)
thomwolf's avatar
thomwolf committed
98
99
100

            config = OpenAIGPTConfig(
                vocab_size_or_config_json_file=self.vocab_size,
101
                n_positions=self.n_positions,
thomwolf's avatar
thomwolf committed
102
103
104
105
106
107
108
109
110
111
112
                n_special=self.n_special,
                n_embd=self.n_embd,
                n_layer=self.n_layer,
                n_head=self.n_head,
                afn=self.afn,
                resid_pdrop=self.resid_pdrop,
                attn_pdrop=self.attn_pdrop,
                embd_pdrop=self.embd_pdrop,
                initializer_range=self.initializer_range)

            return (config, input_ids, token_type_ids, position_ids,
thomwolf's avatar
thomwolf committed
113
                    mc_labels, lm_labels, mc_token_ids)
thomwolf's avatar
thomwolf committed
114
115

        def create_openai_model(self, config, input_ids, token_type_ids, position_ids,
thomwolf's avatar
thomwolf committed
116
                                mc_labels, lm_labels, mc_token_ids):
thomwolf's avatar
thomwolf committed
117
            model = OpenAIGPTModel(config)
thomwolf's avatar
thomwolf committed
118
            model.eval()
thomwolf's avatar
thomwolf committed
119
120
121
122
123
124
125
126
127
128
129
130
            hidden_states = model(input_ids, position_ids, token_type_ids)
            outputs = {
                "hidden_states": hidden_states,
            }
            return outputs

        def check_openai_model_output(self, result):
            self.parent.assertListEqual(
                list(result["hidden_states"].size()),
                [self.batch_size, self.n_choices, self.seq_length, self.n_embd])


thomwolf's avatar
thomwolf committed
131
        def create_openai_lm_head(self, config, input_ids, token_type_ids, position_ids,
thomwolf's avatar
thomwolf committed
132
                                       mc_labels, lm_labels, mc_token_ids):
thomwolf's avatar
thomwolf committed
133
            model = OpenAIGPTLMHeadModel(config)
thomwolf's avatar
thomwolf committed
134
            model.eval()
thomwolf's avatar
thomwolf committed
135
136
137
138
139
140
141
142
143
            loss = model(input_ids, position_ids, token_type_ids, lm_labels)
            lm_logits = model(input_ids, position_ids, token_type_ids)
            outputs = {
                "loss": loss,
                "lm_logits": lm_logits,
            }
            return outputs

        def check_openai_lm_head_output(self, result):
144
            total_voc = self.n_special + self.vocab_size
thomwolf's avatar
thomwolf committed
145
146
147
148
149
150
151
152
153
            self.parent.assertListEqual(
                list(result["lm_logits"].size()),
                [self.batch_size, self.n_choices, self.seq_length, total_voc])

        def check_openai_lm_head_loss_output(self, result):
            self.parent.assertListEqual(
                list(result["loss"].size()),
                [])

thomwolf's avatar
thomwolf committed
154
        def create_openai_double_heads(self, config, input_ids, token_type_ids, position_ids,
thomwolf's avatar
thomwolf committed
155
                                       mc_labels, lm_labels, mc_token_ids):
thomwolf's avatar
thomwolf committed
156
            model = OpenAIGPTDoubleHeadsModel(config)
thomwolf's avatar
thomwolf committed
157
            model.eval()
thomwolf's avatar
thomwolf committed
158
            loss = model(input_ids, mc_token_ids,
thomwolf's avatar
thomwolf committed
159
160
                         lm_labels=lm_labels, mc_labels=mc_labels,
                         token_type_ids=token_type_ids, position_ids=position_ids)
thomwolf's avatar
thomwolf committed
161
            lm_logits, mc_logits = model(input_ids, mc_token_ids, position_ids=position_ids, token_type_ids=token_type_ids)
thomwolf's avatar
thomwolf committed
162
163
164
            outputs = {
                "loss": loss,
                "lm_logits": lm_logits,
thomwolf's avatar
thomwolf committed
165
                "mc_logits": mc_logits,
thomwolf's avatar
thomwolf committed
166
167
168
169
            }
            return outputs

        def check_openai_double_heads_output(self, result):
170
            total_voc = self.n_special + self.vocab_size
thomwolf's avatar
thomwolf committed
171
172
173
174
            self.parent.assertListEqual(
                list(result["lm_logits"].size()),
                [self.batch_size, self.n_choices, self.seq_length, total_voc])
            self.parent.assertListEqual(
thomwolf's avatar
thomwolf committed
175
                list(result["mc_logits"].size()),
thomwolf's avatar
thomwolf committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
                [self.batch_size, self.n_choices])

        def check_openai_double_heads_loss_output(self, result):
            self.parent.assertListEqual(
                [list(l.size()) for l in result["loss"]],
                [[], []])

    def test_default(self):
        self.run_tester(OpenAIGPTModelTest.OpenAIGPTModelTester(self))

    def test_config_to_json_string(self):
        config = OpenAIGPTConfig(vocab_size_or_config_json_file=99, n_embd=37)
        obj = json.loads(config.to_json_string())
        self.assertEqual(obj["vocab_size"], 99)
        self.assertEqual(obj["n_embd"], 37)

192
193
194
195
196
197
198
199
    def test_config_to_json_file(self):
        config_first = OpenAIGPTConfig(vocab_size_or_config_json_file=99, n_embd=37)
        json_file_path = "/tmp/config.json"
        config_first.to_json_file(json_file_path)
        config_second = OpenAIGPTConfig.from_json_file(json_file_path)
        os.remove(json_file_path)
        self.assertEqual(config_second.to_dict(), config_first.to_dict())

thomwolf's avatar
thomwolf committed
200
201
202
203
204
    def run_tester(self, tester):
        config_and_inputs = tester.prepare_config_and_inputs()
        output_result = tester.create_openai_model(*config_and_inputs)
        tester.check_openai_model_output(output_result)

thomwolf's avatar
thomwolf committed
205
206
207
208
        output_result = tester.create_openai_lm_head(*config_and_inputs)
        tester.check_openai_lm_head_output(output_result)
        tester.check_openai_lm_head_loss_output(output_result)

thomwolf's avatar
thomwolf committed
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
        output_result = tester.create_openai_double_heads(*config_and_inputs)
        tester.check_openai_double_heads_output(output_result)
        tester.check_openai_double_heads_loss_output(output_result)

    @classmethod
    def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
        """Creates a random int32 tensor of the shape within the vocab size."""
        if rng is None:
            rng = random.Random()

        total_dims = 1
        for dim in shape:
            total_dims *= dim

        values = []
        for _ in range(total_dims):
            values.append(rng.randint(0, vocab_size - 1))

        return torch.tensor(data=values, dtype=torch.long).view(shape).contiguous()


if __name__ == "__main__":
    unittest.main()