fblgit commited on
Commit
16df845
·
verified ·
1 Parent(s): e56d9fd

Create README.md

Browse files
Files changed (1) hide show
  1. README.md +266 -0
README.md ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - en
4
+ license: other
5
+ license_name: qwen
6
+ license_link: https://huggingface.co/Qwen/Qwen2.5-72B-Instruct/blob/main/LICENSE
7
+ library_name: transformers
8
+ tags:
9
+ - generated_from_trainer
10
+ base_model: Qwen/Qwen2.5-1.5B-Instruct
11
+ model-index:
12
+ - name: miniclaus-qw1.5B-UNAMGS
13
+ results: []
14
+ datasets:
15
+ - Magpie-Align/Magpie-Pro-MT-300K-v0.1
16
+ ---
17
+
18
+ # miniclaus-qw1.5B-UNAMGS-GRPO
19
+
20
+ This version is RL with GRPO on GSM8k for 1400 steps using this code:
21
+ ```
22
+ # train_grpo.py
23
+ import re
24
+ import torch
25
+ from datasets import load_dataset, Dataset
26
+ from transformers import AutoTokenizer, AutoModelForCausalLM
27
+ from peft import LoraConfig
28
+ from trl import GRPOConfig, GRPOTrainer
29
+
30
+ # Load and prep dataset
31
+
32
+ SYSTEM_PROMPT = """
33
+ Respond exclusively the following format:
34
+
35
+ <reasoning>
36
+ ...
37
+ </reasoning>
38
+ <answer>
39
+ ...
40
+ </answer>
41
+
42
+ Its imperative to follow strictritly your final result answer within the <answer>$result</answer> and be terse.
43
+ """
44
+
45
+ XML_COT_FORMAT = """\
46
+ <reasoning>
47
+ {reasoning}
48
+ </reasoning>
49
+ <answer>
50
+ {answer}
51
+ </answer>
52
+ """
53
+
54
+ def extract_xml_answer(text: str) -> str:
55
+ answer = text.split("<answer>")[-1]
56
+ answer = answer.split("</answer>")[0]
57
+ return answer.strip()
58
+
59
+ def extract_hash_answer(text: str) -> str | None:
60
+ if "####" not in text:
61
+ return None
62
+ return text.split("####")[1].strip()
63
+
64
+ # uncomment middle messages for 1-shot prompting
65
+ def get_gsm8k_questions(split = "train") -> Dataset:
66
+ data = load_dataset('openai/gsm8k', 'main')[split] # type: ignore
67
+ data = data.map(lambda x: { # type: ignore
68
+ 'prompt': [
69
+ {'role': 'system', 'content': SYSTEM_PROMPT},
70
+ #{'role': 'user', 'content': 'What is the largest single-digit prime number?'},
71
+ #{'role': 'assistant', 'content': XML_COT_FORMAT.format(
72
+ # reasoning="9 is divisble by 3 and 8 is divisible by 2, but 7 is prime.",
73
+ # answer="7"
74
+ #)},
75
+ {'role': 'user', 'content': x['question']}
76
+ ],
77
+ 'answer': extract_hash_answer(x['answer'])
78
+ }) # type: ignore
79
+ return data # type: ignore
80
+
81
+ dataset = get_gsm8k_questions()
82
+
83
+ # Reward functions
84
+ def int_reward_func(completions, **kwargs) -> list[float]:
85
+ responses = [completion[0]['content'] for completion in completions]
86
+ extracted_responses = [extract_xml_answer(r) for r in responses]
87
+ return [0.5 if r.isdigit() else 0.0 for r in extracted_responses]
88
+
89
+ def strict_format_reward_func(completions, **kwargs) -> list[float]:
90
+ """Reward function that checks if the completion has a specific format."""
91
+ pattern = r"^<reasoning>\n.*?\n</reasoning>\n<answer>\n.*?\n</answer>\n$"
92
+ responses = [completion[0]["content"] for completion in completions]
93
+ matches = [re.match(pattern, r) for r in responses]
94
+ return [0.5 if match else 0.0 for match in matches]
95
+
96
+ def soft_format_reward_func(completions, **kwargs) -> list[float]:
97
+ """Reward function that checks if the completion has a specific format."""
98
+ pattern = r"<reasoning>.*?</reasoning>\s*<answer>.*?</answer>"
99
+ responses = [completion[0]["content"] for completion in completions]
100
+ matches = [re.match(pattern, r) for r in responses]
101
+ return [0.5 if match else 0.0 for match in matches]
102
+
103
+ def correctness_reward_func(prompts, completions, answer, **kwargs) -> list[float]:
104
+ responses = [completion[0]['content'] for completion in completions]
105
+ q = prompts[0][-1]['content']
106
+ extracted_responses = [extract_xml_answer(r) for r in responses]
107
+
108
+ # Extract the last number from each extracted response
109
+ last_numbers = []
110
+ for response in extracted_responses:
111
+ numbers = re.findall(r'\d+', response)
112
+ last_num = numbers[-1] if numbers else None
113
+ last_numbers.append(last_num)
114
+
115
+ print('-'*20, f"Question:\n{q}", f"\nAnswer:\n{answer[0]}", f"\nResponse:\n{responses[0]}",
116
+ f"\nExtracted:\n{extracted_responses[0]}", f"\nLast Number:\n{last_numbers[0]}")
117
+
118
+ # Compare the last number to the answer
119
+ return [2.0 if ln == a else 0.0 for ln, a in zip(last_numbers, answer)]
120
+
121
+ def count_xml(text) -> float:
122
+ count = 0.0
123
+ if text.count("<reasoning>\n") == 1:
124
+ count += 0.125
125
+ if text.count("\n</reasoning>\n") == 1:
126
+ count += 0.125
127
+ if text.count("\n<answer>\n") == 1:
128
+ count += 0.125
129
+ count -= len(text.split("\n</answer>\n")[-1])*0.001
130
+ if text.count("\n</answer>") == 1:
131
+ count += 0.125
132
+ count -= (len(text.split("\n</answer>")[-1]) - 1)*0.001
133
+ return count
134
+
135
+ def xmlcount_reward_func(completions, **kwargs) -> list[float]:
136
+ contents = [completion[0]["content"] for completion in completions]
137
+ return [count_xml(c) for c in contents]
138
+
139
+ model_name = 'fblgit/miniclaus-qw1.5B-UNAMGS'
140
+
141
+ if "Llama" in model_name or 'l318b' in model_name:
142
+ output_dir = "outputs/Llama-1B-GRPO"
143
+ run_name = "Llama-1B-GRPO-gsm8k"
144
+ else:
145
+ output_dir="outputs/Qwen-1.5B-GRPO"
146
+ run_name="Qwen-1.5B-GRPO-gsm8k"
147
+
148
+ training_args = GRPOConfig(
149
+ output_dir=output_dir,
150
+ run_name=run_name,
151
+ learning_rate=5e-6,
152
+ adam_beta1 = 0.9,
153
+ adam_beta2 = 0.99,
154
+ weight_decay = 0.1,
155
+ warmup_ratio = 0.1,
156
+ lr_scheduler_type='cosine',
157
+ logging_steps=1,
158
+ bf16=True,
159
+ tf32=True,
160
+ per_device_train_batch_size=1,
161
+ gradient_accumulation_steps=4,
162
+ #num_generations=16,
163
+ num_generations=6,
164
+ max_prompt_length=256,
165
+ max_completion_length=512,
166
+ num_train_epochs=1,
167
+ save_steps=100,
168
+ max_grad_norm=0.1,
169
+ report_to="wandb",
170
+ log_on_each_node=False,
171
+ )
172
+ model = AutoModelForCausalLM.from_pretrained(
173
+ model_name,
174
+ torch_dtype=torch.bfloat16,
175
+ attn_implementation="flash_attention_2",
176
+ device_map='cuda:0',
177
+ use_cache=True,
178
+ ).to(device="cuda:0", dtype=torch.bfloat16)
179
+
180
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
181
+ tokenizer.pad_token = tokenizer.eos_token
182
+
183
+ # use peft at your own risk; not working for me with multi-GPU training
184
+ trainer = GRPOTrainer(
185
+ model=model,
186
+ processing_class=tokenizer,
187
+ reward_funcs=[
188
+ xmlcount_reward_func,
189
+ soft_format_reward_func,
190
+ strict_format_reward_func,
191
+ int_reward_func,
192
+ correctness_reward_func],
193
+ args=training_args,
194
+ train_dataset=dataset,
195
+ )
196
+ trainer.train()
197
+ ```
198
+
199
+ Trained with `Magpie-Align/Magpie-Pro-MT-300K-v0.1` and `GSM8k`
200
+
201
+ Using MGS & UNA (MLP) on this tiny but powerful model, together with GRPO.
202
+
203
+ ![miniclaus-qw1.5B-UNAMGS](https://huggingface.co/fblgit/miniclaus-qw1.5B-UNAMGS/resolve/main/miniclaus_qw15-UNAMGS.png)
204
+ [<img src="https://raw.githubusercontent.com/axolotl-ai-cloud/axolotl/main/image/axolotl-badge-web.png" alt="Built with Axolotl" width="200" height="32"/>](https://github.com/axolotl-ai-cloud/axolotl)
205
+
206
+ ## Benchmarks
207
+ So far we ran a few:
208
+ ```
209
+ | Tasks |Version|Filter|n-shot| Metric | |Value | |Stderr|
210
+ |-------------------------------------|-------|------|-----:|--------|---|-----:|---|-----:|
211
+ |leaderboard_gpqa | N/A| | | | | | | |
212
+ | - leaderboard_gpqa_diamond | 1|none | 0|acc_norm|↑ |0.3030|± |0.0327|
213
+ | - leaderboard_gpqa_extended | 1|none | 0|acc_norm|↑ |0.3004|± |0.0196|
214
+ | - leaderboard_gpqa_main | 1|none | 0|acc_norm|↑ |0.2969|± |0.0216|
215
+ |leaderboard_musr | N/A| | | | | | | |
216
+ | - leaderboard_musr_murder_mysteries | 1|none | 0|acc_norm|↑ |0.5400|± |0.0316|
217
+ | - leaderboard_musr_object_placements| 1|none | 0|acc_norm|↑ |0.3203|± |0.0292|
218
+ | - leaderboard_musr_team_allocation | 1|none | 0|acc_norm|↑ |0.4080|± |0.0311|
219
+
220
+ |Tasks|Version| Filter |n-shot| Metric | |Value | |Stderr|
221
+ |-----|------:|----------------|-----:|-----------|---|-----:|---|-----:|
222
+ |gsm8k| 3|flexible-extract| 5|exact_match|↑ |0.5974|± |0.0135|
223
+ | | |strict-match | 5|exact_match|↑ |0.5921|± |0.0135|
224
+ ```
225
+
226
+ There is some increased score in GSM and GPQA & MUSR, but this doesnt happens in all checkpoints and this is the one with the best marks.
227
+
228
+ ## Thanks
229
+ - Deepseek Team for the GRPO researches
230
+ - HuggingFace for adopting GRPO on TRL
231
+ - Qwen Team for their outstanding model
232
+ - MagPie Team for contributing plenty of datasets
233
+ - Cybertron Cloud Compute
234
+
235
+ ## Citations
236
+ ```
237
+ @misc{miniclaus-qw15,
238
+ title={MiniClaus: 1.5B UNAMGS},
239
+ author={Xavier Murias},
240
+ year={2024},
241
+ publisher = {HuggingFace},
242
+ journal = {HuggingFace repository},
243
+ howpublished = {\url{https://huggingface.co/fblgit/miniclaus-qw1.5B-UNAMGS}},
244
+ }
245
+ @misc{Magpie,
246
+ title={Magpie: Alignment Data Synthesis from Scratch by Prompting Aligned LLMs with Nothing},
247
+ author={Zhangchen Xu and Fengqing Jiang and Luyao Niu and Yuntian Deng and Radha Poovendran and Yejin Choi and Bill Yuchen Lin},
248
+ year={2024},
249
+ eprint={2406.08464},
250
+ archivePrefix={arXiv},
251
+ primaryClass={cs.CL}
252
+ }
253
+ @misc{qwen2.5,
254
+ title = {Qwen2.5: A Party of Foundation Models},
255
+ url = {https://qwenlm.github.io/blog/qwen2.5/},
256
+ author = {Qwen Team},
257
+ month = {September},
258
+ year = {2024}
259
+ }
260
+ @article{qwen2,
261
+ title={Qwen2 Technical Report},
262
+ author={An Yang and Baosong Yang and Binyuan Hui and Bo Zheng and Bowen Yu and Chang Zhou and Chengpeng Li and Chengyuan Li and Dayiheng Liu and Fei Huang and Guanting Dong and Haoran Wei and Huan Lin and Jialong Tang and Jialin Wang and Jian Yang and Jianhong Tu and Jianwei Zhang and Jianxin Ma and Jin Xu and Jingren Zhou and Jinze Bai and Jinzheng He and Junyang Lin and Kai Dang and Keming Lu and Keqin Chen and Kexin Yang and Mei Li and Mingfeng Xue and Na Ni and Pei Zhang and Peng Wang and Ru Peng and Rui Men and Ruize Gao and Runji Lin and Shijie Wang and Shuai Bai and Sinan Tan and Tianhang Zhu and Tianhao Li and Tianyu Liu and Wenbin Ge and Xiaodong Deng and Xiaohuan Zhou and Xingzhang Ren and Xinyu Zhang and Xipin Wei and Xuancheng Ren and Yang Fan and Yang Yao and Yichang Zhang and Yu Wan and Yunfei Chu and Yuqiong Liu and Zeyu Cui and Zhenru Zhang and Zhihao Fan},
263
+ journal={arXiv preprint arXiv:2407.10671},
264
+ year={2024}
265
+ }
266
+ ```