简介

本篇博客基于Andriy Burkov的grpo开源代码,简单跑通GRPO的完整流程。使用的GPU资源为1张3090(24G)。原作者代码见:GRPO_From-Scratch以及GRPO_Qwen-0_5_Instruct。注:原作者使用8张80G A100完成实验。

GRPO

GRPO算法原理见alg-grpo,原作者在这块的实现基本遵从DeepSeek技术报告中的损失公式,后面代码处详细展开。

$$ \begin{align*} \mathcal{J}_{\text{GRPO}}(\theta) &= \mathbb{E}\left[q \sim P(Q), \{o_i\}_{i=1}^G \sim \pi_{\theta_{\text{old}}}(O|q)\right]\\ &=\frac{1}{G} \sum_{i=1}^G \left\{ \min \left[ \frac{\pi_{\theta}(o_i | q)}{\pi_{\theta_{\text{old}}}(o_i | q)} A_i, \text{clip}\left( \frac{\pi_{\theta}(o_i | q)}{\pi_{\theta_{\text{old}}}(o_i | q)}, 1 - \epsilon, 1 + \epsilon \right) A_i \right] - \beta \mathbb D_{\text{KL}}[\pi_{\theta} \| \pi_{\text{ref}}] \right\}\\ &=\frac{1}{G} \sum_{i=1}^G\frac{1}{\vert o_i\vert}\sum_{t=1}^{\vert o_i\vert}\left\{\min\left[\frac{\pi_\theta(o_{i,t}\vert q,o_{i,< t})}{\pi_{\theta_{old}}(o_{i,t}\vert q, o_{i,< t})}\hat A_{i,t},\ \text{clip}\left(\frac{\pi_\theta(o_{i,t}\vert q,o_{i,< t})}{\pi_{\theta_{old}}(o_{i,t}\vert q,o_{i, < t})},1-\epsilon,1+\epsilon\right)\hat A_{i,t}\right] - \beta\mathbb D_{KL}[\pi_\theta\Vert\pi_{\text{ref}}]\right\} \end{align*} $$
$$ D_{\text{KL}}(\pi_{\theta} \| \pi_{\text{ref}}) = \frac{\pi_{\text{ref}}(o_{i, t} | q, o_{i, < t})}{\pi_{\theta}(o_{i, t} | q, o_{i, < t})} - \log \frac{\pi_{\text{ref}}(o_{i, t} | q, o_{i, < t})}{\pi_{\theta}(o_{i, t} | q, o_{i, < t})} - 1, $$
$$ \hat A_{i,t}=A_i = \frac{r_i - \text{mean}(\{r_1, r_2, \cdots, r_G\})}{\text{std}(\{r_1, r_2, \cdots, r_G\})}. $$

GRPO算法出自文章DeepSeekMath (2024),其中KL散度的计算采用了Approximating KL Divergence中的无偏估计方法,即$\mathbb D_{KL}(q\Vert p)=r-1-\log r$,其中$r=\log\frac{p(x)}{q(x)}$,该估计相比$-\log r$具有更小的方差,比$\frac{1}{2}(\log r)^2$具有更小的偏差(无偏)。

代码

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
import random
import copy
import re
import os
import numpy as np
import wandb
import torch
import pdb
import torch.nn as nn
from torch.nn.utils.rnn import pad_sequence
from transformers import AutoModelForCausalLM, AutoTokenizer
from datasets import load_dataset, load_from_disk
from tqdm import tqdm

