gpt.py 5.34 KB
Newer Older
1
2
import copy

3
4
5
6
7
8
9
10
11
12
13
import torch
import transformers

from ..registry import ModelAttribute, model_zoo

# ===============================
# Register single-sentence GPT
# ===============================


def data_gen():
14
15
16
    # Generated from following code snippet
    #
    # from transformers import GPT2Tokenizer
17
    # input = 'Hello, my dog is cute is cute' (last two words repeated to satisfy length requirement)
18
19
20
    # tokenized_input = tokenizer(input, return_tensors='pt')
    # input_ids = tokenized_input['input_ids']
    # attention_mask = tokenized_input['attention_mask']
21
22
    input_ids = torch.tensor([[15496, 11, 616, 3290, 318, 13779, 318, 13779]], dtype=torch.int64)
    attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1]], dtype=torch.int64)
23
    return dict(input_ids=input_ids, attention_mask=attention_mask)
24
25


26
27
28
29
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()
30
    data["labels"] = data["input_ids"].clone()
31
    return data
32
33


34
35
36
37
38
def data_gen_for_question_answering():
    # question answering data gen
    # `labels` is the type not the token id for token classification, 0 or 1
    data = data_gen()
    start_positions = torch.tensor([0], dtype=torch.int64)
39
    data["start_positions"] = start_positions
40
    end_positions = torch.tensor([1], dtype=torch.int64)
41
    data["end_positions"] = end_positions
42
43
44
    return data


45
46
47
48
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()
49
    data["labels"] = torch.tensor([[0, 0, 0, 0, 0, 0, 0, 1]], dtype=torch.int64)
50
51
52
53
54
55
    return data


def data_gen_for_sequence_classification():
    # sequence classification data gen
    data = data_gen()
56
    data["labels"] = torch.tensor([1], dtype=torch.int64)
57
58
59
    return data


60
def date_gen_for_double_heads():
61
62
63
64
    num_choices = 2
    batch_size = 2
    input_ids = torch.tensor(
        [[15496, 11, 616, 3290, 318, 13779, 318, 13779], [15496, 11, 616, 3290, 318, 13779, 318, 13779]],
65
66
        dtype=torch.int64,
    )
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1]], dtype=torch.int64)
    mc_labels = torch.zeros(input_ids.shape[0], dtype=torch.int64)

    mc_token_ids = torch.arange(0, num_choices, dtype=torch.int64)
    mc_token_ids = mc_token_ids.expand((batch_size, num_choices))
    multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, num_choices, -1).contiguous()
    multiple_choice_input_mask = attention_mask.unsqueeze(1).expand(-1, num_choices, -1).contiguous()

    inputs = {
        "input_ids": multiple_choice_inputs_ids,
        "mc_token_ids": mc_token_ids,
        "attention_mask": multiple_choice_input_mask,
        "labels": multiple_choice_inputs_ids,
        "mc_labels": mc_labels,
    }
    return inputs
83
84


85
# define output transform function
86
87
output_transform_fn = lambda x: x

88
# define loss function
89
loss_fn_for_gpt2_model = lambda x: torch.nn.functional.mse_loss(
90
    x["last_hidden_state"], torch.ones_like(x["last_hidden_state"])
91
)
92
loss_fn = lambda x: x["loss"]
93

94
95
96
config = transformers.GPT2Config(
    n_layer=2,
    n_head=4,
97
    n_embd=128,
98
99
100
101
102
103
104
105
106
    vocab_size=50258,
    attn_pdrop=0,
    embd_pdrop=0,
    resid_pdrop=0,
    summary_first_dropout=0,
    hidden_dropout=0,
    problem_type="single_label_classification",
    pad_token_id=50256,
)
107
108
109

config_for_token_classification = copy.deepcopy(config)
config_for_token_classification.num_labels = 2
110
111

# register the following models
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
model_zoo.register(
    name="transformers_gpt",
    model_fn=lambda: transformers.GPT2Model(config),
    data_gen_fn=data_gen,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn_for_gpt2_model,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_gpt_lm",
    model_fn=lambda: transformers.GPT2LMHeadModel(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_gpt_double_heads",
    model_fn=lambda: transformers.GPT2DoubleHeadsModel(config),
    data_gen_fn=date_gen_for_double_heads,
    output_transform_fn=output_transform_fn,
    loss_fn=lambda x: x.loss + x.mc_loss,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_gpt_for_question_answering",
    model_fn=lambda: transformers.GPT2ForQuestionAnswering(config),
    data_gen_fn=data_gen_for_question_answering,
    output_transform_fn=output_transform_fn,
    loss_fn=loss_fn,
    model_attribute=ModelAttribute(has_control_flow=True),
)
model_zoo.register(
    name="transformers_gpt_for_token_classification",
    model_fn=lambda: transformers.GPT2ForTokenClassification(config_for_token_classification),
    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_gpt_for_sequence_classification",
    model_fn=lambda: transformers.GPT2ForSequenceClassification(config_for_token_classification),
    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),
)