├── .gitignore
├── assets
├── intro.png
└── toy.png
├── requirements.txt
├── templates
└── alpaca.json
├── fine-tuning-unlike.sh
├── merge.py
├── prompter.py
├── scripts
├── generate.py
└── convert2alpaca.py
├── README.md
├── LICENSE
├── modeling_llama_unlikelihood.py
└── finetune_unlikelihood.py
/.gitignore:
--------------------------------------------------------------------------------
1 | wandb/*
2 | wandb
3 | saved_models/*
4 |
--------------------------------------------------------------------------------
/assets/intro.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwxu21/CUT/HEAD/assets/intro.png
--------------------------------------------------------------------------------
/assets/toy.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwxu21/CUT/HEAD/assets/toy.png
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | accelerate==0.23.0
2 | alpaca-eval==0.3.0
3 | anthropic==0.3.11
4 | bitsandbytes==0.41.1
5 | datasets==2.16.1
6 | evaluate==0.4.0
7 | fire==0.5.0
8 | fschat==0.2.29
9 | huggingface-hub
10 | matplotlib-inline==0.1.6
11 | nltk==3.8.1
12 | numpy==1.25.2
13 | openai==0.27.9
14 | OpenCC==1.1.6
15 | pandas==2.0.3
16 | peft==0.5.0
17 | prompt-toolkit==3.0.39
18 | rouge-score==0.1.2
19 | sacrebleu==1.5.0
20 | safetensors==0.3.3
21 | scikit-learn==1.3.0
22 | scipy==1.11.2
23 | sentence-transformers==2.2.2
24 | sentencepiece==0.1.99
25 | six==1.16.0
26 | tokenizers==0.13.3
27 | torch==2.0.1
28 | torchaudio==2.0.2
29 | torchvision==0.15.2
30 | tqdm==4.66.1
31 | tqdm-multiprocess==0.0.11
32 | transformers==4.33.2
33 | pynvml
34 | protobuf==4.24.3
35 | safetensors==0.3.3
36 | wandb
37 |
--------------------------------------------------------------------------------
/templates/alpaca.json:
--------------------------------------------------------------------------------
1 | {
2 | "description": "Template used by Alpaca-LoRA.",
3 | "prompt_input": "Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Input:\n{input}\n\n### Response:\n",
4 | "prompt_no_input": "Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\n{instruction}\n\n### Response:\n",
5 | "prompt_no_input_judge": "Below is an instruction that describes a task. Write a response to the instruction and the response should match the corresponding judgment.\n\n### Instruction:\n{instruction}\n\n### Judgment:\n{judgment}\n\n### Response:\n",
6 | "response_split": "### Response:"
7 | }
--------------------------------------------------------------------------------
/fine-tuning-unlike.sh:
--------------------------------------------------------------------------------
1 |
2 | export PATH=/root/miniconda3/envs/NegInstruct/bin:$PATH
3 | threshold=1.1
4 | weight_unlike=1
5 | name=cut-1plus-13b
6 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node=8 --master_port=1233 finetune_unlikelihood.py \
7 | --base_model saved_models/llama2-13b-chat-hf \
8 | --data-path data/iter/train-alpaca-sample-iter1.json \
9 | --output_dir ./saved_models/lora/${name} \
10 | --batch_size 8 \
11 | --micro_batch_size 1 \
12 | --num_epochs 1 \
13 | --learning_rate 0.0004 \
14 | --cutoff_len 2048 \
15 | --val_set_size 0 \
16 | --lora_r 16 \
17 | --lora_alpha 16 \
18 | --lora_dropout 0.05 \
19 | --lora_target_modules '[gate_proj, down_proj, up_proj]' \
20 | --train_on_inputs False \
21 | --add_eos_token False \
22 | --group_by_length False \
23 | --prompt_template_name alpaca \
24 | --lr_scheduler 'cosine' \
25 | --warmup_steps 100\
26 | --weight_unlike ${weight_unlike}\
27 | --threshold ${threshold}\
28 | --downsample 0.25\
29 |
30 | CUDA_VISIBLE_DEVICES=0 python merge.py \
31 | --base_model_name_or_path saved_models/llama2-13b-chat-hf \
32 | --peft_model_path ./saved_models/lora/${name} \
33 | --output_dir ./saved_models/${name}
34 |
--------------------------------------------------------------------------------
/merge.py:
--------------------------------------------------------------------------------
1 | from transformers import AutoModelForCausalLM, AutoTokenizer
2 | from peft import PeftModel
3 | import torch
4 |
5 | import os
6 | import argparse
7 |
8 | def get_args():
9 | parser = argparse.ArgumentParser()
10 | parser.add_argument("--base_model_name_or_path", type=str)
11 | parser.add_argument("--peft_model_path", type=str)
12 | parser.add_argument("--output_dir", type=str)
13 | parser.add_argument("--device", type=str, default="auto")
14 |
15 | return parser.parse_args()
16 |
17 | def main():
18 | args = get_args()
19 |
20 | if args.device == 'auto':
21 | device_arg = { 'device_map': 'auto' }
22 | else:
23 | device_arg = { 'device_map': { "": args.device} }
24 |
25 | print(f"Loading base model: {args.base_model_name_or_path}")
26 | base_model = AutoModelForCausalLM.from_pretrained(
27 | args.base_model_name_or_path,
28 | return_dict=True,
29 | torch_dtype=torch.float16,
30 | **device_arg
31 | )
32 |
33 | print(f"Loading PEFT: {args.peft_model_path}")
34 | model = PeftModel.from_pretrained(base_model, args.peft_model_path, **device_arg)
35 | # print(model.state_dict())
36 | print(f"Running merge_and_unload")
37 | model = model.merge_and_unload()
38 |
39 | tokenizer = AutoTokenizer.from_pretrained(args.base_model_name_or_path)
40 |
41 | model.save_pretrained(f"{args.output_dir}")
42 | tokenizer.save_pretrained(f"{args.output_dir}")
43 | print(f"Model saved to {args.output_dir}")
44 |
45 | if __name__ == "__main__" :
46 | main()
--------------------------------------------------------------------------------
/prompter.py:
--------------------------------------------------------------------------------
1 | """
2 | A dedicated helper to manage templates and prompt building.
3 | """
4 |
5 | import json
6 | import os.path as osp
7 | from typing import Union
8 |
9 |
10 | class Prompter(object):
11 | __slots__ = ("template", "_verbose")
12 |
13 | def __init__(self, template_name: str = "", verbose: bool = False):
14 | self._verbose = verbose
15 | if not template_name:
16 | # Enforce the default here, so the constructor can be called with '' and will not break.
17 | template_name = "alpaca"
18 | file_name = osp.join("templates", f"{template_name}.json")
19 | if not osp.exists(file_name):
20 | raise ValueError(f"Can't read {file_name}")
21 | with open(file_name) as fp:
22 | self.template = json.load(fp)
23 | if self._verbose:
24 | print(
25 | f"Using prompt template {template_name}: {self.template['description']}"
26 | )
27 |
28 | def generate_prompt(
29 | self,
30 | data_point,
31 | output=False,
32 | ) -> str:
33 | # returns the full prompt from instruction and optional input
34 | # if a label (=response, =output) is provided, it's also appended.
35 | instruction = data_point['instruction']
36 | label = data_point['output']
37 | res = instruction
38 | if output:
39 | res = f"{res}{label}"
40 | if self._verbose:
41 | print(res)
42 | return res
43 |
44 | def get_response(self, output: str) -> str:
45 | return output.split(self.template["response_split"])[1].strip()
--------------------------------------------------------------------------------
/scripts/generate.py:
--------------------------------------------------------------------------------
1 | from transformers import AutoModelForCausalLM, AutoTokenizer
2 | import torch
3 | import datasets
4 | import os, json
5 | import argparse
6 | from tqdm import tqdm
7 |
8 | def get_args():
9 | parser = argparse.ArgumentParser()
10 | parser.add_argument("--base_model_name_or_path", type=str)
11 | parser.add_argument("--template", type=str, default="../templates/alpaca.json")
12 | parser.add_argument("--device", type=str, default="auto")
13 | parser.add_argument("--verbose", type=bool, default=False)
14 |
15 |
16 | return parser.parse_args()
17 |
18 |
19 | def evaluate(prompt, model, tokenizer, spliter, device='cuda'):
20 | input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
21 | generation_output = model.generate(input_ids=input_ids, num_beams=1, num_return_sequences=1,
22 | max_new_tokens=2048, temperature=0., top_p=1)
23 | output = tokenizer.decode(generation_output[0], skip_special_tokens=True)
24 | output = output.split(spliter, 1)[-1]
25 | return output
26 |
27 |
28 | def main():
29 | args = get_args()
30 |
31 | if args.device == 'auto':
32 | device_arg = {'device_map': 'auto'}
33 | else:
34 | device_arg = {'device_map': {"": args.device}}
35 |
36 | print(f"Loading base model: {args.base_model_name_or_path}")
37 | model = AutoModelForCausalLM.from_pretrained(args.base_model_name_or_path,
38 | return_dict=True,
39 | torch_dtype=torch.float16,
40 | **device_arg)
41 | tokenizer = AutoTokenizer.from_pretrained(args.base_model_name_or_path)
42 | generator = args.base_model_name_or_path.split("/")[-1]
43 | with open(args.template) as fp:
44 | template = json.load(fp)
45 |
46 | eval_set = datasets.load_dataset("tatsu-lab/alpaca_eval",
47 | "alpaca_eval")["eval"]
48 | save_data = []
49 | for i_e, example in tqdm(enumerate(eval_set), desc='generating'):
50 |
51 | instruction = example["instruction"]
52 | input_text = template["prompt_no_input"].format(
53 | instruction=instruction)
54 | spliter = template['response_split']
55 | if "dpo" in args.base_model_name_or_path:
56 | input_text = template["prompt_dpo"].format(instruction=instruction)
57 | spliter = template['dpo_split']
58 | output = evaluate(input_text, model, tokenizer, spliter)
59 |
60 | if args.verbose:
61 | print("instruction", instruction)
62 | print("output", output)
63 | input()
64 | save_one = {
65 | "instruction": example["instruction"],
66 | "output": output.strip(),
67 | "generator": generator,
68 | 'dataset': example['dataset'],
69 | }
70 | save_data.append(save_one)
71 |
72 | save_file = os.path.join(args.base_model_name_or_path, "alpaca_eval.json")
73 | with open(save_file, 'w') as writer:
74 | json.dump(save_data, writer, ensure_ascii=False, indent=2)
75 |
76 |
77 | if __name__ == "__main__" :
78 | main()
79 |
--------------------------------------------------------------------------------
/scripts/convert2alpaca.py:
--------------------------------------------------------------------------------
1 | import json
2 | import random
3 | import os
4 | random.seed(42)
5 |
6 | def process_open_summary(addr, addr_save):
7 | f = []
8 | count = 0
9 | with open(addr) as reader:
10 | for line in reader:
11 | x = json.loads(line)
12 | x = x['data']
13 | x_passage = x['passage']['text']
14 |
15 | for question in x['questions']:
16 | x_question = question['question']
17 |
18 | x_instruction = f'{x_passage}\n{x_question}'
19 | rankings = question['rankings']
20 | max_index = rankings.index(max(rankings))
21 | ans = question['answers'][max_index]
22 | x_out = ans['answer']
23 | if ('skip' in ans['feedback'] and ans['feedback']['skip'] == True) or x_out == "":
24 | continue
25 |
26 | cirtique = ans['feedback']['critiques']
27 | count += 1
28 | if cirtique is None or cirtique == []:
29 | assert ans['feedback']['rating'] == 7
30 | x_judgment = None
31 | x_i_ans = None
32 | x_score = None
33 | new_x = {
34 | 'output':x_out,
35 | 'input':None,
36 | 'instruction':x_instruction,
37 | 'reason':None,
38 | 'judgment': x_judgment,
39 | 'i_ans':x_i_ans,
40 | 'score':x_score,
41 | }
42 |
43 | f.append(new_x)
44 | else:
45 | # cirtique = cirtique[0]
46 | x_judgment = ""
47 | for critique_one in cirtique:
48 | x_judgment = x_judgment + " " + critique_one['text']
49 | x_i_ans = critique_one['refinement']
50 | if x_i_ans == "":
51 | continue
52 | x_score = 1
53 |
54 | x_judgment = x_judgment.strip()
55 | new_x = {
56 | 'output':x_out,
57 | 'input':None,
58 | 'instruction':x_instruction,
59 | 'reason':None,
60 | 'judgment': x_judgment,
61 | 'i_ans':x_i_ans,
62 | 'score':x_score,
63 | }
64 | f.append(new_x)
65 | print(count)
66 | with open(addr_save, 'w') as writer:
67 | json.dump(f, writer, ensure_ascii=False, indent=2)
68 | return f
69 |
70 | def process_Shepherd(addr, feedback_addr, addr_save):
71 | f = []
72 | data = []
73 | feedback = []
74 | with open(addr) as reader:
75 | for line in reader:
76 | x = json.loads(line)
77 | data.append(x)
78 | with open(feedback_addr) as reader:
79 | for line in reader:
80 | x = json.loads(line)
81 | feedback.append(x)
82 |
83 | for i in range(len(data)):
84 | data_one = data[i]
85 | feedback_one = feedback[i]
86 | x_out = feedback_one['answer']
87 | x_instruction = feedback_one['question']
88 | x_judgment = feedback_one['feedback']
89 | x_socre = 1
90 | x_i_ans = data_one['metadata']['output_correct']
91 | assert data_one['metadata']['context'] == feedback_one['question']
92 | assert data_one['metadata']['output_candidate'] == feedback_one['answer']
93 | x_ref = None
94 | new_x = {
95 | 'output':x_out,
96 | 'input':None,
97 | 'instruction':x_instruction,
98 | 'reason':None,
99 | 'judgment': x_judgment,
100 | 'i_ans':x_i_ans,
101 | 'score':x_socre,
102 | "ref":x_ref,
103 | }
104 | f.append(new_x)
105 | with open(addr_save, 'w') as writer:
106 | json.dump(f, writer, ensure_ascii=False, indent=2)
107 | return f
108 |
109 | def combine_ians(addr1, addr2):
110 | with open(addr1, ) as reader:
111 | f1 = json.load(reader)
112 | with open(addr2, ) as reader:
113 | f2 = json.load(reader)
114 | new_f = []
115 | for i in range(len(f1)):
116 | new_one = f2[i]
117 | new_one['i_ans'] = f1[i]['i_ans']
118 | new_f.append(new_one)
119 | with open(addr2, 'w') as writer:
120 | json.dump(new_f, writer, ensure_ascii=False, indent=2)
121 | return new_f
122 |
123 | if __name__ == "__main__":
124 | data_file = "data/open_summary/critiques.train.jsonl"
125 | save_file = "data/open_summary/train-alpaca.json"
126 | if not os.path.exists("data/open_summary"):
127 | os.mkdir("data/open_summary")
128 | process_open_summary(data_file, save_file)
129 | data_file = "data/open_summary/critiques.test.jsonl"
130 | save_file = "data/open_summary/test-alpaca.json"
131 | process_open_summary(data_file, save_file)
132 | data_file = "data/Shepherd/human_data_raw.jsonl"
133 | feedback_file = "data/Shepherd/human_data_for_model.jsonl"
134 | save_file = "data/Shepherd/train-alpaca.json"
135 | if not os.path.exists("data/Shepherd"):
136 | os.mkdir("data/Shepherd")
137 | f = process_Shepherd(data_file, feedback_file, save_file)
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Reasons to Reject? Aligning Language Models with Judgments
2 |
3 | This repository contains code and resources of our paper,
4 |
5 | [Reasons to Reject? Aligning Language Models with Judgments](https://arxiv.org/abs/2312.14591).
6 |
7 | Weiwen Xu, Deng Cai, Zhisong Zhang, Wai Lam, Shuming Shi
8 |
9 |
10 |
11 | ### Catalogue:
12 | * 1. Introduction
13 | * 2. Dataset
14 | * 3. Fine-tuning
15 | * 4. Inference
16 | * 5. Testing
17 | ****
18 |
19 |
20 |
21 | #### 1. Introduction
22 |
23 | As humans, we consistently engage in interactions with our peers and receive feedback in the form of natural language. This language feedback allows us to reflect on our actions, maintain appropriate behavior, and rectify our errors. The question arises naturally: can we use language feedback to align large language models (LLMs)?
24 |
25 |
26 |
27 | In contrast to previous research that aligns LLMs with reward or preference data, we present the first systematic exploration of alignment through the lens of language feedback (i.e., judgment). We commence with an in-depth investigation of potential methods that can be adapted for aligning LLMs with judgments, revealing that these methods are unable to fully capitalize on the judgments. To facilitate more effective utilization of judgments, we propose a novel framework, Contrastive Unlikelihood Training (CUT), that allows for fine-grained inappropriate content detection and correction based on judgments.
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 | Our offline alignment results show that, with merely 1317 off-the-shelf judgment data, CUT (LLaMA2-13b) can beat the 175B DaVinci003 and surpass the best baseline by 52.34 points on AlpacaEval. The online alignment results demonstrate that CUT can align LLMs (LLaMA2-chat-13b) in an iterative fashion using model-specific judgment data, with a steady performance improvement from 81.09 to 91.36 points on AlpacaEval. Our analysis further suggests that judgments exhibit greater potential than rewards for LLM alignment and warrant future research.
36 |
37 |
38 |
39 | #### 2. Dataset
40 |
41 | ##### 2.1. Offline Alignment
42 |
43 | To reproduce the offline experiments, please use the datasets from [Summarization Train](https://openaipublic.blob.core.windows.net/critiques/dataset/critiques/train.jsonl.gz), [Summarization Test](https://openaipublic.blob.core.windows.net/critiques/dataset/critiques/test.jsonl.gz), and [Shepherd](https://github.com/facebookresearch/Shepherd).
44 | Please use the script `scripts/convert2alpaca.py` to convert the data into the Alpaca Format.
45 |
46 |
47 | ##### 2.2. Online Alignment
48 |
49 | To reproduce the online experiments, we provide the training instances for 5 online interations in `data/iter`.
50 |
51 | ##### 2.3. Judgment v.s. Rewards
52 |
53 | We sample 1000 * 4 instruction-response-judgment triplets from [UltraFeedback](https://github.com/OpenBMB/UltraFeedback) and re-annotate them with only negative judgments. The new judgment data can be found in `data/UltraFeedback`.
54 |
55 |
56 |
57 | #### 3. Fine-tuning
58 |
59 | ##### 3.1. Prepare the environment
60 |
61 | ```bash
62 | pip install -r requirments.txt
63 | ```
64 |
65 | ##### 3.2. Train LLMs with CUT
66 |
67 | ###### 3.2.1. Online Alignment (the first online iteration as an example)
68 |
69 | ```bash
70 | threshold=1.1
71 | weight_unlike=1
72 | name=cut-1plus-13b
73 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node=8 --master_port=1233 finetune_unlikelihood.py \
74 | --base_model saved_models/llama2-13b-chat-hf \
75 | --data-path data/iter/train-alpaca-sample-iter1.json \
76 | --output_dir ./saved_models/lora/${name} \
77 | --batch_size 8 \
78 | --micro_batch_size 1 \
79 | --num_epochs 1 \
80 | --learning_rate 0.0004 \
81 | --cutoff_len 2048 \
82 | --val_set_size 0 \
83 | --lora_r 16 \
84 | --lora_alpha 16 \
85 | --lora_dropout 0.05 \
86 | --lora_target_modules '[gate_proj, down_proj, up_proj]' \
87 | --train_on_inputs False \
88 | --add_eos_token False \
89 | --group_by_length False \
90 | --prompt_template_name alpaca \
91 | --lr_scheduler 'cosine' \
92 | --warmup_steps 100\
93 | --weight_unlike ${weight_unlike}\
94 | --threshold ${threshold}\
95 | --downsample 0.25\
96 |
97 | CUDA_VISIBLE_DEVICES=0 python merge.py \
98 | --base_model_name_or_path saved_models/llama2-13b-chat-hf \
99 | --peft_model_path ./saved_models/lora/${name} \
100 | --output_dir ./saved_models/${name}
101 | ```
102 |
103 | ###### 3.2.2. Offline alignment (Shepherd as an example)
104 | First, get the Shepherd dataset according to Sec. 2.1. Then use the following script:
105 | ```bash
106 | threshold=1.2
107 | weight_unlike=0.5
108 | name=cut-1plus-13b
109 | CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 torchrun --nproc_per_node=8 --master_port=1233 finetune_unlikelihood.py \
110 | --base_model saved_models/llama2-13b-chat-hf \
111 | --data-path data/Shepherd/train-alpaca.json \
112 | --output_dir ./saved_models/lora/${name} \
113 | --batch_size 8 \
114 | --micro_batch_size 1 \
115 | --num_epochs 1 \
116 | --learning_rate 0.0004 \
117 | --cutoff_len 2048 \
118 | --val_set_size 0 \
119 | --lora_r 16 \
120 | --lora_alpha 16 \
121 | --lora_dropout 0.05 \
122 | --lora_target_modules '[gate_proj, down_proj, up_proj]' \
123 | --train_on_inputs False \
124 | --add_eos_token False \
125 | --group_by_length False \
126 | --prompt_template_name alpaca \
127 | --lr_scheduler 'cosine' \
128 | --warmup_steps 100\
129 | --weight_unlike ${weight_unlike}\
130 | --threshold ${threshold}\
131 | --downsample 0.25\
132 |
133 | CUDA_VISIBLE_DEVICES=0 python merge.py \
134 | --base_model_name_or_path saved_models/llama2-13b-chat-hf \
135 | --peft_model_path ./saved_models/lora/${name} \
136 | --output_dir ./saved_models/${name}
137 | ```
138 |
139 |
140 |
141 | #### 4. Inference
142 |
143 | ##### 4.1. Checkpoint Release
144 |
145 | We present our [CUT model](https://huggingface.co/xww033/cut-13b), which has undergone four online iterations and successfully achieved a score of 91.36 points on [AlpacaEval](https://tatsu-lab.github.io/alpaca_eval).
146 |
147 | ##### 4.2. Inference Template
148 |
149 | We follow the inference template used from [Stanford Alpaca](https://github.com/tatsu-lab/stanford_alpaca):
150 |
151 | ```
152 | Below is an instruction that describes a task. Write a response that appropriately completes the request.
153 |
154 | ### Instruction:
155 | {instruction}
156 |
157 | ### Response:
158 | ```
159 |
160 | ##### 4.3. CLI
161 |
162 | [Fastchat](https://github.com/lm-sys/FastChat) provides a simple setup for those interested in trying our aligned model. After downloading the [CUT model](https://huggingface.co/xww033/cut-13b) through HuggingFace, clone the Fastchat repository:
163 |
164 | ```bash
165 | git clone https://github.com/lm-sys/FastChat.git
166 | cd FastChat
167 | ```
168 |
169 | Download the required packages:
170 |
171 | ```bash
172 | pip install --upgrade pip # enable PEP 660 support
173 | pip install -e .
174 | ```
175 |
176 | Finally, run the following:
177 |
178 | ```bash
179 | python -m fastchat.serve.cli --model-path xww033/cut-13b --conv-template alpaca
180 | ```
181 |
182 |
183 |
184 |
185 | #### 5. Testing
186 |
187 | ##### 5.1. Generation-based Evaluation
188 |
189 | We evaluate the model on [AlpacaEval](https://tatsu-lab.github.io/alpaca_eval). Please first install the evaluation tool:
190 |
191 | ```bash
192 | pip install alpaca-eval
193 | ```
194 |
195 | The following script is employed to request the LLM to produce responses to the provided 805 instructions:
196 |
197 | ```bash
198 | python scripts/generate.py --base_model_name_or_path
199 | ```
200 |
201 | The generated responses would be saved in `/alpaca_eval.json`, which is subsequently submitted for GPT4 evaluation:
202 |
203 | ```
204 | alpaca_eval --model_outputs /alpaca_eval.json
205 | ```
206 |
207 | ##### 5.2. Ranking-based Evaluation
208 |
209 | We evaluate the model's performance on ARC, HellaSwag, MMLU and TruthfulQA, utilizing the [LLM Evaluation Harness](https://github.com/EleutherAI/lm-evaluation-harness).
210 |
211 | ## BibTeX
212 |
213 | ```
214 | @article{xu2023reasons,
215 | title={Reasons to Reject? Aligning Language Models with Judgments},
216 | author={Xu, Weiwen and Cai, Deng and Zhang, Zhisong and Lam, Wai and Shi, Shuming},
217 | journal={arXiv preprint arXiv:2312.14591},
218 | year={2023}
219 | }
220 | ```
221 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/modeling_llama_unlikelihood.py:
--------------------------------------------------------------------------------
1 | # coding=utf-8
2 | # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3 | #
4 | # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5 | # and OPT implementations in this library. It has been modified from its
6 | # original forms to accommodate minor architectural differences compared
7 | # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8 | #
9 | # Licensed under the Apache License, Version 2.0 (the "License");
10 | # you may not use this file except in compliance with the License.
11 | # You may obtain a copy of the License at
12 | #
13 | # http://www.apache.org/licenses/LICENSE-2.0
14 | #
15 | # Unless required by applicable law or agreed to in writing, software
16 | # distributed under the License is distributed on an "AS IS" BASIS,
17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 | # See the License for the specific language governing permissions and
19 | # limitations under the License.
20 | """ PyTorch LLaMA model."""
21 | from typing import List, Optional, Tuple, Union
22 | import torch
23 | import torch.nn.functional as F
24 | import torch.utils.checkpoint
25 | from torch import nn
26 | from torch.nn import CrossEntropyLoss, NLLLoss
27 | from transformers.activations import ACT2FN
28 | from transformers.modeling_outputs import CausalLMOutputWithPast
29 | from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
30 | from transformers.models.llama.modeling_llama import LLAMA_INPUTS_DOCSTRING, LlamaPreTrainedModel, LlamaModel, LLAMA_START_DOCSTRING
31 |
32 | from peft.peft_model import PeftModel, PeftConfig, _get_batch_size, PeftType
33 | import warnings
34 | logger = logging.get_logger(__name__)
35 |
36 | _CONFIG_FOR_DOC = "LlamaConfig"
37 |
38 |
39 | class LlamaForCausalLM(LlamaPreTrainedModel):
40 | _tied_weights_keys = ["lm_head.weight"]
41 |
42 | def __init__(self, config, threshold):
43 | super().__init__(config)
44 | self.model = LlamaModel(config)
45 | self.vocab_size = config.vocab_size
46 | self.threshold = threshold
47 | self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
48 |
49 | # Initialize weights and apply final processing
50 | self.post_init()
51 |
52 | def get_input_embeddings(self):
53 | return self.model.embed_tokens
54 |
55 | def set_input_embeddings(self, value):
56 | self.model.embed_tokens = value
57 |
58 | def get_output_embeddings(self):
59 | return self.lm_head
60 |
61 | def set_output_embeddings(self, new_embeddings):
62 | self.lm_head = new_embeddings
63 |
64 | def set_decoder(self, decoder):
65 | self.model = decoder
66 |
67 | def get_decoder(self):
68 | return self.model
69 |
70 | @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
71 | @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
72 | def forward(
73 | self,
74 | input_ids: torch.LongTensor = None,
75 | attention_mask: Optional[torch.Tensor] = None,
76 | position_ids: Optional[torch.LongTensor] = None,
77 | weight_like: Optional[torch.Tensor] = None,
78 | weight_unlike: Optional[torch.Tensor] = None,
79 | past_key_values: Optional[List[torch.FloatTensor]] = None,
80 | inputs_embeds: Optional[torch.FloatTensor] = None,
81 | labels: Optional[torch.LongTensor] = None,
82 | use_cache: Optional[bool] = None,
83 | input_ids_neg=None,
84 | attention_mask_neg=None,
85 | labels_neg=None,
86 | output_attentions: Optional[bool] = None,
87 | output_hidden_states: Optional[bool] = None,
88 | return_dict: Optional[bool] = None,
89 | ) -> Union[Tuple, CausalLMOutputWithPast]:
90 | r"""
91 | Args:
92 | labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
93 | Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
94 | config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
95 | (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
96 |
97 | Returns:
98 |
99 | Example:
100 |
101 | ```python
102 | >>> from transformers import AutoTokenizer, LlamaForCausalLM
103 |
104 | >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
105 | >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
106 |
107 | >>> prompt = "Hey, are you conscious? Can you talk to me?"
108 | >>> inputs = tokenizer(prompt, return_tensors="pt")
109 |
110 | >>> # Generate
111 | >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
112 | >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
113 | "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
114 | ```"""
115 | output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
116 | output_hidden_states = (
117 | output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
118 | )
119 | return_dict = return_dict if return_dict is not None else self.config.use_return_dict
120 | # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
121 | outputs = self.model(
122 | input_ids=input_ids,
123 | attention_mask=attention_mask,
124 | position_ids=position_ids,
125 | past_key_values=past_key_values,
126 | inputs_embeds=inputs_embeds,
127 | use_cache=use_cache,
128 | output_attentions=output_attentions,
129 | output_hidden_states=output_hidden_states,
130 | return_dict=return_dict,
131 | )
132 | hidden_states = outputs[0]
133 | if self.config.pretraining_tp > 1:
134 | lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
135 | logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
136 | logits = torch.cat(logits, dim=-1)
137 | else:
138 | logits = self.lm_head(hidden_states)
139 | logits = logits.float()
140 | probs = torch.softmax(logits,dim=2)
141 | batch_size2, seq_length, hidden_size = probs.size()
142 | batch_size = batch_size2 // 2
143 |
144 | loss = None
145 | unlike_mask = weight_unlike.ne(-1).view(-1).to(probs.device)
146 | if labels is not None:
147 | # Shift so that tokens < n predict n
148 | shift_probs_pos = probs[:batch_size][..., :-1, :].contiguous()
149 | shift_labels = labels[..., 1:].contiguous()
150 | # Flatten the tokens
151 | loss_fct = NLLLoss()
152 | shift_probs_pos = shift_probs_pos.view(-1, self.config.vocab_size)
153 | shift_logits = torch.log(shift_probs_pos)
154 | shift_labels = shift_labels.view(-1)
155 | # Enable model parallelism
156 | shift_labels = shift_labels.to(shift_logits.device)
157 | loss = loss_fct(shift_logits, shift_labels)
158 |
159 | loss = loss
160 | if unlike_mask.any():
161 | loss_unlike = self.unlikelihood(probs, labels, labels_neg, weight_unlike, unlike_mask)
162 | loss = (loss_unlike + loss) / 2
163 |
164 | if not return_dict:
165 | output = (logits,) + outputs[1:]
166 | return (loss,) + output if loss is not None else output
167 |
168 | return CausalLMOutputWithPast(
169 | loss=loss,
170 | logits=logits,
171 | past_key_values=outputs.past_key_values,
172 | hidden_states=outputs.hidden_states,
173 | attentions=outputs.attentions,
174 | )
175 | def unlikelihood(self, probs, labels, labels_neg, weight_unlike, unlike_mask):
176 | labels = labels.to(probs.device)
177 | labels_neg = labels_neg.to(probs.device)
178 | weight_unlike = weight_unlike.to(probs.device)
179 | shift_probs = probs[..., :-1, :].contiguous()
180 | shift_labels = labels[..., 1:].contiguous()
181 | shift_labels_neg = labels_neg[..., 1:].contiguous()
182 | valid_indices = shift_labels[unlike_mask] != -100
183 | valid_indices_neg = shift_labels_neg[unlike_mask] != -100
184 | # assert (valid_indices == valid_indices_neg).all()
185 | batch_size2, seq_length, hidden_size = shift_probs.size()
186 | batch_size = batch_size2 // 2
187 | device = probs.device
188 | label_clamped = torch.clamp(shift_labels, min=0, max=hidden_size - 1)
189 | label_clamped_neg = torch.clamp(shift_labels_neg, min=0, max=hidden_size - 1)
190 | rows, cols = torch.meshgrid(torch.arange(batch_size, device=device), torch.arange(seq_length, device=device))
191 | probs_out = shift_probs[:batch_size][rows, cols, label_clamped][unlike_mask]
192 | probs_out_neg = shift_probs[batch_size:][rows, cols, label_clamped_neg][unlike_mask]
193 | valid_prob = probs_out[valid_indices]
194 | valid_prob_neg = probs_out_neg[valid_indices_neg]
195 | scale = (valid_prob / valid_prob_neg).detach()
196 | unlike_indices = scale > self.threshold # give some margins
197 | valid_prob_neg[unlike_indices] = 1 - valid_prob_neg[unlike_indices]
198 | valid_prob_neg[valid_prob_neg == 0] += 1e-5 # avoid 0
199 | valid_lprob_neg = torch.log(valid_prob_neg)
200 | valid_lprob_neg[unlike_indices] = weight_unlike[unlike_mask][0][0] * valid_lprob_neg[unlike_indices]
201 | valid_lprob_neg[~unlike_indices] = valid_lprob_neg[~unlike_indices]
202 | loss_unlike = -torch.sum(valid_lprob_neg)/ valid_lprob_neg.size(0)
203 | return loss_unlike
204 |
205 |
206 | def prepare_inputs_for_generation(
207 | self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
208 | ):
209 | if past_key_values:
210 | input_ids = input_ids[:, -1:]
211 |
212 | position_ids = kwargs.get("position_ids", None)
213 | if attention_mask is not None and position_ids is None:
214 | # create position_ids on the fly for batch generation
215 | position_ids = attention_mask.long().cumsum(-1) - 1
216 | position_ids.masked_fill_(attention_mask == 0, 1)
217 | if past_key_values:
218 | position_ids = position_ids[:, -1].unsqueeze(-1)
219 |
220 | # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
221 | if inputs_embeds is not None and past_key_values is None:
222 | model_inputs = {"inputs_embeds": inputs_embeds}
223 | else:
224 | model_inputs = {"input_ids": input_ids}
225 |
226 | model_inputs.update(
227 | {
228 | "position_ids": position_ids,
229 | "past_key_values": past_key_values,
230 | "use_cache": kwargs.get("use_cache"),
231 | "attention_mask": attention_mask,
232 | }
233 | )
234 | return model_inputs
235 |
236 | @staticmethod
237 | def _reorder_cache(past_key_values, beam_idx):
238 | reordered_past = ()
239 | for layer_past in past_key_values:
240 | reordered_past += (
241 | tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
242 | )
243 | return reordered_past
244 |
245 | class PeftModelForCausalLM(PeftModel):
246 | """
247 | Peft model for causal language modeling.
248 |
249 | Args:
250 | model ([`~transformers.PreTrainedModel`]): Base transformer model.
251 | peft_config ([`PeftConfig`]): Peft config.
252 |
253 |
254 | Example:
255 |
256 | ```py
257 | >>> from transformers import AutoModelForCausalLM
258 | >>> from peft import PeftModelForCausalLM, get_peft_config
259 |
260 | >>> config = {
261 | ... "peft_type": "PREFIX_TUNING",
262 | ... "task_type": "CAUSAL_LM",
263 | ... "inference_mode": False,
264 | ... "num_virtual_tokens": 20,
265 | ... "token_dim": 1280,
266 | ... "num_transformer_submodules": 1,
267 | ... "num_attention_heads": 20,
268 | ... "num_layers": 36,
269 | ... "encoder_hidden_size": 1280,
270 | ... "prefix_projection": False,
271 | ... "postprocess_past_key_value_function": None,
272 | ... }
273 |
274 | >>> peft_config = get_peft_config(config)
275 | >>> model = AutoModelForCausalLM.from_pretrained("gpt2-large")
276 | >>> peft_model = PeftModelForCausalLM(model, peft_config)
277 | >>> peft_model.print_trainable_parameters()
278 | trainable params: 1843200 || all params: 775873280 || trainable%: 0.23756456724479544
279 | ```
280 | """
281 |
282 | def __init__(self, model, peft_config: PeftConfig, adapter_name="default"):
283 | super().__init__(model, peft_config, adapter_name)
284 | self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation
285 |
286 | def forward(
287 | self,
288 | input_ids=None,
289 | attention_mask=None,
290 | inputs_embeds=None,
291 | labels=None,
292 | input_ids_neg=None,
293 | attention_mask_neg=None,
294 | labels_neg=None,
295 | output_attentions=None,
296 | output_hidden_states=None,
297 | return_dict=None,
298 | weight_like=None,
299 | weight_unlike=None,
300 | **kwargs,
301 | ):
302 | peft_config = self.active_peft_config
303 | kwargs.update({'weight_like':weight_like, 'weight_unlike':weight_unlike, "labels_neg": labels_neg})
304 | input_ids = torch.cat([input_ids, input_ids_neg], dim=0)
305 | attention_mask = torch.cat([attention_mask, attention_mask_neg], dim=0)
306 | if not peft_config.is_prompt_learning:
307 | if self.base_model.config.model_type == "mpt":
308 | if inputs_embeds is not None:
309 | raise AssertionError("forward in MPTForCausalLM does not support inputs_embeds")
310 | return self.base_model(
311 | input_ids=input_ids,
312 | attention_mask=attention_mask,
313 | labels=labels,
314 | output_attentions=output_attentions,
315 | output_hidden_states=output_hidden_states,
316 | return_dict=return_dict,
317 | **kwargs,
318 | )
319 |
320 | return self.base_model(
321 | input_ids=input_ids,
322 | attention_mask=attention_mask,
323 | inputs_embeds=inputs_embeds,
324 | labels=labels,
325 | output_attentions=output_attentions,
326 | output_hidden_states=output_hidden_states,
327 | return_dict=return_dict,
328 | **kwargs,
329 | )
330 | batch_size = _get_batch_size(input_ids, inputs_embeds)
331 | if attention_mask is not None:
332 | # concat prompt attention mask
333 | prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device)
334 | attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1)
335 |
336 | if kwargs.get("position_ids", None) is not None:
337 | warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
338 | kwargs["position_ids"] = None
339 | if kwargs.get("token_type_ids", None) is not None:
340 | warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids")
341 | kwargs["token_type_ids"] = None
342 | kwargs.update(
343 | {
344 | "attention_mask": attention_mask,
345 | "labels": labels,
346 | "output_attentions": output_attentions,
347 | "output_hidden_states": output_hidden_states,
348 | "return_dict": return_dict,
349 | }
350 | )
351 |
352 | if peft_config.peft_type == PeftType.PREFIX_TUNING:
353 | past_key_values = self.get_prompt(batch_size)
354 | return self.base_model(
355 | input_ids=input_ids, inputs_embeds=inputs_embeds, past_key_values=past_key_values, **kwargs
356 | )
357 | else:
358 | if inputs_embeds is None:
359 | inputs_embeds = self.word_embeddings(input_ids)
360 | # concat prompt labels
361 | if labels is not None:
362 | prefix_labels = torch.full((batch_size, peft_config.num_virtual_tokens), -100).to(labels.device)
363 | kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1)
364 | prompts = self.get_prompt(batch_size=batch_size)
365 | prompts = prompts.to(inputs_embeds.dtype)
366 | inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1)
367 | return self.base_model(inputs_embeds=inputs_embeds, **kwargs)
368 |
369 | def generate(self, **kwargs):
370 | self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation
371 | if hasattr(self.base_model, "model"):
372 | self.base_model.model.generation_config = self.generation_config
373 | else:
374 | self.base_model.generation_config = self.generation_config
375 | try:
376 | outputs = self.base_model.generate(**kwargs)
377 | except:
378 | self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
379 | raise
380 | else:
381 | self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation
382 | return outputs
383 |
384 | def prepare_inputs_for_generation(self, *args, **kwargs):
385 | peft_config = self.active_peft_config
386 | model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs)
387 | if peft_config.is_prompt_learning:
388 | if model_kwargs.get("attention_mask", None) is not None:
389 | prefix_attention_mask = torch.ones(
390 | model_kwargs["input_ids"].shape[0], peft_config.num_virtual_tokens
391 | ).to(model_kwargs["input_ids"].device)
392 | model_kwargs["attention_mask"] = torch.cat(
393 | (prefix_attention_mask, model_kwargs["attention_mask"]), dim=1
394 | )
395 |
396 | if model_kwargs.get("position_ids", None) is not None:
397 | warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.")
398 | model_kwargs["position_ids"] = None
399 |
400 | if kwargs.get("token_type_ids", None) is not None:
401 | warnings.warn(
402 | "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids"
403 | )
404 | kwargs["token_type_ids"] = None
405 |
406 | if model_kwargs["past_key_values"] is None and peft_config.peft_type == PeftType.PREFIX_TUNING:
407 | past_key_values = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0])
408 | model_kwargs["past_key_values"] = past_key_values
409 | else:
410 | if model_kwargs["past_key_values"] is None:
411 | inputs_embeds = self.word_embeddings(model_kwargs["input_ids"])
412 | prompts = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0])
413 | prompts = prompts.to(inputs_embeds.dtype)
414 | model_kwargs["inputs_embeds"] = torch.cat((prompts, inputs_embeds), dim=1)
415 | model_kwargs["input_ids"] = None
416 |
417 | return model_kwargs
--------------------------------------------------------------------------------
/finetune_unlikelihood.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | from typing import List
4 | import json
5 | import fire
6 | import torch
7 | from torch.utils.data import DataLoader
8 | import transformers
9 | from datasets import load_dataset, concatenate_datasets, Dataset
10 | from transformers import TrainerCallback, TrainingArguments, TrainerState, TrainerControl
11 | from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
12 | from peft import (
13 | LoraConfig,
14 | prepare_model_for_int8_training,
15 | set_peft_model_state_dict,
16 | MODEL_TYPE_TO_PEFT_MODEL_MAPPING,
17 | PeftModel,
18 | )
19 | from peft.utils import _prepare_prompt_learning_config
20 | from transformers.tokenization_utils_base import PreTrainedTokenizerBase
21 | from transformers.utils import PaddingStrategy
22 | from transformers import LlamaTokenizer, LlamaConfig
23 | from modeling_llama_unlikelihood import LlamaForCausalLM, PeftModelForCausalLM
24 | from prompter import Prompter
25 | from typing import Optional, Union, Any
26 | from dataclasses import dataclass
27 | import numpy as np
28 | import random
29 | seed = 42
30 | random.seed(seed)
31 | np.random.seed(seed)
32 | torch.manual_seed(seed)
33 | torch.cuda.manual_seed_all(seed)
34 |
35 | @dataclass
36 | class MyDataCollator:
37 | """
38 | Data collator that will dynamically pad the inputs received, as well as the labels.
39 |
40 | Args:
41 | tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]):
42 | The tokenizer used for encoding the data.
43 | model ([`PreTrainedModel`]):
44 | The model that is being trained. If set and has the *prepare_decoder_input_ids_from_labels*, use it to
45 | prepare the *decoder_input_ids*
46 |
47 | This is useful when using *label_smoothing* to avoid calculating loss twice.
48 | padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`):
49 | Select a strategy to pad the returned sequences (according to the model's padding side and padding index)
50 | among:
51 |
52 | - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single
53 | sequence is provided).
54 | - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
55 | acceptable input length for the model if that argument is not provided.
56 | - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths).
57 | max_length (`int`, *optional*):
58 | Maximum length of the returned list and optionally padding length (see above).
59 | pad_to_multiple_of (`int`, *optional*):
60 | If set will pad the sequence to a multiple of the provided value.
61 |
62 | This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >=
63 | 7.5 (Volta).
64 | label_pad_token_id (`int`, *optional*, defaults to -100):
65 | The id to use when padding the labels (-100 will be automatically ignored by PyTorch loss functions).
66 | return_tensors (`str`):
67 | The type of Tensor to return. Allowable values are "np", "pt" and "tf".
68 | """
69 | tokenizer: PreTrainedTokenizerBase
70 | model: Optional[Any] = None
71 | padding: Union[bool, str, PaddingStrategy] = True
72 | max_length: Optional[int] = None
73 | pad_to_multiple_of: Optional[int] = None
74 | label_pad_token_id: int = -100
75 | return_tensors: str = "pt"
76 |
77 | def __call__(self, features, return_tensors=None):
78 |
79 | if return_tensors is None:
80 | return_tensors = self.return_tensors
81 | labels = [feature["labels"] for feature in features] if "labels" in features[0].keys() else None
82 | labels_neg = [feature["labels_neg"] for feature in features] if "labels_neg" in features[0].keys() else None
83 | # We have to pad the labels before calling `tokenizer.pad` as this method won't pad them and needs them of the
84 | # same length to return tensors.
85 | if labels is not None:
86 | max_label_length = max(len(l) for l in labels)
87 | if labels_neg is not None:
88 | max_label_length_neg = max(len(l) for l in labels_neg)
89 | max_label_length = max(max_label_length, max_label_length_neg)
90 | if self.pad_to_multiple_of is not None:
91 | max_label_length = (
92 | (max_label_length + self.pad_to_multiple_of - 1)
93 | // self.pad_to_multiple_of
94 | * self.pad_to_multiple_of
95 | )
96 | # self.tokenizer.padding_side = "left"
97 | padding_side = self.tokenizer.padding_side
98 |
99 | for feature in features:
100 | feature['weight_like'] = [feature['weight_like']]
101 | feature['weight_unlike'] = [feature['weight_unlike']]
102 | remainder = [self.label_pad_token_id] * (max_label_length - len(feature["labels"]))
103 | remainder_length = max_label_length - len(feature["labels_neg"])
104 | remainder_label = [self.label_pad_token_id] * remainder_length
105 | remainder_ids = [self.tokenizer.pad_token_id] * remainder_length
106 | remainder_mask = [0] * remainder_length
107 | if isinstance(feature["labels"], list):
108 | feature["labels"] = (
109 | feature["labels"] + remainder if padding_side == "right" else remainder + feature["labels"]
110 | )
111 | feature["labels_neg"] = (
112 | feature["labels_neg"] + remainder_label if padding_side == "right" else remainder_label + feature["labels_neg"]
113 | )
114 | feature["input_ids_neg"] = (
115 | feature["input_ids_neg"] + remainder_ids if padding_side == "right" else remainder_ids + feature["input_ids_neg"]
116 | )
117 | feature["attention_mask_neg"] = (
118 | feature["attention_mask_neg"] + remainder_mask if padding_side == "right" else remainder_mask + feature["attention_mask_neg"]
119 | )
120 | elif padding_side == "right":
121 | feature["labels"] = np.concatenate([feature["labels"], remainder]).astype(np.int64)
122 | feature["labels_neg"] = np.concatenate([feature["labels_neg"], remainder_label]).astype(np.int64)
123 | feature["input_ids_neg"] = np.concatenate([feature["input_ids_neg"], remainder_ids]).astype(np.int64)
124 | feature["attention_mask_neg"] = np.concatenate([feature["attention_mask_neg"], remainder_mask]).astype(np.int64)
125 | else:
126 | feature["labels"] = np.concatenate([remainder, feature["labels"]]).astype(np.int64)
127 | feature["labels_neg"] = np.concatenate([remainder_label, feature["labels_neg"]]).astype(np.int64)
128 | feature["input_ids_neg"] = np.concatenate([remainder_ids, feature["input_ids_neg"]]).astype(np.int64)
129 | feature["attention_mask_neg"] = np.concatenate([remainder_mask, feature["attention_mask_neg"]]).astype(np.int64)
130 |
131 | features = self.tokenizer.pad(
132 | features,
133 | padding=self.padding,
134 | max_length=max_label_length,
135 | pad_to_multiple_of=self.pad_to_multiple_of,
136 | return_tensors=return_tensors,
137 | )
138 |
139 | # prepare decoder_input_ids
140 | if (
141 | labels is not None
142 | and self.model is not None
143 | and hasattr(self.model, "prepare_decoder_input_ids_from_labels")
144 | ):
145 | decoder_input_ids = self.model.prepare_decoder_input_ids_from_labels(labels=features["labels"])
146 | features["decoder_input_ids"] = decoder_input_ids
147 | return features
148 |
149 | class SavePeftModelCallback(TrainerCallback):
150 | def on_save(
151 | self,
152 | args: TrainingArguments,
153 | state: TrainerState,
154 | control: TrainerControl,
155 | **kwargs,
156 | ):
157 | checkpoint_folder = os.path.join(args.output_dir, f"{PREFIX_CHECKPOINT_DIR}-{state.global_step}")
158 |
159 | kwargs["model"].save_pretrained(checkpoint_folder)
160 |
161 | pytorch_model_path = os.path.join(checkpoint_folder, "pytorch_model.bin")
162 | torch.save({}, pytorch_model_path)
163 | return control
164 |
165 |
166 | class LoadBestPeftModelCallback(TrainerCallback):
167 | def on_train_end(
168 | self,
169 | args: TrainingArguments,
170 | state: TrainerState,
171 | control: TrainerControl,
172 | **kwargs,
173 | ):
174 | print(f"Loading best peft model from {state.best_model_checkpoint} (score: {state.best_metric}).")
175 | best_model_path = os.path.join(state.best_model_checkpoint, "adapter_model.bin")
176 | adapters_weights = torch.load(best_model_path)
177 | model = kwargs["model"]
178 | set_peft_model_state_dict(model, adapters_weights)
179 | return control
180 |
181 | def get_peft_model(model, peft_config, adapter_name: str = "default"):
182 | """
183 | Returns a Peft model object from a model and a config.
184 |
185 | Args:
186 | model ([`transformers.PreTrainedModel`]): Model to be wrapped.
187 | peft_config ([`PeftConfig`]): Configuration object containing the parameters of the Peft model.
188 | """
189 | model_config = getattr(model, "config", {"model_type": "custom"})
190 | if hasattr(model_config, "to_dict"):
191 | model_config = model_config.to_dict()
192 |
193 | peft_config.base_model_name_or_path = model.__dict__.get("name_or_path", None)
194 |
195 | if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning:
196 | return PeftModel(model, peft_config, adapter_name=adapter_name)
197 | if peft_config.is_prompt_learning:
198 | peft_config = _prepare_prompt_learning_config(peft_config, model_config)
199 | return PeftModelForCausalLM(model, peft_config, adapter_name=adapter_name)
200 |
201 | def train(
202 | # model/data params
203 | base_model: str = "",
204 | data_path: str = "",
205 | output_dir: str = "",
206 | # training hyperparams
207 | batch_size: int = 128,
208 | micro_batch_size: int = 8,
209 | num_epochs: int = 1,
210 | learning_rate: float = 3e-4,
211 | cutoff_len: int = 4096,
212 | val_set_size: int = 0,
213 | lr_scheduler: str = "cosine",
214 | warmup_steps: int = 100,
215 | # lora hyperparams
216 | lora_r: int = 16,
217 | lora_alpha: int = 16,
218 | lora_dropout: float = 0.05,
219 | # from peft docs: ["q_proj", "k_proj", "v_proj", "o_proj", "fc_in", "fc_out", "wte", "gate_proj", "down_proj", "up_proj"]
220 | lora_target_modules: List[str] = ["gate_proj", "down_proj", "up_proj"],
221 | # llm hyperparams
222 | train_on_inputs: bool = False, # if False, masks out inputs in loss
223 | add_eos_token: bool = False,
224 | group_by_length: bool = False, # faster, but produces an odd training loss curve
225 | # wandb params
226 | wandb_project: str = "",
227 | wandb_run_name: str = "",
228 | wandb_watch: str = "", # options: false | gradients | all
229 | wandb_log_model: str = "", # options: false | true
230 | resume_from_checkpoint: str = None, # either training checkpoint or final adapter
231 | prompt_template_name: str = "alpaca",
232 | weight_unlike: float = 0.1,
233 | threshold: float = 1.1,
234 | downsample: float = -1,
235 | debug: bool = False,
236 | ):
237 | if int(os.environ.get("LOCAL_RANK", 0)) == 0:
238 | print(
239 | f"Params using prompt template {prompt_template_name}\n"
240 | f"the unlikelihood weight for the incorrect token in the incorrect response: {weight_unlike}\n"
241 | f"the threshold to determine the unlikelihood token: {threshold}\n"
242 | f"downssample rate for Hindsight-P: {downsample}\n"
243 | f"base_model: {base_model}\n"
244 | f"data_path: {data_path}\n"
245 | f"output_dir: {output_dir}\n"
246 | f"batch_size: {batch_size}\n"
247 | f"micro_batch_size: {micro_batch_size}\n"
248 | f"num_epochs: {num_epochs}\n"
249 | f"learning_rate: {learning_rate}\n"
250 | f"cutoff_len: {cutoff_len}\n"
251 | f"val_set_size: {val_set_size}\n"
252 | f"lr_scheduler: {lr_scheduler}\n"
253 | f"warmup_steps: {warmup_steps}\n"
254 | f"lora_r: {lora_r}\n"
255 | f"lora_alpha: {lora_alpha}\n"
256 | f"lora_dropout: {lora_dropout}\n"
257 | f"lora_target_modules: {lora_target_modules}\n"
258 | f"train_on_inputs: {train_on_inputs}\n"
259 | f"add_eos_token: {add_eos_token}\n"
260 | f"group_by_length: {group_by_length}\n"
261 | f"wandb_project: {wandb_project}\n"
262 | f"wandb_run_name: {wandb_run_name}\n"
263 | f"wandb_watch: {wandb_watch}\n"
264 | f"wandb_log_model: {wandb_log_model}\n"
265 | f"resume_from_checkpoint: {resume_from_checkpoint or False}\n"
266 | )
267 | assert (
268 | base_model
269 | ), "Please specify a --base_model, e.g. --base_model='huggyllama/llama-7b'"
270 | gradient_accumulation_steps = batch_size // micro_batch_size
271 |
272 | prompter = Prompter(prompt_template_name)
273 | if not debug:
274 | device_map = "auto"
275 | else:
276 | device_map = "cpu"
277 | world_size = int(os.environ.get("WORLD_SIZE", 1))
278 | local_rank = int(os.environ.get("LOCAL_RANK", 0))
279 | ddp = world_size != 1
280 | if ddp:
281 | device_map = {"": int(os.environ.get("LOCAL_RANK") or 0)}
282 | gradient_accumulation_steps = gradient_accumulation_steps // world_size
283 | print("gradient_accumulation_steps: ", gradient_accumulation_steps)
284 |
285 | # Check if parameter passed or if set within environ
286 | use_wandb = len(wandb_project) > 0 or (
287 | "WANDB_PROJECT" in os.environ and len(os.environ["WANDB_PROJECT"]) > 0
288 | )
289 | use_wandb =False
290 | # Only overwrite environ if wandb param passed
291 | if len(wandb_project) > 0:
292 | os.environ["WANDB_PROJECT"] = wandb_project
293 | if len(wandb_watch) > 0:
294 | os.environ["WANDB_WATCH"] = wandb_watch
295 | if len(wandb_log_model) > 0:
296 | os.environ["WANDB_LOG_MODEL"] = wandb_log_model
297 | if not debug:
298 | model = LlamaForCausalLM.from_pretrained(
299 | base_model,
300 | load_in_8bit=True,
301 | torch_dtype=torch.float16,
302 | device_map=device_map,
303 | threshold=threshold)
304 | else:
305 | config_llama = LlamaConfig.from_pretrained(
306 | base_model,)
307 | model = LlamaForCausalLM(config_llama,threshold=threshold)
308 | tokenizer = LlamaTokenizer.from_pretrained(base_model)
309 | model = prepare_model_for_int8_training(model)
310 | if not debug:
311 | config = LoraConfig(
312 | r=lora_r,
313 | lora_alpha=lora_alpha,
314 | target_modules=lora_target_modules,
315 | lora_dropout=lora_dropout,
316 | bias="none",
317 | task_type="CAUSAL_LM")
318 |
319 | model = get_peft_model(model, config)
320 | model.print_trainable_parameters()
321 | bos = tokenizer.bos_token_id
322 | eos = tokenizer.eos_token_id
323 | pad = tokenizer.pad_token_id
324 | print("pre-trained model's BOS EOS and PAD token id:",bos,eos,pad," => It should be 1 2 None")
325 |
326 | tokenizer.pad_token_id = 0 # unk. we want this to be different from the eos token
327 | tokenizer.padding_side = "right"
328 | def pad_token(mode):
329 | if mode == 'input_ids':
330 | return tokenizer.pad_token_id
331 | elif mode == 'attention_mask':
332 | return 0
333 | elif mode == 'labels':
334 | return -100
335 | def tokenize(prompt, add_eos_token=True):
336 | result = tokenizer(
337 | prompt,
338 | truncation=False,
339 | padding=False,
340 | return_tensors=None,
341 | )
342 | if len(result["input_ids"]) > cutoff_len: # truncate from left side to keep the response complete
343 | n_overflow = len(result["input_ids"]) - cutoff_len
344 | result["input_ids"] = result["input_ids"][-cutoff_len:]
345 | result["attention_mask"] = result["attention_mask"][-cutoff_len:]
346 | else:
347 | n_overflow = 0
348 | if (
349 | result["input_ids"][-1] != tokenizer.eos_token_id
350 | and add_eos_token
351 | ):
352 | result["input_ids"].append(tokenizer.eos_token_id)
353 | result["attention_mask"].append(1)
354 |
355 | result["labels"] = result["input_ids"].copy()
356 | result["n_overflow"] = n_overflow
357 | return result, n_overflow
358 |
359 | def generate_and_tokenize_prompt(data_point):
360 | instructions = data_point['instruction_list']
361 | tokenized_full_prompt_list = []
362 | for i_i, instruction in enumerate(instructions):
363 | data_point['instruction'] = instruction
364 | full_prompt = prompter.generate_prompt(
365 | data_point, output=True)
366 |
367 | tokenized_full_prompt, n_overflow_full = tokenize(full_prompt)
368 | if not train_on_inputs:
369 | user_prompt = prompter.generate_prompt(
370 | data_point, output=False)
371 |
372 | tokenized_user_prompt, n_overflow_user = tokenize(
373 | user_prompt, add_eos_token=add_eos_token)
374 |
375 | user_prompt_len = len(tokenized_user_prompt["input_ids"])
376 | offset = n_overflow_full - n_overflow_user
377 | user_prompt_len = user_prompt_len - offset
378 | if add_eos_token:
379 | user_prompt_len -= 1
380 | if user_prompt_len > 0:
381 | tokenized_full_prompt["labels"] = [
382 | -100
383 | ] * user_prompt_len + tokenized_full_prompt["labels"][
384 | user_prompt_len:
385 | ] # TODO: Speed up?
386 | assert len(tokenized_full_prompt["labels"]) == len(tokenized_full_prompt["input_ids"])
387 | if i_i == 0:
388 | answer_len = len(tokenized_full_prompt["labels"]) - user_prompt_len
389 | elif i_i == 1:
390 | answer_len2 = len(tokenized_full_prompt["labels"]) - user_prompt_len
391 | assert answer_len == answer_len2
392 | tokenized_full_prompt_list.append(tokenized_full_prompt)
393 | if len(tokenized_full_prompt_list) == 1:
394 | tokenized_full_prompt = tokenized_full_prompt_list[0]
395 | tokenized_full_prompt['input_ids_neg'] = [pad_token('input_ids')] * len(tokenized_full_prompt['input_ids'])
396 | tokenized_full_prompt['attention_mask_neg'] = [pad_token('attention_mask')] * len(tokenized_full_prompt['attention_mask'])
397 | tokenized_full_prompt['labels_neg'] = [pad_token('labels')] * len(tokenized_full_prompt['labels'])
398 | else:
399 | tokenized_full_prompt = tokenized_full_prompt_list[0]
400 | tokenized_full_prompt_neg = tokenized_full_prompt_list[1]
401 | tokenized_full_prompt['input_ids_neg'] = tokenized_full_prompt_neg['input_ids']
402 | tokenized_full_prompt['attention_mask_neg'] = tokenized_full_prompt_neg['attention_mask']
403 | tokenized_full_prompt['labels_neg'] = tokenized_full_prompt_neg['labels']
404 | return tokenized_full_prompt
405 |
406 |
407 |
408 | if data_path.endswith(".json") or data_path.endswith(".jsonl"):
409 | data = load_dataset("json", data_files=data_path)
410 | else:
411 | data = load_dataset(data_path)
412 |
413 | if resume_from_checkpoint:
414 | # Check the available weights and load them
415 | checkpoint_name = os.path.join(
416 | resume_from_checkpoint, "pytorch_model.bin"
417 | ) # Full checkpoint
418 | if not os.path.exists(checkpoint_name):
419 | checkpoint_name = os.path.join(
420 | resume_from_checkpoint, "adapter_model.bin"
421 | ) # only LoRA model - LoRA config above has to fit
422 | resume_from_checkpoint = (
423 | False # So the trainer won't try loading its state
424 | )
425 | # The two files above have a different name depending on how they were saved, but are actually the same.
426 | if os.path.exists(checkpoint_name):
427 | print(f"Restarting from {checkpoint_name}")
428 | adapters_weights = torch.load(checkpoint_name)
429 | set_peft_model_state_dict(model, adapters_weights)
430 | else:
431 | print(f"Checkpoint {checkpoint_name} not found")
432 |
433 |
434 | file_name = os.path.join("templates", f"{prompt_template_name}.json")
435 | with open(file_name) as fp:
436 | template = json.load(fp)
437 |
438 | train_processed = []
439 | n_pos = 0
440 | n_neg = 0
441 | pos_ids = []
442 | for ix,x in enumerate(data["train"]):
443 | x_judgment = x['judgment']
444 | x_score = x['score'] if 'score' in x else None
445 | if x_score is not None and x_score >= 7:
446 | x_judgment = None
447 | x_input = x['input']
448 | x_instruction = x['instruction']
449 | x_out = x['output']
450 | x_i_ans = x['i_ans'] if "i_ans" in x else None
451 | if x_input:
452 | x_instruction = f"{x_instruction}\n{x_input}"
453 | if x_judgment is not None:
454 | hindsight_n = template["prompt_no_input_judge"].format(judgment=x_judgment, instruction=x_instruction)
455 | unfaithful = template["prompt_no_input"].format(instruction=x_instruction)
456 | x_new = {
457 | 'output':x_out,
458 | 'input':None,
459 | 'instruction_list':[hindsight_n,unfaithful],
460 | 'i_ans':x_i_ans,
461 | 'score':x_score,
462 | "weight_like":1,
463 | "weight_unlike":weight_unlike,
464 | }
465 | n_neg += 1
466 | train_processed.append(x_new)
467 | else:
468 | hindsight_p = template["prompt_no_input"].format(instruction=x_instruction)
469 | x_new = {
470 | 'output':x_out,
471 | 'input':None,
472 | 'instruction_list':[hindsight_p],
473 | 'i_ans':x_i_ans,
474 | 'score':x_score,
475 | "weight_like":1,
476 | "weight_unlike":-1,
477 | }
478 | n_pos += 1
479 | pos_ids.append(len(train_processed))
480 | train_processed.append(x_new)
481 | print(f"n_pos:{n_pos}, n_neg:{n_neg}")
482 | if downsample != -1:
483 | n_keep = int(n_neg * downsample)
484 | if n_keep < n_pos:
485 | pos_keep_ids = random.sample(pos_ids, n_keep)
486 | pos_ids = sorted(pos_ids, reverse=True)
487 | for idx in pos_ids:
488 | if idx not in pos_keep_ids:
489 | train_processed.pop(idx)
490 | print(f"after downsampling, the total num of train data is: {len(train_processed)}")
491 | train_processed = Dataset.from_list(train_processed)
492 | print(f"num of training data: {len(train_processed)}")
493 | train_data = train_processed.map(generate_and_tokenize_prompt)
494 | val_data = None
495 |
496 |
497 | if not ddp and torch.cuda.device_count() > 1:
498 | # keeps Trainer from trying its own DataParallelism when more than 1 gpu is available
499 | model.is_parallelizable = True
500 | model.model_parallel = True
501 |
502 | trainer = transformers.Trainer(
503 | model=model,
504 | train_dataset=train_data,
505 | eval_dataset=val_data,
506 | args=transformers.TrainingArguments(
507 | per_device_train_batch_size=micro_batch_size,
508 | gradient_accumulation_steps=gradient_accumulation_steps,
509 | warmup_steps=warmup_steps,
510 | num_train_epochs=num_epochs,
511 | learning_rate=learning_rate,
512 | # dataloader_num_workers=16,
513 | # fp16=True,
514 | bf16=True if not debug else False,
515 | logging_steps=1,
516 | optim="adamw_torch",
517 | evaluation_strategy="steps" if val_set_size > 0 else "no",
518 | save_strategy="steps",
519 | eval_steps=200 if val_set_size > 0 else None,
520 | save_steps=1000,
521 | lr_scheduler_type=lr_scheduler,
522 | output_dir=output_dir,
523 | save_total_limit=2,
524 | load_best_model_at_end=True if val_set_size > 0 else False,
525 | ddp_find_unused_parameters=False if ddp else None,
526 | group_by_length=group_by_length,
527 | report_to="wandb" if use_wandb else None,
528 | run_name=wandb_run_name if use_wandb else None,
529 | ),
530 | data_collator=MyDataCollator(
531 | tokenizer, pad_to_multiple_of=8, return_tensors="pt", padding="max_length"
532 | ),
533 | )
534 | model.config.use_cache = False
535 |
536 | if torch.__version__ >= "2" and sys.platform != "win32":
537 | model = torch.compile(model)
538 |
539 | trainer.train(resume_from_checkpoint=resume_from_checkpoint)
540 | if local_rank == 0:
541 | model.save_pretrained(output_dir)
542 | # model.base_model.save_pretrained(output_dir)
543 | pytorch_model_path = os.path.join(output_dir, "pytorch_model.bin")
544 | torch.save({}, pytorch_model_path)
545 | tokenizer.save_pretrained(output_dir)
546 |
547 |
548 | if __name__ == "__main__":
549 | torch.cuda.empty_cache()
550 | fire.Fire(train)
--------------------------------------------------------------------------------