def set_random_seed(seed: int=42):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if torch.cuda.is_available():
        torch.cuda.manual_seed_all(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False

set_random_seed(42)

os.environ['WANDB_API_KEY'] = "YOUR_API_KEY"
os.environ['WANDB_PROJECT'] = "GRPO-Qwen-2.5-1.5B-Instruct"

# 设置系统prompt
SYSTEM_PROMPT = """
Respond in the following format:
<reasoning>
...
</reasoning>
<answer>
...
</answer>
"""
def extract_answer_from_model_output(text):
    """
   Extracts the value from the last <answer> tag in the text.

   Args:
       text (str): The model-generated text containing XML-style <answer> tags.

   Returns:
       str or None: The content inside the <answer> tags, or None if no valid answer is found.

   Explanation:
       1. Splits the text on the <answer> tag to isolate content after the tag.
       2. Checks if at least one <answer> tag exists in the text.
       3. For the last <answer> segment:
          - Verifies it contains a closing </answer> tag.
          - Extracts only the content between the tags.
       4. Returns None if the answer is empty (just "...") or if tags are missing.
   """
    parts = text.split('<answer>')
    if len(parts) < 2: # No <answer> tag found
        return None
    last_part = parts[-1]

    if '</answer>' not in last_part:
        return None
    answer = last_part.split('</answer>')[0].strip()
    return None if answer == "..." else answer

def extract_answer_from_dataset(text):
    """
   Extracts the answer from the GSM8K dataset examples.

   Args:
       text (str): The dataset example text containing a question and answer.

   Returns:
       str or None: The extracted answer part after the '####' delimiter, or None if not found.

   Explanation:
       1. Checks if the text contains the '####' delimiter that separates question from answer.
       2. If found, splits the text at this delimiter and returns the second part (the answer).
       3. The answer is stripped of leading/trailing whitespace.
       4. Returns None if no delimiter is present.
   """
    if "####" not in text:
        return None
    return text.split("####")[1].strip()

def prepare_dataset(split="train"):
    """
   Load and prepare the GSM8K dataset for training with string prompts.

   Args:
       split (str): The dataset split to load ("train" or "test"). Defaults to "train".

   Returns:
       list: A list of formatted examples, each containing a prompt string and answer.

   Explanation:
       1. Loads the GSM8K dataset from the Hugging Face datasets hub.
       2. For each example in the dataset:
          - Creates a list of messages with system prompt and the question.
          - Converts this list into a single string prompt using build_prompt().
          - Extracts the answer from the dataset example.
          - Creates a formatted example dictionary with prompt and answer.
       3. Returns the list of formatted examples ready for model training or evaluation.
   """
    # 从本地加载,服务器端连接不上huggingface,使用train部分的数据
    data = load_from_disk('/data/ztq147/gsm8k')[split]
    # data = load_dataset('openai/gsm8k', 'main')[split]
    # 一个formatted数据包含“prompt”和“answer”,其中“prompt”格式为SYSTEM_PROMPT\n QUESTION;“answer”格式为ANSWER
    formatted_data = []
    for example in data:
        prompt_str = build_prompt(
            [
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": example['question']}
            ]
        )
        formatted_example = {
            "prompt": prompt_str,
            "answer": extract_answer_from_dataset(example["answer"])
        }
        formatted_data.append(formatted_example)
    return formatted_data

def build_prompt(messages):
    """
   Build a single prompt string from a list of messages.

   Args:
       messages (list): A list of message dictionaries, each with 'role' and 'content' keys.

   Returns:
       str: A concatenated string of all message contents.

   Explanation:
       1. Takes a list of message dictionaries in the typical chat format.
       2. Extracts the 'content' field from each message and strips whitespace.
       3. Joins all content strings with newlines to create a single prompt.
       4. This preserves the training format while converting from structured messages to a string.
   """
    return "\n".join([msg["content"].strip() for msg in messages])

def extract_last_number(text):
    """
    Extracts the last number appearing in the text.
    
    Args:
       text (str): The text to extract a number from.
    
    Returns:
       float or None: The last number in the text, or None if no number is found.
    
    Explanation:
       1. Removes dollar signs and percent symbols from the text.
       2. Uses regex to find a number that appears at the end of the text (possibly after whitespace).
       3. The pattern matches numbers that appear at the end of the string, with or without decimal points.
       4. Returns the found number as a float, or None if no match is found.
    """
    text = text.replace('$', '').replace('%', '')
    pattern = r'(?:^|\s|=)\s*(-?\d*\.?\d+)\s*$'
    match = re.search(pattern, text)
    return float(match.group(1)) if match else None

def extract_single_number(text):
    """
    Extracts the last number appearing in the text.
    
    Args:
       text (str): The text to extract a number from.
    
    Returns:
       float or None: The last number in the text, or None if no number is found.
    
    Explanation:
       1. Removes dollar signs and percent symbols from the text.
       2. Uses regex to find a number that appears at the end of the text (possibly after whitespace).
       3. The pattern matches numbers that appear at the end of the string, with or without decimal points.
       4. Returns the found number as a float, or None if no match is found.
    """
    text = text.replace('$', '').replace('%', '')
    pattern = r'(?:^|\s|=)\s*(-?\d*\.?\d+)\s*$'
    match = re.search(pattern, text)
    return float(match.group(1)) if match else None

def evaluate_model(model, tokenizer, eval_examples, device):
    """
    Evaluates the model on a set of examples and prints detailed results.
    
    Args:
       model: The language model to evaluate.
       tokenizer: The tokenizer for encoding inputs and decoding outputs.
       eval_examples (list): List of evaluation examples, each containing "prompt" and "answer".
       device: The device (CPU or GPU) to run evaluation on.
    
    Returns:
       float: The accuracy percentage (correct predictions / total examples * 100).
    
    Explanation:
       1. Sets the model to evaluation mode.
       2. For each example in the evaluation set:
          - Encodes the prompt and generates a response using the model.
          - Extracts the predicted answer from the generated response.
          - Compares the predicted answer with the expected answer using multiple methods:
            a. Exact string matching
            b. Single number extraction and comparison
            c. Last number extraction and comparison
          - Prints detailed information about each example.
       3. Calculates and returns the overall accuracy.
       4. Returns the model to training mode.
    """
    model.eval()
    correct = 0
    total = len(eval_examples)
    print("\n" + "="*50)
    print("EVALUATION ON", total, "EXAMPLES")
    print("="*50)

    for example in eval_examples:
        full_prompt = example["prompt"]
        expected = example["answer"]

        inputs = tokenizer.encode(full_prompt, return_tensors="pt").to(device)
        # early_stopping=False,表示模型会一直生直到达到最大新标记数(max_new_tokens)。
        # forced_eos_token_id=tokenizer.eos_token_id,当生成到最大长度时,默认将最后一个token换成eos_token_id。
        with torch.no_grad():
            outputs = model.generate(
                inputs,
                max_new_tokens=512,
                temperature=0.7,
                num_return_sequences=1,
                pad_token_id=tokenizer.pad_token_id,
                eos_token_id=tokenizer.eos_token_id,
                forced_eos_token_id=tokenizer.eos_token_id,
                early_stopping=False,
            )
        response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        # 关于数学类问题评估的方法,这里不太了解,之前没做过
        try:
            predicted = extract_answer_from_model_output(response)

            if predicted == expected:
                is_correct = True
            else:
                pred_num = extract_single_number(str(predicted))
                exp_num = extract_single_number(str(expected))
                if pred_num is not None and exp_num is not None and pred_num == exp_num:
                    is_correct = True
                else:
                    pred_num = extract_last_number(str(predicted))
                    exp_num = extract_last_number(str(expected))
                    is_correct = (pred_num is not None and exp_num is not None and pred_num == exp_num)
            if is_correct:
                correct += 1

            print("\nPrompt:")
            print(full_prompt)
            print("\nExpected Answer:")
            print(expected)
            print("\nExtracted Answer:")
            print(predicted)
            print("\nFull Generated Response:")
            print(response)
            print("\nCorrect:", "✓" if is_correct else "✗")
            print("-"*50)

        except Exception as e:
            print("\nFailed to parse model output for prompt:")
            print(full_prompt)
            print("Error:", e)
            print("-"*50)

    accuracy = (correct / total) * 100
    print(f"\nAccuracy: {accuracy:.2f}% ({correct}/{total})")
    print("="*50)

    model.train()
    return accuracy

def correctness_reward(prompts, completions, answer, **kwargs):
    """
    Assigns a reward based on the correctness of the model's answer.
    
    Args:
    prompts (list): List of input prompts.
    completions (list): List of model completions, each containing content.
    answer (list): List of expected answers.
    **kwargs: Additional keyword arguments.
    
    Returns:
    list: List of numerical rewards for each completion.
    
    Explanation:
    1. Extracts the content from each completion.
    2. Extracts the answer portion from each response using extract_answer_from_model_output.
    3. Assigns rewards based on matching criteria:
      - 2.0 points for an exact match
      - 1.5 points for numeric equivalence (when values match but format differs)
      - 0.0 points for incorrect answers
    4. Tracks completion lengths for analysis.
    """
    responses = [completion[0]['content'] for completion in completions]
    extracted = [extract_answer_from_model_output(r) for r in responses]
    rewards = []
    for r, a in zip(extracted, answer):
        if r == a: # Exact match case
            rewards.append(2.0)
        else:
            r_num = extract_single_number(str(r))
            a_num = extract_single_number(str(a))
            if r_num is not None and a_num is not None and r_num == a_num:
                rewards.append(1.5)
            else:
                rewards.append(0.0)
    completion_lengths = [len(response.split()) for response in responses]
    return rewards

def format_reward(completions, **kwargs):
    """
    Assigns a reward for adhering to the desired XML format.
    
    Args:
       completions (list): List of model completions, each containing content.
       **kwargs: Additional keyword arguments.
    
    Returns:
       list: List of format compliance scores for each completion.
    
    Explanation:
       1. Extracts the content from each completion.
       2. Evaluates format compliance by checking for required XML tags:
          - 0.2 points for each tag present (<reasoning>, </reasoning>, <answer>, </answer>)
          - Maximum score of 0.8 for perfect format compliance
       3. Stores and returns the format compliance scores.
    """
    responses = [completion[0]['content'] for completion in completions]
    rewards = []
    format_scores = []
    for response in responses:
        score = 0.0
        if "<reasoning>" in response: score += 0.2
        if "</reasoning>" in response: score += 0.2
        if "<answer>" in response: score += 0.2
        if "</answer>" in response: score += 0.2
        rewards.append(score)
        format_scores.append(score)
    return rewards

def combined_reward(prompts, completions, answer):
    """
    Combines correctness and format rewards.
    
    Args:
       prompts (list[str]): List of prompt texts
       completions (list[list[dict]]): List of completion dictionaries
       answer (list[str]): List of expected answers
    
    Returns:
       list[float]: Combined rewards for each prompt-completion pair
    
    Explanation:
       1. Calculates separate rewards for correctness and format compliance.
       2. Combines the rewards with the following weights:
          - Correctness score range: 0.0 to 2.0
          - Format score range: 0.0 to 0.8
          - Total possible range: 0.0 to 2.8
       3. Returns the combined reward for each example.
    """
    # Get individual rewards
    correctness_scores = correctness_reward(prompts=prompts, completions=completions, answer=answer)
    format_scores = format_reward(completions=completions)
    
    # Combine rewards - correctness is weighted more heavily
    combined_rewards = []
    for c_score, f_score in zip(correctness_scores, format_scores):
        # Correctness score range: 0.0 to 2.0
        # Format score range: 0.0 to 0.8
        # Total range: 0.0 to 2.8
        combined_rewards.append(c_score + f_score)
    
    return combined_rewards

def selective_log_softmax(logits, input_ids):
    """
    Computes log probabilities for specific tokens in the vocabulary.
    
    Args:
        logits (torch.Tensor): The raw logits output from the model.
        input_ids (torch.Tensor): The token IDs for which we want the log probabilities.
    
    Returns:
        torch.Tensor: Log probabilities of the selected tokens.
    
    Explanation:
        1. Applies log softmax to convert logits to log probabilities over the vocabulary.
        2. Uses gather to extract only the log probabilities corresponding to the input_ids.
        3. Removes the extra dimension to match the original shape of input_ids.
    """
    log_probs = nn.functional.log_softmax(logits, dim=-1)
    return log_probs.gather(dim=-1, index=input_ids.unsqueeze(-1)).squeeze(-1)

def compute_log_probs(model, input_ids, attention_mask, logits_to_keep):
    """
    Computes the log probabilities for a batch of tokens.
    
    Args:
        model: The language model.
        input_ids (torch.Tensor): Token IDs for input sequences.
        attention_mask (torch.Tensor): Attention mask for input sequences.
        logits_to_keep (int): Number of tokens to keep from the end of the sequence.
    
    Returns:
        torch.Tensor: Log probabilities of the selected tokens.
    
    Explanation:
        1. Gets logits from the model for the input sequence.
        2. Selects logits for all tokens except the last one (as we predict next tokens).
        3. Selects only the last 'logits_to_keep' tokens from both logits and input_ids.
        4. Computes log probabilities for these tokens using selective_log_softmax.
    """
    logits = model(input_ids=input_ids, attention_mask=attention_mask).logits[:, :-1, :]
    input_ids = input_ids[:, -logits_to_keep:]  # select the generation part, remove the prompt part
    logits = logits[:, -logits_to_keep:, :]     # the same as input_ids
    return selective_log_softmax(logits, input_ids)

def create_completion_mask(completion_ids, eos_token_id):
    """
    Creates a mask for completion tokens that excludes tokens after the EOS token.
    
    Args:
        completion_ids (torch.Tensor): Token IDs of the generated completions.
        eos_token_id (int): The ID of the end-of-sequence token.
    
    Returns:
        torch.Tensor: A binary mask with 1s for valid tokens and 0s after the EOS token.
    
    Explanation:
        1. Identifies positions where EOS tokens occur in each sequence.
        2. Finds the index of the first EOS token in each sequence.
        3. Creates a mask where positions before and including the first EOS are 1, others are 0.
        4. If no EOS token is found in a sequence, all positions are set to 1.
    """
    is_eos = completion_ids == eos_token_id # shape (bs, max_completion_length)
    eos_idx = torch.full((is_eos.size(0),), is_eos.size(1), dtype=torch.long, device=completion_ids.device) # 表示每个completion的第一个Eos_token的位置,初始化全为max_completion_length. shape (bs, )
    mask_exists = is_eos.any(dim=1) # 返回一个布尔向量 shape (bs, ),表示哪些序列包含至少一个Eos token
    eos_idx[mask_exists] = is_eos.int().argmax(dim=1)[mask_exists] # 对于包含Eos token的序列,找到第一个Eos token的位置,is_eos.int().argmax(dim=1)返回每个序列中第一个Eos token的索引。
    sequence_indices = torch.arange(is_eos.size(1), device=completion_ids.device).expand(is_eos.size(0), -1) # shape (bs, max_completion_length)
    return (sequence_indices <= eos_idx.unsqueeze(1)).int()

def generate_completions(model, tokenizer, prompts, num_generations=4, max_completion_length=32):
    """
    Generates multiple completions for each prompt.

    Args:
        model: The language model.
        tokenizer: The tokenizer for encoding and decoding text.
        prompts (list): List of text prompts.
        num_generations (int): Number of completions to generate per prompt.
        max_completion_length (int): Maximum number of tokens to generate.

    Returns:
        tuple: Containing prompt IDs, prompt mask, completion IDs, and completion mask.

    Explanation:
        1. Encodes the prompts and moves them to the appropriate device.
        2. Repeats each prompt num_generations times to generate multiple completions.
        3. Generates completions using the model with specified parameters.
        4. Extracts the completion IDs (excluding the prompt tokens).
        5. Creates a mask for the completions using create_completion_mask.
    """
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    inputs = tokenizer(prompts, return_tensors="pt", padding=True, padding_side="left")
    prompt_ids = inputs["input_ids"].to(device)
    prompt_mask = inputs["attention_mask"].to(device)
    print(f"Input batch size: {prompt_ids.size(0)}, Device before model: {prompt_ids.device}")
    prompt_length = prompt_ids.size(1)
    # .repeat_interleave 沿着dim=0重复num_generations次,使得prompt_ids和prompt_mask的维度都增加了num_generations倍
    prompt_ids = prompt_ids.repeat_interleave(num_generations, dim=0)   # shape (bs * num_generations, max_prompt_length)
    prompt_mask = prompt_mask.repeat_interleave(num_generations, dim=0)   # shape (bs * num_generations, max_prompt_length)
    outputs = model.generate(
        prompt_ids,
        attention_mask=prompt_mask,
        max_new_tokens=max_completion_length,
        do_sample=True,
        temperature=1.0,
        pad_token_id=tokenizer.pad_token_id,
        eos_token_id=tokenizer.eos_token_id,
        early_stopping=False
    )
    print(f"Output batch size: {outputs.size(0)}, Device after model: {outputs.device}")
    # completio_ids只包含模型生成的answer部分,长度为max_completion_length
    completion_ids = outputs[:, prompt_length:]  # shape (bs * num_generations, max_completion_length)
    completion_mask = create_completion_mask(completion_ids, tokenizer.eos_token_id)  # shape (bs * num_generations, max_completion_length)
    return prompt_ids, prompt_mask, completion_ids, completion_mask

def generate_rollout_data(model, ref_model, tokenizer, batch_samples, num_generations, max_completion_length):
    """
    Generates data for GRPO rollouts including completions and log probabilities.

    Args:
        model: The policy model being trained.
        ref_model: The reference model for KL divergence calculation.
        tokenizer: The tokenizer for encoding and decoding text.
        batch_samples (list): Batch of training samples.
        num_generations (int): Number of completions to generate per sample.
        max_completion_length (int): Maximum completion length.

    Returns:
        dict: Dictionary containing all data needed for GRPO updates.

    Explanation:
        1. Extracts prompts and expected answers from the batch samples.
        2. Generates completions using the current policy model.
        3. Combines prompt and completion tokens.
        4. Computes log probabilities from both the policy model and reference model.
        5. Formats completions for reward calculation.
        6. Repeats prompts and answers to match the number of generated completions.
        7. Returns all data needed for GRPO loss calculation.
    """
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    prompts = [sample["prompt"] if isinstance(sample, dict) else sample[0] for sample in batch_samples]
    answers = [sample["answer"] if isinstance(sample, dict) else sample[1] for sample in batch_samples]
    with torch.no_grad():
        prompt_ids, prompt_mask, completion_ids, completion_mask = generate_completions(
            model, tokenizer, prompts, num_generations, max_completion_length
        )
        input_ids = torch.cat([prompt_ids, completion_ids], dim=1)  # shape (bs * num_generations, max_prompt_length + max_completion_length)
        attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)  # shape (bs * num_generations, max_prompt_length + max_completion_length)
        logits_to_keep = completion_ids.size(1)  # max_completion_length
        old_log_probs = compute_log_probs(model, input_ids, attention_mask, logits_to_keep)  # shape (bs * num_generations, max_completion_length)
        ref_log_probs = compute_log_probs(ref_model, input_ids, attention_mask, logits_to_keep)  # shape (bs * num_generations, max_completion_length)
    formatted_completions = [[{'content': tokenizer.decode(ids, skip_special_tokens=True)}] for ids in completion_ids]
    repeated_prompts = [p for p in prompts for _ in range(num_generations)]
    repeated_answers = [a for a in answers for _ in range(num_generations)]
    return {
        "input_ids": input_ids,
        "attention_mask": attention_mask,
        "completion_mask": completion_mask,
        "old_log_probs": old_log_probs,
        "ref_log_probs": ref_log_probs,
        "formatted_completions": formatted_completions,
        "repeated_prompts": repeated_prompts,
        "repeated_answers": repeated_answers,
        "logits_to_keep": logits_to_keep,
        "batch_size": len(prompts),
        "num_generations": num_generations
    }

