|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. |
| 3 | +# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 6 | +# you may not use this file except in compliance with the License. |
| 7 | +# You may obtain a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | +# See the License for the specific language governing permissions and |
| 15 | +# limitations under the License. |
| 16 | +""" |
| 17 | +Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa). |
| 18 | +GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned |
| 19 | +using a masked language modeling (MLM) loss. |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import absolute_import |
| 23 | +import os |
| 24 | +import sys |
| 25 | +import torch |
| 26 | +import logging |
| 27 | +import argparse |
| 28 | +import math |
| 29 | +import numpy as np |
| 30 | +from io import open |
| 31 | +from tqdm import tqdm |
| 32 | + |
| 33 | +try: |
| 34 | + from torch.utils.tensorboard import SummaryWriter |
| 35 | +except: |
| 36 | + from tensorboardX import SummaryWriter |
| 37 | + |
| 38 | +from torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler, TensorDataset |
| 39 | +from torch.utils.data.distributed import DistributedSampler |
| 40 | +from transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup, |
| 41 | + RobertaConfig, RobertaModel, RobertaTokenizer, |
| 42 | + BartConfig, BartForConditionalGeneration, BartTokenizer, |
| 43 | + T5Config, T5ForConditionalGeneration, T5Tokenizer) |
| 44 | +import multiprocessing |
| 45 | +import pdb |
| 46 | +import time |
| 47 | + |
| 48 | +from models import DefectModel |
| 49 | +from configs import add_args, set_seed |
| 50 | +from utils import get_filenames, get_elapse_time, load_and_cache_defect_data |
| 51 | +from models import get_model_size, load_codet5 |
| 52 | + |
| 53 | +MODEL_CLASSES = {'roberta': (RobertaConfig, RobertaModel, RobertaTokenizer), |
| 54 | + 't5': (T5Config, T5ForConditionalGeneration, T5Tokenizer), |
| 55 | + 'codet5': (T5Config, T5ForConditionalGeneration, RobertaTokenizer), |
| 56 | + 'bart': (BartConfig, BartForConditionalGeneration, BartTokenizer)} |
| 57 | + |
| 58 | +cpu_cont = multiprocessing.cpu_count() |
| 59 | + |
| 60 | +logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', |
| 61 | + datefmt='%m/%d/%Y %H:%M:%S', |
| 62 | + level=logging.INFO) |
| 63 | +logger = logging.getLogger(__name__) |
| 64 | + |
| 65 | + |
| 66 | +def evaluate(args, model, eval_examples, eval_data, write_to_pred=False): |
| 67 | + eval_sampler = SequentialSampler(eval_data) |
| 68 | + eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) |
| 69 | + |
| 70 | + # Eval! |
| 71 | + logger.info("***** Running evaluation *****") |
| 72 | + logger.info(" Num examples = %d", len(eval_examples)) |
| 73 | + logger.info(" Num batches = %d", len(eval_dataloader)) |
| 74 | + logger.info(" Batch size = %d", args.eval_batch_size) |
| 75 | + eval_loss = 0.0 |
| 76 | + nb_eval_steps = 0 |
| 77 | + model.eval() |
| 78 | + logits = [] |
| 79 | + labels = [] |
| 80 | + for batch in tqdm(eval_dataloader, total=len(eval_dataloader), desc="Evaluating"): |
| 81 | + inputs = batch[0].to(args.device) |
| 82 | + label = batch[1].to(args.device) |
| 83 | + with torch.no_grad(): |
| 84 | + lm_loss, logit = model(inputs, label) |
| 85 | + eval_loss += lm_loss.mean().item() |
| 86 | + logits.append(logit.cpu().numpy()) |
| 87 | + labels.append(label.cpu().numpy()) |
| 88 | + nb_eval_steps += 1 |
| 89 | + logits = np.concatenate(logits, 0) |
| 90 | + labels = np.concatenate(labels, 0) |
| 91 | + preds = logits[:, 1] > 0.5 |
| 92 | + eval_acc = np.mean(labels == preds) |
| 93 | + eval_loss = eval_loss / nb_eval_steps |
| 94 | + perplexity = torch.tensor(eval_loss) |
| 95 | + |
| 96 | + result = { |
| 97 | + "eval_loss": float(perplexity), |
| 98 | + "eval_acc": round(eval_acc, 4), |
| 99 | + } |
| 100 | + |
| 101 | + logger.info("***** Eval results *****") |
| 102 | + for key in sorted(result.keys()): |
| 103 | + logger.info(" %s = %s", key, str(round(result[key], 4))) |
| 104 | + |
| 105 | + if write_to_pred: |
| 106 | + with open(os.path.join(args.output_dir, "predictions.txt"), 'w') as f: |
| 107 | + for example, pred in zip(eval_examples, preds): |
| 108 | + if pred: |
| 109 | + f.write(str(example.idx) + '\t1\n') |
| 110 | + else: |
| 111 | + f.write(str(example.idx) + '\t0\n') |
| 112 | + |
| 113 | + return result |
| 114 | + |
| 115 | + |
| 116 | +def main(): |
| 117 | + parser = argparse.ArgumentParser() |
| 118 | + t0 = time.time() |
| 119 | + args = add_args(parser) |
| 120 | + logger.info(args) |
| 121 | + |
| 122 | + # Setup CUDA, GPU & distributed training |
| 123 | + if args.local_rank == -1 or args.no_cuda: |
| 124 | + device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu") |
| 125 | + args.n_gpu = torch.cuda.device_count() |
| 126 | + else: # Initializes the distributed backend which will take care of sychronizing nodes/GPUs |
| 127 | + torch.cuda.set_device(args.local_rank) |
| 128 | + device = torch.device("cuda", args.local_rank) |
| 129 | + torch.distributed.init_process_group(backend='nccl') |
| 130 | + args.n_gpu = 1 |
| 131 | + |
| 132 | + logger.warning("Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, cpu count: %d", |
| 133 | + args.local_rank, device, args.n_gpu, bool(args.local_rank != -1), cpu_cont) |
| 134 | + args.device = device |
| 135 | + set_seed(args) |
| 136 | + |
| 137 | + # Build model |
| 138 | + config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type] |
| 139 | + config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path) |
| 140 | + model = model_class.from_pretrained(args.model_name_or_path) |
| 141 | + |
| 142 | + if args.model_type == 'codet5': |
| 143 | + # reset special ids: pad_token_id = 0, bos_token_id = 1, eos_token_id = 2 |
| 144 | + config, model, tokenizer = load_codet5(config, model, tokenizer_class, |
| 145 | + load_extra_ids=False, add_lang_ids=False, |
| 146 | + tokenizer_path=args.tokenizer_path) |
| 147 | + else: |
| 148 | + tokenizer = tokenizer_class.from_pretrained(args.tokenizer_name) |
| 149 | + |
| 150 | + model = DefectModel(model, config, tokenizer, args) |
| 151 | + logger.info("Finish loading model [%s] from %s", get_model_size(model), args.model_name_or_path) |
| 152 | + |
| 153 | + if args.load_model_path is not None: |
| 154 | + logger.info("Reload model from {}".format(args.load_model_path)) |
| 155 | + model.load_state_dict(torch.load(args.load_model_path)) |
| 156 | + |
| 157 | + model.to(device) |
| 158 | + |
| 159 | + pool = multiprocessing.Pool(cpu_cont) |
| 160 | + args.train_filename, args.dev_filename, args.test_filename = get_filenames(args.data_dir, args.task, args.sub_task) |
| 161 | + fa = open(os.path.join(args.output_dir, 'summary.log'), 'a+') |
| 162 | + |
| 163 | + if args.do_train: |
| 164 | + if args.n_gpu > 1: |
| 165 | + # multi-gpu training |
| 166 | + model = torch.nn.DataParallel(model) |
| 167 | + if args.local_rank in [-1, 0] and args.data_num == -1: |
| 168 | + summary_fn = '{}/{}'.format(args.summary_dir, '/'.join(args.output_dir.split('/')[1:])) |
| 169 | + tb_writer = SummaryWriter(summary_fn) |
| 170 | + |
| 171 | + # Prepare training data loader |
| 172 | + train_examples, train_data = load_and_cache_defect_data(args, args.train_filename, pool, tokenizer, 'train', |
| 173 | + is_sample=False) |
| 174 | + if args.local_rank == -1: |
| 175 | + train_sampler = RandomSampler(train_data) |
| 176 | + else: |
| 177 | + train_sampler = DistributedSampler(train_data) |
| 178 | + train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size) |
| 179 | + |
| 180 | + num_train_optimization_steps = args.num_train_epochs * len(train_dataloader) |
| 181 | + save_steps = max(len(train_dataloader), 1) |
| 182 | + |
| 183 | + # Prepare optimizer and schedule (linear warmup and decay) |
| 184 | + no_decay = ['bias', 'LayerNorm.weight'] |
| 185 | + optimizer_grouped_parameters = [ |
| 186 | + {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], |
| 187 | + 'weight_decay': args.weight_decay}, |
| 188 | + {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0} |
| 189 | + ] |
| 190 | + optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon) |
| 191 | + |
| 192 | + if args.warmup_steps < 1: |
| 193 | + warmup_steps = num_train_optimization_steps * args.warmup_steps |
| 194 | + else: |
| 195 | + warmup_steps = int(args.warmup_steps) |
| 196 | + scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, |
| 197 | + num_training_steps=num_train_optimization_steps) |
| 198 | + |
| 199 | + # Start training |
| 200 | + train_example_num = len(train_data) |
| 201 | + logger.info("***** Running training *****") |
| 202 | + logger.info(" Num examples = %d", train_example_num) |
| 203 | + logger.info(" Batch size = %d", args.train_batch_size) |
| 204 | + logger.info(" Batch num = %d", math.ceil(train_example_num / args.train_batch_size)) |
| 205 | + logger.info(" Num epoch = %d", args.num_train_epochs) |
| 206 | + |
| 207 | + global_step, best_acc = 0, 0 |
| 208 | + not_acc_inc_cnt = 0 |
| 209 | + is_early_stop = False |
| 210 | + for cur_epoch in range(args.start_epoch, int(args.num_train_epochs)): |
| 211 | + bar = tqdm(train_dataloader, total=len(train_dataloader), desc="Training") |
| 212 | + nb_tr_examples, nb_tr_steps, tr_loss = 0, 0, 0 |
| 213 | + model.train() |
| 214 | + for step, batch in enumerate(bar): |
| 215 | + batch = tuple(t.to(device) for t in batch) |
| 216 | + source_ids, labels = batch |
| 217 | + # pdb.set_trace() |
| 218 | + |
| 219 | + loss, logits = model(source_ids, labels) |
| 220 | + |
| 221 | + if args.n_gpu > 1: |
| 222 | + loss = loss.mean() # mean() to average on multi-gpu. |
| 223 | + if args.gradient_accumulation_steps > 1: |
| 224 | + loss = loss / args.gradient_accumulation_steps |
| 225 | + tr_loss += loss.item() |
| 226 | + |
| 227 | + nb_tr_examples += source_ids.size(0) |
| 228 | + nb_tr_steps += 1 |
| 229 | + loss.backward() |
| 230 | + torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm) |
| 231 | + |
| 232 | + if nb_tr_steps % args.gradient_accumulation_steps == 0: |
| 233 | + # Update parameters |
| 234 | + optimizer.step() |
| 235 | + optimizer.zero_grad() |
| 236 | + scheduler.step() |
| 237 | + global_step += 1 |
| 238 | + train_loss = round(tr_loss * args.gradient_accumulation_steps / nb_tr_steps, 4) |
| 239 | + bar.set_description("[{}] Train loss {}".format(cur_epoch, round(train_loss, 3))) |
| 240 | + |
| 241 | + if (step + 1) % save_steps == 0 and args.do_eval: |
| 242 | + logger.info("***** CUDA.empty_cache() *****") |
| 243 | + torch.cuda.empty_cache() |
| 244 | + |
| 245 | + eval_examples, eval_data = load_and_cache_defect_data(args, args.dev_filename, pool, tokenizer, |
| 246 | + 'valid', is_sample=False) |
| 247 | + |
| 248 | + result = evaluate(args, model, eval_examples, eval_data) |
| 249 | + eval_acc = result['eval_acc'] |
| 250 | + |
| 251 | + if args.data_num == -1: |
| 252 | + tb_writer.add_scalar('dev_acc', round(eval_acc, 4), cur_epoch) |
| 253 | + |
| 254 | + # save last checkpoint |
| 255 | + last_output_dir = os.path.join(args.output_dir, 'checkpoint-last') |
| 256 | + if not os.path.exists(last_output_dir): |
| 257 | + os.makedirs(last_output_dir) |
| 258 | + |
| 259 | + if True or args.data_num == -1 and args.save_last_checkpoints: |
| 260 | + model_to_save = model.module if hasattr(model, 'module') else model |
| 261 | + output_model_file = os.path.join(last_output_dir, "pytorch_model.bin") |
| 262 | + torch.save(model_to_save.state_dict(), output_model_file) |
| 263 | + logger.info("Save the last model into %s", output_model_file) |
| 264 | + |
| 265 | + if eval_acc > best_acc: |
| 266 | + not_acc_inc_cnt = 0 |
| 267 | + logger.info(" Best acc: %s", round(eval_acc, 4)) |
| 268 | + logger.info(" " + "*" * 20) |
| 269 | + fa.write("[%d] Best acc changed into %.4f\n" % (cur_epoch, round(eval_acc, 4))) |
| 270 | + best_acc = eval_acc |
| 271 | + # Save best checkpoint for best ppl |
| 272 | + output_dir = os.path.join(args.output_dir, 'checkpoint-best-acc') |
| 273 | + if not os.path.exists(output_dir): |
| 274 | + os.makedirs(output_dir) |
| 275 | + if args.data_num == -1 or True: |
| 276 | + model_to_save = model.module if hasattr(model, 'module') else model |
| 277 | + output_model_file = os.path.join(output_dir, "pytorch_model.bin") |
| 278 | + torch.save(model_to_save.state_dict(), output_model_file) |
| 279 | + logger.info("Save the best ppl model into %s", output_model_file) |
| 280 | + else: |
| 281 | + not_acc_inc_cnt += 1 |
| 282 | + logger.info("acc does not increase for %d epochs", not_acc_inc_cnt) |
| 283 | + if not_acc_inc_cnt > args.patience: |
| 284 | + logger.info("Early stop as acc do not increase for %d times", not_acc_inc_cnt) |
| 285 | + fa.write("[%d] Early stop as not_acc_inc_cnt=%d\n" % (cur_epoch, not_acc_inc_cnt)) |
| 286 | + is_early_stop = True |
| 287 | + break |
| 288 | + |
| 289 | + model.train() |
| 290 | + if is_early_stop: |
| 291 | + break |
| 292 | + |
| 293 | + logger.info("***** CUDA.empty_cache() *****") |
| 294 | + torch.cuda.empty_cache() |
| 295 | + |
| 296 | + if args.local_rank in [-1, 0] and args.data_num == -1: |
| 297 | + tb_writer.close() |
| 298 | + |
| 299 | + if args.do_test: |
| 300 | + logger.info(" " + "***** Testing *****") |
| 301 | + logger.info(" Batch size = %d", args.eval_batch_size) |
| 302 | + |
| 303 | + for criteria in ['best-acc']: # , 'last' |
| 304 | + file = os.path.join(args.output_dir, 'checkpoint-{}/pytorch_model.bin'.format(criteria)) |
| 305 | + # logger.info("*" * 10 + "Start testing" + "*" * 10) |
| 306 | + logger.info("Reload model from {}".format(file)) |
| 307 | + model.load_state_dict(torch.load(file)) |
| 308 | + |
| 309 | + if args.n_gpu > 1: |
| 310 | + # multi-gpu training |
| 311 | + model = torch.nn.DataParallel(model) |
| 312 | + |
| 313 | + eval_examples, eval_data = load_and_cache_defect_data(args, args.test_filename, pool, tokenizer, 'test', |
| 314 | + False) |
| 315 | + |
| 316 | + result = evaluate(args, model, eval_examples, eval_data, write_to_pred=True) |
| 317 | + logger.info(" test_acc=%.4f", result['eval_acc']) |
| 318 | + logger.info(" " + "*" * 20) |
| 319 | + |
| 320 | + fa.write("[%s] test-acc: %.4f\n" % (criteria, result['eval_acc'])) |
| 321 | + if args.res_fn: |
| 322 | + with open(args.res_fn, 'a+') as f: |
| 323 | + f.write('[Time: {}] {}\n'.format(get_elapse_time(t0), file)) |
| 324 | + f.write("[%s] acc: %.4f\n\n" % ( |
| 325 | + criteria, result['eval_acc'])) |
| 326 | + fa.close() |
| 327 | + |
| 328 | + |
| 329 | +if __name__ == "__main__": |
| 330 | + # print(' '.join(sys.argv[1:])) |
| 331 | + main() |
0 commit comments