Download Script/Model/CodeT5+/code-generation/run_generation.py from docz1105/ComBack_Models: direct link, hf CLI and curl.
- Browser
- Download file 23.5 kB
-
https://huggingface.co/docz1105/ComBack_Models/resolve/1d84adc33f34e682a192dbb7e831787d905bf583/Script/Model/CodeT5%2B/code-generation/run_generation.py
- Command line
-
hf download hf://docz1105/ComBack_Models@1d84adc33f34e682a192dbb7e831787d905bf583/Script/Model/CodeT5+/code-generation/run_generation.py
-
curl -L -o run_generation.py https://huggingface.co/docz1105/ComBack_Models/resolve/1d84adc33f34e682a192dbb7e831787d905bf583/Script/Model/CodeT5%2B/code-generation/run_generation.py
23.5 kB
| # coding=utf-8 | |
| # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. | |
| # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| """ | |
| Fine-tuning the library models for language modeling on a text file (GPT, GPT-2, BERT, RoBERTa). | |
| GPT and GPT-2 are fine-tuned using a causal language modeling (CLM) loss while BERT and RoBERTa are fine-tuned | |
| using a masked language modeling (MLM) loss. | |
| """ | |
| from __future__ import absolute_import | |
| import os | |
| import sys | |
| from bleu import _bleu | |
| import pickle | |
| import torch | |
| import json | |
| import random | |
| import logging | |
| import argparse | |
| import numpy as np | |
| from io import open | |
| from itertools import cycle | |
| import torch.nn as nn | |
| from tqdm import tqdm, trange | |
| from torch.nn.utils.rnn import pad_sequence | |
| from fuzzywuzzy import fuzz | |
| from torch.utils.data import DataLoader, Dataset, SequentialSampler, RandomSampler,TensorDataset | |
| from torch.utils.data.distributed import DistributedSampler | |
| from transformers import (WEIGHTS_NAME, AdamW, get_linear_schedule_with_warmup, T5ForConditionalGeneration, AutoTokenizer) | |
| logging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', | |
| datefmt = '%m/%d/%Y %H:%M:%S', | |
| level = logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| divide_number = 3 | |
| # | |
| class Example(object): | |
| """A single training/test example.""" | |
| def __init__(self, | |
| idx, | |
| source, | |
| ts_v, | |
| target, | |
| ): | |
| self.idx = idx | |
| self.source = source | |
| self.ts_v = ts_v | |
| self.target = target | |
| def read_examples(filename): | |
| """Read examples from filename.""" | |
| examples=[] | |
| with open(filename,encoding="utf-8") as f: | |
| for idx, line in enumerate(f): | |
| line=line.strip() | |
| js=json.loads(line) | |
| examples.append( | |
| Example( | |
| idx = idx, | |
| source=" ".join(js['natrual_language']), | |
| ts_v = ",".join(js['TS_V_token']), | |
| target = " ".join(js["ground_truth"][1:-1]), | |
| ) | |
| ) | |
| return examples | |
| class InputFeatures(object): | |
| """A single training/test features for a example.""" | |
| def __init__(self, | |
| example_id, | |
| source_ids, source_mask, | |
| target_ids, target_mask | |
| ): | |
| self.example_id = example_id | |
| self.source_ids = source_ids | |
| self.source_mask = source_mask | |
| self.target_ids = target_ids | |
| self.target_mask = target_mask | |
| def convert_examples_to_features(examples, tokenizer, args,stage=None): | |
| features = [] | |
| for example_index, example in enumerate(examples): | |
| #source | |
| source_ids = torch.LongTensor(tokenizer.encode(example.source + tokenizer.pad_token + example.ts_v, | |
| add_special_tokens=True, max_length=args.max_source_length, truncation=True)) | |
| source_mask = torch.ones_like(source_ids) | |
| #target | |
| if stage=="test": | |
| target_tokens = tokenizer.tokenize("None") | |
| else: | |
| target_tokens = tokenizer.tokenize(example.target)[:args.max_target_length-2] | |
| target_ids = torch.LongTensor(tokenizer.encode(example.target, | |
| add_special_tokens=True, max_length=args.max_target_length, truncation=True)) | |
| target_mask = torch.ones_like(target_ids) | |
| features.append( | |
| InputFeatures( | |
| example_index, | |
| source_ids, source_mask, | |
| target_ids, target_mask | |
| ) | |
| ) | |
| return features | |
| def set_seed(seed=20240124): | |
| random.seed(seed) | |
| os.environ['PYHTONHASHSEED'] = str(seed) | |
| np.random.seed(seed) | |
| torch.manual_seed(seed) | |
| torch.cuda.manual_seed(seed) | |
| torch.backends.cudnn.deterministic = True | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| ## Required parameters | |
| parser.add_argument("--model_name_or_path", default=None, type=str, required=True, | |
| help="Path to pre-trained model: e.g. roberta-base" ) | |
| parser.add_argument("--load_model_path", default=None, type=str, | |
| help="Path to trained model" ) | |
| parser.add_argument("--output_dir", default=None, type=str, required=True, | |
| help="The output directory where the model predictions and checkpoints will be written.") | |
| ## Other parameters | |
| parser.add_argument("--train_filename", default=None, type=str, | |
| help="The train filename. Should contain the .jsonl files for this task.") | |
| parser.add_argument("--dev_filename", default=None, type=str, | |
| help="The dev filename. Should contain the .jsonl files for this task.") | |
| parser.add_argument("--test_filename", default=None, type=str, | |
| help="The test filename. Should contain the .jsonl files for this task.") | |
| parser.add_argument("--max_source_length", default=256, type=int, | |
| help="The maximum total source sequence length after tokenization. Sequences longer " | |
| "than this will be truncated, sequences shorter will be padded.") | |
| parser.add_argument("--max_target_length", default=512, type=int, | |
| help="The maximum total target sequence length after tokenization. Sequences longer " | |
| "than this will be truncated, sequences shorter will be padded.") | |
| parser.add_argument("--do_train", action='store_true', | |
| help="Whether to run training.") | |
| parser.add_argument("--do_eval", action='store_true', | |
| help="Whether to run eval on the dev set.") | |
| parser.add_argument("--do_test", action='store_true', | |
| help="Whether to run eval on the dev set.") | |
| parser.add_argument("--no_cuda", action='store_true', | |
| help="Avoid using CUDA when available") | |
| parser.add_argument("--train_batch_size", default=8, type=int, | |
| help="Batch size per GPU/CPU for training.") | |
| parser.add_argument("--eval_batch_size", default=8, type=int, | |
| help="Batch size per GPU/CPU for evaluation.") | |
| parser.add_argument('--gradient_accumulation_steps', type=int, default=1, | |
| help="Number of updates steps to accumulate before performing a backward/update pass.") | |
| parser.add_argument("--learning_rate", default=5e-5, type=float, | |
| help="The initial learning rate for Adam.") | |
| parser.add_argument("--beam_size", default=10, type=int, | |
| help="beam size for beam search") | |
| parser.add_argument("--weight_decay", default=0.0, type=float, | |
| help="Weight deay if we apply some.") | |
| parser.add_argument("--adam_epsilon", default=1e-8, type=float, | |
| help="Epsilon for Adam optimizer.") | |
| parser.add_argument("--max_grad_norm", default=1.0, type=float, | |
| help="Max gradient norm.") | |
| parser.add_argument("--num_train_epochs", default=3, type=int, | |
| help="Total number of training epochs to perform.") | |
| parser.add_argument('--seed', type=int, default=20240124, | |
| help="random seed for initialization") | |
| # print arguments | |
| args = parser.parse_args() | |
| # set log | |
| logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', | |
| datefmt='%m/%d/%Y %H:%M:%S',level=logging.INFO ) | |
| # set device | |
| device = torch.device("cuda" if torch.cuda.is_available() else "cpu") | |
| args.n_gpu = torch.cuda.device_count() | |
| args.device = device | |
| logger.info("device: %s, n_gpu: %s",device, args.n_gpu) | |
| # Set seed | |
| set_seed(args.seed) | |
| # make dir if output_dir not exist | |
| if os.path.exists(args.output_dir) is False: | |
| os.makedirs(args.output_dir) | |
| # build model | |
| tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) | |
| is_trust = False | |
| if "codet5p-220m" in args.model_name_or_path: | |
| is_trust = False | |
| else: | |
| is_trust = True | |
| model = T5ForConditionalGeneration.from_pretrained(args.model_name_or_path) | |
| logger.info("Training/evaluation parameters %s", args) | |
| if args.load_model_path is not None: | |
| logger.info("reload model from {}".format(args.load_model_path + "/pytorch_model.bin")) | |
| model.load_state_dict(torch.load(args.load_model_path + "/pytorch_model.bin")) | |
| model.to(args.device) | |
| if args.n_gpu > 1: | |
| # multi-gpu training | |
| model = torch.nn.DataParallel(model) | |
| if args.do_train: | |
| # Prepare training data loader | |
| train_examples = read_examples(args.train_filename) | |
| train_features = convert_examples_to_features(train_examples, tokenizer,args,stage='train') | |
| all_source_ids = pad_sequence([f.source_ids for f in train_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_source_mask = pad_sequence([f.source_mask for f in train_features], batch_first=True, padding_value=0) | |
| all_target_ids = pad_sequence([f.target_ids for f in train_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_target_mask = pad_sequence([f.target_mask for f in train_features], batch_first=True, padding_value=0) | |
| train_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask) | |
| train_sampler = RandomSampler(train_data) | |
| train_dataloader = DataLoader(train_data, sampler=train_sampler, batch_size=args.train_batch_size // args.gradient_accumulation_steps) | |
| # 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=int(len(train_dataloader)*args.num_train_epochs*0.1), | |
| num_training_steps=len(train_dataloader)*args.num_train_epochs) | |
| #Start training | |
| logger.info("***** Running training *****") | |
| logger.info(" Num examples = %d", len(train_examples)) | |
| logger.info(" Batch size = %d", args.train_batch_size * args.gradient_accumulation_steps) | |
| logger.info(" Num epoch = %d", args.num_train_epochs) | |
| model.train() | |
| patience, best_score, losses, dev_dataset = 0, 0, [], {} | |
| for epoch in range(args.num_train_epochs): | |
| for idx,batch in enumerate(train_dataloader): | |
| batch = tuple(t.to(device) for t in batch) | |
| source_ids,source_mask,target_ids,target_mask = batch | |
| # loss,_,_ = model(source_ids=source_ids,target_ids=target_ids) | |
| loss = model(input_ids=source_ids, attention_mask=source_mask.gt(0), | |
| labels=target_ids, decoder_attention_mask=target_mask.gt(0)).loss | |
| if args.n_gpu > 1: | |
| loss = loss.mean() # mean() to average on multi-gpu. | |
| if args.gradient_accumulation_steps > 1: | |
| loss = loss / args.gradient_accumulation_steps | |
| losses.append(loss.item()) | |
| loss.backward() | |
| if len(losses) % args.gradient_accumulation_steps == 0: | |
| #Update parameters | |
| optimizer.step() | |
| optimizer.zero_grad() | |
| scheduler.step() | |
| if len(losses) // args.gradient_accumulation_steps % 100 == 0: | |
| logger.info("epoch {} step {} loss {}".format(epoch, | |
| len(losses)//args.gradient_accumulation_steps, | |
| round(np.mean(losses[-100*args.gradient_accumulation_steps:]),4))) | |
| if args.do_eval: | |
| #Eval model with dev dataset | |
| if 'dev_loss' in dev_dataset: | |
| eval_examples,eval_data = dev_dataset['dev_loss'] | |
| else: | |
| eval_examples = read_examples(args.dev_filename) | |
| eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='dev') | |
| all_source_ids = pad_sequence([f.source_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_source_mask = pad_sequence([f.source_mask for f in eval_features], batch_first=True, padding_value=0) | |
| all_target_ids = pad_sequence([f.target_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_target_mask = pad_sequence([f.target_mask for f in eval_features], batch_first=True, padding_value=0) | |
| eval_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask) | |
| dev_dataset['dev_loss' ]= eval_examples,eval_data | |
| eval_sampler = SequentialSampler(eval_data) | |
| eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) | |
| logger.info("\n***** Running evaluation *****") | |
| logger.info(" Num examples = %d", len(eval_examples)) | |
| logger.info(" Batch size = %d", args.eval_batch_size) | |
| #Start Evaling model | |
| model.eval() | |
| eval_loss,tokens_num = 0,0 | |
| for batch in eval_dataloader: | |
| batch = tuple(t.to(device) for t in batch) | |
| source_ids,source_mask,target_ids,target_mask = batch | |
| with torch.no_grad(): | |
| loss = model(input_ids=source_ids, attention_mask=source_mask, | |
| labels=target_ids, decoder_attention_mask=target_mask).loss | |
| if args.n_gpu > 1: | |
| loss = loss.mean() # mean() to average on multi-gpu. | |
| if args.gradient_accumulation_steps > 1: | |
| loss = loss / args.gradient_accumulation_steps | |
| eval_loss += loss.item() | |
| tokens_num += 1 | |
| #Pring loss of dev dataset | |
| model.train() | |
| eval_loss = eval_loss / tokens_num | |
| result = {'eval_ppl': round(np.exp(eval_loss),5)} | |
| for key in sorted(result.keys()): | |
| logger.info(" %s = %s", key, str(result[key])) | |
| logger.info(" "+"*"*20) | |
| #Calculate bleu | |
| if 'dev_bleu' in dev_dataset: | |
| eval_examples,eval_data=dev_dataset['dev_bleu'] | |
| else: | |
| eval_examples = read_examples(args.dev_filename) | |
| # eval_examples = random.sample(eval_examples) | |
| eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='test') | |
| all_source_ids = pad_sequence([f.source_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_source_mask = pad_sequence([f.source_mask for f in eval_features], batch_first=True, padding_value=0) | |
| all_target_ids = pad_sequence([f.target_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_target_mask = pad_sequence([f.target_mask for f in eval_features], batch_first=True, padding_value=0) | |
| eval_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask) | |
| dev_dataset['dev_bleu'] = eval_examples,eval_data | |
| eval_sampler = SequentialSampler(eval_data) | |
| eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) | |
| model.eval() | |
| p=[] | |
| for batch in eval_dataloader: | |
| batch = tuple(t.to(device) for t in batch) | |
| source_ids,source_mask,target_ids,target_mask = batch | |
| with torch.no_grad(): | |
| preds = model.module.generate(source_ids, attention_mask=source_mask, use_cache=True, | |
| num_beams=args.beam_size, max_new_tokens =args.max_target_length) | |
| # convert ids to text | |
| for pred in preds: | |
| # print(pred) | |
| text = tokenizer.decode(pred, skip_special_tokens=True, clean_up_tokenization_spaces=False) | |
| p.append(text) | |
| model.train() | |
| predictions = [] | |
| res_list = [] | |
| EM = [] | |
| is_gened = False | |
| with open(args.output_dir+"/dev.output",'w') as f, open(args.output_dir+"/dev.gold",'w') as f1: | |
| for ref,gold in zip(p,eval_examples): | |
| predictions.append(ref) | |
| if len(ref) > 0: | |
| is_gened = True | |
| f.write(ref+'\n') | |
| f1.write(gold.target+'\n') | |
| EM.append(ref.split()==gold.target.split()) | |
| res_list.append([ref,gold.target]) | |
| if is_gened: | |
| dev_bleu = _bleu(args.output_dir+"/dev.gold", args.output_dir+"/dev.output") | |
| else: | |
| dev_bleu = 0 | |
| logger.info(" %s = %s "%("Epoch",str(epoch))) | |
| logger.info(" %s = %s "%("bleu-4",str(dev_bleu))) | |
| logger.info(" %s = %s "%("EM",str(round(np.mean(EM)*100,2)))) | |
| logger.info(" "+"*"*20) | |
| dev_score = (dev_bleu+round(np.mean(EM)*100,2)) | |
| if dev_score>best_score: | |
| best_score=dev_score | |
| # Save best checkpoint for best bleu | |
| output_dir = args.output_dir | |
| if not os.path.exists(output_dir): | |
| os.makedirs(output_dir) | |
| model_to_save = model.module if hasattr(model, 'module') else model # Only save the model it-self | |
| output_model_file = os.path.join(output_dir, "pytorch_model.bin") | |
| torch.save(model_to_save.state_dict(), output_model_file) | |
| patience = 0 | |
| else: | |
| patience += 1 | |
| if patience == 3: | |
| break | |
| output_dir = args.output_dir | |
| with open(output_dir + "/last_training_result.jsonl", 'w') as wf: | |
| for line in res_list: | |
| dic = {} | |
| dic["Pred"] = line[0] | |
| dic["GT"] = line[1] | |
| wf.write(json.dumps(dic)) | |
| wf.write("\n") | |
| logger.info(" Best score:%s",best_score) | |
| logger.info(" "+"*"*20) | |
| if args.do_test: | |
| res_list = [] | |
| if args.load_model_path is not None: | |
| checkpoint_prefix = 'pytorch_model.bin' | |
| output_dir = os.path.join(args.output_dir, checkpoint_prefix) | |
| model_to_load = model.module if hasattr(model, 'module') else model | |
| model_to_load.load_state_dict(torch.load(output_dir)) | |
| eval_examples = read_examples(args.test_filename) | |
| eval_features = convert_examples_to_features(eval_examples, tokenizer, args,stage='test') | |
| all_source_ids = pad_sequence([f.source_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_source_mask = pad_sequence([f.source_mask for f in eval_features], batch_first=True, padding_value=0) | |
| all_target_ids = pad_sequence([f.target_ids for f in eval_features], batch_first=True, padding_value=tokenizer.pad_token_id) | |
| all_target_mask = pad_sequence([f.target_mask for f in eval_features], batch_first=True, padding_value=0) | |
| eval_data = TensorDataset(all_source_ids,all_source_mask,all_target_ids,all_target_mask) | |
| # Calculate bleu | |
| eval_sampler = SequentialSampler(eval_data) | |
| eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.eval_batch_size) | |
| model.eval() | |
| p=[] | |
| for batch in tqdm(eval_dataloader,total=len(eval_dataloader)): | |
| batch = tuple(t.to(device) for t in batch) | |
| source_ids, source_mask, _, _ = batch | |
| with torch.no_grad(): | |
| preds = model.module.generate(source_ids, attention_mask=source_mask, use_cache=True, | |
| num_beams=args.beam_size, max_new_tokens =args.max_target_length) | |
| for pred in preds: | |
| # print(pred) | |
| text = tokenizer.decode(pred, skip_special_tokens=True, clean_up_tokenization_spaces=False) | |
| p.append(text) | |
| predictions=[] | |
| EM = [] | |
| edit_dis = 0 | |
| cnt = 0 | |
| with open(args.output_dir+"/test.output",'w') as f, open(args.output_dir+"/test.gold",'w') as f1: | |
| for ref,gold in zip(p,eval_examples): | |
| res_list.append([ref,gold.target]) | |
| predictions.append(ref) | |
| f.write(ref+'\n') | |
| f1.write(gold.target+'\n') | |
| EM.append(ref.split()==gold.target.split()) | |
| edit_dis += fuzz.ratio(ref, gold.target) | |
| cnt += 1 | |
| dev_bleu = _bleu(args.output_dir+"/test.gold", args.output_dir+"/test.output") | |
| logger.info(" %s = %s "%("bleu-4",str(dev_bleu))) | |
| logger.info(" %s = %s "%("EM",str(round(np.mean(EM)*100,2)))) | |
| logger.info(" %s = %s "%("Edit Distance",str(round(float(edit_dis)/cnt,2)))) | |
| logger.info(" "+"*"*20) | |
| with open(args.output_dir + "/last_training_result.jsonl", 'w') as wf: | |
| for line in res_list: | |
| dic = {} | |
| dic["Pred"] = line[0] | |
| dic["GT"] = line[1] | |
| wf.write(json.dumps(dic)) | |
| wf.write("\n") | |
| if __name__ == "__main__": | |
| main() | |