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
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from time import time
from datetime import timedelta
from copy import deepcopy
import random
import numpy as np
import pandas as pd
from ml_metrics import mapk
import torch
from torch.optim import AdamW
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data import Dataset, DataLoader
from transformers import BertTokenizerFast, BertForMultipleChoice
# Random seed
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
# CUDA device
use_cuda_device = 0
torch.cuda.set_device(use_cuda_device)
print("Using CUDA device: %d" % torch.cuda.current_device())
# ## Settings
# In[ ]:
# Input files
document_csv_path = '../input/ntust-ir2020-homework6/documents.csv'
training_csv_path = '../input/ntust-ir2020-homework6/train_queries.csv'
testing_csv_path = '../input/ntust-ir2020-homework6/test_queries.csv'
# Input limitation
max_query_length = 64
max_input_length = 512
num_negatives = 3 # num. of negative documents to pair with a positive document
# Model finetuning
model_name_or_path = "bert-base-uncased"
max_epochs = 1
learning_rate = 3e-5
dev_set_ratio = 0.2 # make a ratio of training set as development set for rescoring weight sniffing
max_patience = 0 # earlystop if avg. loss on development set doesn't decrease for num. of epochs
batch_size = 2 # num. of inputs = 8 requires ~9200 MB VRAM (num. of inputs = batch_size * (num_negatives + 1))
num_workers = 2 # num. of jobs for pytorch dataloader
# Save paths
save_model_path = "models/bert_base_uncased" # assign `None` for not saving the model
save_submission_path = "bm25_bert_rescoring.csv"
K = 1000 # for MAP@K
# ## Preparing
# In[ ]:
# Build and save BERT tokenizer
tokenizer = BertTokenizerFast.from_pretrained(model_name_or_path)
if save_model_path is not None:
save_tokenizer_path = "%s/tokenizer" % (save_model_path)
tokenizer.save_pretrained(save_tokenizer_path)
# Collect mapping of all document id and text
doc_id_to_text = {}
doc_df = pd.read_csv(document_csv_path)
doc_df.fillna("<Empty Document>", inplace=True)
id_text_pair = zip(doc_df["doc_id"], doc_df["doc_text"])
for i, pair in enumerate(id_text_pair, start=1):
doc_id, doc_text = pair
doc_id_to_text[doc_id] = doc_text
print("Progress: %d/%d\r" % (i, len(doc_df)), end='')
doc_df.tail()
# # Training
# ## Split a ratio of training set as development set
# In[ ]:
train_df = pd.read_csv(training_csv_path)
dev_df, train_df = np.split(train_df, [int(dev_set_ratio*len(train_df))])
dev_df.reset_index(drop=True, inplace=True)
train_df.reset_index(drop=True, inplace=True)
print("train_df shape:", train_df.shape)
print("dev_df shape:", dev_df.shape)
train_df.tail()
# ## Build instances for training/development set
# In[ ]:
get_ipython().run_cell_magic('time', '', 'doc_id_to_token_ids = {}\n\n\ndef preprocess_df(df):\n \'\'\' Preprocess DataFrame into training instances for BERT. \'\'\'\n instances = []\n \n # Parse CSV\n for i, row in df.iterrows():\n query_id, query_text, pos_doc_ids, bm25_top1000, _ = row\n pos_doc_id_list = pos_doc_ids.split()\n pos_doc_id_set = set(pos_doc_id_list)\n bm25_top1000_list = bm25_top1000.split()\n bm25_top1000_set = set(bm25_top1000_list)\n\n # Pair BM25 neg. with pos. samples\n labeled_pos_neg_list = []\n for pos_doc_id in pos_doc_id_list:\n neg_doc_id_set = bm25_top1000_set - pos_doc_id_set\n neg_doc_ids = random.sample(neg_doc_id_set, num_negatives)\n pos_position = random.randint(0, num_negatives)\n pos_neg_doc_ids = neg_doc_ids\n pos_neg_doc_ids.insert(pos_position, pos_doc_id)\n labeled_sample = (pos_neg_doc_ids, pos_position)\n labeled_pos_neg_list.append(labeled_sample)\n \n # Make query tokens for BERT\n query_tokens = tokenizer.tokenize(query_text)\n if len(query_tokens) > max_query_length: # truncation\n query_tokens = query_tokens[:max_query_length]\n query_token_ids = tokenizer.convert_tokens_to_ids(query_tokens)\n query_token_ids.insert(0, tokenizer.cls_token_id)\n query_token_ids.append(tokenizer.sep_token_id)\n\n # Make input instances for all query/doc pairs\n for doc_ids, label in labeled_pos_neg_list:\n paired_input_ids = []\n paired_attention_mask = []\n paired_token_type_ids = []\n \n # Merge all pos/neg inputs as a single sample\n for doc_id in doc_ids:\n if doc_id in doc_id_to_token_ids:\n doc_token_ids = doc_id_to_token_ids[doc_id]\n else:\n doc_text = doc_id_to_text[doc_id]\n doc_tokens = tokenizer.tokenize(doc_text)\n doc_token_ids = tokenizer.convert_tokens_to_ids(doc_tokens)\n doc_id_to_token_ids[doc_id] = doc_token_ids\n doc_token_ids.append(tokenizer.sep_token_id)\n\n # make input sequences for BERT\n input_ids = query_token_ids + doc_token_ids\n token_type_ids = [0 for token_id in query_token_ids]\n token_type_ids.extend(1 for token_id in doc_token_ids)\n if len(input_ids) > max_input_length: # truncation\n input_ids = input_ids[:max_input_length]\n token_type_ids = token_type_ids[:max_input_length]\n attention_mask = [1 for token_id in input_ids]\n \n # convert and collect inputs as tensors\n input_ids = torch.LongTensor(input_ids)\n attention_mask = torch.FloatTensor(attention_mask)\n token_type_ids = torch.LongTensor(token_type_ids)\n paired_input_ids.append(input_ids)\n paired_attention_mask.append(attention_mask)\n paired_token_type_ids.append(token_type_ids)\n label = torch.LongTensor([label]).squeeze()\n \n # Pre-pad tensor pairs for efficiency\n paired_input_ids = pad_sequence(paired_input_ids, batch_first=True)\n paired_attention_mask = pad_sequence(paired_attention_mask, batch_first=True)\n paired_token_type_ids = pad_sequence(paired_token_type_ids, batch_first=True)\n\n # collect all inputs as a dictionary\n instance = {}\n instance[\'input_ids\'] = paired_input_ids.T # transpose for code efficiency\n instance[\'attention_mask\'] = paired_attention_mask.T\n instance[\'token_type_ids\'] = paired_token_type_ids.T\n instance[\'label\'] = label\n instances.append(instance)\n\n print("Progress: %d/%d\\r" % (i+1, len(df)), end=\'\')\n print()\n return instances\n\ntrain_instances = preprocess_df(train_df)\ndev_instances = preprocess_df(dev_df)\n\nprint("num. train_instances: %d" % len(train_instances))\nprint("num. dev_instances: %d" % len(dev_instances))\nprint("input_ids.T shape:", train_instances[0][\'input_ids\'].T.shape)\ntrain_instances[0][\'input_ids\'].T\n')
# ## Build dataset and dataloader for PyTorch
# In[ ]:
class TrainingDataset(Dataset):
def __init__(self, instances):
self.instances = instances
def __len__(self):
return len(self.instances)
def __getitem__(self, i):
instance = self.instances[i]
input_ids = instance['input_ids']
attention_mask = instance['attention_mask']
token_type_ids = instance['token_type_ids']
label = instance['label']
return input_ids, attention_mask, token_type_ids, label
def get_train_dataloader(instances, batch_size=2, num_workers=4):
def collate_fn(batch):
input_ids, attention_mask, token_type_ids, labels = zip(*batch)
input_ids = pad_sequence(input_ids, batch_first=True).transpose(1,2).contiguous() # re-transpose
attention_mask = pad_sequence(attention_mask, batch_first=True).transpose(1,2).contiguous()
token_type_ids = pad_sequence(token_type_ids, batch_first=True).transpose(1,2).contiguous()
labels = torch.stack(labels)
return input_ids, attention_mask, token_type_ids, labels
dataset = TrainingDataset(instances)
dataloader = DataLoader(dataset, collate_fn=collate_fn, shuffle=True, \
batch_size=batch_size, num_workers=num_workers)
return dataloader
# Demo
dataloader = get_train_dataloader(train_instances)
for batch in dataloader:
input_ids, attention_mask, token_type_ids, labels = batch
break
print(input_ids.shape)
input_ids
# ## Initialize and finetune BERT
# In[ ]:
model = BertForMultipleChoice.from_pretrained(model_name_or_path)
model.cuda()
optimizer = AdamW(model.parameters(), lr=learning_rate)
optimizer.zero_grad()
# ### (TO-DO!) Define validation function for earlystopping
# In[ ]:
def validate(model, instances):
total_loss = 0
model.eval()
dataloader = get_train_dataloader(instances, batch_size=batch_size, num_workers=num_workers)
for batch in dataloader:
batch = (tensor.cuda() for tensor in batch)
input_ids, attention_mask, token_type_ids, labels = batch
''' TO-DO:
1. Compute the cross-entropy loss (using built-in loss of BertForMultipleChoice)
(Hint: You need to call a function of model which takes all the 4 tensors in the batch as inputs)
2. Sum up the loss of all dev-set samples
(Hint: The built-in loss is averaged, so you should multiply it with the batch size)
'''
with torch.no_grad():
### 1. insert_missing_code
loss = model( input_ids = input_ids, attention_mask = attention_mask,
token_type_ids = token_type_ids, labels = labels, return_dict=1 ).loss
### 2. insert_missing_code
total_loss += loss * batch_size
avg_loss = total_loss / len(instances)
return avg_loss
# ### (TO-DO!) Let's train this beeg boy ;-)
# In[ ]:
patience, best_dev_loss = 0, 1e10
best_state_dict = model.state_dict()
start_time = time()
dataloader = get_train_dataloader(train_instances, batch_size=batch_size, num_workers=num_workers)
for epoch in range(1, max_epochs+1):
model.train()
for i, batch in enumerate(dataloader, start=1):
batch = (tensor.cuda() for tensor in batch)
input_ids, attention_mask, token_type_ids, labels = batch
# Backpropogation
''' TO-DO:
1. Compute the cross-entropy loss (using built-in loss of BertForMultipleChoice)
(Hint: You need to call a function of model which takes all the 4 tensors in the batch as inputs)
2. Perform backpropogation on the loss (i.e. compute gradients)
3. Optimize the model.
(Hint: These two lines of codes can be found in PyTorch tutorial)
'''
### 1. insert_missing_code
loss = model( input_ids = input_ids, attention_mask = attention_mask,
token_type_ids = token_type_ids, labels = labels, return_dict=1 ).loss
### 2. insert_missing_code
loss.backward()
### 3. insert_missing_code
optimizer.step()
optimizer.zero_grad()
# Progress bar with timer ;-)
elapsed_time = time() - start_time
elapsed_time = timedelta(seconds=int(elapsed_time))
print("Epoch: %d/%d | Batch: %d/%d | loss=%.5f | %s \r" \
% (epoch, max_epochs, i, len(dataloader), loss, elapsed_time), end='')
# Save parameters of each epoch
if save_model_path is not None:
save_checkpoint_path = "%s/epoch_%d" % (save_model_path, epoch)
model.save_pretrained(save_checkpoint_path)
# Get avg. loss on development set
print("Epoch: %d/%d | Validating... \r" % (epoch, max_epochs), end='')
dev_loss = validate(model, dev_instances)
elapsed_time = time() - start_time
elapsed_time = timedelta(seconds=int(elapsed_time))
print("Epoch: %d/%d | dev_loss=%.5f | %s " \
% (epoch, max_epochs, dev_loss, elapsed_time))
# Track best checkpoint and earlystop patience
if dev_loss < best_dev_loss:
patience = 0
best_dev_loss = dev_loss
best_state_dict = deepcopy(model.state_dict())
if save_model_path is not None:
model.save_pretrained(save_model_path)
else:
patience += 1
if patience > max_patience:
print('Earlystop at epoch %d' % epoch)
break
# Restore parameters with best loss on development set
model.load_state_dict(best_state_dict)
# # Testing
# In[ ]:
class TestingDataset(Dataset):
def __init__(self, instances):
self.instances = instances
def __len__(self):
return len(self.instances)
def __getitem__(self, i):
instance = self.instances[i]
input_ids = instance['input_ids']
attention_mask = instance['attention_mask']
token_type_ids = instance['token_type_ids']
input_ids = torch.LongTensor(input_ids)
attention_mask = torch.FloatTensor(attention_mask)
token_type_ids = torch.LongTensor(token_type_ids)
return input_ids, attention_mask, token_type_ids,
def get_test_dataloader(instances, batch_size=8, num_workers=4):
def collate_fn(batch):
input_ids, attention_mask, token_type_ids = zip(*batch)
input_ids = pad_sequence(input_ids, batch_first=True).unsqueeze(1) # predict as single choice
attention_mask = pad_sequence(attention_mask, batch_first=True).unsqueeze(1)
token_type_ids = pad_sequence(token_type_ids, batch_first=True).unsqueeze(1)
return input_ids, attention_mask, token_type_ids
dataset = TestingDataset(instances)
dataloader = DataLoader(dataset, collate_fn=collate_fn, shuffle=False, \
batch_size=batch_size, num_workers=num_workers)
return dataloader
# ## (TO-DO!) Define function to predict BERT scores
# In[ ]:
def predict_query_doc_scores(model, df):
model.eval()
start_time = time()
# Parse CSV
query_id_list = df["query_id"]
query_text_list = df["query_text"]
bm25_top1000_list = df["bm25_top1000"]
# Treat {1 query, K documents} as a dataset for prediction
query_doc_scores = []
query_doc_ids = []
rows = zip(query_id_list, query_text_list, bm25_top1000_list)
for qi, row in enumerate(rows, start=1):
query_id, query_text, bm25_top1000 = row
bm25_doc_id_list = bm25_top1000.split()
query_doc_ids.append(bm25_doc_id_list)
#################################################
# Collect all instances of query/doc pairs
#################################################
query_instances = []
# Make query tokens for BERT
query_tokens = tokenizer.tokenize(query_text)
if len(query_tokens) > max_query_length: # truncation
query_tokens = query_tokens[:max_query_length]
query_token_ids = tokenizer.convert_tokens_to_ids(query_tokens)
query_token_ids.insert(0, tokenizer.cls_token_id)
query_token_ids.append(tokenizer.sep_token_id)
# Make input instances for all query/doc pairs
for i, doc_id in enumerate(bm25_doc_id_list, start=1):
if doc_id in doc_id_to_token_ids:
doc_token_ids = doc_id_to_token_ids[doc_id]
else:
doc_text = doc_id_to_text[doc_id]
doc_tokens = tokenizer.tokenize(doc_text)
doc_token_ids = tokenizer.convert_tokens_to_ids(doc_tokens)
doc_id_to_token_ids[doc_id] = doc_token_ids
doc_token_ids.append(tokenizer.sep_token_id)
# make input sequences for BERT
input_ids = query_token_ids + doc_token_ids
token_type_ids = [0 for token_id in query_token_ids]
token_type_ids.extend(1 for token_id in doc_token_ids)
if len(input_ids) > max_input_length: # truncation
input_ids = input_ids[:max_input_length]
token_type_ids = token_type_ids[:max_input_length]
attention_mask = [1 for token_id in input_ids]
# convert and collect inputs as tensors
input_ids = torch.LongTensor(input_ids)
attention_mask = torch.FloatTensor(attention_mask)
token_type_ids = torch.LongTensor(token_type_ids)
# collect all inputs as a dictionary
instance = {}
instance['input_ids'] = input_ids
instance['attention_mask'] = attention_mask
instance['token_type_ids'] = token_type_ids
query_instances.append(instance)
#################################################################
# Predict relevance scores for all BM25-top-1000 documents
#################################################################
doc_scores = np.empty((0,1))
# Predict scores for each document
dataloader = get_test_dataloader(query_instances, batch_size=batch_size*(num_negatives+1), num_workers=num_workers)
for di, batch in enumerate(dataloader, start=1):
batch = (tensor.cuda() for tensor in batch)
input_ids, attention_mask, token_type_ids = batch
''' TO-DO:
1. Compute the logits as relevance scores (using the same function of how you compute built-in loss)
(Hint: You need to call a function of model which takes all the 3 tensors in the batch as inputs)
2. The scores are still on GPU. Reallocate them on CPU, and convert into numpy arrays.
(Hint: You need to call two functions on the `scores` tensors. You can find them in PyTorch tutorial.)
'''
with torch.no_grad():
### 1. insert_missing_code_to_compute_logits ###
scores = model( input_ids=input_ids, attention_mask=attention_mask,
token_type_ids=token_type_ids, return_dict=True ).logits
# merge all scores into a big numpy array
### step 2. insert_missing_function_1()###.###insert_missing_function_2()
scores = scores.cpu().numpy()
doc_scores = np.vstack((doc_scores, scores)) ## 新增new row
# Progress bar with timer ;-)
elapsed_time = time() - start_time
elapsed_time = timedelta(seconds=int(elapsed_time))
print("Query: %d/%d | Progress: %d/%d | %s \r" \
% (qi, len(df), di, len(dataloader), elapsed_time), end='')
# merge all query/BM25 document pair scores
query_doc_scores.append(doc_scores)
query_doc_scores = np.hstack(query_doc_scores).T
print()
return query_doc_scores, query_doc_ids
# In[ ]:
# ## (TO-DO!) Find best weight of BERT for BM25 rescoring on training set
# In[ ]:
dev_query_doc_scores, dev_query_doc_ids = predict_query_doc_scores(model, dev_df)
print('---- Grid search weight for "BM25 + weight * BERT" ----')
best_map_score, best_bert_weight = -100, 0.0
bert_scores = dev_query_doc_scores
n_query = dev_query_doc_scores.shape[0]
# Get MAP@K of BM25 baseline
query_pos_doc_ids = dev_df['pos_doc_ids'].values.tolist()
actual = [doc_ids.split() for doc_ids in query_pos_doc_ids]
bm25_predicted = [doc_id_list[:K] for doc_id_list in dev_query_doc_ids]
map_score = mapk(actual, bm25_predicted, k=K)
best_map_score = map_score
print("weight=%.1f: %.5f (BM25 baseline)" % (0, 100*map_score))
# Collect BM25 scores into same format of BERT scores
''' TO-DO:
1. Convert the BM25 top-1000 scores into 2d numpy arrays
2. BM25 scores should have the same shape and orders as `dev_query_doc_scores` (i.e. BERT scores)
(Hint: If there are 24 dev-set queries, the shape should be (24, 1000) )
'''
### 2. insert_whatever_you_want_to_meet_the_requirement_in_step2.
bm25_scores = [scores.split() for scores in dev_df["bm25_top1000_scores"]]
bm25_scores = [[float(score) for score in scores] for scores in bm25_scores]
bm25_scores = np.array(bm25_scores)
# Grid search for BM25 + BERT rescoring
low_bound, high_bound, scale = 0, 5, 1000
grids = [i / scale for i in range(low_bound * scale+1, high_bound * scale+1)]
for weight in grids:
''' TO-DO:
1. Compute the weighted scores using `bm25_scores`, `weight`, and `bert_scores`
'''
weighted_scores = bm25_scores + weight * bert_scores ### 1. insert_missing_code ###
# sort index and map to document ids as output
rescore_argsort = np.flip(weighted_scores.argsort(), axis=1)
predicted = []
for i in range(n_query): # num. of queries
predicted.append([dev_query_doc_ids[i][idx] for idx in rescore_argsort[i]][:K])
map_score = mapk(actual, predicted, k=K)
# show part of results for human evaluation
if weight * 10 % 2 == 0:
print("weight=%.1f: %.5f" % (weight, 100*map_score))
# track weight with best MAP@10
if map_score > best_map_score:
best_map_score = map_score
best_bert_weight = weight
print("\nHighest MAP@%d = %.5f found at weight=%.3f" % (K, 100*best_map_score, best_bert_weight))
# ## (TO-DO!) Rescore testing set with BERT for submission
# In[ ]:
# Predict BERT scores for testing set
test_df = pd.read_csv(testing_csv_path)
query_id_list = test_df["query_id"]
n_query = len(query_id_list)
test_query_doc_scores, test_query_doc_ids = predict_query_doc_scores(model, test_df)
bert_scores = test_query_doc_scores
# In[ ]:
# Rescore query/document score with BM25 + BERT
bm25_scores = [scores.split() for scores in test_df["bm25_top1000_scores"]] # parse into 2d list of string
bm25_scores = [[float(score) for score in scores] for scores in bm25_scores] # convert to float
bm25_scores = np.array(bm25_scores)
''' TO-DO:
1. Compute the weighted scores using `bm25_scores`, `best_bert_weight`, and `bert_scores`
'''
### 1. insesrt_missing_code ###
weighted_scores = bm25_scores + best_bert_weight * bert_scores
# Rerank document ids with new scores
rescore_argsort = np.flip(weighted_scores.argsort(), axis=1)
ranked_doc_id_list = []
for i in range(n_query): # num. of queries
ranked_doc_id_list.append([test_query_doc_ids[i][idx] for idx in rescore_argsort[i]][:K])
ranked_doc_ids = [' '.join(doc_id_list) for doc_id_list in ranked_doc_id_list]
# Save reranked results for submission
data = {'query_id': query_id_list, 'ranked_doc_ids': ranked_doc_ids}
submission_df = pd.DataFrame(data)
submission_df.reset_index(drop=True, inplace=True)
submission_df.to_csv(save_submission_path, index=False)
print("Saved submission file as `%s`" % save_submission_path)
|