def grpo_loss(model, ref_model, rollout_data, tokenizer, reward_function, beta=0.01, epsilon=0.2):
    """
    Computes the GRPO loss for updating the policy model.

    Args:
        model: The policy model being trained.
        ref_model: The reference model for KL divergence calculation.
        rollout_data (dict): Data generated by generate_rollout_data.
        tokenizer: The tokenizer for encoding and decoding text.
        reward_function: Function that calculates rewards for completions.
        beta (float): KL penalty coefficient.
        epsilon (float): Clipping parameter for PPO.

    Returns:
        torch.Tensor: The GRPO loss to be minimized.

    Explanation:
        1. Computes current token log probabilities using the policy model.
        2. Calculates the probability ratio between current and old policies.
        3. Computes rewards using the provided reward_function.
        4. Calculates advantages by standardizing rewards within each prompt.
        5. Computes the PPO surrogate objective with clipping.
        6. Calculates the KL divergence between reference and policy models.
        7. Combines surrogate loss and KL penalty.
        8. Averages the loss across all tokens and batches.
    """
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    input_ids = rollout_data["input_ids"]
    attention_mask = rollout_data["attention_mask"]
    completion_mask = rollout_data["completion_mask"]
    logits_to_keep = rollout_data["logits_to_keep"]
    old_log_probs = rollout_data["old_log_probs"]
    ref_log_probs = rollout_data["ref_log_probs"]
    token_log_probs = compute_log_probs(model, input_ids, attention_mask, logits_to_keep)
    ratio = torch.exp(token_log_probs - old_log_probs)  # shape (bs * num_generations, max_completion_length)
    rewards = torch.tensor(
        reward_function(prompts=rollout_data["repeated_prompts"], completions=rollout_data["formatted_completions"], answer=rollout_data["repeated_answers"]),
        dtype=torch.float32,
        device=device
    )  # shape (bs * num_generations,)
    #print(f"Rewards: {rewards}")  # Debug rewards
    batch_size = rollout_data["batch_size"]
    num_generations = rollout_data["num_generations"]
    rewards = rewards.view(batch_size, num_generations)
    avg_reward = rewards.mean().item()
    print("Average Reward:", avg_reward)
    mean_rewards = rewards.mean(dim=1).repeat_interleave(num_generations)  # shape (bs * num_generations,)
    std_rewards = rewards.std(dim=1).repeat_interleave(num_generations)  # shape (bs * num_generations,)
    advantages = ((rewards.view(-1) - mean_rewards) / (std_rewards + 1e-4)).unsqueeze(1)  # shape (bs * num_generations, 1)
    surr1 = ratio * advantages  # shape (bs * num_generations, max_completion_length)
    surr2 = torch.clamp(ratio, 1 - epsilon, 1 + epsilon) * advantages  # shape (bs * num_generations, max_completion_length)
    surrogate_loss = torch.min(surr1, surr2)  # shape (bs * num_generations, max_completion_length)
    kl = torch.exp(ref_log_probs - token_log_probs) - (ref_log_probs - token_log_probs) - 1  # shape (bs * num_generations, max_completion_length)
    per_token_loss = surrogate_loss - beta * kl  # shape (bs * num_generations, max_completion_length)
    loss = -((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()  # completion_mask用于把生成部分中eos token之后的部分mask掉,只保留生成部分的loss,其中每个completion都会对生成有效长度的loss进行平均,然后再对batch求平均,得到batch的loss。这里添加负号因为GRPO优化目标是最大化改值,这里用梯度下降来优化,所以这里加负号
    return loss, avg_reward

def train_with_grpo(model, tokenizer, train_data, num_iterations=1, num_steps=500, batch_size=4, num_generations=4, gradient_accumulation_steps=4, max_completion_length=128, beta=0.1, learning_rate=5e-6, mu=3, epsilon=0.2, reward_function=None, device_ids=None):
    """
    This function is your original working code (train_with_grpo_static)
    with an added outer loop for iterative GRPO updates per the pseudocode.

    Args:
        model: The language model to train.
        tokenizer: The tokenizer for encoding and decoding text.
        train_data (list): Training dataset.
        num_iterations (int): Number of outer iterations (reference model updates).
        num_steps (int): Number of batch updates per iteration.
        batch_size (int): Number of prompts per batch.
        num_generations (int): Number of completions per prompt.
        max_completion_length (int): Maximum token length for completions.
        beta (float): KL penalty coefficient.
        learning_rate (float): Learning rate for optimizer.
        mu (int): Number of policy updates per batch.
        epsilon (float): PPO clipping parameter.
        reward_function: Function that calculates rewards for completions.
        device_ids (list): List of GPU device IDs for DataParallel.

    Returns:
        The trained model.

    Explanation:
        1. For each outer iteration:
           - Creates a reference model as a deep copy of the current policy model.
           - Reinitializes the optimizer for the policy model.
           - For each training step:
             a. Samples a batch of examples from the training data.
             b. Generates rollout data including completions and log probabilities.
             c. For mu iterations:
                i. Computes the GRPO loss.
                ii. Updates the policy model using gradient descent.
           - Monitors GPU memory usage and prints progress information.
    """
    # assert device_ids is not None and len(device_ids) > 1

    # device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    # model = nn.DataParallel(model, device_ids=device_ids).cuda()
    # print(f"Model wrapped with DataParallel across GPUs: {device_ids}")

    # num_iterations表示ref_model迭代次数
    for iteration in range(num_iterations):
        print(f"\nIteration {iteration+1}/{num_iterations}")

        # Create a reference model (deep copy) and set it to eval mode.
        ref_model = copy.deepcopy(model)
        ref_model.eval()
        for param in ref_model.parameters():
            param.requires_grad = False
        print("Reference model created.")

        optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate)
        model.train()
        # pdb.set_trace()
        # Inner loop: your original training steps.
        for step in tqdm(range(num_steps)):
            batch_samples = random.sample(train_data, batch_size)
            with torch.no_grad():
                # 生成经验数据
                rollout_data = generate_rollout_data(
                    model,
                    ref_model,
                    tokenizer,
                    batch_samples,
                    num_generations,
                    max_completion_length,
                )
            # 对每批经验池数据学习的次数,一般设置mu=1
            for grpo_iter in range(mu):
                loss, avg_reward = grpo_loss(
                    model,
                    ref_model,
                    rollout_data,
                    tokenizer,
                    reward_function,
                    beta=beta,
                    epsilon=epsilon,
                )
                loss.backward()
                if (step + 1) % gradient_accumulation_steps == 0:
                    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=0.1)
                    optimizer.step()
                    optimizer.zero_grad()
                wandb.log({
                    "loss": loss.item(),
                    "average_reward": avg_reward,
                    "iteration": iteration + 1,
                    "step": step + 1,
                    "grpo_iter": grpo_iter + 1
                })
                print(f"Iteration {iteration+1}/{num_iterations}, Step {step+1}/{num_steps}, "
                      f"GRPO iter {grpo_iter+1}/{mu}, loss: {loss.item():.4f}")
    return model

