"extensions/csrc/scaled_softmax.py" did not exist on "8e85d2440a7d980a37431110ed583260d6cca7fe"
bert.py 8.58 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
31
32
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
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()
    data['labels'] = data['input_ids'].clone()
    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()
    data['next_sentence_label'] = torch.tensor([1], dtype=torch.int64)
    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()
    data['labels'] = torch.tensor([1], dtype=torch.int64)
    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()
    data['labels'] = torch.tensor([[1, 0, 0, 0, 0, 0, 0, 0]], dtype=torch.int64)
    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)
    input_ids = torch.tensor([[[
        101, 1999, 3304, 1010, 10733, 2366, 1999, 5337, 10906, 1010, 2107, 2004, 2012, 1037, 4825, 1010, 2003, 3591,
72
73
        4895, 14540, 6610, 2094, 1012, 102, 2009, 2003, 8828, 2007, 1037, 9292, 1998, 1037, 5442, 1012, 102, 102, 5442,
        1012, 102, 102
74
75
76
77
    ],
                               [
                                   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,
78
                                   2218, 1999, 1996, 2192, 1012, 102, 0, 0, 1012, 102, 0, 0
79
                               ]]])
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
    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
                                    ]]])
96
97
98
99
100
    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
101
102
103
104
105
106
107
108
109
110
111
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)
    data['start_positions'] = start_positions
    end_positions = torch.tensor([1], dtype=torch.int64)
    data['end_positions'] = end_positions
    return data


112
# define output transform function
113
114
output_transform_fn = lambda x: x

115
# define loss funciton
116

117
118
loss_fn_for_bert_model = lambda x: torch.nn.functional.mse_loss(x.last_hidden_state, torch.ones_like(x.last_hidden_state
                                                                                                    ))
119
120
121
122
123
124
125
126
loss_fn = lambda x: x.loss

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)
127
128
129

# register the BERT variants
model_zoo.register(name='transformers_bert',
130
                   model_fn=lambda: transformers.BertModel(config, add_pooling_layer=False),
131
                   data_gen_fn=data_gen,
132
                   output_transform_fn=output_transform_fn,
133
                   loss_fn=loss_fn_for_bert_model,
134
135
136
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_for_pretraining',
                   model_fn=lambda: transformers.BertForPreTraining(config),
137
                   data_gen_fn=data_gen_for_pretraining,
138
                   output_transform_fn=output_transform_fn,
139
                   loss_fn=loss_fn,
140
141
142
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_lm_head_model',
                   model_fn=lambda: transformers.BertLMHeadModel(config),
143
                   data_gen_fn=data_gen_for_lm,
144
                   output_transform_fn=output_transform_fn,
145
                   loss_fn=loss_fn,
146
147
148
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_for_masked_lm',
                   model_fn=lambda: transformers.BertForMaskedLM(config),
149
                   data_gen_fn=data_gen_for_lm,
150
                   output_transform_fn=output_transform_fn,
151
                   loss_fn=loss_fn,
152
153
154
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_for_sequence_classification',
                   model_fn=lambda: transformers.BertForSequenceClassification(config),
155
                   data_gen_fn=data_gen_for_sequence_classification,
156
                   output_transform_fn=output_transform_fn,
157
                   loss_fn=loss_fn,
158
159
160
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_for_token_classification',
                   model_fn=lambda: transformers.BertForTokenClassification(config),
161
                   data_gen_fn=data_gen_for_token_classification,
162
                   output_transform_fn=output_transform_fn,
163
                   loss_fn=loss_fn,
164
165
166
                   model_attribute=ModelAttribute(has_control_flow=True))
model_zoo.register(name='transformers_bert_for_next_sentence',
                   model_fn=lambda: transformers.BertForNextSentencePrediction(config),
167
                   data_gen_fn=data_gen_for_sequence_classification,
168
                   output_transform_fn=output_transform_fn,
169
                   loss_fn=loss_fn,
170
171
172
173
174
                   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,
175
                   loss_fn=loss_fn,
176
                   model_attribute=ModelAttribute(has_control_flow=True))
Jianghai's avatar
Jianghai committed
177
178
179
180
181
182
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))