Dongfu Jiang commited on
Commit
02971ea
1 Parent(s): 3f84fdc

Update README.md

Browse files
Files changed (1) hide show
  1. README.md +327 -0
README.md CHANGED
@@ -1,3 +1,330 @@
1
  ---
2
  license: mit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: mit
3
+ datasets:
4
+ - openai/summarize_from_feedback
5
+ - openai/webgpt_comparisons
6
+ - Dahoas/instruct-synthetic-prompt-responses
7
+ - Anthropic/hh-rlhf
8
+ - lmsys/chatbot_arena_conversations
9
+ - openbmb/UltraFeedback
10
+ metrics:
11
+ - accuracy
12
+ tags:
13
+ - reward_model
14
+ - reward-model
15
+ - RLHF
16
+ - evaluation
17
+ - llm
18
+ - instruction
19
+ - reranking
20
+ language:
21
+ - en
22
+ pipeline_tag: text-generation
23
  ---
24
+
25
+ **This is the hugging face compatible version of [llm-blender/PairRM](https://huggingface.co/llm-blender/PairRM)**, which can be loaded directly with:
26
+ ```python
27
+ import os
28
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
29
+ from llm_blender.pair_ranker.pairrm import DebertaV2PairRM
30
+ from transformers import AutoTokenizer
31
+ from typing import List
32
+ pairrm = DebertaV2PairRM.from_pretrained("llm-blender/PairRM-hf", device_map="cuda:0")
33
+ tokenizer = AutoTokenizer.from_pretrained('llm-blender/PairRM-hf')
34
+ source_prefix = "<|source|>"
35
+ cand1_prefix = "<|candidate1|>"
36
+ cand2_prefix = "<|candidate2|>"
37
+ inputs = ["hello!", "I love you!"]
38
+ candidates_A = ["hi!", "I hate you!"]
39
+ candidates_B = ["f**k off!", "I love you, too!"]
40
+ def tokenize_pair(sources:List[str], candidate1s:List[str], candidate2s:List[str]):
41
+ ids = []
42
+ assert len(sources) == len(candidate1s) == len(candidate2s)
43
+ for i in range(len(sources)):
44
+ source_ids = tokenizer.encode(source_prefix + sources[i])
45
+ candidate1_ids = tokenizer.encode(cand1_prefix + candidate1s[i])
46
+ candidate2_ids = tokenizer.encode(cand2_prefix + candidate2s[i])
47
+ ids.append(source_ids + candidate1_ids + candidate2_ids)
48
+ encodings = tokenizer.pad({"input_ids": ids}, return_tensors="pt")
49
+ return encodings
50
+
51
+ encodings = tokenize_pair(inputs, candidates_A, candidates_B)
52
+ encodings = {k:v.to(pairrm.device) for k,v in encodings.items()}
53
+ outputs = pairrm(**encodings)
54
+ logits = outputs.logits.tolist()
55
+ comparison_results = outputs.logits > 0
56
+ print(logits)
57
+ # [1.9003021717071533, -1.2547134160995483]
58
+ print(comparison_results)
59
+ # tensor([ True, False], device='cuda:0'), which means whether candidate A is better than candidate B for each input
60
+ ```
61
+
62
+ The above code produces exactly the same results with the following code using original llm-blender wrapper:
63
+ ```python
64
+ import os
65
+ os.environ["CUDA_VISIBLE_DEVICES"] = "0"
66
+ import llm_blender
67
+ blender = llm_blender.Blender()
68
+ # Load Ranker
69
+ blender.loadranker("llm-blender/PairRM") # load ranker checkpoint
70
+ inputs = ["hello!", "I love you!"]
71
+ candidates_A = ["hi!", "I hate you!"]
72
+ candidates_B = ["f**k off!", "I love you, too!"]
73
+ logits = blender.compare(inputs, candidates_A, candidates_B, return_logits=True, mode="[A,B]")
74
+ comparison_results = logits > 0
75
+ print(logits)
76
+ # [ 1.9 -1.255]
77
+ print(comparison_results)
78
+ # tensor([ True, False], device='cuda:0'), which means whether candidate A is better than candidate B for each input
79
+ ```
80
+
81
+ # Pairwise Reward Model for LLMs (PairRM) from LLM-Blender
82
+
83
+
84
+ - Github: [https://github.com/yuchenlin/LLM-Blender](https://github.com/yuchenlin/LLM-Blender)
85
+ - Paper: [https://arxiv.org/abs/2306.02561](https://arxiv.org/abs/2306.02561)
86
+ - Space Demo: [https://huggingface.co/spaces/llm-blender/LLM-Blender](https://huggingface.co/spaces/llm-blender/LLM-Blender)
87
+
88
+
89
+ ## Introduction
90
+
91
+ Pairwise Reward Model (PairRM) takes an instruction and a **pair** of output candidates as the input,
92
+ and output a score for each candidate to measure their **relative** quality.
93
+ PairRM can be used to (re-)rank a list of candidate outputs and thus can be used an LLM evaluator to efficiently assess the quality of LLMs in local environment.
94
+ PairRM can also be used to enhance the decoding by `best-of-n sampling` (i.e., reranking N sampled outputs).
95
+ Apart from that, one can also use PairRM to further align instruction-tuned LLMs with RLHF methods.
96
+
97
+ Unlike the other RMs that encode and score each candidate respectively,
98
+ PairRM takes a pair of candidates and compares them side-by-side to indentify the subtle differences between them.
99
+ Also, PairRM is based on [`microsoft/deberta-v3-large`](https://huggingface.co/microsoft/deberta-v3-large), and thus it is super efficient: **0.4B**.
100
+ We trained PairRM on a diverse collection of six human-preference datasets (see more [here](https://huggingface.co/llm-blender/PairRM#training-datasets)).
101
+
102
+ PairRM is part of the LLM-Blender project (ACL 2023). Please see our [paper](https://arxiv.org/abs/2306.02561) above to know more.
103
+
104
+
105
+ ## Installation
106
+
107
+ - First install `llm-blender`
108
+ ```bash
109
+ pip install git+https://github.com/yuchenlin/LLM-Blender.git
110
+ ```
111
+
112
+ - Then load PairRM:
113
+ ```python
114
+ import llm_blender
115
+ blender = llm_blender.Blender()
116
+ blender.loadranker("llm-blender/PairRM") # load PairRM
117
+ ```
118
+
119
+
120
+ ## Usage
121
+
122
+ ### Use Case 1: Comparing/Ranking output candidates given an instruction
123
+
124
+ - Ranking a list candidate responses
125
+
126
+ ```python
127
+ inputs = ["hello, how are you!", "I love you!"]
128
+ candidates_texts = [["get out!", "hi! I am fine, thanks!", "bye!"],
129
+ ["I love you too!", "I hate you!", "Thanks! You're a good guy!"]]
130
+ ranks = blender.rank(inputs, candidates_texts, return_scores=False, batch_size=1)
131
+ # ranks is a list of ranks
132
+ # ranks[i][j] represents the ranks of candidate-j for input-i
133
+ """
134
+ ranks -->
135
+ array([[3, 1, 2], # it means "hi! I am fine, thanks!" ranks the 1st, "bye" ranks the 2nd, and "get out!" ranks the 3rd.
136
+ [1, 3, 2]], # it means "I love you too"! ranks the the 1st, and "I hate you!" ranks the 3rd.
137
+ dtype=int32)
138
+
139
+ """
140
+ ```
141
+
142
+ - Directly comparing two candidate responses
143
+ ```python
144
+ inputs = ["hello!", "I love you!"]
145
+ candidates_A = ["hi!", "I hate you!"]
146
+ candidates_B = ["f**k off!", "I love you, too!"]
147
+ comparison_results = blender.compare(inputs, candidates_A, candidates_B)
148
+ # comparison_results is a list of bool, where comparison_results[i] denotes
149
+ # whether candidates_A[i] is better than candidates_B[i] for inputs[i]
150
+ # Example: comparison_results[0]--> True
151
+ ```
152
+
153
+ <details><summary> Comparing two multi-turn conversations. </summary>
154
+
155
+ ```python
156
+ conv1 = [
157
+ {
158
+ "content": "hello",
159
+ "role": "USER"
160
+ },
161
+ {
162
+ "content": "[assistant1‘s response 1]",
163
+ "role": "ASSISTANT"
164
+ },
165
+ ...
166
+ ]
167
+ conv2 = [
168
+ {
169
+ "content": "hello",
170
+ "role": "USER"
171
+ },
172
+ {
173
+ "content": "[assistant2's response 1]",
174
+ "role": "ASSISTANT"
175
+ },
176
+ ...
177
+ ]
178
+ comparison_results = blender.compare_conversations([conv1], [conv2])
179
+ # comparison_results is a list of bool, where each element denotes whether all the responses in conv1 together is better than that of conv2
180
+ ```
181
+ </details>
182
+
183
+
184
+ ### Use Case 2: Best-of-n Sampling (Decoding Enhancment)
185
+
186
+ **Best-of-n Sampling**, aka, rejection sampling, is a strategy to enhance the response quality by selecting the one that was ranked highest by the reward model
187
+ (see more in [OpenAI WebGPT section 3.2](https://arxiv.org/pdf/2112.09332.pdf) and [OpenAI Blog](https://openai.com/research/measuring-goodharts-law)).
188
+ Best-of-n sampling with PairRM is a very easy way to imporve your LLMs with only a few changes of your inference code:
189
+
190
+ ```python
191
+ # loading models
192
+ import llm_blender
193
+ from transformers import AutoTokenizer, AutoModelForCausalLM
194
+ tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta")
195
+ model = AutoModelForCausalLM.from_pretrained("HuggingFaceH4/zephyr-7b-beta", device_map="auto")
196
+ system_message = {"role": "system", "content": "You are a friendly chatbot."}
197
+
198
+ # formatting your inputs
199
+ inputs = ["can you tell me a joke about OpenAI?"]
200
+ messages = [[system_message, {"role": "user", "content": _input}] for _input in inputs]
201
+ prompts = [tokenizer.apply_chat_template(m, tokenize=False, add_generation_prompt=True) for m in messages]
202
+
203
+ # Conventional generation method
204
+ input_ids = tokenizer(prompts[0], return_tensors="pt").input_ids
205
+ sampled_outputs = model.generate(input_ids, do_sample=True, top_k=50, top_p=0.95, num_return_sequences=1)
206
+ print(tokenizer.decode(sampled_outputs[0][len(input_ids[0]):], skip_special_tokens=False))
207
+ # --> The output could be a bad case such as a very short one, e.g., `Sure`
208
+
209
+ # PairRM for best-of-n sampling
210
+ blender = llm_blender.Blender()
211
+ blender.loadranker("llm-blender/PairRM") # load ranker checkpoint
212
+ outputs = blender.best_of_n_generate(model, tokenizer, prompts, n=10)
213
+
214
+ print("### Prompt:\n", prompts[0])
215
+ print("### best-of-n generations:\n", outputs[0])
216
+ # --> The output will be much more stable and consistently better than single sampling, for example:
217
+ """
218
+ Sure, here's a joke about OpenAI:
219
+
220
+ Why did OpenAI decide to hire a mime as their new AI researcher?
221
+
222
+ Because they wanted someone who could communicate complex ideas without making a sound!
223
+
224
+ (Note: This is a joke, not a reflection of OpenAI's actual hiring practices.)
225
+ """
226
+ ```
227
+
228
+ ### Use case 3: RLHF
229
+ PairRM has been trained on various high-quality and large-scale datasets with human preference annotations
230
+ and shown great correlation with human preferences with an extremely small model size (0.4B),
231
+ approching the performance of GPT-4.
232
+ PairRM will better help the future alignment of LLMs in a more efficient and effective way.
233
+ With a `blender.compare()` function, you can apply PairRM to popular RLHF toolkits such as [trl](https://huggingface.co/docs/trl/index).
234
+
235
+ **🔥 Check more details on our example jupyter notebook usage: [`blender_usage.ipynb`](https://github.com/yuchenlin/LLM-Blender/blob/main/blender_usage.ipynb)**
236
+
237
+
238
+ Learn more in our LLM-Blender Github [README.md](https://github.com/yuchenlin/LLM-Blender#rank-and-fusion)
239
+
240
+
241
+
242
+
243
+ ## Statistics
244
+
245
+ ### Context length
246
+ | PairRanker type | Source max length | Candidate max length | Total max length |
247
+ |:-----------------:|:-----------------:|----------------------|------------------|
248
+ | [pair-ranker](https://huggingface.co/llm-blender/pair-ranker) (our previous version) | 128 | 128 | 384 |
249
+ | [PairRM](https://huggingface.co/llm-blender/pair-reward-model/) (This model) | 1224 | 412 | 2048 |
250
+
251
+ ### Training Datasets
252
+ - [openai/summarize_from_feedback](https://huggingface.co/datasets/openai/summarize_from_feedback)
253
+ - [openai/webgpt_comparisons](https://huggingface.co/datasets/openai/webgpt_comparisons)
254
+ - [Dahoas/instruct-synthetic-prompt-responses](https://huggingface.co/datasets/Dahoas/instruct-synthetic-prompt-responses)
255
+ - [Anthropic/hh-rlhf](https://huggingface.co/datasets/Anthropic/hh-rlhf)
256
+ - [lmsys/chatbot_arena_conversations](https://huggingface.co/datasets/lmsys/chatbot_arena_conversations)
257
+ - [openbmb/UltraFeedback](https://huggingface.co/datasets/openbmb/UltraFeedback)
258
+
259
+ ### Performance
260
+ PairRM has been trained on various high-quality and large-scale dataset with human preference annotations and exhibits great correlation with human preferences
261
+ with an extremly small model size (0.4B), approching the performance of GPT-4.
262
+
263
+ We test the pairwise comparison on
264
+ - [Auto-J pairwise testdata](https://github.com/GAIR-NLP/auto-j#pairwise-response-comparison)
265
+ - [HHH-alignment](https://huggingface.co/datasets/HuggingFaceH4/hhh_alignment)
266
+ - [MT-bench-human-judgements](https://huggingface.co/datasets/lmsys/mt_bench_human_judgments)
267
+
268
+ All following results are reported as pairwise comparison accuracies (agreements).
269
+
270
+ #### Auto-J Pairwise test data performance
271
+
272
+ | Model | Summ | Exam | Code | Rewriting | Crea W | Func W | Comm | NLP | Overall |
273
+ |:---------------------:|:---------:|:---------:|:---------:|:---------:|:---------:|:---------:|:-----:|:--------:|:---------:|
274
+ | Closed -source Models |
275
+ | ChatGPT | 33.3 | 40.3 | 36.6 | 31.6 | 48.2 | 40.4 | 47.6 | 45.8 | 42.7 |
276
+ | Claude -2 | 30.6 | 36.1 | 41.7 | 34.2 | 48.1 | 42.5 | 40.6 | 48.5 | 42.4 |
277
+ | GPT -4 | 59.7 | 51.4 | 69.2 | 58.3 | 66.7 | 60.4 | 58.3 | 65.2 | 61.9 |
278
+ | Open -source Models |
279
+ | SteamSHP | 33.3 | 29.2 | 26.7 | 33.3 | 40.7 | 31.3 | 51.4 | 51.9 | 40.6 |
280
+ | PandaLM | 29.2 | 33.3 | 31.7 | 23.3 | 43.5 | 32.9 | 44.8 | 48.9 | 38.9 |
281
+ | LLaMA -2-Chat -13B | 20.8 | 27.8 | 19.2 | 20 | 31.5 | 27.5 | 35.8 | 31.8 | 29 |
282
+ | Vicuna -13B-v1.5 | 30.6 | 23.6 | 35 | 28.3 | 36.1 | 37.5 | 45.5 | 39.8 | 37.3 |
283
+ | WizardLM -13B-v1.2 | 22.2 | 20.8 | 32.5 | 19.2 | 28.7 | 25.4 | 29.2 | 33 | 27.8 |
284
+ | LLAMA -2-chat -70B | 34.7 | 33.3 | 36.7 | 35.8 | 51.4 | 54.2 | 47.2 | 47.7 | 45.9 |
285
+ | AUTO -J (13b) | 45.8 | 38.9 | **59.2** | 47.5 | 54.6 | 57.1 | **58** | 57.6 | 54.8 |
286
+ | UltraRM (13b) | 56.94 | 43.06 | 55.0 | 53.33 | **67.13** | **64.17** | 56.25 | 59.85 | **59.85** |
287
+ | **PairRM (0.4b)** | **56.94** | **52.78** | 58.33 | **55.83** | 61.57 | 59.17 | 57.64 | **62.5** | 59.05 |
288
+
289
+ #### HHH-Alignment and MT-bench human judgements
290
+
291
+ | Evaluator LM | HHH ALIGNMENT | | | | | MT BENCH HUMAN JUDG . |
292
+ |:-------------------------:|:-------------:|:---------:|:---------:|:--------:|:-----------:|:---------------------:|
293
+ | | Help . | Harm . | Hon . | Other | Total Avg . | Human Preference |
294
+ | RANDOM | 50 | 50 | 50 | 50 | 50 | 34.26 |
295
+ | STANFORDNLP REWARD MODEL | 69.49 | 60.34 | 52.46 | 51.16 | 58.82 | 44.79 |
296
+ | ALMOST REWARD MODEL | 74.58 | 67.24 | 78.69 | 86.05 | 76.02 | 49.9 |
297
+ | LLAMA2 -CHAT 7B | 66.1 | 81.03 | 70.49 | 74.42 | 72.85 | 51.78 |
298
+ | LLAMA2 -CHAT 13B | 74.58 | 87.93 | 55.74 | 79.07 | 73.76 | 52.34 |
299
+ | LLAMA2 -CHAT 70B | 66.1 | **89.66** | 67.21 | 74.42 | 74.21 | 53.67 |
300
+ | LLAMA2 -CHAT 13B+COARSE . | 68.74 | 68.97 | 65.57 | 67.44 | 67.42 | 46.89 |
301
+ | GPT -3.5-TURBO -0613 | 76.27 | 87.93 | 67.21 | 86.05 | 78.73 | 57.12 |
302
+ | PROMETHEUS 7B | 69.49 | 84.48 | 78.69 | 90.7 | 80.09 | 55.14 |
303
+ | PROMETHEUS 13B | 81.36 | 82.76 | 75.41 | 76.74 | 79.19 | 57.72 |
304
+ | UltraRM (13B) | **86.44** | 79.31 | **81.97** | 88.37 | 83.71 | 56 |
305
+ | **PairRM (0.4B)** | 84.75 | 84.48 | 80.33 | **90.7** | **84.62** | **59** |
306
+ | GPT -4-0613 | 91.53 | 93.1 | 85.25 | 83.72 | 88.69 | 63.87 |
307
+
308
+ **While PairRM is a extremely small model (0.4B) based on deberta, the pairwise comparison aggrement performance approches GPT-4's performance!**
309
+
310
+ Two reasons to attribute:
311
+ - Our PairRM specically designed model arch for pairwise comparison through bidirectional attention (See LLM-blender paper for more details)
312
+ - The high-quality and large-scale human preference annotation data it was train on (see training dataset list on this hugging face page)
313
+
314
+
315
+
316
+
317
+
318
+
319
+ ## Citation & Credits
320
+ If you are using PairRM in your research, please cite LLM-blender.
321
+ ```bibtex
322
+ @inproceedings{llm-blender-2023,
323
+ title = "LLM-Blender: Ensembling Large Language Models with Pairwise Comparison and Generative Fusion",
324
+ author = "Jiang, Dongfu and Ren, Xiang and Lin, Bill Yuchen",
325
+ booktitle = "Proceedings of the 61th Annual Meeting of the Association for Computational Linguistics (ACL 2023)",
326
+ year = "2023"
327
+ }
328
+
329
+ ```
330
+