def optimize_model_memory(model):
    """
    Optimizes the model to use less memory during training.

    Args:
        model: The language model to optimize.

    Returns:
        The optimized model.

    Explanation:
        1. Sets the model to training mode.
        2. Disables KV caching to save memory.
        3. Enables gradient checkpointing to trade computation for memory.
        4. Ensures that input embeddings require gradients:
           - Either uses the built-in method if available.
           - Or adds a forward hook to the input embeddings layer.
        5. Returns the optimized model ready for memory-efficient training.
    """
    model.train()
    model.config.use_cache = False  # 不使用kv-cache缓存,减小显存消耗

    # First ensure inputs will require gradients
    if hasattr(model, "enable_input_require_grads"):
        model.enable_input_require_grads()
    else:
        def make_inputs_require_grad(module, input, output):
            output.requires_grad_(True)
        model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)

    # Then enable gradient checkpointing
    model.gradient_checkpointing_enable()

    return model

if __name__ == "__main__":
    # Main execution
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
    model_name = "/model/ztq147/Qwen/Qwen2.5-1.5B-Instruct"
    output_dir = "/data/ztq147/temp_models/math_solver_model"
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    print("Downloading model...")
    model = AutoModelForCausalLM.from_pretrained(
        model_name,
        torch_dtype=torch.bfloat16,
        device_map='auto'
    )
    print("Model downloaded")

    tokenizer = AutoTokenizer.from_pretrained(model_name, padding_side="left")
    tokenizer.pad_token = tokenizer.eos_token
    model.config.pad_token_id = tokenizer.eos_token_id
    model.config.eos_token_id = tokenizer.eos_token_id
    # setting the number of device
    # device_ids = list(range(8))

    all_data = prepare_dataset("train")
    random.shuffle(all_data)
    size_of_eval_data = 30
    eval_data = all_data[:size_of_eval_data]
    train_data = all_data[size_of_eval_data:]

    # print("\nInital model evaluation before finetuning:")
    # pre_grpo_accuracy = evaluate_model(model, tokenizer, eval_data, device)
    # print(f"Pre-GRPO Accuracy: {pre_grpo_accuracy:.2f}%")

    model = optimize_model_memory(model)
    print("\nStarting RL fine-tuning using GRPO...")

    training_config = {
    'num_iterations': 1,
    'num_steps': 500,
    'batch_size': 2,
    'num_generations': 8,
    'gradient_accumulation_steps': 4,
    'max_completion_length': 256,
    'beta': 0.04,
    'learning_rate': 5e-6,
    'mu': 1,
    'epsilon': 0.1
    }
    wandb.init(project=os.environ["WANDB_PROJECT"], reinit=True)
    print("Weights & Biases initialized.")
    # pdb.set_trace()
    model = train_with_grpo(
        model=model,
        tokenizer=tokenizer,
        train_data=train_data,
        reward_function=combined_reward,
        # device_ids=device_ids,
        **training_config
    )

    wandb.finish()
    print("Training completed and wandb run finished.")
    print("\nFinalmodel evaluation after GTPO RL fine-tuning:")
    post_grpo_accuracy = evaluate_model(model, tokenizer, eval_data, device)
    print(f"Post-GRPO Accuracy: {post_grpo_accuracy:.2f}%")

    print("\nSaving GTPO fine-tuned model...")
    model.save_pretrained(output_dir)
    tokenizer.save_pretrained(output_dir)

