lbourdois commited on
Commit
45977c6
·
verified ·
1 Parent(s): d56472a

Improve language tag

Browse files

Hi! As the model is multilingual, this is a PR to add other languages than English to the language tag to improve the referencing. Note that 29 languages are announced in the README, but only 13 are explicitly listed. I was therefore only able to add these 13 languages.

Files changed (1) hide show
  1. README.md +222 -210
README.md CHANGED
@@ -1,210 +1,222 @@
1
- ---
2
- license: apache-2.0
3
- language:
4
- - ja
5
- library_name: transformers
6
- base_model:
7
- - Qwen/Qwen2.5-0.5B
8
- ---
9
-
10
- 簡単な算数問題を解けるように GRPO で学習してみた。学習コードは下の方にあります。
11
-
12
- 学習データは簡単な問題なのでその場で合成したものを使いました。(コード参照)
13
-
14
- prompt format:
15
- ```
16
- あなたはアシスタントとして回答します。
17
- ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
18
- 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
19
- 「ユーザー」の質問の後に、「アシスタント」が回答します。
20
- ユーザー:
21
- 次の ? に入る数値を計算して回答してください。
22
- {formula}
23
-
24
- アシスタント:
25
- ```
26
-
27
- example `formula`:
28
- ```
29
- 4 + 3 * 2 = ?
30
- ```
31
-
32
- expected output:
33
- ```xml
34
- <think>思考内容</think><answer>解答</answer>
35
- ```
36
-
37
- ## Example
38
-
39
- ```py
40
- from transformers import pipeline
41
-
42
- formula = "9 + 3 * 5 = ?" # A + B * C か A * B + C の形式のみ対応
43
-
44
- prompt = f"""\
45
- あなたはアシスタントとして回答します。
46
- ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
47
- 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
48
- 「ユーザー」の質問の後に、「アシスタント」が回答します。
49
- ユーザー:
50
- 次の ? に入る数値を計算して回答してください。
51
- {formula}
52
-
53
- アシスタント:
54
- """
55
-
56
- print(pipe(prompt)[0]["generated_text"][len(prompt):])
57
- # <think>9 + 3 * 5 = 9 + 15 = 24</think><answer>24</answer>
58
- ```
59
-
60
- ## Training information
61
-
62
- - Base model: [Qwen/Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B)
63
- - Device: 1x A100 80G
64
- - GPU Hour: about 1 hour
65
- - Total training steps: 140 steps ([the last checkpoint](https://huggingface.co/p1atdev/qwen2.5-0.5b-grpo-math-01/blob/9ede090f5ed41d88c16ffbc56a81b0772f19679e/model.safetensors))
66
-
67
- Wandb log: https://wandb.ai/p1atdev/grpo-math-01/runs/ytv8wxll
68
-
69
- ## Training code
70
-
71
- ```py
72
- import random
73
- import re
74
-
75
- import torch
76
- from datasets import Dataset
77
- from trl import GRPOConfig, GRPOTrainer
78
- from transformers import AutoTokenizer, AutoModelForCausalLM
79
- import wandb
80
-
81
- SYSTEM_PROMPT = """命令:
82
- あなたはアシスタントとして回答します。
83
- ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
84
- 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
85
- 「ユーザー」の質問の後に、「アシスタント」が回答します。
86
- ユーザー:
87
- """
88
- MODEL_NAME = "Qwen/Qwen2.5-0.5B"
89
-
90
- def generate_problem():
91
- # written by ChatGPT
92
- # 1~10 の間のランダムな整数を3つ生成
93
- a = random.randint(1, 10)
94
- b = random.randint(1, 10)
95
- c = random.randint(1, 10)
96
-
97
- # 足し算と掛け算の両方を含むように、2通りのパターンからランダムに選択
98
- if random.randint(0, 1) == 0:
99
- # パターン1: 足し算+掛け算 => 例: a + b * c
100
- expression = f"{a} + {b} * {c}"
101
- else:
102
- # パターン2: 掛け算+足し算 => 例: a * b + c
103
- expression = f"{a} * {b} + {c}"
104
-
105
- # Python eval() を用いて答えを計算(演算子の優先順位に従う)
106
- answer = eval(expression)
107
-
108
- return f"{expression} = ?", answer
109
-
110
-
111
- def generate_random_pair(max_count: int):
112
- for i in range(max_count):
113
- formula, answer = generate_problem()
114
- question = f"""{SYSTEM_PROMPT}
115
- 次の ? に入る数値を計算して回答してください。
116
- {formula}
117
-
118
- アシスタント:
119
- """
120
- yield {"id": i, "prompt": question, "ground_truth": answer}
121
-
122
-
123
- # format reward
124
- FORMAT_PATTERN = re.compile(r"^<think>.*?</think><answer>.*?</answer>$")
125
-
126
- def format_reward_func(completions: list[str], **kwargs):
127
- """Reward function that checks if the completion has a specific format."""
128
- matches = [FORMAT_PATTERN.match(content) for content in completions]
129
- return [1.0 if match else 0.0 for match in matches]
130
-
131
-
132
- # answer reward
133
- ANSWER_PATTERN = re.compile(r"<answer>(\d+)</answer>")
134
-
135
- def answer_reward_func(completions: list[str], ground_truth: list[str], **kwargs):
136
- # Regular expression to capture content inside \boxed{}
137
- matches = [ANSWER_PATTERN.search(completion) for completion in completions]
138
- contents = [match.group(1) if match else "" for match in matches]
139
- # Reward 1 if the content is the same as the ground truth, 0 otherwise
140
- return [1.0 if c == str(gt) else 0.0 for c, gt in zip(contents, ground_truth)]
141
-
142
-
143
- def main():
144
- ds = Dataset.from_generator(generate_random_pair, gen_kwargs={"max_count": 100000}) # 100000 is too many, we don't need so much for this task
145
- model = AutoModelForCausalLM.from_pretrained(
146
- MODEL_NAME,
147
- attn_implementation="flash_attention_2",
148
- torch_dtype=torch.bfloat16,
149
- device_map="auto",
150
- )
151
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
152
- tokenizer.pad_token = tokenizer.eos_token
153
-
154
- project_name = YOUR_WANDB_PROJECT_NAME
155
- push_hub_name = YOUR_PUSH_HUB_NAME
156
-
157
- wandb.init(project=project_name)
158
- train_args = GRPOConfig(
159
- output_dir="./grpo-01", #! output path
160
- use_vllm=False, # True to use vLLM
161
- overwrite_output_dir=True,
162
- num_train_epochs=10,
163
- num_generations=4,
164
- per_device_train_batch_size=16,
165
- # per_device_eval_batch_size=4,
166
- gradient_accumulation_steps=1,
167
- gradient_checkpointing=True,
168
- learning_rate=1e-4, # maybe a bit high
169
- warmup_ratio=0.01,
170
- weight_decay=0.01,
171
- optim="adamw_8bit",
172
- adam_epsilon=1e-8,
173
- lr_scheduler_type="cosine_with_min_lr",
174
- lr_scheduler_kwargs={
175
- "min_lr": 5e-5,
176
- "num_cycles": 0.5,
177
- },
178
- # eval_strategy="steps", # eval did not work well
179
- # eval_steps=10,
180
- save_steps=10,
181
- save_total_limit=2,
182
- logging_steps=1,
183
- logging_first_step=True,
184
- # load_best_model_at_end=True,
185
- # metric_for_best_model="eval_loss",
186
- torch_compile=False, # compile does not work
187
- fp16=False,
188
- bf16=True,
189
- report_to=["wandb"],
190
- hub_model_id=push_hub_name,
191
- hub_private_repo=True,
192
- push_to_hub=True,
193
- save_safetensors=True,
194
- )
195
-
196
- trainer = GRPOTrainer(
197
- model=model,
198
- processing_class=tokenizer,
199
- train_dataset=ds,
200
- # eval_dataset=ds["test"],
201
- reward_funcs=[format_reward_func, answer_reward_func],
202
- args=train_args,
203
- )
204
-
205
- trainer.train()
206
-
207
-
208
- if __name__ == "__main__":
209
- main()
210
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - zho
5
+ - eng
6
+ - fra
7
+ - spa
8
+ - por
9
+ - deu
10
+ - ita
11
+ - rus
12
+ - jpn
13
+ - kor
14
+ - vie
15
+ - tha
16
+ - ara
17
+ library_name: transformers
18
+ base_model:
19
+ - Qwen/Qwen2.5-0.5B
20
+ ---
21
+
22
+ 簡単な算数問題を解けるように GRPO で学習してみた。学習コードは下の方にあります。
23
+
24
+ 学習データは簡単な問題なのでその場で合成したものを使いました。(コード参照)
25
+
26
+ prompt format:
27
+ ```
28
+ あなたはアシスタントとして回答します。
29
+ ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
30
+ 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
31
+ 「ユーザー」の質問の後に、「アシスタント」が回答します。
32
+ ユーザー:
33
+ 次の ? に入る数値を計算して回答してください。
34
+ {formula}
35
+
36
+ アシスタント:
37
+ ```
38
+
39
+ example `formula`:
40
+ ```
41
+ 4 + 3 * 2 = ?
42
+ ```
43
+
44
+ expected output:
45
+ ```xml
46
+ <think>思考内容</think><answer>解答</answer>
47
+ ```
48
+
49
+ ## Example
50
+
51
+ ```py
52
+ from transformers import pipeline
53
+
54
+ formula = "9 + 3 * 5 = ?" # A + B * C か A * B + C の形式のみ対応
55
+
56
+ prompt = f"""\
57
+ あなたはアシスタントとして回答します。
58
+ ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
59
+ 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
60
+ 「ユーザー」の質問の後に、「アシスタント」が回答します。
61
+ ユーザー:
62
+ 次の ? に入る数値を計算して回答してください。
63
+ {formula}
64
+
65
+ アシスタント:
66
+ """
67
+
68
+ print(pipe(prompt)[0]["generated_text"][len(prompt):])
69
+ # <think>9 + 3 * 5 = 9 + 15 = 24</think><answer>24</answer>
70
+ ```
71
+
72
+ ## Training information
73
+
74
+ - Base model: [Qwen/Qwen2.5-0.5B](https://huggingface.co/Qwen/Qwen2.5-0.5B)
75
+ - Device: 1x A100 80G
76
+ - GPU Hour: about 1 hour
77
+ - Total training steps: 140 steps ([the last checkpoint](https://huggingface.co/p1atdev/qwen2.5-0.5b-grpo-math-01/blob/9ede090f5ed41d88c16ffbc56a81b0772f19679e/model.safetensors))
78
+
79
+ Wandb log: https://wandb.ai/p1atdev/grpo-math-01/runs/ytv8wxll
80
+
81
+ ## Training code
82
+
83
+ ```py
84
+ import random
85
+ import re
86
+
87
+ import torch
88
+ from datasets import Dataset
89
+ from trl import GRPOConfig, GRPOTrainer
90
+ from transformers import AutoTokenizer, AutoModelForCausalLM
91
+ import wandb
92
+
93
+ SYSTEM_PROMPT = """命令:
94
+ あなたはアシスタントとして回答します。
95
+ ユーザーの質問に対して、<think></think>ブロック内で思考してから<answer></answer>でファイナルアンサーしてください。
96
+ 具体的には、「<think>ここに思考過程</think><answer>ここに解答</answer>」という形です。
97
+ 「ユーザー」の質問の後に、「アシスタント」が回答します。
98
+ ユーザー:
99
+ """
100
+ MODEL_NAME = "Qwen/Qwen2.5-0.5B"
101
+
102
+ def generate_problem():
103
+ # written by ChatGPT
104
+ # 1~10 の間のランダムな整数を3つ生成
105
+ a = random.randint(1, 10)
106
+ b = random.randint(1, 10)
107
+ c = random.randint(1, 10)
108
+
109
+ # 足し算と掛け算の両方を含むように、2通りのパターンからランダムに選択
110
+ if random.randint(0, 1) == 0:
111
+ # パターン1: 足し算+掛け算 => 例: a + b * c
112
+ expression = f"{a} + {b} * {c}"
113
+ else:
114
+ # パターン2: 掛け算+足し算 => 例: a * b + c
115
+ expression = f"{a} * {b} + {c}"
116
+
117
+ # Python の eval() を用いて答えを計算(演算子の優先順位に従う)
118
+ answer = eval(expression)
119
+
120
+ return f"{expression} = ?", answer
121
+
122
+
123
+ def generate_random_pair(max_count: int):
124
+ for i in range(max_count):
125
+ formula, answer = generate_problem()
126
+ question = f"""{SYSTEM_PROMPT}
127
+ 次の ? に入る数値を計算して回答してください。
128
+ {formula}
129
+
130
+ アシスタント:
131
+ """
132
+ yield {"id": i, "prompt": question, "ground_truth": answer}
133
+
134
+
135
+ # format reward
136
+ FORMAT_PATTERN = re.compile(r"^<think>.*?</think><answer>.*?</answer>$")
137
+
138
+ def format_reward_func(completions: list[str], **kwargs):
139
+ """Reward function that checks if the completion has a specific format."""
140
+ matches = [FORMAT_PATTERN.match(content) for content in completions]
141
+ return [1.0 if match else 0.0 for match in matches]
142
+
143
+
144
+ # answer reward
145
+ ANSWER_PATTERN = re.compile(r"<answer>(\d+)</answer>")
146
+
147
+ def answer_reward_func(completions: list[str], ground_truth: list[str], **kwargs):
148
+ # Regular expression to capture content inside \boxed{}
149
+ matches = [ANSWER_PATTERN.search(completion) for completion in completions]
150
+ contents = [match.group(1) if match else "" for match in matches]
151
+ # Reward 1 if the content is the same as the ground truth, 0 otherwise
152
+ return [1.0 if c == str(gt) else 0.0 for c, gt in zip(contents, ground_truth)]
153
+
154
+
155
+ def main():
156
+ ds = Dataset.from_generator(generate_random_pair, gen_kwargs={"max_count": 100000}) # 100000 is too many, we don't need so much for this task
157
+ model = AutoModelForCausalLM.from_pretrained(
158
+ MODEL_NAME,
159
+ attn_implementation="flash_attention_2",
160
+ torch_dtype=torch.bfloat16,
161
+ device_map="auto",
162
+ )
163
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
164
+ tokenizer.pad_token = tokenizer.eos_token
165
+
166
+ project_name = YOUR_WANDB_PROJECT_NAME
167
+ push_hub_name = YOUR_PUSH_HUB_NAME
168
+
169
+ wandb.init(project=project_name)
170
+ train_args = GRPOConfig(
171
+ output_dir="./grpo-01", #! output path
172
+ use_vllm=False, # True to use vLLM
173
+ overwrite_output_dir=True,
174
+ num_train_epochs=10,
175
+ num_generations=4,
176
+ per_device_train_batch_size=16,
177
+ # per_device_eval_batch_size=4,
178
+ gradient_accumulation_steps=1,
179
+ gradient_checkpointing=True,
180
+ learning_rate=1e-4, # maybe a bit high
181
+ warmup_ratio=0.01,
182
+ weight_decay=0.01,
183
+ optim="adamw_8bit",
184
+ adam_epsilon=1e-8,
185
+ lr_scheduler_type="cosine_with_min_lr",
186
+ lr_scheduler_kwargs={
187
+ "min_lr": 5e-5,
188
+ "num_cycles": 0.5,
189
+ },
190
+ # eval_strategy="steps", # eval did not work well
191
+ # eval_steps=10,
192
+ save_steps=10,
193
+ save_total_limit=2,
194
+ logging_steps=1,
195
+ logging_first_step=True,
196
+ # load_best_model_at_end=True,
197
+ # metric_for_best_model="eval_loss",
198
+ torch_compile=False, # compile does not work
199
+ fp16=False,
200
+ bf16=True,
201
+ report_to=["wandb"],
202
+ hub_model_id=push_hub_name,
203
+ hub_private_repo=True,
204
+ push_to_hub=True,
205
+ save_safetensors=True,
206
+ )
207
+
208
+ trainer = GRPOTrainer(
209
+ model=model,
210
+ processing_class=tokenizer,
211
+ train_dataset=ds,
212
+ # eval_dataset=ds["test"],
213
+ reward_funcs=[format_reward_func, answer_reward_func],
214
+ args=train_args,
215
+ )
216
+
217
+ trainer.train()
218
+
219
+
220
+ if __name__ == "__main__":
221
+ main()
222
+ ```