bert.py 12.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
import torch
import transformers

from ..registry import ModelAttribute, model_zoo

# ===============================
# Register single-sentence BERT
# ===============================


11
12
13
14
15
16
17
18
19
20
21
22
# define data gen function
def data_gen():
    # Generated from following code snippet
    #
    # from transformers import BertTokenizer
    # input = 'Hello, my dog is cute'
    # tokenized_input = tokenizer(input, return_tensors='pt')
    # input_ids = tokenized_input['input_ids']
    # attention_mask = tokenized_input['attention_mask']
    # token_type_ids = tokenized_input['token_type_ids']
    input_ids = torch.tensor([[101, 7592, 1010, 2026, 3899, 2003, 10140, 102]], dtype=torch.int64)
    token_type_ids = torch.tensor([[0, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int64)
23
    attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 0]], dtype=torch.int64)
24
25
26
    return dict(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask)


27
28
29
30
def data_gen_for_lm():
    # LM data gen
    # the `labels` of LM is the token of the output, cause no padding, use `input_ids` as `labels`
    data = data_gen()
31
    data["labels"] = data["input_ids"].clone()
32
33
34
35
36
37
38
    return data


def data_gen_for_pretraining():
    # pretraining data gen
    # `next_sentence_label` is the label for next sentence prediction, 0 or 1
    data = data_gen_for_lm()
39
    data["next_sentence_label"] = torch.tensor([1], dtype=torch.int64)
40
41
42
43
44
45
46
    return data


def data_gen_for_sequence_classification():
    # sequence classification data gen
    # `labels` is the label for sequence classification, 0 or 1
    data = data_gen()
47
    data["labels"] = torch.tensor([1], dtype=torch.int64)
48
49
50
51
52
53
54
    return data


def data_gen_for_token_classification():
    # token classification data gen
    # `labels` is the type not the token id for token classification, 0 or 1
    data = data_gen()
55
    data["labels"] = torch.tensor([[1, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int64)
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    return data


def data_gen_for_mcq():
    # multiple choice question data gen
    # Generated from following code snippet
    #
    # tokenizer = transformers.BertTokenizer.from_pretrained("bert-base-uncased")
    # prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
    # choice0 = "It is eaten with a fork and a knife."
    # choice1 = "It is eaten while held in the hand."
    # data = tokenizer([prompt, prompt], [choice0, choice1], return_tensors="pt", padding=True)
    # data = {k: v.unsqueeze(0) for k, v in encoding.items()}
    # data['labels'] = torch.tensor([0], dtype=torch.int64)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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
210
211
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
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    input_ids = torch.tensor(
        [
            [
                [
                    101,
                    1999,
                    3304,
                    1010,
                    10733,
                    2366,
                    1999,
                    5337,
                    10906,
                    1010,
                    2107,
                    2004,
                    2012,
                    1037,
                    4825,
                    1010,
                    2003,
                    3591,
                    4895,
                    14540,
                    6610,
                    2094,
                    1012,
                    102,
                    2009,
                    2003,
                    8828,
                    2007,
                    1037,
                    9292,
                    1998,
                    1037,
                    5442,
                    1012,
                    102,
                    102,
                    5442,
                    1012,
                    102,
                    102,
                ],
                [
                    101,
                    1999,
                    3304,
                    1010,
                    10733,
                    2366,
                    1999,
                    5337,
                    10906,
                    1010,
                    2107,
                    2004,
                    2012,
                    1037,
                    4825,
                    1010,
                    2003,
                    3591,
                    4895,
                    14540,
                    6610,
                    2094,
                    1012,
                    102,
                    2009,
                    2003,
                    8828,
                    2096,
                    2218,
                    1999,
                    1996,
                    2192,
                    1012,
                    102,
                    0,
                    0,
                    1012,
                    102,
                    0,
                    0,
                ],
            ]
        ]
    )
    token_type_ids = torch.tensor(
        [
            [
                [
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                ],
                [
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    0,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    0,
                    0,
                    1,
                    1,
                    0,
                    0,
                ],
            ]
        ]
    )
    attention_mask = torch.tensor(
        [
            [
                [
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                ],
                [
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    1,
                    0,
                    0,
                    1,
                    1,
                    0,
                    0,
                ],
            ]
        ]
    )
340
341
342
343
344
    labels = torch.tensor([0], dtype=torch.int64)

    return dict(input_ids=input_ids, token_type_ids=token_type_ids, attention_mask=attention_mask, labels=labels)


Jianghai's avatar
Jianghai committed
345
346
347
348
349
def data_gen_for_qa():
    # generating data for question answering
    # no need for labels and use start and end position instead
    data = data_gen()
    start_positions = torch.tensor([0], dtype=torch.int64)
350
    data["start_positions"] = start_positions
Jianghai's avatar
Jianghai committed
351
    end_positions = torch.tensor([1], dtype=torch.int64)
352
    data["end_positions"] = end_positions
Jianghai's avatar
Jianghai committed
353
354
355
    return data


356
# define output transform function
357
358
output_transform_fn = lambda x: x

359
# define loss funciton
360

361
loss_fn_for_bert_model = lambda x: torch.nn.functional.mse_loss(
362
    x["last_hidden_state"], torch.ones_like(x["last_hidden_state"])
363
)
364
loss_fn = lambda x: x["loss"]
365

366
367
368
369
370
371
372
373
config = transformers.BertConfig(
    hidden_size=128,
    num_hidden_layers=2,
    num_attention_heads=4,
    intermediate_size=256,
    hidden_dropout_prob=0,
    attention_probs_dropout_prob=0,
)
374
375

# register the BERT variants
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
model_zoo.register(
    name="transformers_bert",
    model_fn=lambda: transformers.BertModel(config, add_pooling_layer=False),
    data_gen_fn=data_gen,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn_for_bert_model,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_pretraining",
    model_fn=lambda: transformers.BertForPreTraining(config),
    data_gen_fn=data_gen_for_pretraining,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_lm_head_model",
    model_fn=lambda: transformers.BertLMHeadModel(config),
    data_gen_fn=data_gen_for_lm,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_masked_lm",
    model_fn=lambda: transformers.BertForMaskedLM(config),
    data_gen_fn=data_gen_for_lm,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_sequence_classification",
    model_fn=lambda: transformers.BertForSequenceClassification(config),
    data_gen_fn=data_gen_for_sequence_classification,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_token_classification",
    model_fn=lambda: transformers.BertForTokenClassification(config),
    data_gen_fn=data_gen_for_token_classification,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_next_sentence",
    model_fn=lambda: transformers.BertForNextSentencePrediction(config),
    data_gen_fn=data_gen_for_sequence_classification,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_mcq",
    model_fn=lambda: transformers.BertForMultipleChoice(config),
    data_gen_fn=data_gen_for_mcq,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_bert_for_question_answering",
    model_fn=lambda: transformers.BertForQuestionAnswering(config),
    data_gen_fn=data_gen_for_qa,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)