Training reasoning models with reinforcement learning
local graph
Chapter 6 — Training reasoning models with reinforcement learning
Section titled “Chapter 6 — Training reasoning models with reinforcement learning”Training reasoning models with reinforcement learning
This chapter covers
- The difference between reinforcement learning with human feedback and reinforcement learning with verifiable rewards
- Training reasoning LLMs as a reinforcement learning problem with task-correctness rewards
- Sampling multiple responses per prompt to compute group-relative learning signals
- Updating the LLM weights using group-based policy optimization for improved reasoning
Reasoning performance and answer accuracy can be improved both by increasing the inference compute budget and by using specific model-training methods. This chapter, as shown in figure 6.1, focuses on reinforcement learning (RL), the most commonly used training method for reasoning models.
We’ll first go through a general introduction to RL in the context of LLMs. Then we’ll discuss the two most common RL approaches used for LLMs.
graph LR
subgraph G1 ["1 - Conventional LLM"]
direction TB
A1["Loading pretrained weights"]
A2["Text generation"]
end
subgraph G2 ["2 - Evaluation"]
direction TB
B1["Benchmark-based evaluation"]
B2["Judgment-based evaluation"]
end
subgraph G3 ["3 - Inference techniques"]
direction TB
C1["Advanced text generation and voting"]
C2["Self-refinement"]
end
subgraph G4 ["4 - Training techniques"]
direction TB
D1["Reinforcement learning"]
D2["Distillation"]
end
G1 --> G2 --> G3 --> G4
[!visual-conversion] Figure 6.1 — A model of the topics covered in this book (printed p. 180, scan page-192.png). This chapter focuses on techniques that improve reasoning with additional training (stage 4). Specifically, this chapter covers reinforcement learning (RL). Stage 4 is highlighted in the print, annotated “This chapter focuses on reinforcement learning, a technique that can be used to improve reasoning behavior via training (changing the model weights).” Print stage headings: Stage 1: LLM basics (chapter 2) · Stage 2: Measuring performance (chapter 3) · Stage 3: Reasoning without training (chapters 4 and 5) · Stage 4: Reasoning with training (chapters 6 to 8).
6.1 Introduction to RL for LLMs
Section titled “6.1 Introduction to RL for LLMs”Inference-time scaling and training-time scaling are two distinct approaches for improving the reasoning performance of LLMs, as illustrated in figure 6.2. Inference-time scaling increases accuracy by spending more computation per generated answer, whereas training-time scaling improves accuracy by investing additional computation during training. This chapter focuses on training-time scaling.
While figure 6.2 presents inference-time scaling and training-time scaling as separate concepts, in practice they can be combined. For example, after improving a model’s reasoning capabilities through RL, which is the core focus of this chapter, inference-time-scaling techniques such as those introduced in chapters 4 and 5 can be applied to further boost performance.
RL focuses on how models learn from sequences of actions and their outcomes, with classic examples being agents trained to play chess, Go, or video games. While RL for LLMs builds on this research, it differs in important ways and often resembles familiar LLM-training techniques. Since this book focuses on language models, we will not cover RL in general but instead focus on how RL is applied in LLM training.
So what does RL mean for LLMs in practice? At a high level, RL is typically applied as a post-training stage on top of a pretrained language model, sometimes after instruction fine-tuning. This setup is illustrated in figure 6.3.
There are two common RL stages for LLMs: reasoning training and preference tuning. As shown in figure 6.3, RL is usually applied after instruction fine-tuning, and preference tuning often follows reasoning training.
Benchmark accuracy 100 | | | Inference-time scaling | Training (this chapter) 80 | (previous chapter) | | | * * 60 | # # # | * * * | # | * * 40 | # | * | # | * 20 | |* | | 0 +------------------------------------+--------------------------------- 10^0 10^1 10^2 10^0 10^1 10^2 Inference-time compute (log scale) Training-time compute (log scale)
Less expensive -------------------> More expensive
"Spending more resources during "Spending more resources for inference can result in better training can result in better accuracy." accuracy."[!visual-conversion] Figure 6.2 — Conceptual comparison of inference-time scaling and training-time scaling (printed p. 181, scan page-193.png). Increasing compute at inference improves accuracy by spending more resources per-answer generation, while increasing compute during training improves accuracy by investing more resources up front. The same two-panel layout as figure 4.2. The individual data-point values are not recoverable at scan resolution — the markers above indicate the rising trend only.
graph LR
P["Pretrained LLM"] --> I["Instruction fine-tuning"]
I --> R["Reinforcement learning (RL)"]
R --> RT["Reasoning training<br/>with RL, with verifiable<br/>rewards (RLVR)"]
R --> PT["Preference tuning<br/>with RL, with human<br/>feedback (RLHF)"]
[!visual-conversion] Figure 6.3 — Common training stages for LLMs (printed p. 181, scan page-193.png). The ordering of the reasoning training and preference-tuning stages can vary, and some pipelines interleave reasoning and preference tuning rather than strictly sequencing them. Print annotations: on instruction fine-tuning — “Train the LLM to follow basic instructions (e.g., ‘Summarize this text: …’)”; on RLVR — “Train the LLM on answer correctness for complex tasks (e.g., solve complex math or code problems)”; on RLHF — “Train the LLM on human preferences to prefer one answer type over another (e.g., prefer a clear answer over a rambling one).”
As the DeepSeek team demonstrated in its DeepSeek-R1 work, though, reasoning-focused RL can also be applied directly to the pretrained base model, skipping both instruction fine-tuning and preference tuning. The resulting model is generally weaker in reasoning accuracy than one that goes through the full training pipeline, but it still exhibits clear, robust reasoning behavior. More importantly, applying reasoning training directly to the base model avoids mixing the effects of multiple training stages, making it easier to attribute any observed improvements specifically to the reasoning training itself.
Before getting further into the details of how RL is implemented for LLMs, let’s briefly compare RL with pretraining at a conceptual level. During pretraining, an LLM is trained to predict the next token in large amounts of text, and many of the model’s core abilities and emergent behaviors (such as answering knowledge-based questions and following simple instructions) develop at this stage.
NOTE Pretraining is the main focus of my earlier book, Build a Large Language Model (From Scratch), but familiarity with that material is not required to follow this chapter or the rest of this book.
Applying RL on top of a pretrained model is attractive because it lets us optimize whole outputs, such as answer correctness or preferences, rather than individual tokens and next-token prediction. In this sense, pretraining mainly builds knowledge, while RL shapes how the model uses that knowledge, including its reasoning behavior.
As outlined in figure 6.4, the next two subsections provide a high-level overview of how RL is used in LLM training, and they set the context for the method we’ll use in the rest of this chapter.
6.1.1 The original RL pipeline with human feedback (RLHF)
Section titled “6.1.1 The original RL pipeline with human feedback (RLHF)”In 2022, the InstructGPT paper “Training language models to follow instructions with human feedback” (https://arxiv.org/abs/2203.02155) introduced reinforcement learning with human feedback (RLHF), a training approach that uses human preference labels to modify model behavior. In fact, RLHF was a key ingredient in turning GPT-3 into the original model used in ChatGPT, which arguably made LLMs broadly popular in 2022.
At a high level, RLHF is the most popular method for implementing the preference-tuning stage. Before RLHF, LLMs were primarily trained through pretraining and, in some cases, supervised fine-tuning, both of which are based on next-token prediction objectives. RLHF moves beyond this token-level optimization and instead optimizes models on whole outputs (in this case, RLHF optimizes for how humans rank and evaluate LLM outputs).
To make this more concrete, consider the following prompt: “I am looking to buy a laptop for programming and everyday use. What should I consider?”
The core part of this chapter is focused on implementing RLVR using the GRPO algorithm.
High-level introduction to reinforcement learning
Training techniques
Reinforcement learning
Distillation
Introduction to reinforcement learning (RL)
Reinforcement learning with human feedback (RLHF)
Reinforcement learning with verifiable rewards (RLVR)
RLVR with GRPO overview
Loading a pretrained LLM and training dataset
Implementing GRPO stages
Implementing a GRPO training loop
Loading and evaluating the trained model
A common step in LLM development that aligns the LLM with human preferences
A technique related to RLHF but focused on developing reasoning capabilities
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.4 — Road map of this chapter (printed p. 182, scan page-194.png). After this section’s brief introduction to RL for LLMs, we’ll discuss the difference between two RL stages, RLHF and RLVR. In the rest of the chapter, we’ll focus on implementing RLVR using the GRPO algorithm. The placeholder for this figure did not survive OCR and has been restored at its print location.
The model might generate two candidate responses:
- Response A: “You should consider the CPU, RAM, storage, GPU, screen resolution, battery life, keyboard quality, port selection, thermal design, and price.”
- Response B: “For programming and everyday use, focus on a fast CPU, at least 16 GB of RAM, and an SSD with at least 256 GB storage. A comfortable keyboard and good battery life also matter. A GPU may only matter if you plan to train small LLMs locally.”
Both responses mention relevant points, but a human data annotator might prefer response B because it is more concrete and specific to the use case stated in the prompt. In RLHF, such pairwise preferences are collected across many prompts and used to train the model to favor responses that humans consistently rank higher.
As shown in figure 6.5, RLHF has two main steps: (1) training a reward model (which is itself an LLM), and (2) using that reward model to score the target LLM outputs and fine-tune it.
Step 1 — Train a reward model
graph LR
P["Prompt:<br/>'Explain RLHF in a simple way'"] --> L["LLM"]
L --> A["A: 'RLHF is like giving an AI a thumbs up or...'"]
L --> B["B: 'First the model learns language from lots of text, then humans...'"]
L --> C["C: 'RLHF trains an AI by rewarding good behavior and discouraging...'"]
L --> D["D: 'Think of RLHF as coaching: the AI finds an answer...'"]
A --> R["Ranking: D > C > A > B"]
B --> R
C --> R
D --> R
R --> RM["Reward model<br/>(outputs a numeric score)"]
Step 2 — Use the reward model to calculate rewards and update the LLM
graph LR
Q["'Why do we need sleep?'"] --> L2["LLM to train"]
L2 --> S["Sample a response:<br/>'Sleep helps the brain organize...'"]
S --> RM2["Reward model"]
RM2 --> RS["Reward score"]
RS -->|"used inside an RL objective"| L2
[!visual-conversion] Figure 6.5 — A two-stage overview of reinforcement learning with human feedback (RLHF) (printed p. 184, scan page-196.png). First, a reward model is trained on human-ranked responses to assign a preference score to each. Second, the LLM is updated using these reward scores within an RL objective to encourage preferred responses and discourage less desirable ones. Print annotations: “Sample multiple responses from an input prompt (e.g., using temperature and top-p sampling from the previous chapter)”, “Humans rank the different responses by preference”, “Use ranked responses to train a reward model that outputs a numeric score”, “Score the response with the trained reward model”, and “Use a reward score inside an RL objective to compute a training signal that is used to update the model you want to train.”
The first step in RLHF is training a reward model, as illustrated in the top subpanel of figure 6.5. Here, we have the LLM generate multiple responses per prompt (for example, using the temperature scaling and top-p filtering approach explained in chapter 4) and ask human annotators to rank the answers from best to worst based on human preference.
These human preferences are converted into training targets for the reward model using a statistical preference model that maps pairwise comparisons to relative quality scores. The reward model, which is usually a separate model initialized from a pretrained LLM, is trained to output a single-number (scalar) reward score for each response that reflects its perceived quality. The idea is that the reward model can automatically score new model outputs, eliminating the need for human annotation at every training step.
The second step in RLHF trains the LLM on the reward scores the reward model assigns to its answers (for example, a bad answer may receive −2, and a good answer may receive +2).
We’re discussing RLHF here because it can be viewed as a precursor to reasoning-focused RL methods such as reinforcement learning with verifiable rewards (RLVR). While the source of the training signals for RLHF and RLVR differs, the underlying structure of the pipeline (generating responses, scoring them, and updating the model via RL) is closely related.
6.1.2 From human feedback to verifiable rewards
Section titled “6.1.2 From human feedback to verifiable rewards”RLHF can be fairly involved because it requires training an additional reward model, which is often a large LLM that is also expensive to train. Reinforcement learning with verifiable rewards (RLVR) simplifies this setup by replacing the LLM reward model with verifiable rewards, which are computed deterministically and without human annotation. For example, the math verifier introduced in chapter 3 is a verifiable reward generator for math problems. Given a math problem (and a correct solution), a math verifier automatically checks whether a generated solution’s final answer matches the ground truth and assigns a corresponding reward: 1 for a correct response and 0 for an incorrect one.
In RLVR, the two-step RLHF pipeline shown in figure 6.5 collapses into a single training loop that resembles step 2 in RLHF: the model generates responses, the verifier assigns rewards, and these rewards are used directly to update the model. This simplified RLVR training procedure is outlined in figure 6.6.
graph LR
Q["'What is the value of<br/>3 × (4 + 6) − 5?'"] --> L["LLM to train"]
L -->|"Samples a response"| A["'First compute the parentheses...<br/>So the answer is 25.'"]
A --> E["Extracted answer: '25'"]
REF["The correct reference answer"] --> V["Verifier"]
E --> V
V --> C["Correct / incorrect"]
C -->|"reward (correctness label) used inside an RL<br/>objective to compute a training signal"| L
[!visual-conversion] Figure 6.6 — Overview of RLVR (printed p. 185, scan page-197.png). The LLM generates a response that is evaluated by a deterministic verifier, such as the math verifier from chapter 3, which assigns a correctness label that’s used as a reward signal within an RL objective to update the model. Print annotation on the verifier: “Deterministic verifier that checks answer correctness (e.g., the math verifier we developed in chapter 3).”
The popularity of RLVR can largely be traced to the success of DeepSeek-R1 in 2025 (https://arxiv.org/abs/2501.12948), which demonstrated that strong reasoning performance can be achieved without relying on human preference data or a learned reward model. DeepSeek-R1 trained reasoning behavior by using automatically verifiable rewards, including correctness checks for math problems (similar to our verifier in chapter 3) and code compilation and execution for code-related tasks.
Code execution is outside the scope of this book because it would require training the LLM in a secure execution environment. That would mean compiling and running model-generated code inside an isolated sandbox so it cannot access the host system, private files, or external services in unsafe ways, making the setup considerably more complex than solving math problems. Either way, the idea behind verifying math tasks (checking whether an answer is correct as a binary label) and code compilation (checking whether code compiles, also as a binary label) is similar, and the RLVR training algorithm would be identical.
To summarize, RLVR offers several practical advantages over RLHF. First, it removes the need to train and maintain a separate reward model, which is often comparable in size and cost to the base LLM.
Second, RLVR requires access to reliable verification signals, which restricts it to certain domains, such as math and code. But verifiable rewards are deterministic and reproducible, meaning they produce the same result every time for the same output, which avoids the noise and inconsistency that arise in human preference annotations.
Finally, RLVR scales naturally to large training sets because, given a reference solution, rewards can be computed automatically for any number of model-generated answers without additional human labeling effort.
6.2 RLVR using GRPO
Section titled “6.2 RLVR using GRPO”Now that we’ve looked at the big picture and seen how RL fits within the overall development cycle of LLMs, we’ll turn to the implementation. Specifically, we’ll implement RLVR to train a reasoning model, as illustrated in the chapter road map in figure 6.7. This method is similar to DeepSeek-R1-Zero, but we’ll apply it at a much smaller scale, using a smaller model and less data, since a comparable full training run would require several hundred thousand dollars in GPU compute.
RLVR defines the overall training setup, namely, the use of automatically verifiable rewards. In addition, we need a concrete policy optimization algorithm that can be used within this RLVR framework to update the model weights and train the model.
The term “policy” is RL-specific jargon and refers, in this context, to the LLM we want to train. Specifically, we’ll use the Group Relative Policy Optimization (GRPO) algorithm for policy optimization. In short, RLVR determines what learning signal is available, and GRPO determines how that signal is used to update the model weights.
We now get to the core part of this chapter, which is about implementing RLVR using the GRPO algorithm.
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.7 — We’ve seen the two main RL approaches for LLMs, RLHF and RLVR (printed p. 187, scan page-199.png). The remaining sections of this chapter focus on implementing RLVR using the GRPO algorithm, from loading the dataset to implementing the full training loop. Steps 1 to 3 are ticked and step 4 is highlighted, annotated “We now get to the core part of this chapter, which is about implementing RLVR using the GRPO algorithm.”
Policy gradient algorithms
A widely used policy gradient algorithm for LLMs is Proximal Policy Optimization (PPO), which was popularized in RLHF. In principle, the same algorithm could also be applied in an RLVR setting.
When training the DeepSeek-R1 reasoning models, the DeepSeek team opted for a simpler alternative, GRPO, which was originally introduced in their “DeepSeekMath” paper (https://arxiv.org/abs/2402.03300). GRPO is more resource friendly than PPO because it doesn’t require a separate value model to estimate the value function. Instead, GRPO derives its learning signal from relative comparisons within a group of sampled responses, which substantially reduces computational overhead. If you’re interested, you can find a more detailed side-by-side comparison of PPO and GRPO in my article “The State of Reinforcement Learning for LLM Reasoning” (https://magazine.sebastianraschka.com/p/the-state-of-llm-reasoning-model-training).
(continued) In this chapter, we’ll focus on implementing RLVR using GRPO, much like what DeepSeek-R1 and other popular reasoning models use. In the next chapter, we’ll build on this foundation and introduce several practical extensions to GRPO that further improve training stability and reasoning performance.
6.2.1 High-level GRPO intuition via a chef analogy
Section titled “6.2.1 High-level GRPO intuition via a chef analogy”The technical details of the GRPO algorithm for RLVR can initially be a bit overwhelming because it has many moving parts and a lot of domain-specific RL terminology. So before we start with a technical overview and implementation, take a look at figure 6.8, which introduces the technical terms and approach of GRPO through the analogy of a chef preparing a meal.
graph TD
P["1 - Prompt<br/>Customer request (e.g., lasagna)"] --> R["2 - Rollouts<br/>Generate multiple recipes"]
R --> C["3 - Completions<br/>Serve multiple dishes"]
C --> RW["4 - Reward<br/>Get customer feedback"]
RW --> A["5 - Advantages<br/>Relative performance among dishes"]
C --> LP["6 - Logprobs<br/>Measure cooking style likelihood"]
LP --> RF["7 - Reference logprobs<br/>Check original cookbook"]
A --> PG["8 - Policy gradient loss<br/>Preference-based cooking adjustment"]
RF --> KL["9 - Kullback-Leibler (KL) loss term<br/>Style-preservation penalty"]
PG --> TL["10 - Total loss<br/>Overall cooking adjustment"]
KL --> TL
TL --> U["11 - Update cooking style<br/>Gradient-based model weight update"]
U --> P
[!visual-conversion] Figure 6.8 — Overview of the GRPO algorithm for RLVR using a chef analogy (printed p. 188, scan page-200.png). Multiple rollouts are generated and scored, relative advantages are computed, and a policy gradient objective with a KL-based regularization loss term is used to update the model parameters. Print annotations: “Content in boxes illustrates the GRPO algorithm for RLVR via a chef (cooking) analogy” and “The term next to each box represents the technical term used when implementing reinforcement learning algorithms like GRPO.”
Walking through the flowchart in figure 6.8, imagine we’re running a small food delivery service:
-
Each day, we receive a single customer request (the prompt) asking us to prepare a certain dish (for example, lasagna).
-
For that request, we cook our famous lasagna dish, but while doing so, we try out several different recipe variations (the rollouts).
-
After preparing the recipes, we create multiple dishes (completions). Note that in the LLM setting, a rollout refers to the entire generation process for a prompt, while a completion is the resulting output text. In practice, the two terms are often used interchangeably.
-
Customers only give us feedback (the reward) after tasting the entire dish, not while it is being prepared. This means we judge the final result as a whole rather than judging the individual cooking steps.
-
We compare how the dishes performed relative to each other based on the customer feedback from stage 4. This helps us identify which recipe variations received higher rewards and which received lower rewards for this particular request.
-
For each completed dish, we also keep track of how typical it was of our current cooking style, that is, how closely it followed our usual techniques and ingredient choices (logprobs).
-
Using relative feedback from stage 5 and how characteristic each dish was of our current cooking style from stage 6, we determine how to tweak the cooking style (policy gradient loss). Here, we want to reinforce choices that led to better dishes and reduce those that led to worse ones.
-
At the same time, we consult our original cookbook.
-
We then apply a style-preservation penalty that encourages trying new recipe variations but prevents overly drastic changes to our cooking style that could scare away existing customers.
-
The preference-based adjustment and the cooking style-preservation penalty are combined into a single overall measure, or overall loss, that determines how the cooking style should change. The goal is to balance customer satisfaction with consistency.
-
Finally, we update the cooking style (gradient-based model weight update) so that future dishes are more likely to satisfy customer preferences while remaining close to the original cookbook.
Even in this relatively basic analogy, GRPO still has lots of components and moving parts.
6.2.2 The high-level GRPO procedure
Following the chef analogy from the previous section, the flowchart in figure 6.9 provides a technical overview of the GRPO algorithm for RLVR, with concrete values that we will compute as we implement GRPO step by step.
Using temperature scaling and top-p filtering from chapter 4, we let the LLM generate different responses (rollouts) from a given prompt.
We compute the log probability (logprob) of each answer (rollout) as in the previous chapter.
We will compute the KL term in the next chapter.
We compute a correctness and format reward using the math verifier from chapter 3.
We compute the advantages from the list of reward values.
Prompt “Half the value of 3x - 9 is x + 37. What is the value of x? Write the final result in \boxed{}”
LLM to train
Logprobs
LLM to train
Reference LLM
Logprobs
Reference logprobs
-7.9243
-7.6128
-20.1546
-20.6031
-16.6130
-16.2687
-23.3677
-23.6049
Rollouts
Policy gradient loss
-2.5764
Total loss
-2.5839
We calculate loss gradient and update model weights.
We elementwise-multiply advantages and logprobs and average the resulting values to calculate the loss.
Prompt: “Half the value of 3x − 9 is x + 37. What is the value of x? Write the final result in \boxed{}”
| # | Rollout | Reward | Advantage | Logprob | Reference logprob |
|---|---|---|---|---|---|
| 1 | \boxed{83} | 1.0 | 0.8659 | −7.9243 | −7.6128 |
| 2 | ”…The correct answer is \boxed{83}” | 1.0 | 0.8659 | −20.1546 | −20.6031 |
| 3 | ”…The final answer is 83” | 0.0 | −0.8659 | −16.6130 | −16.2687 |
| 4 | ”…We get \boxed{38}” | 0.0 | −0.8659 | −23.3677 | −23.6049 |
| Loss component | Value |
|---|---|
| Policy gradient loss | −2.5764 |
| KL loss term | −0.0075 |
| Total loss | −2.5839 |
[!visual-conversion] Figure 6.9 — Step-by-step GRPO update for RLVR (printed p. 190, scan page-202.png). (1) A prompt is sampled and multiple rollouts are generated. (2) Each rollout is scored using a verifiable reward. (3) Group-relative advantages are computed from these rewards. (4) The log probability of each rollout under the current model is calculated. (5) Advantages and log probabilities are combined to form the policy gradient loss. (6) A KL regularization term against a reference model is added, and the resulting total loss is used to update the model parameters. Print annotations: “We compute the advantages from the list of reward values”, “We compute a correctness and format reward using the math verifier from chapter 3”, “Using temperature scaling and top-p filtering from chapter 4, we let the LLM generate different responses (rollouts) from a given prompt”, “We compute the log probability (logprob) of each answer (rollout) as in the previous chapter”, “We will compute the KL term in the next chapter”, “We elementwise-multiply advantages and logprobs and average the resulting values to calculate the loss”, and “We calculate loss gradient and update model weights.” All numeric values above are transcribed from the figure. Each rollout is scored using a verifiable reward. (3) Group-relative advantages are computed from these rewards. (4) The log probability of each rollout under the current model is calculated. (5) Advantages and log probabilities are combined to form the policy gradient loss. (6) A KL regularization term against a reference model is added, and the resulting total loss is used to update the model parameters.
The GRPO outline in figure 6.9 contains many technical components. We’ll start by implementing a simplified version of GRPO that omits the KL loss term shown on the right side of the figure. In chapter 7, we’ll add this missing KL loss term for completeness. The KL loss is part of the original GRPO formulation, but it is not strictly essential. Many LLM developers omit it in practice because doing so simplifies implementation and can sometimes improve modeling performance.
NOTE Readers experienced with GRPO or other policy gradient methods may wonder about the use of clipped policy ratios; we’ll cover them in the next chapter.
If the overview shown in figure 6.9 looks complicated, don’t worry. We will build up the algorithm step by step. For now, it’s best to treat figure 6.9 as a high-level road map that will help orient us as we work through the individual pieces.
6.3 Loading a pretrained model
Section titled “6.3 Loading a pretrained model”As in previous chapters, we’ll begin by loading the pretrained model (see stage 5 in figure 6.10), which we’ll then use to generate the rollouts (answers to a prompt) needed for GRPO.
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.10 — In stage 5, we load the pretrained model (this section) and dataset (next section) that we will use for the model training (printed p. 191, scan page-203.png). Steps 1 to 4 are ticked and step 5 is highlighted, annotated “As usual, we start with a pretrained model.”
The following listing shows the same code we’ve used previously for loading the tokenizer and base model.
Listing 6.1 Loading the tokenizer and base model
import torchfrom reasoning_from_scratch.ch02 import get_devicefrom reasoning_from_scratch.ch03 import ( load_model_and_tokenizer)device = get_device()device = torch.device("cpu") # Delete this line to run the code on a GPU (if supported by your machine).model, tokenizer = load_model_and_tokenizer( which_model="base", device=device, use_compile=False)Note that the preceding code runs on the CPU by default, to ensure you get results that are more consistent with those shown in this chapter. Once you have gone through this chapter in full, I recommend deleting the line device = torch.device("cpu") and running the chapter code on a GPU.
Next, to ensure that the model is loaded correctly, we’ll check it with the temperature and top-p sampler code from chapter 4 on a simple math prompt.
Listing 6.2 Generating text with temperature scaling and top-p sampling
from reasoning_from_scratch.ch03 import render_promptfrom reasoning_from_scratch.ch04 import ( generate_text_stream_concat_flex, generate_text_top_p_stream_cache)raw_prompt = ( "Half the value of $3x-9$ is $x+37$." "What is the value of $x$?")prompt = render_prompt(raw_prompt)torch.manual_seed(0)response = generate_text_stream_concat_flex( model, tokenizer, prompt, device, max_new_tokens=2048, verbose=True, generate_func=generate_text_top_p_stream_cache, temperature=0.9, top_p=0.9)print(response)The model prints “\boxed{58}”, which is an incorrect answer (83 is correct), but that’s okay because the goal here was merely to make sure that the code runs without issue.
6.4 Loading a MATH training subset
Section titled “6.4 Loading a MATH training subset”Next, we’ll load the dataset that we’ll use to train the model with GRPO. We’ll use a non-overlapping training subset derived from the original MATH dataset, which means that all MATH-500 evaluation problems are explicitly excluded from the training data. This prevents data leakage and ensures a clean separation between training and evaluation, as illustrated in figure 6.11.
NOTE For details on how this dataset was constructed, see https://github.com/rasbt/math_full_minus_math500.
graph TD
M["Mathematics Aptitude Test of Heuristics (MATH) dataset<br/>12,500 math problems"] --> T["MATH test set ('MATH-500')<br/>500 math problems"]
M --> R["MATH training set<br/>12,000 math problems"]
[!visual-conversion] Figure 6.11 — Structure and split of the MATH dataset (printed p. 193, scan page-205.png). The full dataset contains about 12,500 problems divided into a 500-problem test set (MATH-500), which we used for model evaluation in chapter 3. A non-overlapping set of 12,000 problems is used for training in this chapter. Print annotations: “In chapter 3, we used the MATH-500 dataset for model evaluation”, “In this chapter, we use 12,000 math problems, which don’t overlap with MATH-500, for model training”, and, beside a panel of raw JSON records, “Example problems in MATH to illustrate the structure of the dataset”.
To load the 12,000 math problems from the MATH training set shown in figure 6.11, we’ll define the following load_math_train function. It is similar to the load_math500_test function in chapter 3 except that we specify a different file path.
Listing 6.3 Loading the MATH training set
import jsonimport requestsfrom pathlib import Path
def load_math_train(local_path="math_train.json", save_copy=True): local_path = Path(local_path)
<!-- page: 206 (printed 194) -->url = ( "https://raw.githubusercontent.com/rasbt/", "math_full_minus_math500/refs/heads/main/", "math_full_minus_math500.json")backup_url = ( "https://f001.backblaze2.com/file/reasoning-from-scratch/", "MATH/math_full_minus_math500.json")
if local_path.exists(): with local_path.open("r", encoding="utf-8") as f: data = json.load(f)else: try: r = requests.get(url, timeout=30) r.raise_for_status() except requests.RequestException: print("Using backup URL.") r = requests.get(backup_url, timeout=30) r.raise_for_status()
data = r.json()
if save_copy: with local_path.open("w", encoding="utf-8") as f: json.dump(data, f, indent=2)
return data
math_train = load_math_train()print("Dataset size:", len(math_train))The preceding code should print “Dataset size: 12000” to indicate that the dataset was loaded correctly.
Next, we can print one of the 12,000 entries to get an idea of the dataset structure. For this, we’ll use the pprint function from the pprint standard library because it provides nicer formatting for dictionary entries than the regular print function:
from pprint import pprintpprint(math_train[4])This is the resulting entry (index 4 corresponds to the fifth entry in the dataset):
{ "answer": "6", "level": "Level 3", "problem": ( "Sam is hired for a 20-day period. On days that he " "works, he earns $\$60$. For each day that he does " "not work, $\$30$ is subtracted from his earnings. " "At the end of the 20-day period, he received " "$\$660$. How many days did he not work?" ), "solution": (“Call the number of days Sam works and the ” “number of days he does not… Thus, Sam did not ” “work for days.”
}, “type”: “Algebra”, “unique_id”: 4,
As you can see, each dataset example is stored as a dictionary with several fields. For training, the relevant fields are “problem”, which serves as the prompt, and “answer”, which is the target against which we verify the model’s output using the math verifier.
The dataset also includes a full worked solution in the “solution” field. While such step-by-step solutions could in principle be used to evaluate intermediate reasoning steps, doing so would unnecessarily constrain the model and risk overfitting to a specific solution and style. Instead, we want to allow the model to explore the solution space more freely.
6.5 Sampling rollouts
Section titled “6.5 Sampling rollouts”Now that we’ve set up the pretrained base model and loaded the dataset, we are ready to implement the GRPO stages, as illustrated in figure 6.12.
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.12 — This and the following sections implement the GRPO stages needed to train the LLM via verifiable rewards on the MATH dataset (printed p. 195, scan page-207.png). Steps 1 to 5 are ticked and step 6 is highlighted, annotated “In this section, we begin implementing the individual stages of the GRPO algorithm.”
Figure 6.13 revisits the GRPO overview we introduced earlier in a simplified form that omits the KL loss term, short for Kullback-Leibler divergence loss. We’ll add it in the next chapter. We can think of the KL loss as a penalty term that discourages the updated model from drifting too far from a reference model. Figure 6.13 will serve as a simplified road map that we can refer to as we step through the algorithm’s components.
graph TD
P["1 - Prompt<br/>'Half the value of 3x − 9 is x + 37.<br/>What is the value of x?<br/>Write the final result in \\boxed{}'"] --> L["LLM to train"]
L --> R["Rollouts"]
R --> RW["2 - Rewards"]
RW --> A["3 - Advantages"]
R --> LG["4 - Logprobs"]
A --> PG["5 - Policy gradient loss: −2.5764"]
LG --> PG
PG --> U["6 - Calculate the loss gradient<br/>and update the model weights"]
| # | Rollout | Reward | Advantage | Logprob |
|---|---|---|---|---|
| 1 | \boxed{83} | 1.0 | 0.8659 | −7.9243 |
| 2 | ”…The correct answer is \boxed{83}” | 1.0 | 0.8659 | −20.1546 |
| 3 | ”…The final answer is 83” | 0.0 | −0.8659 | −16.6130 |
| 4 | ”…We get \boxed{38}” | 0.0 | −0.8659 | −23.3677 |
[!visual-conversion] Figure 6.13 — Step-by-step GRPO update for RLVR, without the KL loss term (printed p. 196, scan page-208.png). We’ll begin by prompting the LLM to generate different rollouts. This is the simplified form of figure 6.9: it omits the Kullback-Leibler divergence loss, which is added in the next chapter. Stage 1 is highlighted, annotated “In this first GRPO stage, we pass the prompt to the LLM and let it generate different rollouts (answers).” All numeric values are transcribed from the figure. In this first GRPO stage, we pass the prompt to the LLM and let it generate different rollouts (answers).
As shown in figure 6.13, we’ll first use the LLM to generate multiple rollouts. Here, rollout is an RL term that simply refers to a complete answer generated by the model for a given prompt.
We could reuse the generate_text_stream_concat_flex function from listing 6.2 to generate the rollouts. When we defined that function earlier, though, we decorated it with @inference_mode, which disables several PyTorch features for efficiency. Since we will later perform a backward pass, @inference_mode makes the function incompatible with our training setup. (Here, “backward pass” refers to the step where PyTorch computes gradients from the loss so that the optimizer can update the model weights.) Instead, we need the @torch.no_grad decorator, which disables gradient tracking during the forward pass without switching PyTorch into inference-only mode.
Let’s rewrite the function in a more compact form and call it sample_response. This function will generate the same text as generate_text_stream_concat_flex(…, generate_func=generate_text_top_p_stream_cache). We can verify this by observing that, with the same random_seed, temperature, and top_p settings, both functions produce identical responses.
Listing 6.4 Defining the rollout generation function
from reasoning_from_scratch.qwen3 import KVCachefrom reasoning_from_scratch.ch04 import top_p_filter
@torch.no_grad()def sample_response( model, tokenizer, prompt, device, max_new_tokens=512, temperature=0.8, top_p=0.9,): input_ids = torch.tensor( tokenizer.encode(prompt), device=device )
cache = KVCache(n_layers=model.cfg["n_layers"]) # Cache past keys and values for efficient generation as introduced in chapter 2. model.reset_kv_cache() logits = model(input_ids.unsqueeze(0), cache=cache)[:,-1]
generated = [] for _ in range(max_new_tokens): if temperature and temperature != 1.0: # Apply temperature scaling from chapter 4. logits = logits / temperature
probas = torch.softmax(logits, dim=-1) probas = top_p_filter(probas, top_p) # Apply top-p filter from chapter 4. next_token = torch.multinomial( probas.cpu(), num_samples=1 ).to(device)
token_id = next_token.item() generated.append(token_id)
if ( tokenizer.eos_token_id is not None and token_id == tokenizer.eos_token_id
<!-- page: 210 (printed 198) --> ): break
logits = model(next_token, cache=cache)[: , -1]
full_token_ids = torch.cat( [input_ids, torch.tensor(generated, device=device, dtype=input_ids.dtype),] ) return full_token_ids, input_ids.numel(), tokenizer.decode(generated)Note that the function now also returns the token IDs of the prompt plus answer tokens, the number of tokens (input_ids.numel()), and the answer text (tokenizer .decode(generated)). Returning these will allow us to simplify several downstream functions later on.
Otherwise, there is nothing new here. The code is simply a leaner version of what we developed previously; it combines the generate_text_basic_stream_cache function from chapter 2 directly with temperature and top-p sampling from chapter 4.
Next, we’ll call the function on an example prompt, similar to listing 6.2.
Listing 6.5 Generating rollouts with temperature scaling and top-p sampling
torch.manual_seed(0)
raw_prompt = ( "Half the value of $3x-9$ is $x+37$." "What is the value of $x$?")
prompt = render_prompt(raw_prompt)
token_ids, prompt_len, answer_text = sample_response( model=model, tokenizer=tokenizer, prompt=prompt, device=device, max_new_tokens=512, temperature=0.9, top_p=0.9,)
print(answer_text)Previously, the generate_text_stream_concat_flex sampling function returned “\boxed{58}”. Now the sample_response function explicitly includes the end-of-sequence token in its response: “\boxed{58}<|endoftext|>”. Including this <|endoftext|> token is not strictly necessary, but it prevents the model from unlearning how to generate end-of-sequence tokens during very long training runs.
We could call sample_response multiple times to generate different rollouts, and we will do this later when implementing the full training loop. To keep this GRPO walkthrough example simple and make it easier to follow the step-by-step GRPO outline in figure 6.13, we’ll instead assume that the model produced the following four short responses:
rollouts = [ r"\boxed{83}", r"The correct answer is \boxed{83}", r"The final answer is 83", r"We get \boxed{38}",]6.6 Calculating rewards
Section titled “6.6 Calculating rewards”The second stage of the GRPO procedure involves computing rewards for each rollout, as shown in figure 6.14.
In this second GRPO stage, we calculate the rewards based on the answer correctness and \boxed{} format requirements.
graph TD
P["1 - Prompt<br/>'Half the value of 3x − 9 is x + 37.<br/>What is the value of x?<br/>Write the final result in \\boxed{}'"] --> L["LLM to train"]
L --> R["Rollouts"]
R --> RW["2 - Rewards"]
RW --> A["3 - Advantages"]
R --> LG["4 - Logprobs"]
A --> PG["5 - Policy gradient loss: −2.5764"]
LG --> PG
PG --> U["6 - Calculate the loss gradient<br/>and update the model weights"]
| # | Rollout | Reward | Advantage | Logprob |
|---|---|---|---|---|
| 1 | \boxed{83} | 1.0 | 0.8659 | −7.9243 |
| 2 | ”…The correct answer is \boxed{83}” | 1.0 | 0.8659 | −20.1546 |
| 3 | ”…The final answer is 83” | 0.0 | −0.8659 | −16.6130 |
| 4 | ”…We get \boxed{38}” | 0.0 | −0.8659 | −23.3677 |
[!visual-conversion] Figure 6.14 — The second stage in the GRPO pipeline computes the rewards for each rollout that the LLM generated in the first stage (printed p. 199, scan page-211.png). Stage 1 is ticked and stage 2 is highlighted, annotated “In this second GRPO stage, we calculate the rewards based on the answer correctness and \boxed{} format requirements.” Rollouts 1 and 2 receive a reward of 1.0; rollouts 3 and 4 receive 0.0, since rollout 3 omits the
\boxed{}wrapper and rollout 4 gives the wrong value.
The rewards are computed using the math verifier from chapter 3, and they’re primarily based on answer correctness. By setting fallback=None in the reward_rlvr function in the following listing, we also include an implicit format constraint. For instance, an answer only receives a reward of 1.0 if it is both correct and expressed in the required \boxed{} format.
Listing 6.6 Implementing the reward function
from reasoning_from_scratch.ch03 import ( extract_final_candidate, grade_answer)
def reward_rlvr(answer_text, ground_truth): extracted = extract_final_candidate( answer_text, fallback=None ) if not extracted: return 0.0 correct = grade_answer(extracted, ground_truth) return float(correct)Since the model receives a nonzero reward only if it answers correctly and writes the final answer in the \boxed{} format, we encourage it to learn to produce correct and properly formatted answers.
Let’s give the reward_rlvr function a try and apply it to the rollouts.
Listing 6.7 Applying the reward function to all rollouts
rollout_rewards = []
for answer in rollouts: reward = reward_rlvr(answer_text=answer, ground_truth="83") print(f"Answer: {answer!r}") print(f"Reward: {reward}\n") rollout_rewards.append(reward)The resulting outputs are as follows:
Answer: ‘\boxed{83}’ Reward: 1.0
Answer: ‘The correct answer is \boxed{83}’ Reward: 1.0
Answer: ‘The final answer is 83’ Reward: 0.0
Answer: ‘We get \boxed{38}’ Reward: 0.0
As you can see, the reward function works as intended and only provides a reward 1.0 if the answer contains the correct result (83) and uses the \boxed{} format.
Note that the DeepSeek-R1 team also tried to use process reward models to score intermediate solution steps during training. These attempts were unsuccessful, and the researchers concluded that it is better to train only on final-answer correctness rewards, without intermediate rewards.
Exercise 6.1: Adding format-aware reward shaping
Extend the reward_rlvr function from this chapter so that it assigns partial credit based on output format. Specifically, modify the reward function so that it returns 1.0 if the model produces the correct answer in the required \boxed{} format, 0.5 if the answer is correct but not boxed, and 0.0 otherwise.
6.7 Preparing learning signals from rollouts via advantages
Section titled “6.7 Preparing learning signals from rollouts via advantages”We’ll now move on from rewards to the so-called advantages, as shown in figure 6.15. While rewards tell us how well each individual rollout performed, advantages capture how a rollout performed relative to other rollouts generated for the same prompt.
The advantage values shown in figure 6.15 are computed by a simple formula:
Here
- denotes the reward of the th rollout.
- is the mean reward across the group of rollouts.
- is the corresponding standard deviation.
- is a small constant added for numerical stability to avoid division-by-zero errors.
In code, we can implement the advantage calculation as follows.
Listing 6.8 Calculating advantages
rewards = torch.tensor(rollout_rewards, device=device)advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4)print(rewards)print(advantages)The rewards, which we computed in the previous section, are [1., 1., 0., 0.], and the corresponding advantages are [0.8659, 0.8659, -0.8659, -0.8659]. These advantage values capture which responses performed better than average and which performed worse than average within the group.
In this third GRPO stage, we calculate the advantages based on the rewards.
Prompt “Half the value of 3x - 9 is x + 37. What is the value of x? Write the final result in \boxed{}”
LLM to train
Logprobs
Advantages Rewards
0.8659 ← 1.0 ← “boxed(83)” → -7.9243
0.8659 ← 1.0 ← ”…The correct answer is \boxed{83}” → -20.1546
-0.8659 ← 0.0 ← ”…The final answer is 83” → -16.6130
-0.8659 ← 0.0 ← ”…We get \boxed{38}” → -23.3677
Rollouts
Policy gradient loss -2.5764
Calculate the loss gradient and update the model weights.
Figure 6.15 The third GRPO stage computes the advantage values from the correctness rewards for the answers (rollouts).
NOTE The “GR” (group relative) in GRPO refers to the fact that GRPO generates multiple answers (rollouts) per prompt and compares them relative to each other to construct a learning signal.
You might still wonder what the point of converting rewards into advantages is. At a practical level, the advantage values directly scale the gradients during the policy update. If the advantage is positive, the gradient increases the likelihood of the actions that produced that rollout. If it is negative, the gradient decreases their likelihood. Rollouts with advantages close to zero contribute very little.
Exercise 6.2: Zero-advantage cases Modify the rollout rewards so that all rollouts receive the same reward (for example force all rewards to 0.0 or all to 1.0). Run the advantage computation and verify that the resulting GRPO loss is zero. Why is this behavior desirable in Group Relative Policy Optimization?
6.8 Scoring rollouts with sequence log probabilities
Section titled “6.8 Scoring rollouts with sequence log probabilities”We calculated the rewards and then the advantages from them. Now we’ll take a separate branch from the rollouts and compute their log probabilities (logprobs), as shown in figure 6.16. Logprobs measure how likely the model considers each generated token to be under its current parameters, as discussed in the previous chapter.
graph TD
P["1 - Prompt<br/>'Half the value of 3x − 9 is x + 37.<br/>What is the value of x?<br/>Write the final result in \\boxed{}'"] --> L["LLM to train"]
L --> R["Rollouts"]
R --> RW["2 - Rewards"]
RW --> A["3 - Advantages"]
R --> LG["4 - Logprobs"]
A --> PG["5 - Policy gradient loss: −2.5764"]
LG --> PG
PG --> U["6 - Calculate the loss gradient<br/>and update the model weights"]
| # | Rollout | Reward | Advantage | Logprob |
|---|---|---|---|---|
| 1 | \boxed{83} | 1.0 | 0.8659 | −7.9243 |
| 2 | ”…The correct answer is \boxed{83}” | 1.0 | 0.8659 | −20.1546 |
| 3 | ”…The final answer is 83” | 0.0 | −0.8659 | −16.6130 |
| 4 | ”…We get \boxed{38}” | 0.0 | −0.8659 | −23.3677 |
[!visual-conversion] Figure 6.16 — The fourth stage in the GRPO pipeline computes log probabilities for each rollout (printed p. 203, scan page-215.png). It is related to the logprob scorer we developed in the previous chapter. Stages 1 to 3 are ticked and stage 4 is highlighted, annotated “In this fourth GRPO stage, score the rollouts using log probabilities (logprobs).” related to the logprob scorer we developed in the previous chapter.
As shown in figure 6.16, these logprobs, together with the advantages, form the core ingredients of the GRPO policy gradient loss, which we will implement later on.
In the previous chapter (listing 5.8), we implemented an avg_logprob_answer function that computes per-token logprobs for the model’s answer tokens. These values are obtained by evaluating the likelihood the model assigns to each generated token under its current parameters.
When averaged across the response, these values are often referred to as token-level logprobs and are commonly used for scoring LLM outputs. Averaging is preferred in this context because it provides length normalization, which makes the scores comparable across responses of different lengths.
Mathematical definition of token-level log probabilities
Section titled “Mathematical definition of token-level log probabilities”Mathematically, the token-level logprobs we computed in the previous chapter can be written as
Here
- denote the tokens in the generated response of length .
- represents all previously generated tokens.
- is the input prompt.
- denotes the model’s weight parameters.
This expression is mathematically identical to the one used in the previous chapter; we simply switch from to to distinguish the generated output tokens from the input prompt.
The avg_logprob_answer function from listing 5.8 is repeated and used here to compute the logprobs for the previous prompt and answer_text for illustration.
Listing 6.9 Computing token-level log probabilities (similar to chapter 5)
Section titled “Listing 6.9 Computing token-level log probabilities (similar to chapter 5)”@torch.inference_mode()def avg_logprob_answer(model, tokenizer, prompt, answer, device="cpu"): prompt_ids = tokenizer.encode(prompt) answer_ids = tokenizer.encode(answer) full_ids = torch.tensor(prompt_ids + answer_ids, device=device)
logits = model(full_ids.unsqueeze(0)).squeeze(0) logprobs = torch.log_softmax(logits, dim=-1)
start = len(prompt_ids) - 1 end = full_ids.shape[0] - 1
<!-- page: 217 (printed 205) --> t_idx = torch.arange(start, end, device=device) next_tokens = full_ids[start + 1 : end + 1] next_token_logps = logprobs[t_idx, next_tokens]
return torch.mean(next_token_logps).item()avg_logprob_val = avg_logprob_answer( model, tokenizer, prompt=prompt, answer=answer_text, device=device)print(avg_logprob_val)This returns -0.061279296875.
In GRPO, we do not use averaged token-level logprobs. Instead, we work with sequence-level logprobs. That’s because GRPO assigns a single reward and advantage to each rollout, which applies to the entire generated response. Intuitively, logprob should reflect how likely the model was to generate the whole sequence, not an average per token.
We compute sequence-level logprobs by summing the logprobs of all generated tokens. (This sum corresponds to the log likelihood of producing the full response under the current model parameters.) In contrast, averaging token-level logprobs normalizes by sequence length. While this normalization is useful for scoring and comparing responses of different lengths, it would unintentionally rescale the learning signal in policy optimization and cause longer and shorter responses to contribute unevenly to the update. That kind of length-based rescaling is not part of the original GRPO formulation, which instead uses sequence-level logprobs for the whole rollout. We will revisit token-level logprobs in the next chapter when improving the algorithm.
We can convert the token-level, length-normalized score into a sequence-level logprob by dropping the averaging step and replacing torch.mean(next_token_logps) with torch.sum(next_token_logps) in the code in listing 6.9.
The same result can also be obtained by multiplying the averaged logprob by the number of answer tokens, as long as the token count matches exactly:
sequence_logprob_val = avg_logprob_val * ( len(tokenizer.encode(answer_text)))print(sequence_logprob_val)This now returns -16.239013671875.
These sequence-level logprobs scale linearly with the sequence length , which means that longer responses generally receive more negative logprob values. As a result, for two equally good answers, the optimization implicitly favors the shorter one, since it is cheaper in terms of likelihood. Summed logprobs therefore encourage the model to stop earlier unless producing a longer response is justified by a higher reward.
So, as mentioned before, we can replace torch.mean with torch.sum in the function to obtain sequence-level logprobs. Because we ran the function in inference mode in the previous chapter using the @torch.inference_mode() decorator, we need to redefine it without the decorator so that PyTorch can track gradients.
In addition, because sample_response from listing 6.4 already returns the token_ids and prompt_len, we can simplify the implementation by dropping the explicit tokenization step and the construction of full_ids.
Listing 6.10 Computing sequence-level log probabilities
def sequence_logprob_draft(model, token_ids, prompt_len): logits = model(token_ids.unsqueeze(0)).squeeze(0).float() logprobs = torch.log_softmax(logits, dim=-1)
start = prompt_len - 1 end = token_ids.shape[0] - 1 t_idx = torch.arange(start, end, device=token_ids.device) next_tokens = token_ids[start + 1 : end + 1] next_token_logps = logprobs[t_idx, next_tokens]
return torch.sum(next_token_logps)
print(sequence_logprob_draft(model, token_ids, prompt_len))This produces the following output:
tensor(-16.2998, grad_fn=<SumBackward0>)The result is similar to the -16.2421875 we got earlier (the difference is due to floating-point behavior and rounding).
PyTorch internally builds a computation graph that records each differentiable operation applied to a tensor. The SumBackward0 entry shows that the summation of token log probabilities is part of this graph, which means gradients can propagate back through the sequence-level log probability to the model parameters.
This is exactly what we’ll need for policy optimization later, when we implement the training loop to update the model weights via a backward pass. The backward pass applies the backpropagation algorithm, which is the standard method used in deep learning to compute gradients and update neural network weights.
PyTorch computation graphs, gradients, and backpropagation
As the model produces an output, PyTorch records each mathematical operation that leads from the model parameters to that output. This record is called the computation graph. When we later run the backward pass, PyTorch uses this graph to perform backpropagation; that is, it computes gradients that describe how changes to the model’s parameters would affect the final result. If an operation is part of this g PyTorch can compute gradients through it during training.
Understanding PyTorch’s computation graphs is not required for this chapter, but can learn more, if you’re interested, in my tutorial at https://sebastianraschka.com teaching/pytorch-1h/#3-seeing-models-as-computation-graphs.
This draft implementation works, but we can simplify it a bit and make it more efficient for GPUs. In particular, we can avoid explicitly constructing index ranges and instead use torch.gather to directly select the logprob corresponding to the generated tokens. The following listing shows a more compact, optimized version of the same computation that produces identical results while being easier to read and faster to execute.
Listing 6.11 Optimized sequence-level log probabilities code
def sequence_logprob(model, token_ids, prompt_len): logits = model(token_ids.unsqueeze(0)).squeeze(0).float() logprobs = torch.log_softmax(logits, dim=-1) selected = logprobs[:-1].gather( 1, token_ids[1:].unsqueeze(-1) ).squeeze(-1) return torch.sum(selected[prompt_len - 1:])print(sequence_logprob(model, token_ids, prompt_len))Like the previous code, this returns tensor(-16.2998, grad_fn=
TIP We could compute these logprobs directly in the sample_response function, which would improve efficiency by avoiding calling model(…) twice, in both the sample_response and sequence_logprob functions.
Finally, with our robust and efficient sequence-level logprob function in place, we can calculate the respective logprobs of the four different rollouts.
Listing 6.12 Computing sequence-level log probabilities of all rollouts
rollouts = [ r"\boxed{83}", r"The correct answer is \boxed{83}", r"The final answer is 83", r"We get \boxed{38}",]
rollout_logs = []
for text in rollouts: token_ids = tokenizer.encode(prompt + " " + text) logprob = sequence_logprob(
model=model, token_ids=torch.tensor(token_ids, device=device), prompt_len=prompt_len,)
print(f"Answer: {text}")print(f"Logprob: {logprob.item():.4f}\n")
rollout_logs.append(logprob)This prints the following:
Answer: \boxed{83} Logprob: -7.9243
Answer: The correct answer is \boxed{83} Logprob: -20.1546
Answer: The final answer is 83 Logprob: -16.6130
Answer: We get \boxed{38} Logprob: -23.3677
As you can see, shorter and more concise answers receive higher (less negative) sequence-level logprobs than longer or more verbose responses. The exception is the last answer, which receives the lowest score. Note that this is the only answer that contains the incorrect numerical answer value (38 instead of 83), so this also makes intuitive sense.
Overall, this illustrates how summed logprobs naturally favor concise outputs, which is consistent with their role in GRPO when rewards and advantages are applied at the sequence level.
6.9 From advantages to policy updates via the GRPO loss
Section titled “6.9 From advantages to policy updates via the GRPO loss”We’ll now implement the fifth stage of the GRPO pipeline, where the previously computed advantages and logprobs are combined into a policy gradient loss. We’ll implement the subsequent weight update (stage 6) later as part of the training loop, as shown in figure 6.17.
First, we’ll convert the list of rollout logprobs from the previous section into a PyTorch tensor. Then, we’ll compute the policy gradient loss by multiplying each rollout’s sequence-level logprob by its corresponding advantage, taking the mean across rollouts, and applying a negative sign. Because PyTorch optimizers are defined to minimize a loss, objectives that are naturally written as maximization problems must be sign-flipped.
Listing 6.13 Computing the policy gradient loss
logs = torch.stack(rollout_logs) pg_loss =-(advantages.detach() * logs).mean()From advantages to policy updates via the GRPO loss
print(logps)print(pg_loss)
<!-- CODE-ANNOTATION: Figure 6.17 | A flowchart illustrating the fifth stage of the GRPO pipeline, showing the calculation of policy gradient loss from advantages and logprobs, and the subsequent model weight update. -->Figure 6.17 The fifth stage in the GRPO pipeline computes the policy gradient loss that we'll use to update the model. Stage 6, the model weight update, will be implemented later as part of the training loop.
This prints the following for the logprobs:
tensor([-7.9243, -20.1546, -16.6130, -23.3677],grad_fn=<StackBackward0>)The resulting policy gradient loss value is as follows:
tensor(-2.5764, grad_fn=<NegBackward0>)Note that we use .detach() on the advantages because they are treated as fixed learning signals during the policy update. This prevents gradients from flowing back through the advantage computation, ensuring that only the model parameters influencing the logprobs are updated.
In policy gradient methods, we want to maximize the advantage-weighted logprob of the rollouts, since higher log probabilities for high-advantage rollouts improve the policy. By multiplying this objective by -1, we convert the maximization problem into an equivalent minimization problem. Minimizing the negative objective produces the exact same parameter updates as maximizing the original one, while remaining compatible with PyTorch’s optimizer implementations.
Maximization vs. minimization
To illustrate sign flipping with a concrete example, suppose the objective we want to maximize is the simple scalar value .
Under the maximization view, a larger value is better, so 3 is preferable to 2. PyTorch optimizers minimize, so they would try to reduce this value, which is the opposite of what we want.
Now, suppose we flip the sign and define the loss as . Minimizing is now equivalent to maximizing . For instance, if decreases from -2 to -3, increases from 2 to 3.
Mathematical definition of the policy gradient loss
If you find it easier to follow the computations via mathematical notation, the policy gradient loss used in GRPO can be written as follows:
Here,
- denotes the number of rollouts.
- are the tokens of the -th generated response of length .
- represents all previously generated tokens in that response.
- is the corresponding input prompt.
- is the advantage of the full rollout.
The inner sum computes the sequence-level log probability of a rollout, while the outer average computes the advantage-weighted log probabilities across rollouts.
6.10 Putting everything together in a single GRPO function
Section titled “6.10 Putting everything together in a single GRPO function”We have now completed the most challenging parts of this chapter and wake, each GRPO stage in isolation. Next, we’ll combine the five GRPO stages shoure 6.18 into a single compute_grpo_loss function, which we’ll later use as pafull training loop. (Note that the term “stage” here refers to a conceptual corof the GRPO loss computation, based on how we stepped through the GR**ithm; it’s not a training step in the outer optimization loop.)
graph TD
P["1 - Prompt<br/>'Half the value of 3x − 9 is x + 37.<br/>What is the value of x?<br/>Write the final result in \\boxed{}'"] --> L["LLM to train"]
L --> R["Rollouts"]
R --> RW["2 - Rewards"]
RW --> A["3 - Advantages"]
R --> LG["4 - Logprobs"]
A --> PG["5 - Policy gradient loss: −2.5764"]
LG --> PG
PG --> U["6 - Calculate the loss gradient<br/>and update the model weights"]
| # | Rollout | Reward | Advantage | Logprob |
|---|---|---|---|---|
| 1 | \boxed{83} | 1.0 | 0.8659 | −7.9243 |
| 2 | ”…The correct answer is \boxed{83}” | 1.0 | 0.8659 | −20.1546 |
| 3 | ”…The final answer is 83” | 0.0 | −0.8659 | −16.6130 |
| 4 | ”…We get \boxed{38}” | 0.0 | −0.8659 | −23.3677 |
[!visual-conversion] Figure 6.18 — The complete GRPO workflow where (1) multiple rollouts are generated for a prompt, (2) they are assigned correctness rewards, (3) they are converted into group-relative advantages, and (4) they are combined with log probabilities to (5) compute the policy gradient loss (printed p. 211, scan page-223.png). The loss gradients (6) will be computed and used to update the model in the next section. Stages 1 to 5 are all ticked. Print annotations: “In this section, we code stages 1–5 into a single
compute_grpo_lossfunction that we can use for model training” and “This sixth stage, which calculates the loss gradient and updates model weights, will be added directly in the PyTorch training loop in the next section.” In this section, we code stages 1–5 into a single compute_grpo_loss function that we can use for model training.
The compute_grpo_loss function, which combines all the stages from figure 6.18 that we discussed previously, is shown in the following listing.
Listing 6.14 Combining all the GRPO stages
def compute_grpo_loss( model, tokenizer, example, device, num_rollouts=2, max_new_tokens=256, temperature=0.8, top_p=0.9,): assert num_rollouts >= 2 roll_logps, roll_rewards, samples = [], [], [] prompt = render_prompt(example["problem"])
was_training = model.training model.eval()
for _ in range(num_rollouts): token_ids, prompt_len, text = sample_response( model=model, tokenizer=tokenizer, prompt=prompt, device=device, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, )
reward = reward_rlvr(text, example["answer"]) logp = sequence_logprob(model, token_ids, prompt_len) roll_logps.append(logp) roll_rewards.append(reward) samples.append( { "text": text, "reward": reward, "gen_len": token_ids.numel() - prompt_len, } )
if was_training: model.train()
rewards = torch.tensor(roll_rewards, device=device) advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4) logps = torch.stack(roll_logps)Stage 1: Generate rollouts Stage 2.1: Compute rewards Stage 4.1: Compute logprobs Stage 2.2: Collect all rewards Stage 3: Compute advantages Stage 4.2: Collect all logprobs
pg_loss = -(advantages.detach() * logps).mean()loss = pg_loss # In the next chapter we add a KL term here
return { "loss": loss.item(), "pg_loss": pg_loss.item(), "rewards": roll_rewards, "advantages": advantages.detach().cpu().tolist(), "samples": samples, "loss_tensor": loss,}The compute_grpo_loss function is relatively self-explanatory because it follows same stages we implemented manually in the previous sections. Note, though, h after stage 1, the code proceeds directly to stages 2 and 4 rather than stages 3 and 4. This is purely an implementation choice that simplifies the code structure by avoiding multiple nested for loops while preserving the same logical sequence of operations.
Also note that the pg_loss (policy gradient loss) is identical to the overall loss in our examples. I intentionally omitted the KL loss term here; we’ll add it in chapter 7 for completeness. As discussed earlier, GRPO is often reported to perform better on math problems when the KL loss term is omitted, which is why we are adopting this simplified objective here.
Next, let’s try the new compute_grpo_loss function on an example from the MATH training dataset to ensure that it works. We’ll only sample a small number of roll-outs (num_rollouts=2) and generate a relatively small number of tokens (max_new_tokens=256) for testing purposes. It may still take several seconds for the function to return the results.
Listing 6.15 Computing GRPO stages on a MATH training example
torch.manual_seed(123)
stats = compute_grpo_loss( model=model, tokenizer=tokenizer, example=math_train[4], device=device, num_rollouts=2, max_new_tokens=256, temperature=0.8, top_p=0.9)
pprint(stats)The output is as follows:
{'advantages': [0.0, 0.0], 'loss': -0.0,
<!-- page: 226 (printed 214) --> 'loss_tensor': tensor(-0., grad_fn=<NegBackward0>), 'pg_loss': -0.0, 'rewards': [0.0, 0.0], 'samples': [{'gen_len': 256, 'reward': 0.0, 'text': ' 4\n' 'To solve the problem, let\'s break it down step by step' '...'}]}As you can see from the ‘rewards’ and ‘text’ entries in the ‘samples’ field, the model answers incorrectly. As discussed in section 6.4, a correct answer must include \boxed{6}. Since this condition is not met, the reward is zero, which in turn yields zero advantages and a zero loss. In this case, if we were training the model, the gradient would be zero and the model parameters would not be updated.
6.11 Implementing the GRPO training loop
Section titled “6.11 Implementing the GRPO training loop”We now have all the necessary components in place to implement the full GRPO training loop. In this final section of the chapter, we’ll bring everything together to train the model via RLVR using the GRPO algorithm, as illustrated in figure 6.19.
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.19 — We’ll now implement the training loop to update the model weights (printed p. 214, scan page-226.png). Steps 1 to 6 are ticked and step 7 is highlighted, annotated “So far, we have implemented the individual GRPO stages, which we combined in a
compute_grpo_lossfunction; now, we’ll use this function to train the model.”
The training loop consists of eight main stages, as shown in figure 6.20. A stages are standard components of a typical PyTorch training loop for dee works, including LLMs. The only stage specific to reasoning models is stage we compute the GRPO loss rather than the standard classification loss use other types of deep neural networks and in LLM pretraining.
graph TD
S1["1 - Initialize pretrained model and optimizer"] --> S2["2 - For each training step"]
S2 --> S3["3 - Reset loss gradients from previous step"]
S3 --> S4["4 - GRPO stages to calculate loss"]
S4 --> S5["5 - Backward pass to calculate loss gradients"]
S5 --> S6["6 - Update model weights using loss gradients"]
S6 --> S7["7 - Print reward, response length, and losses"]
S7 --> S8["8 - Save a model checkpoint"]
S8 --> S2
[!visual-conversion] Figure 6.20 — Outline of the training loop (printed p. 215, scan page-227.png). The overall structure follows a standard deep learning training loop. The key difference lies in how the loss is computed: instead of a standard supervised objective, the loss is obtained via the GRPO stages (stage 4). Print annotations: “Stages 1 to 3 are standard operations in a PyTorch training loop”, “Stages 5 and 6 are also standard when training deep neural networks in PyTorch”, and “Stages 7 and 8 are optional steps for tracking and saving the training progress.”
Before discussing the eight stages one by one, it’s helpful to first see how they are implemented in code. Listing 6.16 shows the full training loop illustrated in figure 6.20.
Listing 6.16 Implementing the RLVR training loop
import time
def train_rlvr_grpo( model,
<!-- page: 228 (printed 216) --> tokenizer, math_data, device, steps=None, num_rollouts=2, max_new_tokens=256, temperature=0.8, top_p=0.9, lr=1e-5, checkpoint_every=50, checkpoint_dir=".", csv_log_path=None,): if steps is None: steps = len(math_data)
optimizer = torch.optim.AdamW(model.parameters(), lr=lr) model.train() current_step = 0
if csv_log_path is None: timestamp = time.strftime("%Y%m%d_%H%M%S") csv_log_path = f"train_rlvr_grpo_metrics_{timestamp}.csv" csv_log_path = Path(csv_log_path)
try: for step in range(steps): # Stage 2: Iterate over training steps optimizer.zero_grad() # Stage 3: Reset loss gradient (best practice to do this at the beginning of each step)
current_step = step + 1 example = math_data[step % len(math_data)]
stats = compute_grpo_loss( # Stage 4: Calculate GRPO loss model=model, tokenizer=tokenizer, example=example, device=device, num_rollouts=num_rollouts, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, )
stats["loss_tensor"].backward() # Stage 5: Backward pass to calculate loss gradients torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) # Clip large gradients to improve training stability
optimizer.step() # Stage 6: Update model weights using loss gradients
<!-- page: 229 (printed 217) --> reward_avg = torch.tensor(stats["rewards"]).mean().item() step_tokens = sum( sample["gen_len"] for sample in stats["samples"] ) avg_response_len = ( step_tokens / len(stats["samples"]) if stats["samples"] else 0.0 ) append_csv_metrics( csv_log_path, current_step, steps, stats["loss"], reward_avg, avg_response_len, ) print( f"[Step {current_step}/{steps}] " f"loss={stats['loss']:.4f} " f"reward_avg={reward_avg:.3f} " f"avg_resp_len={avg_response_len:.1f}" )
if checkpoint_every and current_step % checkpoint_every == 0: ckpt_path = save_checkpoint( model=model, checkpoint_dir=checkpoint_dir, step=current_step, ) print(f"Saved checkpoint to {ckpt_path}")
except KeyboardInterrupt: ckpt_path = save_checkpoint( model=model, checkpoint_dir=checkpoint_dir, step=max(1, current_step), suffix="interrupt", ) print(f"\nKeyboardInterrupt. Saved checkpoint to {ckpt_path}") return model
return model
def save_checkpoint(model, checkpoint_dir, step, suffix=""): checkpoint_dir = Path(checkpoint_dir) checkpoint_dir.mkdir(parents=True, exist_ok=True) suffix = f"-{suffix}" if suffix else "" ckpt_path = ( checkpoint_dir / f"qwen3-0.6B-rlvr-grpo-step{step:05d}{suffix}.pth" ) torch.save(model.state_dict(), ckpt_path) return ckpt_path
def append_csv_metrics( # Utility function to save the results to a CSV file csv_log_path, step_idx, total_steps,
<!-- page: 230 (printed 218) --> loss, reward_avg, avg_response_len,): if not csv_log_path.exists(): csv_log_path.write_text( "step,total_steps,loss,reward_avg,avg_response_len\n", encoding="utf-8", ) with csv_log_path.open("a", encoding="utf-8") as f: f.write( f"{step_idx},{total_steps},{loss:.6f},{reward_avg:.6f}," f"{avg_response_len:.6f}\n" )This function implements the full RLVR training loop using GRPO. As mentioned earlier, except for stage 4 (the GRPO loss computation), the structure mirrors a conventional PyTorch training loop where we reset gradients, backpropagate a loss, optionally clip gradients, update parameters via an optimizer step, log metrics, and periodically save checkpoints. (We save the model checkpoints, which are snapshots of the model weights, so we can load, evaluate, and use them later, as we’ll discuss in the next section.)
TIP For a general introduction to training neural networks in PyTorch, see sections 3-8 of my “PyTorch in One Hour: From Tensors to Training Neural Networks on Multiple GPUs” article (https://sebastianraschka.com/teaching/pytorch-1h/).
The key difference here, compared with other standard training loops, is how the loss is constructed. Instead of a standard supervised objective, which is used for most neural networks, including classifiers and for pretraining LLMs, the training signal is computed via the GRPO algorithm as part of the RLVR procedure.
Let’s now run the code and train the model. Earlier, we hardcoded the PyTorch device to “cpu” so that all intermediate results closely match those shown in the book, since “mps” and “cuda” devices can introduce small floating-point differences. Training on a CPU is very slow, though.
For convenience, the following listing includes two lines that automatically select and activate the appropriate device before the train_rlvr_grpo() function call. For instance, it will automatically switch to “cuda” or “mps” simply by running the code in the following listing.
Listing 6.17 Training the model
device = get_device()model.to(device)
torch.manual_seed(0)
train_rlvr_grpo( model=model,
<!-- page: 231 (printed 219) --> tokenizer=tokenizer, math_data=math_train, device=device, steps=50, num_rollouts=4, max_new_tokens=512, temperature=0.8, top_p=0.9, lr=1e-5, checkpoint_every=5, checkpoint_dir=".",)Let’s briefly talk about these settings before we inspect the results. The temperature and top_p settings were set within a common range that encourages some diversity in the answers while still producing coherent text for this model. You can change these settings and see how they affect the results (commonly used ranges are 0.7-0.9).
The number of steps is relatively small, at 50, even though the dataset contains 12,000 entries. This is simply to keep the runtime reasonable, and it can be increased. Even with 50 steps, though, it is sufficient for good results.
The learning rate (lr) can be tweaked, but it is in a reasonable range and works well.
The number of rollouts (num_rollouts=4) and allowed tokens (max_new_tokens=512) are relatively small to reduce resource requirements. If you experience out-of-memory errors, you can further reduce these values, such as by setting num_rollouts=2 and max_new_tokens=64, for testing purposes.
With the current checkpoint_every=5 setting, the model is saved every 5 steps, and each checkpoint requires approximately 1.5 GB of disk space. For longer runs, I recommend setting this number to 50 or 100. Here, it is purposefully small for testing. Also note that an additional checkpoint should be created if the training run is manually interrupted, such as by interrupting the Jupyter notebook execution with the “Interrupt the kernel” button.
Let’s take a brief look at the run’s output (where I interrupted the 50-step run at step 7):
Using Apple Silicon GPU (MPS) [Step 1/50] loss=-0.0000 reward_avg=0.000 avg_resp_len=88.0 [Step 2/50] loss=-0.0000 reward_avg=0.000 avg_resp_len=7.5 [Step 3/50] loss=-0.0000 reward_avg=0.000 avg_resp_len=6.5 [Step 4/50] loss=0.0909 reward_avg=0.250 avg_resp_len=6.5 [Step 5/50] loss=1.1001 reward_avg=0.500 avg_resp_len=300.5 Saved checkpoint to qwen3-0.6B-rlvr-grpo-step00005.pth
KeyboardInterrupt. Saved checkpoint to qwen3-0.6B-rlvr-grpo-step00006-interrupt.pth
You can see that both the loss and reward values fluctuate, which is normal in RL training.
We’ve printed the average reward, which indicates the proportion of sampled responses that are correct. With our num_rollouts=4 setting, a reward_avg of 0.5 means that 2 of the 4 rollouts received a positive reward. Similarly, values of 0.25 and 0.0 indicate one or zero correct responses, respectively.
The loss values should not be over-interpreted. Steps with reward_avg=0.000 produce a near-zero loss because all rollouts receive the same reward, resulting in vanishing group-relative advantages and little to no gradient signal. Larger loss magnitudes, such as at step 3 (see row 4 in the preceding output), simply reflect bigger relative differences between rollouts and are typical for GRPO-style objectives, especially at the beginning of training.
Ideally, we want to see two main trends over time:
-
The average reward should increase when averaged over many steps, as the model learns to produce more accurate responses.
-
The reasoning accuracy should improve (we’ll evaluate this in the next section).
The online code for the book contains a slightly more sophisticated version of the script that also includes an option to evaluate the model periodically on subsets of the MATH-500 test dataset to see whether the model is improving on the target task: https://github.com/rasbt/reasoning-from-scratch/tree/main/ch06/02_rlvr_grpo_scripts_intro.
Batched training
RL can be relatively resource-intensive because we have to generate multiple (long) rollouts via the LLMs for each training step. For this reason, the implementation does not support batching.
If you have access to multiple GPUs, you can use the optional version of this code, with batch and multi-GPU support: https://github.com/rasbt/reasoning-from-scratch/tree/main/ch06/02_rlvr_grpo_scripts_intro. This version trains the model faster.
6.12 Loading and evaluating saved model checkpoints
Section titled “6.12 Loading and evaluating saved model checkpoints”Now we’ll discuss how to load the saved checkpoints from the RLVR training run in the previous section (see figure 6.21). We’ll also evaluate the model on the MATH-500 dataset.
The saved checkpoints can be loaded using the PyTorch state dict approach described in chapter 2, where model_path points to the corresponding .pth checkpoint file:
model.load_state_dict(torch.load("qwen3-0.6B-rlvr-grpo-step00050.pth"))Downloading RLVR checkpoints
If you prefer not to run the GRPO training loop locally because of its runtime cost, you can instead download my pretrained checkpoints. These can be fetched either manually or directly from Python using the following helper function, which downloads the selected checkpoint and makes it available for evaluation or further experimentation:
from reasoning_from_scratch.qwen3 import download_qwen3_grpo_checkpoints download_qwen3_grpo_checkpoints(grpo_type="no_kl", step="00050")Note that this checkpoint was created with settings similar to those in listing 6.17, except that num_rollouts=4 was changed to num_rollouts=8.
graph LR
T["Training techniques"] --> RL["Reinforcement learning"]
T --> DI["Distillation"]
RL --> S1["1 - Introduction to reinforcement learning (RL)"]
S1 --> S2["2 - Reinforcement learning with human feedback (RLHF)"]
S1 --> S3["3 - Reinforcement learning with verifiable rewards (RLVR)"]
S2 --> S4["4 - RLVR with GRPO overview"]
S3 --> S4
S4 --> S5["5 - Loading a pretrained LLM and training dataset"]
S5 --> S6["6 - Implementing GRPO stages"]
S6 --> S7["7 - Implementing GRPO training loop"]
S7 --> S8["8 - Loading and evaluating the trained model"]
[!visual-conversion] Figure 6.21 — Flowchart showing the stages of RLVR with GRPO (printed p. 221, scan page-233.png). All eight steps are complete: we introduced RL, compared RLHF and RLVR, worked through the GRPO stages one at a time, combined them into a single loss function, implemented the training loop, and loaded and evaluated the trained model. The next chapter extends GRPO with the KL loss term and other stability improvements.
These checkpoints are fully compatible with the model evaluation utilities introduced in chapter 3, which allow us to evaluate RL-trained models using the same MATH-500 verification pipeline.
For convenience, you can reuse the evaluation script provided in the chapter 3 bonus materials (https://github.com/rasbt/reasoning-from-scratch/blob/main/ ch03/02_math500-verifier-scripts/evaluate_math500.py) to run evaluations on the MATH-500 dataset by specifying the desired checkpoint path. For example, to evaluate the qwen3-0.6B-rlvr-grpo-step00050.pth checkpoint file, you can run the aforementioned script as follows:
uv run evaluate_math500.py
—dataset_size 500
—which_model base
—checkpoint_path “qwen3-0.6B-rlvr-grpo-step00050.pth”
(If you are not a uv user, replace uv run with python.)
Table 6.1 compares the original base and reasoning models (rows 1 and 2) to the base model we trained via GRPO in this chapter (rows 3–5).
Table 6.1 MATH-500 task accuracy for different base and reasoning models
| Method | Step | Max tokens | Num rollouts | Accuracy | Average tokens | |
|---|---|---|---|---|---|---|
| 1 | Base model (chapter 3) | - | - | - | 15.2% | 78.85 |
| 2 | Reasoning model (chapter 3) | - | - | - | 48.2% | 1369.79 |
| 3 | GRPO (this chapter) | 50 | 256 | 4 | 43.2% | 560.22 |
| 4 | GRPO (this chapter) | 50 | 512 | 4 | 45.6% | 579.81 |
| 5 | GRPO (this chapter) | 50 | 512 | 8 | 47.4% | 586.11 |
The accuracy column in table 6.1 refers to the accuracy on the full 500-sample MATH-500 dataset we used in chapter 3.
The max tokens column identifies the number of tokens allowed per rollout during training. If the number is 512, this encourages the LLM to provide the final boxed answer within that 512-token limit; otherwise, it will not receive a reward during training. The evaluation code was run with a maximum token limit of 2,048, allowing the LLM to generate longer responses during evaluation.
The average tokens column shows the average response length in the evaluation on the MATH-500 dataset. As you can see, compared to the reference reasoning model (row 2), our GRPO models generate shorter responses on average, as expected because of the token-length restriction during training.
Note that the DeepSeek-R1 team observed that responses grow longer over the course of training as the model begins to write intermediate (chain of thought) explanations. To maximize accuracy, it makes sense not to restrict token length too aggressively during training. Longer token lengths, especially when coupled with multiple rollouts, require more computational resources, which is why we capped them at a lower value in this chapter.
As shown in table 6.1, training the reasoning model via GRPO results in 47.4% accuracy (row 5), which is close to the accuracy of the official Qwen3 0.6B reasoning model on MATH-500. The model’s accuracy could be further improved by increasing the response length, sampling more rollouts per prompt, and training for additional
steps. The next chapter will introduce practical tips and techniques for monitoring and improving GRPO training outcomes.
We trained the model for only 50 steps, which already appears sufficient to unlock reasoning behavior in the base model. In my experiments, training for longer does not necessarily improve performance and can even reduce accuracy, since the original GRPO formulation can be unstable over longer runs.
It’s also worth keeping in mind that this chapter implemented a simplified GRPO variant without the KL regularization term. In the next chapter, we’ll return to the full GRPO objective, add the KL term back in, and discuss common improvements for making training more stable over longer runs.
If you’re interested, you can find and download additional checkpoints ranging from 50 to 9,000 at https://huggingface.co/rasbt/qwen3-from-scratch-grpo-checkpoints/tree/main/grpo_original_no_kl.
Summary
- Reinforcement learning (RL) can be used to train LLMs on human preference labels and verifiable rewards.
- RL is typically applied as post-training on top of a pretrained base model, and it can be inserted at different stages of an LLM pipeline, including reasoning training and preference tuning.
- RL with human feedback (RLHF) optimizes for human preferences via a two-stage setup: train a reward model from ranked responses, and then use reward scores to update the LLM.
- RL with verifiable rewards (RLVR) simplifies RLHF by replacing learned reward models with deterministic, automatically computed verifiers (for example, math answer checking).
- GRPO is a policy optimization algorithm that turns verifier rewards into parameter updates. Because GRPO directly optimizes the model using sequence-level rewards without requiring a separate value model, it is particularly convenient.
- GRPO is a more resource-friendly alternative to other RL algorithms for LLMs because it avoids training a separate value model and instead derives learning signals from comparisons within a group of sampled rollouts.
- A “rollout” refers to a full model answer (completion) for a prompt; rewards, advantages, and log probabilities are computed from the rollout in later steps.
- Rewards are computed by a verifier that grants a reward only if the final answer is both correct and extractable in a required format, like “\boxed{}”.
- Raw rewards are transformed into advantages by normalizing each rollout reward relative to the group mean and standard deviation.
- GRPO also relies on sequence-level log probabilities, which are computed by summing token log probabilities over the generated answer tokens.
- Sequence log probabilities, together with the advantages, form the core policy-gradient objective in GRPO.
- The full GRPO loss computation is combined into a single function that performs rollout sampling, reward computation, advantage calculation, log probability computation, and policy-gradient loss calculation.
- The surrounding training loop is a standard deep learning loop, with the key difference being that the loss comes from GRPO rather than conventional classification losses.
- Training is resource intensive because each step requires generating multiple, potentially long rollouts, but even short GRPO runs can increase MATH-500 accuracy from 15% to 47%.