-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
270 lines (217 loc) · 11.5 KB
/
train.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
import os
import torch
import random
import time
import logging
import argparse
import numpy as np
from tqdm import tqdm, trange
import subprocess
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader, SequentialSampler
from transformers import (BertConfig, BertTokenizer, AdamW, get_linear_schedule_with_warmup)
from transformers import AutoModelForSequenceClassification, AutoConfig, AutoTokenizer
from modeling import RankingBERT_Train
from marcodoc.dataset import MSMARCODataset, get_collate_function
from utils import generate_rank, eval_results
logger = logging.getLogger(__name__)
logging.basicConfig(format = '%(asctime)s-%(levelname)s-%(name)s- %(message)s',
datefmt = '%d %H:%M:%S',
level = logging.INFO)
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def save_model(model, output_dir, save_name, args):
save_dir = os.path.join(output_dir, save_name)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
model_to_save = model.module if hasattr(model, 'module') else model
model_to_save.save_pretrained(save_dir)
torch.save(args, os.path.join(save_dir, 'training_args.bin'))
def train(args, model):
""" Train the model """
tb_writer = SummaryWriter(args.log_dir)
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_dataset = MSMARCODataset("train", args.msmarco_dir,
args.collection_memmap_dir, args.tokenize_dir, args.bert_tokenizer_path,
args.max_query_length, args.max_doc_length)
# NOTE: Must Sequential! Pos, Neg, Pos, Neg, ...
train_sampler = SequentialSampler(train_dataset)
collate_fn = get_collate_function(mode="train")
train_dataloader = DataLoader(train_dataset, sampler=train_sampler,
batch_size=args.train_batch_size, num_workers=args.data_num_workers,
collate_fn=collate_fn)
t_total = len(train_dataloader) // args.gradient_accumulation_steps * args.num_train_epochs
# Prepare optimizer and schedule (linear warmup and decay)
no_decay = ['bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},
{'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}
]
optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)
scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps,
num_training_steps=t_total)
# multi-gpu training (should be after apex fp16 initialization)
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Train!
logger.info("***** Running training *****")
logger.info(" Num examples = %d", len(train_dataset))
logger.info(" Num Epochs = %d", args.num_train_epochs)
logger.info(" Instantaneous batch size per GPU = %d", args.per_gpu_train_batch_size)
logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d",
args.train_batch_size * args.gradient_accumulation_steps)
logger.info(" Gradient Accumulation steps = %d", args.gradient_accumulation_steps)
logger.info(" Total optimization steps = %d", t_total)
global_step = 0
tr_loss, logging_loss = 0.0, 0.0
model.zero_grad()
train_iterator = trange(int(args.num_train_epochs), desc="Epoch")
set_seed(args)
for epoch_idx, _ in enumerate(train_iterator):
epoch_iterator = tqdm(train_dataloader, desc="Iteration")
for step, (batch, _, _) in enumerate(epoch_iterator):
batch = {k: v.to(args.device) for k, v in batch.items()}
model.train()
outputs = model(**batch)
loss = outputs[0] # model outputs are always t
# uple in pytorch-transformers (see doc)
if args.n_gpu > 1:
loss = loss.mean() # mean() to average on multi-gpu parallel (not distributed) training
if args.gradient_accumulation_steps > 1:
loss = loss / args.gradient_accumulation_steps
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)
tr_loss += loss.item()
if (step + 1) % args.gradient_accumulation_steps == 0:
optimizer.step()
scheduler.step() # Update learning rate schedule
model.zero_grad()
global_step += 1
if args.evaluate_during_training and (global_step % args.training_eval_steps == 0):
mrr = evaluate(args, model, mode="dev", prefix="step_{}".format(global_step))
tb_writer.add_scalar('ndcg20', mrr, global_step)
if args.logging_steps > 0 and global_step % args.logging_steps == 0:
tb_writer.add_scalar('lr', scheduler.get_last_lr()[0], global_step)
cur_loss = (tr_loss - logging_loss)/args.logging_steps
tb_writer.add_scalar('train/loss', cur_loss, global_step)
logging_loss = tr_loss
if args.save_steps > 0 and global_step % args.save_steps == 0:
# Save model checkpoint
save_model(model, args.model_save_dir, 'ckpt-{}'.format(global_step), args)
def trec_eval(runf):
qrelf = '/data/users/liuyuan/clueweb09/top200/top200tokenized/qrel'
trec_eval_f = '/data/users/liuyuan/bert-reranker/eval/trec_eval'
output = subprocess.check_output([trec_eval_f, '-m', 'ndcg_cut.20', qrelf, runf]).decode().rstrip()
output = output.replace('\t', ' ').split('\n')
logging.info('Eval run file:{}, Metrics:{}'.format(runf, output))
assert len(output) == 1
return float(output[0].split()[2])
def evaluate(args, model, mode, prefix):
eval_output_dir = args.eval_save_dir
if not os.path.exists(eval_output_dir):
os.makedirs(eval_output_dir)
eval_dataset = MSMARCODataset(mode, args.msmarco_dir,
args.collection_memmap_dir, args.tokenize_dir, args.bert_tokenizer_path,
args.max_query_length, args.max_doc_length)
args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu)
# Note that DistributedSampler samples randomly
collate_fn = get_collate_function(mode=mode)
eval_dataloader = DataLoader(eval_dataset, batch_size=args.eval_batch_size,
num_workers=args.data_evaluate_num_workers, collate_fn=collate_fn)
# multi-gpu eval
if args.n_gpu > 1:
model = torch.nn.DataParallel(model)
# Eval!
logger.info("***** Running evaluation {} *****".format(prefix))
logger.info(" Num examples = %d", len(eval_dataset))
logger.info(" Batch size = %d", args.eval_batch_size)
output_file_path = f"{eval_output_dir}/{prefix}.{mode}.score.tsv"
with open(output_file_path, 'w') as outputfile:
for batch, qids, docids in tqdm(eval_dataloader, desc="Evaluating"):
model.eval()
with torch.no_grad():
batch = {k:v.to(args.device) for k, v in batch.items()}
outputs = model(**batch)
# print(outputs)
# print(outputs.shape)
scores = outputs.detach().cpu().numpy()
# print(qids, docids, scores)
assert len(qids) == len(docids) == len(scores)
for qid, docid, score in zip(qids, docids, scores):
outputfile.write(f"{qid}\t{docid}\t{score[0]}\n")
rank_output = f"{eval_output_dir}/{prefix}.{mode}.rank.tsv"
generate_rank(output_file_path, rank_output)
if mode == "dev":
mrr = eval_results(rank_output)
return mrr
def run_parse_args():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument("--task", choices=["train", "dev", "eval"], required=True)
parser.add_argument("--output_dir", type=str, default=f"./data/train")
parser.add_argument("--msmarco_dir", type=str, default=f"./msmarco_document/data/msmarco-doc")
parser.add_argument("--collection_memmap_dir", type=str, default="/data/users/liuyuan/PRADA_trigger/msmarco_document/tokenized_collection_memmap")
parser.add_argument("--tokenize_dir", type=str, default="/data/users/liuyuan/PRADA_trigger/msmarco_document/tokenize_dir")
parser.add_argument("--max_query_length", type=int, default=64)
parser.add_argument("--max_doc_length", type=int, default=445)
# Other parameters
parser.add_argument("--eval_ckpt", type=int, default=None)
parser.add_argument("--per_gpu_eval_batch_size", default=32, type=int,)
parser.add_argument("--per_gpu_train_batch_size", default=32, type=int)
parser.add_argument("--gradient_accumulation_steps", type=int, default=1)
parser.add_argument("--no_cuda", action='store_true')
parser.add_argument('--seed', type=int, default=42)
parser.add_argument("--evaluate_during_training", action="store_true")
parser.add_argument("--training_eval_steps", type=int, default=500)
parser.add_argument("--save_steps", type=int, default=1000)
parser.add_argument("--logging_steps", type=int, default=10)
parser.add_argument("--data_num_workers", default=0, type=int)
parser.add_argument("--data_evaluate_num_workers", default=0, type=int)
parser.add_argument("--learning_rate", default=1e-5, type=float)
parser.add_argument("--weight_decay", default=0.01, type=float)
parser.add_argument("--warmup_steps", default=200, type=int)
parser.add_argument("--adam_epsilon", default=1e-6, type=float)
parser.add_argument("--max_grad_norm", default=1.0, type=float)
parser.add_argument("--num_train_epochs", default=1, type=int)
parser.add_argument("--bert_tokenizer_path", default='/data/users/liuyuan/RankGPT/deberta-10k-rank_net', type=str)
args = parser.parse_args()
time_stamp = time.strftime("%b-%d_%H:%M:%S", time.localtime())
args.log_dir = f"{args.output_dir}/log/{time_stamp}"
args.model_save_dir = f"{args.output_dir}/models"
args.eval_save_dir = f"{args.output_dir}/tmp_eval_results"
return args
def main():
args = run_parse_args()
logger.info(args)
# Setup CUDA, GPU
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = torch.cuda.device_count()
args.device = device
# Setup logging
logger.warning("Device: %s, n_gpu: %s", device, args.n_gpu)
# Set seed
set_seed(args)
if args.task == "train":
load_model_path = f"/data/users/liuyuan/bert-base-uncased"
else:
assert args.eval_ckpt is not None
load_model_path = '/data/users/liuyuan/RankGPT/deberta-10k-rank_net'
# load_model_path = '/data/users/liuyuan/PRADA/data/train/models/ckpt-8000'
# load_model_path = f"{args.model_save_dir}/ckpt-{args.eval_ckpt}"
config = AutoConfig.from_pretrained('/data/users/liuyuan/RankGPT/deberta-10k-rank_net')
model = RankingBERT_Train.from_pretrained(load_model_path, config=config)
model.to(args.device)
logger.info("Training/evaluation parameters %s", args)
# Evaluation
if args.task == "train":
train(args, model)
else:
result = evaluate(args, model, args.task, prefix=f"ckpt-{args.eval_ckpt}")
print(result)
if __name__ == "__main__":
main()