单卡实验结果

作者使用一张3090GPU训练,实验结果如下:

  • batch_size=2, num_generations=8, max_completion_length=256, gradient_accumulation_steps=1, mu=3, num_steps=500, num_iterations=1, beta=0.04, learning_rate=5e-6, epsilon=0.1

最终的测试准确率:Accuracy: 23.33% (7/30)

这里横轴是1500步因为设置了mu=3,所以每个step被记录了三次,这个实验主要想看看mu的影响,个人理解mu=1的情况下,ratio的计算结果应该永远是1。

loss曲线

reward曲线

  • batch_size=1, num_generations=8, max_completion_length=400, gradient_accumulation_steps=12, mu=1, num_steps=1500, num_iterations=1, beta=0.04, learning_rate=5e-6, epsilon=0.1

最终的测试准确率:Accuracy: 36.67% (11/30)

loss曲线

reward曲线

  • batch_size=2, num_generations=8, max_completion_length=256, gradient_accumulation_steps=6, mu=1, num_steps=500, num_iterations=1, beta=0.04, learning_rate=5e-6, epsilon=0.1

最终的测试准确率:Accuracy: 40.00% (12/30)

loss曲线

reward曲线

  • batch_size=2, num_generations=8, max_completion_length=256, gradient_accumulation_steps=1, mu=1, num_steps=500, num_iterations=1, beta=0.04, learning_rate=5e-6, epsilon=0.1

