-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpretrainIf.py
304 lines (255 loc) · 9.05 KB
/
pretrainIf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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
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
from tqdm import tqdm, trange
from IPython.display import clear_output
from transformers import RobertaModel
from transformers import RobertaTokenizer
from transformers import (
get_cosine_schedule_with_warmup,
get_cosine_with_hard_restarts_schedule_with_warmup
)
from transformers import RobertaConfig
from torch.utils.data import (
Dataset, DataLoader,
SequentialSampler, RandomSampler
)
import torch.optim.lr_scheduler as lr_scheduler
from torch.optim.optimizer import Optimizer
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
import torch
import gc
from collections import defaultdict
import json
import matplotlib.pyplot as plt
import os
from glob import glob
import pandas as pd
import numpy as np
train = pd.read_csv('./input/commonlitreadabilityprize/train.csv')
test = pd.read_csv('./input/commonlitreadabilityprize/test.csv')
# %matplotlib inline
gc.enable()
def convert_examples_to_features(data, tokenizer, max_len, is_test=False):
data = data.replace('\n', '')
tok = tokenizer.encode_plus(
data,
max_length=max_len,
truncation=True,
return_attention_mask=True,
return_token_type_ids=True
)
curr_sent = {}
padding_length = max_len - len(tok['input_ids'])
curr_sent['input_ids'] = tok['input_ids'] + ([0] * padding_length)
curr_sent['token_type_ids'] = tok['token_type_ids'] + \
([0] * padding_length)
curr_sent['attention_mask'] = tok['attention_mask'] + \
([0] * padding_length)
return curr_sent
class DatasetRetriever(Dataset):
def __init__(self, data, tokenizer, max_len, is_test=False):
self.data = data
self.excerpts = self.data.excerpt.values.tolist()
self.tokenizer = tokenizer
self.is_test = is_test
self.max_len = max_len
def __len__(self):
return len(self.data)
def __getitem__(self, item):
if not self.is_test:
excerpt, label = self.excerpts[item], self.targets[item]
features = convert_examples_to_features(
excerpt, self.tokenizer,
self.max_len, self.is_test
)
return {
'input_ids': torch.tensor(features['input_ids'], dtype=torch.long),
'token_type_ids': torch.tensor(features['token_type_ids'], dtype=torch.long),
'attention_mask': torch.tensor(features['attention_mask'], dtype=torch.long),
'label': torch.tensor(label, dtype=torch.double),
}
else:
excerpt = self.excerpts[item]
features = convert_examples_to_features(
excerpt, self.tokenizer,
self.max_len, self.is_test
)
return {
'input_ids': torch.tensor(features['input_ids'], dtype=torch.long),
'token_type_ids': torch.tensor(features['token_type_ids'], dtype=torch.long),
'attention_mask': torch.tensor(features['attention_mask'], dtype=torch.long),
}
class CommonLitModel(nn.Module):
def __init__(
self,
model_name,
config,
multisample_dropout=False,
output_hidden_states=False
):
super(CommonLitModel, self).__init__()
self.config = config
self.roberta = RobertaModel.from_pretrained(
model_name,
output_hidden_states=output_hidden_states
)
self.layer_norm = nn.LayerNorm(config.hidden_size)
if multisample_dropout:
self.dropouts = nn.ModuleList([
nn.Dropout(0.5) for _ in range(5)
])
else:
self.dropouts = nn.ModuleList([nn.Dropout(0.3)])
self.regressor = nn.Linear(config.hidden_size, 1)
self._init_weights(self.layer_norm)
self._init_weights(self.regressor)
def _init_weights(self, module):
if isinstance(module, nn.Linear):
module.weight.data.normal_(
mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(
mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
def forward(
self,
input_ids=None,
attention_mask=None,
token_type_ids=None,
labels=None
):
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
)
sequence_output = outputs[1]
sequence_output = self.layer_norm(sequence_output)
# multi-sample dropout
for i, dropout in enumerate(self.dropouts):
if i == 0:
logits = self.regressor(dropout(sequence_output))
else:
logits += self.regressor(dropout(sequence_output))
logits /= len(self.dropouts)
# calculate loss
loss = None
if labels is not None:
loss_fn = torch.nn.MSELoss()
logits = logits.view(-1).to(labels.dtype)
loss = torch.sqrt(loss_fn(logits, labels.view(-1)))
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
def make_model(model_name='roberta-base', num_labels=1):
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
config = RobertaConfig.from_pretrained(model_name)
config.update({'num_labels': num_labels})
model = CommonLitModel(model_name, config=config)
return model, tokenizer
def make_loader(
data,
tokenizer,
max_len,
batch_size,
):
test_dataset = DatasetRetriever(data, tokenizer, max_len, is_test=True)
test_sampler = SequentialSampler(test_dataset)
test_loader = DataLoader(
test_dataset,
batch_size=batch_size // 2,
sampler=test_sampler,
pin_memory=False,
drop_last=False,
num_workers=0
)
return test_loader
class Evaluator:
def __init__(self, model, scalar=None):
self.model = model
self.scalar = scalar
def evaluate(self, data_loader, tokenizer):
preds = []
self.model.eval()
total_loss = 0
with torch.no_grad():
for batch_idx, batch_data in enumerate(data_loader):
input_ids, attention_mask, token_type_ids = batch_data['input_ids'], \
batch_data['attention_mask'], batch_data['token_type_ids']
input_ids, attention_mask, token_type_ids = input_ids.cuda(), \
attention_mask.cuda(), token_type_ids.cuda()
if self.scalar is not None:
with torch.cuda.amp.autocast():
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
else:
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids
)
logits = outputs[0].detach().cpu().numpy().squeeze().tolist()
preds += logits
return preds
def config(fold):
torch.manual_seed(2021)
torch.cuda.manual_seed(2021)
torch.cuda.manual_seed_all(2021)
max_len = 250
batch_size = 8
model, tokenizer = make_model(
model_name='./output/',
num_labels=1
)
model.load_state_dict(
torch.load(f'./model{fold}.bin')
)
test_loader = make_loader(
test, tokenizer, max_len=max_len,
batch_size=batch_size
)
if torch.cuda.device_count() >= 1:
print('Model pushed to {} GPU(s), type {}.'.format(
torch.cuda.device_count(),
torch.cuda.get_device_name(0))
)
model = model.cuda()
else:
raise ValueError('CPU training is not supported')
# scaler = torch.cuda.amp.GradScaler()
scaler = None
return (
model, tokenizer,
test_loader, scaler
)
def run(fold=0):
model, tokenizer, \
test_loader, scaler = config(fold)
import time
evaluator = Evaluator(model, scaler)
test_time_list = []
torch.cuda.synchronize()
tic1 = time.time()
preds = evaluator.evaluate(test_loader, tokenizer)
torch.cuda.synchronize()
tic2 = time.time()
test_time_list.append(tic2 - tic1)
del model, tokenizer, test_loader, scaler
gc.collect()
torch.cuda.empty_cache()
return preds
pred_df = pd.DataFrame()
for fold in tqdm(range(5)):
pred_df[f'fold{fold}'] = run(fold)
sub = pd.read_csv('./input/commonlitreadabilityprize/sample_submission.csv')
sub['target'] = pred_df.mean(axis=1).values.tolist()
sub.to_csv('submission.csv', index=False)
print(sub)