|
| 1 | +import json |
| 2 | +import os |
| 3 | +from dataclasses import dataclass, field |
| 4 | +from typing import Optional |
| 5 | +import numpy as np |
| 6 | +import torch |
| 7 | +from datasets import load_dataset |
| 8 | +from tqdm import tqdm |
| 9 | +from transformers import AutoTokenizer, HfArgumentParser, pipeline |
| 10 | +from accelerate import Accelerator |
| 11 | + |
| 12 | +tqdm.pandas() |
| 13 | + |
| 14 | +##### |
| 15 | +# This script takes a dataset as the input, where each sample is {"prompt": "the pormpt", "responses": ["response1", "response2", "response3", ...]} |
| 16 | +# The script will compute the reward for each input-output pair, and eventually output a new dataset, where each sample contains {"prompt": "the pormpt", "responses": ["response1", "response2", "response3", ...], "rewards": [reward1, reward2, ...]} |
| 17 | +##### |
| 18 | + |
| 19 | + |
| 20 | +@dataclass |
| 21 | +class ScriptArguments: |
| 22 | + """ |
| 23 | + The arguments for the DPO training script. |
| 24 | + """ |
| 25 | + |
| 26 | + dataset_name_or_path: Optional[str] = field( |
| 27 | + default="uf_split0_responses_K8.jsonl", |
| 28 | + metadata={"help": "the location of the dataset name or path"}, |
| 29 | + ) |
| 30 | + output_dir: Optional[str] = field( |
| 31 | + default="uf_split0_responses_K8_reward.json", |
| 32 | + metadata={"help": "the location of the output file"}, |
| 33 | + ) |
| 34 | + record_dir: Optional[str] = field( |
| 35 | + default=None, |
| 36 | + metadata={"help": "the location of the recording file"}, |
| 37 | + ) |
| 38 | + reward_name_or_path: Optional[str] = field( |
| 39 | + default="sfairXC/FsfairX-LLaMA3-RM-v0.1", |
| 40 | + metadata={"help": "the name of the reward model"}, |
| 41 | + ) |
| 42 | + input_output_delimiter: Optional[str] = field( |
| 43 | + default="", |
| 44 | + metadata={"help": "the delimiter between input and output"}, |
| 45 | + ) |
| 46 | + K: Optional[int] = field( |
| 47 | + default=8, |
| 48 | + metadata={"help": "the number of responses per prompt"}, |
| 49 | + ) |
| 50 | + |
| 51 | + |
| 52 | +accelerator = Accelerator() |
| 53 | + |
| 54 | +parser = HfArgumentParser(ScriptArguments) |
| 55 | +script_args = parser.parse_args_into_dataclasses()[0] |
| 56 | + |
| 57 | +device = accelerator.device |
| 58 | +pipe_kwargs = { |
| 59 | + "return_all_scores": True, |
| 60 | + "function_to_apply": "none", |
| 61 | + "batch_size": 1, |
| 62 | +} |
| 63 | +reward_model = script_args.reward_name_or_path |
| 64 | +rm_tokenizer = AutoTokenizer.from_pretrained(reward_model) |
| 65 | +rm_pipe = pipeline( |
| 66 | + "sentiment-analysis", |
| 67 | + model=reward_model, |
| 68 | + device=device, |
| 69 | + tokenizer=rm_tokenizer, |
| 70 | + model_kwargs={"torch_dtype": torch.bfloat16}, |
| 71 | + truncation=True, |
| 72 | +) |
| 73 | + |
| 74 | + |
| 75 | +ds_dir = script_args.dataset_name_or_path |
| 76 | +world_size = int(os.getenv("WORLD_SIZE", "1")) |
| 77 | +ds = load_dataset("json", data_files=ds_dir, split="train") |
| 78 | + |
| 79 | +local_rank = Accelerator().local_process_index |
| 80 | + |
| 81 | +data_size = len(ds["prompt"]) |
| 82 | + |
| 83 | +share = int(data_size / world_size) + 1 |
| 84 | +ds = ds.select(np.arange(local_rank * share, min((local_rank + 1) * share, len(ds)))) |
| 85 | + |
| 86 | +""" |
| 87 | +We process the data format here and query the reward model to get the rewards. |
| 88 | +""" |
| 89 | + |
| 90 | + |
| 91 | +def get_reward(test_texts): |
| 92 | + pipe_outputs = rm_pipe(test_texts, **pipe_kwargs) |
| 93 | + rewards = [output[0]["score"] for output in pipe_outputs] |
| 94 | + return rewards |
| 95 | + |
| 96 | + |
| 97 | +def change_of_format(prom, resp): |
| 98 | + # To be modified according to the reward model and the LLM you use |
| 99 | + # Be careful about multi-turn conversions |
| 100 | + """ |
| 101 | + prom = prom.replace("<s>GPT4 Correct User: ", "").replace("<|end_of_turn|>GPT4 Correct Assistant:", "") |
| 102 | +
|
| 103 | + final_resp = resp.split("GPT4 Correct User")[0] |
| 104 | + """ |
| 105 | + message = prom + [{"role": "assistant", "content": resp}] |
| 106 | + return rm_tokenizer.apply_chat_template(message, tokenize=False).replace(rm_tokenizer.bos_token, "") |
| 107 | + |
| 108 | + |
| 109 | +data = [] |
| 110 | + |
| 111 | +# tqdm is used to show the progress bar |
| 112 | +with torch.no_grad(): |
| 113 | + for sample in tqdm(ds): |
| 114 | + # The VLLM may not generate responses for some prompts because it is too long, we skip them |
| 115 | + if len(sample["responses"]) < script_args.K: |
| 116 | + continue |
| 117 | + test_texts = [change_of_format(sample['prompt'], tmp_output) for tmp_output in sample['responses']] |
| 118 | + |
| 119 | + rewards = get_reward(test_texts) |
| 120 | + data.append({"prompt": sample["prompt"], "responses": sample["responses"], "rewards": rewards}) |
| 121 | + |
| 122 | + |
| 123 | +# Send the data to other GPUs |
| 124 | +world_size = int(os.getenv("WORLD_SIZE", "1")) |
| 125 | +all_process_list = [{}] * world_size |
| 126 | + |
| 127 | +data_to_send = { |
| 128 | + "data": [[data[i]] for i in range(len(data))], |
| 129 | +} |
| 130 | + |
| 131 | +import torch.distributed as dist |
| 132 | + |
| 133 | +dist.all_gather_object(all_process_list, data_to_send) |
| 134 | +gathered_data = [] |
| 135 | + |
| 136 | + |
| 137 | +for i in range(world_size): |
| 138 | + tmp_data = [tmp[0] for tmp in all_process_list[i]["data"]] |
| 139 | + gathered_data.extend(tmp_data) |
| 140 | + |
| 141 | +all_rewards = [sample["rewards"] for sample in gathered_data] |
| 142 | +top1_scores = np.mean(np.max(all_rewards, axis=1)) |
| 143 | +mean_scores = np.mean(all_rewards) |
| 144 | + |
| 145 | + |
| 146 | +if local_rank == 0: |
| 147 | + print( |
| 148 | + "Collect {} data from {} inputs. mean score {} top1 score: {}".format( |
| 149 | + len(gathered_data), data_size, mean_scores, top1_scores |
| 150 | + ) |
| 151 | + ) |
| 152 | + if len(gathered_data) < data_size: |
| 153 | + print( |
| 154 | + "Some of the prompts are with responses < {}. This can happen because the prompt is too long and is ignored by VLLM".format( |
| 155 | + script_args.K |
| 156 | + ) |
| 157 | + ) |
| 158 | + |
| 159 | + with open(script_args.output_dir, "w", encoding="utf8") as f: |
| 160 | + for i in range(len(gathered_data)): |
| 161 | + json.dump(gathered_data[i], f, ensure_ascii=False) |
| 162 | + f.write('\n') |
| 163 | + |
| 164 | + if script_args.record_dir is not None: |
| 165 | + with open(script_args.record_dir, "a") as f: |
| 166 | + f.write(str(mean_scores) + "\t" + str(top1_scores) + "\n") |
0 commit comments