最终的测试准确率:Accuracy: 46.67% (14/30)

loss曲线

reward曲线

单卡实验小结

从上面简单的几次实验结果来看,最好的是batch_size=2, num_generations=8, max_completion_length=256, gradient_accumulation_steps=1, mu=1, num_steps=500, num_iterations=1, beta=0.04, learning_rate=5e-6, epsilon=0.1,准确率达到了46.67%,但是这个结果与原作者的90%的准确率有较大差距,原作者用8张80G显存的A100,batch_size设置为7(一张卡放1条数据,原文用了数据并行nn.DataParallel),最大生成长度设置为400,num_generations设置为12,mu=1,gradient_accumulation_steps=1,一共训练500步,其他参数与本文这个设置的其他参数一致。

整体看对结果影响较大的参数有max_completino_length和num_generations。相反,设置gradient_accumulation_steps并没能带来大batch_size的效果(这个不确定是不是代码写的有问题),反而降低性能,mu的设置大于1也降低了性能。

实验的loss曲线也没有原文那种稳定的上升趋势,虽然不理解为啥loss是上升的,本文贴的所有loss图均是设置了最大Y值,实际上会存在很多loss很高的脉冲(十几到几百),这个脉冲存在的原因也不太清楚。reward图和原文的有一定相似性。

References

[1] Shao et al. “DeepSeekMath: Pushing the Limits of Mathematical Reasoning in Open Language Models” arXiv preprint arXiv:2402.03300 (2024).

[2] John Schulman. “Approximating KL Divergence” John Schulman’s Homepage 2020.

[3] Andriy Burkov. “Coding GRPO from Scratch: A Guide to Distributed Implementation with Qwen2.5-1.5B-Instruct” github 2025.