-
Notifications
You must be signed in to change notification settings - Fork 193
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
34 changed files
with
1,154 additions
and
161 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
compute_environment: LOCAL_MACHINE | ||
deepspeed_config: {} | ||
distributed_type: MULTI_GPU | ||
downcast_bf16: 'no' | ||
dynamo_backend: 'NO' | ||
fsdp_config: {} | ||
gpu_ids: all | ||
machine_rank: 0 | ||
main_training_function: main | ||
megatron_lm_config: {} | ||
mixed_precision: bf16 | ||
num_machines: 1 | ||
num_processes: 8 | ||
rdzv_backend: static | ||
same_network: true | ||
use_cpu: false |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
#import some packages and reward funcs | ||
import os | ||
import argparse | ||
import json | ||
import tqdm | ||
import torch | ||
import torch.nn.functional as F | ||
import metrics2 | ||
from transformers import ( | ||
AutoConfig, | ||
AutoTokenizer, | ||
LlamaTokenizer, | ||
AutoModelForCausalLM | ||
) | ||
from infer_func_now import setup_seed, generate_pipeline | ||
from accelerate import Accelerator | ||
from accelerate.utils import InitProcessGroupKwargs | ||
from datetime import timedelta | ||
|
||
def get_args(): | ||
parser = argparse.ArgumentParser(description="") | ||
parser.add_argument('--index', type=str) | ||
parser.add_argument('--stage', type=int) | ||
parser.add_argument('--directory', default="best_checkpoint", type=str) | ||
args = parser.parse_args() | ||
return args | ||
|
||
if __name__ == "__main__": | ||
args = get_args() | ||
kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=5400)) | ||
accelerator = Accelerator(kwargs_handlers=[kwargs])# **accelerator_log_kwargs) | ||
rank = int(os.environ['RANK']) | ||
rank_sum = accelerator.num_processes | ||
model_name_or_path = os.path.join("..", "checkpoints", f"index_{args.index}", f"stage_{args.stage}", f"{args.directory}") | ||
model_device = "cuda:{}".format(rank) | ||
|
||
model_config = AutoConfig.from_pretrained(model_name_or_path) | ||
model = AutoModelForCausalLM.from_pretrained(model_name_or_path, config=model_config, torch_dtype=torch.bfloat16).to(model_device) | ||
if accelerator.is_main_process: | ||
print(type(model)) | ||
print(model.config) | ||
if model.config.architectures[0].lower() == "llamaforcausallm": | ||
tokenizer = LlamaTokenizer.from_pretrained(model_name_or_path) | ||
tokenizer.unk_token = "<unk>" | ||
tokenizer.bos_token = "<s>" | ||
tokenizer.eos_token = "</s>" | ||
else: | ||
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) | ||
|
||
tokenizer.pad_token=tokenizer.eos_token, | ||
tokenizer.pad_token_id=tokenizer.eos_token_id, | ||
tokenizer.sep_token = "<sep>" | ||
model.resize_token_embeddings(len(tokenizer)) | ||
|
||
print(model.dtype) | ||
torch.cuda.empty_cache() | ||
model.eval() | ||
print(f"Rank {rank} is activated...") | ||
if accelerator.is_main_process: | ||
file_name = "test.json" | ||
save_path = os.path.join("inference_res/cache", "infer_generate_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
if os.path.exists(save_path): | ||
os.remove(save_path) | ||
accelerator.wait_for_everyone() | ||
|
||
file_name = "test.json" | ||
file_path = os.path.join("..", "data", "summarize_test", file_name) | ||
with open(file_path, "r", encoding='utf-8') as f: | ||
infer_data = {line_index: json.loads(l) for line_index, l in enumerate(f.readlines()) if (line_index-rank) % rank_sum == 0} | ||
|
||
for line_index in infer_data: | ||
infer_data[line_index]["line_index"] = line_index | ||
infer_data = [infer_data[line_index] for line_index in infer_data] | ||
|
||
prompts = [l['prefix'][0] for l in infer_data] | ||
|
||
setup_seed() | ||
generated_suffixes, truncated_prompts = generate_pipeline(model, tokenizer, prompts, add_special_tokens=True) | ||
setup_seed() | ||
save_path = os.path.join("inference_res/cache", "infer_generate_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
|
||
for index in range(len(infer_data)): | ||
infer_data[index]['infer'] = {"t": generated_suffixes[index]} | ||
with open(save_path, 'a', encoding='utf-8') as f: | ||
for line in infer_data: | ||
content = json.dumps(line, ensure_ascii=False) | ||
f.write(content+'\n') | ||
|
||
accelerator.wait_for_everyone() | ||
|
||
print("") | ||
if accelerator.is_main_process: | ||
print("Eval on {}".format(file_name)) | ||
torch.cuda.empty_cache() | ||
accelerator.wait_for_everyone() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
#import some packages and reward funcs | ||
import os | ||
import argparse | ||
import json | ||
import tqdm | ||
import torch | ||
import torch.nn.functional as F | ||
import metrics2 | ||
from transformers import ( | ||
AutoConfig, | ||
AutoTokenizer, | ||
LlamaTokenizer, | ||
AutoModelForCausalLM | ||
) | ||
from peft import PeftConfig, PeftModel | ||
from infer_func_now import setup_seed | ||
from accelerate import Accelerator | ||
from accelerate.utils import InitProcessGroupKwargs | ||
from datetime import timedelta | ||
|
||
def get_args(): | ||
parser = argparse.ArgumentParser(description="") | ||
parser.add_argument('--index', type=str) | ||
parser.add_argument('--stage', type=int) | ||
parser.add_argument('--directory', default="best_checkpoint", type=str) | ||
args = parser.parse_args() | ||
return args | ||
|
||
if __name__ == "__main__": | ||
args = get_args() | ||
setup_seed() | ||
kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=5400)) | ||
accelerator = Accelerator(kwargs_handlers=[kwargs]) | ||
rank = int(os.environ['RANK']) | ||
rank_sum = accelerator.num_processes | ||
torch.cuda.empty_cache() | ||
print(f"Rank {rank} is activated...") | ||
if accelerator.is_main_process: | ||
file_name = "test.json" | ||
save_path = os.path.join("inference_res", "infer_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
if os.path.exists(save_path): | ||
os.remove(save_path) | ||
|
||
save_path = os.path.join("inference_res/cache", "infer_generate_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
with open(save_path, 'r', encoding='utf-8') as f: | ||
infer_data = [json.loads(l) for l in f.readlines()] | ||
if "line_index" in infer_data[0]: | ||
infer_data = {l["line_index"]: l for l in infer_data} | ||
with open(save_path, 'w', encoding='utf-8') as f: | ||
infer_data = [infer_data[line_index] for line_index in range(len(infer_data))] | ||
for line in infer_data: | ||
content = json.dumps(line, ensure_ascii=False) | ||
f.write(content+'\n') | ||
|
||
accelerator.wait_for_everyone() | ||
|
||
get_score, reward_batch_size = metrics2.create_reward_fn() | ||
|
||
file_name = "test.json" | ||
save_path = os.path.join("inference_res/cache", "infer_generate_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
with open(save_path, 'r', encoding='utf-8') as f: | ||
infer_data = [json.loads(l) for line_index, l in enumerate(f.readlines()) if (line_index - rank) % rank_sum == 0] | ||
raw_prefixes = [l['prefix'][0].strip() + " " for l in infer_data] | ||
generated_suffixes = [l['infer']["t"].strip() for l in infer_data] | ||
|
||
setup_seed() | ||
rewards = [] | ||
batch_size = reward_batch_size | ||
for index in tqdm.tqdm(range(0,len(raw_prefixes), batch_size), desc=f"Rank {rank} rewarding..."): | ||
if len(raw_prefixes) - index < batch_size: | ||
batch_size = len(raw_prefixes) - index | ||
rewards.extend(torch.sigmoid(get_score(raw_prefixes[index:index+batch_size], generated_suffixes[index:index+batch_size])).cpu().detach().numpy().tolist()) | ||
assert len(rewards) == len(generated_suffixes) and len(rewards) == len(infer_data), (len(rewards), len(generated_suffixes), len(infer_data)) | ||
|
||
for index in range(len(infer_data)): | ||
infer_data[index]["infer"]["score"] = rewards[index] | ||
infer_data[index]["infer"]["bleu"] = metrics2.get_bleu(infer_data[index]['infer']['t'], infer_data[index]['suffix'][0]) | ||
|
||
save_path = os.path.join("inference_res", "infer_main_{}_{}_{}".format(args.index, args.stage, file_name)) | ||
with open(save_path, 'a', encoding='utf-8') as f: | ||
for line in infer_data: | ||
content = json.dumps(line, ensure_ascii=False) | ||
f.write(content+'\n') | ||
print(f"Rank {rank} completed!") |
Oops, something went wrong.