Skip to content
ImagineWorld

Improving GRPO for reinforcement learning

node_idnode-book_build-a-reasoning-model_chapter-07-improving-grpo-for-reinforcement-learning
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleImproving GRPO for reinforcement learning
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 7 — Improving GRPO for reinforcement learning

Section titled “Chapter 7 — Improving GRPO for reinforcement learning”

Improving GRPO for reinforcement learning

This chapter covers

  • Interpreting training curves and evaluation metrics
  • Preventing the model from exploiting the reward signal
  • Extending task-correctness rewards with additional response-formatting rewards

Previously, we implemented the GRPO algorithm for reinforcement learning with verifiable rewards (RLVR) from end to end. Now, as shown in figure 7.1, we’ll pick up from that baseline and focus on what happens when we run longer training.

In particular, we’ll discuss which metrics are worth tracking (beyond reward and accuracy), how to spot failure modes early, and why training can become unstable even when the code is “correct.” As it turns out, basic GRPO can lead to training instability, so this chapter also introduces practical GRPO extensions and fixes that are used in reasoning-model training.

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 7.1 — A model of the topics covered in this book (printed p. 226, scan page-238.png). This chapter provides deeper coverage of the GRPO algorithm for reinforcement learning with verifiable rewards. Stage 4 is highlighted, annotated “This chapter follows up with a more detailed treatment of reinforcement learning, analyzing training results and suggesting improvements.” 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).

We implemented GRPO (Group Relative Policy Optimization) in the previous chapter; we’ll now revisit the training run and analyze it more thoroughly. We’ll also revisit the KL loss term that we omitted in the previous chapter and discuss some practical tips and algorithmic choices that become important in real training runs. These topics are summarized in the chapter overview in figure 7.2.

The examples in this chapter are based on actual experiments, but the results should be interpreted with care. To draw strong conclusions about the effect of individual settings, each experiment would need to be repeated multiple times and the results averaged, since randomness in sampling and optimization can lead to noticeable variation between runs. That said, the examples shown here are sufficient to illustrate the main ideas and the relevant tradeoffs.

NOTE This chapter focuses on additional technical details and practical considerations for using GRPO. If you find the content in this chapter too technical, you can move on, as the next chapter does not depend on it.

In chapter 6, we ran a short GRPO training loop and briefly examined the results. For example, the output of a short run was structured as follows:

[Step 1/50] loss=-0.0000 reward_avg=0.000 avg_resp_len=5.5 [Step 2/50] loss=-0.0000 reward_avg=0.000 avg_resp_len=6.8 [Step 3/50] loss=0.3592 reward_avg=0.250 avg_resp_len=7.8

[Step 4/50] loss=2.7401 reward_avg=0.250 avg_resp_len=56.5 [Step 5/50] loss=3.3214 reward_avg=0.500 avg_resp_len=251.2

…

Previously, we implemented a basic GRPO training pipeline.

Now, we’ll analyze the training results a bit more closely and make several modifications to the GRPO training code.

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.2 — A chapter overview showing the different topics covered in this chapter (printed p. 227, scan page-239.png). Print annotations: “Previously, we implemented a basic GRPO training pipeline” over the chapter-6 column, and “Now, we’ll analyze the training results a bit more closely and make several modifications to the GRPO training code” over this chapter’s six topics.

Let’s pick up from this point and discuss which metrics to track when training with GRPO, and how they can help interpret and debug training behavior.

7.2.1 Executing a GRPO training run

The code in chapter 6 was designed to strike a balance between implementing the complete GRPO pipeline and keeping the implementation compact enough to remain readable. For convenience, the book’s supplementary materials include an equivalent script that contains the same code and can be run from the terminal (more on this later): https://mng.bz/oZxN.

For each GRPO improvement introduced in this chapter, we’ll use related reference scripts from the supplementary materials to avoid duplicating large code blocks in the text. The helper function in listing 7.1 will download the relevant scripts from the supplementary materials and save them locally for you to use in this chapter. This will let us avoid repeating long code passages and keep the focus on the main changes in the GRPO implementations.

Listing 7.1 Helper function to download supplementary materials

from pathlib import Path
import requests
def download_from_github(rel_path, out=None):
github_raw_base = (
"https://raw.githubusercontent.com/rasbt/"
"reasoning-from-scratch/refs/heads/main/"
)
rel_path = Path(rel_path)
out = Path(out) if out is not None else Path(rel_path.name) # Base URL
if out.exists():
size_kb = out.stat().st_size / 1e3
print(f"{out}: {size_kb:.1f} KB (cached)")
return out # Use the URL filename as default output file name.
r = requests.get(github_raw_base + rel_path.as_posix()) # Skip the download if the file already exists locally.
r.raise_for_status()
out.write_bytes(r.content)
size_kb = out.stat().st_size / 1e3
print(f"{out}: {size_kb:.1f} KB") # Download the file.

Using the preceding helper function, you can download the script with the GRPO training code from chapter 6 as follows:

download_from_github(
"ch06/02_rlvr_grpo_scripts_intro/rlvr_grpo_original_no_kl.py"
)

You should see the following output: rlvr_grpo_original_no_kl.py: 13.4 KB. If the downloaded file is much smaller than the size listed here, the download may not have completed correctly. In that case, double-check the URLs and see the troubleshooting guide for additional suggestions: https://github.com/rasbt/reasoning-from-scratch/ blob/main/troubleshooting.md. The resulting script can be run from a terminal as shown in figure 7.3.

TIP It’s also possible to run the training script from a code cell in a Jupyter Notebook by prepending ”!”, that is, !uv run rlvr_grpo_original_no_kl.py. If you are not a uv user, replace the uv run shown in figure 7.3 with python, as follows:

python rlvr_grpo_original_no_kl.py
—steps 500
—max_new_tokens 1024

02_rlvr_grpo_scripts_intro — uv run rlvr_grpo_original_no_kl.py --steps 500 --max_new_tokens 1024...
02_rlvr_grpo_scripts_intro git:(main) × uv run rlvr_grpo_original_no_kl.py \
--steps 500 \
--max_new_tokens 1024
Uninstalled 1 package in 492ms
Installed 1 package in 152ms
Using Apple Silicon GPU (MPS)
✓ qwen3/qwen3-0.6B-base.pth already up-to-date
[Step 1/500] loss=-0.0000 reward_avg=0.000 tok/sec=13.3 avg_resp_len=6.4
[Step 2/500] loss=-0.3649 reward_avg=0.125 tok/sec=13.7 avg_resp_len=6.6
[Step 3/500] loss=-10.0437 reward_avg=0.125 tok/sec=32.2 avg_resp_len=33.6
[Step 4/500] loss=-0.0000 reward_avg=0.000 tok/sec=10.0 avg_resp_len=2.8
[Step 5/500] loss=-0.0000 reward_avg=0.000 tok/sec=35.8 avg_resp_len=95.8
[Step 6/500] loss=6.6892 reward_avg=0.500 tok/sec=36.5 avg_resp_len=257.9
[Step 7/500] loss=-0.0000 reward_avg=0.000 tok/sec=31.7 avg_resp_len=697.1
[Step 8/500] loss=4.7342 reward_avg=0.625 tok/sec=33.2 avg_resp_len=124.5
[Step 9/500] loss=-0.0000 reward_avg=0.000 tok/sec=22.5 avg_resp_len=577.0
[Step 10/500] loss=-0.0000 reward_avg=0.000 tok/sec=33.9 avg_resp_len=378.4
[Step 11/500] loss=-0.0000 reward_avg=1.000 tok/sec=25.1 avg_resp_len=227.1
[Step 12/500] loss=-0.0000 reward_avg=0.000 tok/sec=34.6 avg_resp_len=342.1
[Step 13/500] loss=-0.0000 reward_avg=0.000 tok/sec=30.2 avg_resp_len=196.8
[Step 14/500] loss=-0.0000 reward_avg=1.000 tok/sec=36.5 avg_resp_len=235.2
[Step 15/500] loss=-0.0000 reward_avg=1.000 tok/sec=29.3 avg_resp_len=170.9
[Step 16/500] loss=-0.0000 reward_avg=1.000 tok/sec=30.8 avg_resp_len=270.1

[!visual-conversion] Figure 7.3 — Output from a GRPO training run in a terminal, showing several training statistics, such as loss, average reward, tokens/sec throughput, and average response length (printed p. 229, scan page-241.png). The print is a terminal screenshot; its session is transcribed verbatim in the ```text block above rather than embedded as a raster. The placeholder for this figure did not survive OCR and has been restored at its print location.

TIP You can add —show_eta to the preceding code execution command to show an estimate of the script’s total runtime on your machine.

If you prefer not to run the training code yourself, which is reasonable given its computational cost, the supplementary materials provide log files from this run. You can download them as follows:

download_from_github( "ch07/02_logs/ch06_rlvr_grpo_original_no_kl_metrics.txt" ) download_from_github( "ch07/02_logs/ch06_rlvr_grpo_original_no_kl_metrics.csv" )

The first file, ending in .txt, is the plain output file that shows output statistics similar to those in figure 7.3. The second file, ending in .csv, is a comma-separated values file that provides more structure for this information, making it easier to extract and plot the data for further analysis.

To inspect the training run, we can plot the results from the log files using Matplotlib. We’ll define a plotting function that we’ll use throughout this chapter.

Listing 7.2 Plotting function to visualize training results from log files

import csv
import matplotlib.pyplot as plt
def moving_average(values, window_fraction=0.25):
window_size = max(1, int(window_fraction * len(values)))
smoothed = []
for i in range(len(values)):
start_idx = max(0, i - window_size + 1)
window_mean = sum(values[start_idx : i + 1]) / (i - start_idx + 1)
smoothed.append(window_mean)
return smoothed
def plot_grpo_metrics(csv_path, columns, save_as=None):
data = {name: {"steps": [], "values": []} for name in columns}
with Path(csv_path).open(newline="") as f: <!-- Open and read the CSV log file. -->
reader = csv.DictReader(f)
for row in reader:
if not row or not row.get("step"):
continue
step = int(row["step"]) <!-- Use the training step as the shared x-axis across all metrics. -->
for name in columns:
value_str = row.get(name)
if value_str:
data[name]["steps"].append(step)
data[name]["values"].append(float(value_str))
fig, axes = plt.subplots(2, 2, sharex=True, figsize=(6, 4)) <!-- Create a fixed grid so loss, rewards, response length, etc., can be shown side by side. -->
axes = axes.ravel()
for i, name in enumerate(columns):
steps = data[name]["steps"]
values = data[name]["values"]
if not values: <!-- Skip metrics that are not present. -->
fig.delaxes(axes[i])
continue
if name == "eval_acc":
axes[i].bar(steps, values, width=20) <!-- Evaluation accuracy as a barplot because we don't have data for each step -->
else:
axes[i].plot(steps, values, alpha=0.4)
axes[i].plot(steps, moving_average(values))
axes[i].set_ylabel(name)
for j in (2, 3):
if axes[j] in fig.axes:
axes[j].set_xlabel("Step")
plt.tight_layout()
if save_as is not None:
plt.savefig(save_as)
plt.show()

The .csv file we downloaded has multiple columns. Using the plot_grpo_metrics function we defined in listing 7.2, we can plot the loss, average reward, average response length, and evaluation accuracy:

plot_grpo_metrics(
"ch06_rlvr_grpo_original_no_kl_metrics.csv",
columns=["loss", "reward_avg", "avg_response_len", "eval_acc"]
)

The resulting plot is shown in figure 7.4.

loss reward_avg
0 |~~~~-_ 1.00 |
| \ 0.75 | __--~~~~~~
-2000 | \ ||| 0.50 | _-~
| \ ||| 0.25 | _-~
-4000 | ~|||||||||||| 0.00 |~~~~
+-------------------- +--------------------
0 200 400 0 200 400
Step Step
avg_response_len eval_acc 1000 | _--~~~~--__ 40 | # # # #
| _- ~~--__ 30 | # # # # #
750 | _- 20 | # # # # # #
| _- 10 | # # # # # #
500 |~||| 0 +--------------------
| 0 200 400
250 +-------------------- Step
0 200 400
Step

[!visual-conversion] Figure 7.4 — The four metrics tracked during the GRPO training run (loss, average reward, response length, and evaluation accuracy) (printed p. 231, scan page-243.png). The orange centerline represents a moving average over the last 25% of values, which helps reveal overall trends in the otherwise noisy training signals. The evaluation accuracy is shown as a bar plot since it is computed only every 50 steps rather than at each step. Print annotations: “The orange line shows a moving average”, “An increasing number of spikes in later steps”, and “Average response length increases and then starts to decrease.” The per-step values are not recoverable at scan resolution — the sketches above reproduce the axes, ranges and the trend each panel shows, not measured data. Exact step values for the first few steps are given in the body text (for example, [Step 4/50] loss=2.7401 reward_avg=0.250 avg_resp_len=56.5). The orange line shows a moving average. An increasing number of spikes in later steps

Average response length increases and then starts to decrease.

Figure 7.4 The four metrics tracked during the GRPO training run (loss, average reward, average response length, and evaluation accuracy). The orange centerline represents a moving average over the last 25% of values, which helps reveal overall trends in the otherwise noisy training signals. The evaluation accuracy is shown as a bar plot since it is computed only every 50 steps rather than at each step.

A few general observations stand out in the plots shown in figure 7.4. The average response length should initially increase, ideally, along with an improvement in accuracy, which is largely what we see here, although there is a noticeable decline later in the run, just before step 400. Compared to LLM pretraining, which is outside the scope of this book and is covered in more detail in my previous book, Build A Large Language Model (From Scratch), the loss value itself is less informative and mainly serves as a sanity check. Overall, the loss should remain relatively stable. Some fluctuations are expected, but the larger spikes that appear halfway through the run are somewhat concerning.

The average reward should also increase over time. In principle, an average reward of 1.00 means that all sampled responses are correct, which is desirable, but it also means that the training signal has disappeared. At that point, further training is unlikely to be useful, and stopping early can save us time and resources.

Finally, performance on the external target task, here measured by MATH-500 accuracy, should improve. In this run, accuracy increases at first but then begins to decline, which points to problems and instabilities in the training process.

In summary, the training run shows fast gains early on, followed by diminishing returns after approximately 50 steps. One likely reason is that the underlying algorithm is not particularly stable over longer runs. Another possible explanation is that later training examples are more difficult, but this would not account for the decline in evaluation accuracy, which is computed from the same 500 MATH-500 test samples every 50 steps.

Note that the main goal of this section has been to introduce, analyze, and discuss various training metrics. We have focused on some basic ones, and in the next section we’ll extend this list and look at additional metrics that are commonly tracked during GRPO training.

Evaluation accuracy (eval_acc), here measured on the MATH-500 benchmark, is not tracked by default during training. It can be computed periodically by adding the setting —eval_on_checkpoint 500 when running the training script, but this is not recommended because it significantly slows down training. Alternatively, it can be calculated separately after training using the evaluate_math500.py script introduced in chapter 3:

download_from_github(
"ch03/02_math500-verifier-scripts/evaluate_math500.py"
)

The evaluation can then be run as follows for a given checkpoint:

Terminal window
uv run evaluate_math500.py \
--dataset_size 500 \

—checkpoint_path
“checkpoints/rlvr_grpo_original_no_kl/ qwen3-0.6B-rlvr-grpo-step00050.pth”

In this run, evaluation accuracy is included in the log file. (If you are not a uv user, replace uv run with python.)

7.3 Tracking more advanced GRPO performance metrics

Section titled “7.3 Tracking more advanced GRPO performance metrics”

Beyond the small set of basic metrics for monitoring GRPO training runs, several additional metrics can help in understanding the training dynamics, as illustrated in figure 7.5.

Next, we analyze additional training metrics.

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.5 — We have analyzed basic GRPO training metrics; we’ll now add more advanced metrics to analyze the training run (printed p. 233, scan page-245.png). Topic 1 is ticked and topic 2 is highlighted, annotated “Next, we analyze additional training metrics.” analyze the training run.

Two examples of the more advanced metrics mentioned in figure 7.5 are the rollout advantages already computed in the compute_grpo_loss function in chapter 6 and the entropy of the generated sequences.

As part of the GRPO algorithm, we compute so-called advantages, as discussed in chapter 6 and shown in figure 7.6. Beyond their role in the loss computation, these values are useful for analyzing and understanding training dynamics.

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"]
#RolloutRewardAdvantageLogprob
1\boxed{83}1.00.8659−7.9243
2”…The correct answer is \boxed{83}”1.00.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 7.6 — GRPO overview from chapter 6 (printed p. 234, scan page-246.png). The advantages are shown in step 3, annotated “Previously, we computed the advantages from the rewards.” This is the same worked example as figures 6.13–6.18; all numeric values are transcribed from the figure.

In particular, we compute two summary statistics derived from the advantages shown in figure 7.6, namely, their average value (the sample mean) and their standard deviation.

Listing 7.3 Computing advantage statistics

import torch
def compute_advantage_stats(rewards_list):
rewards = torch.tensor(rewards_list)
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4)
adv_avg = advantages.mean().item()
adv_std = advantages.std().item()
return advantages, adv_avg, adv_std

The rewards and advantages below are what we already compute in GRPO.

Now, we also compute the average (mean) and standard deviation (std).

As a simple illustration, consider a small sample of four reward values, similar to those shown in figure 7.6:

adv, adv_avg, adv_std = compute_advantage_stats([1., 1., 0., 0.])
print(f"Advantages: {adv}")
print(f"Advantage mean = {adv_avg:.4f}, std = {adv_std:.4f}")

The output is as follows:

Advantages: tensor([ 0.8659, 0.8659, -0.8659, -0.8659]) Advantage mean = 0.0000, std = 0.9998

Because of how advantages are computed in GRPO, their mean is always zero. In practice, this makes the mean mostly a sanity check that the implementation behaves as expected.

The standard deviation is more informative. Values close to 1 indicate a well-scaled gradient signal and are usually associated with stable updates. Very small values point to a vanishing learning signal, which often happens when rewards collapse. Very large values indicate overly spiky updates that can destabilize training.

An extreme case occurs when all rewards in the sampled group are identical. In that case, the normalized advantages are also identical, with a standard deviation of zero. As a result, the policy gradient update becomes zero, and no model weight update occurs. In other words, the model fails to learn from these cases. For example, consider the following scenario:

adv, adv_avg, adv_std = compute_advantage_stats([0., 0., 0., 0.])
print(f"Advantages: {adv}")
print(f"Advantage mean = {adv_avg:.4f}, std = {adv_std:.4f}")

which prints the following outputs:

Advantages: tensor([0., 0., 0., 0.]) Advantage mean = 0.0000, std = 0.0000

The outputs are similar if we replace the all-zero rewards in compute_advantage_ stats([0., 0., 0., 0.]) with all-one rewards in compute_advantage_stats([1., 1., 1., 1.]).

In practice, it is best to consider the advantage statistics together with the average reward. As mentioned earlier, an average reward of 1.0 is actually a desirable outcome, even though it means that the training signal has disappeared, because the model is answering everything correctly. At this point, it usually makes sense to stop training or to switch to more challenging examples.

Before we track and analyze the advantage statistics introduced in the previous section, let’s introduce another metric, entropy.

Entropy measures how uncertain the model is when generating the next token. High entropy means the probabilities are spread across many possible tokens, which encourages exploration. Low entropy means most of the probability is concentrated on a single token, which makes the model increasingly deterministic. Low entropy can also signal training collapse, where the model stops exploring and keeps producing the same outputs.

Before computing entropy, let’s briefly revisit how we calculated log-probability values (logprobs) in chapter 5, as summarized in figure 7.7.

graph TD
    A["1 - Convert input text into token IDs and pass them to the LLM<br/>'This is the prompt'"] --> L["LLM"]
    L --> B["2 - Get scores for next token (logits)"]
    B --> C["3 - Select token ID with highest score → Token ID 5"]
    C --> D["4 - Use vocabulary mapping to convert token ID back into token string → 'this'"]
Token indexLogitstorch.softmax(logits)torch.log_softmax(logits)
0–5range approx. −2.0 to 2.00.0 to 1.00 down to approx. −4
5 (selected)largest logitlargest probabilitylargest (least negative) log probability, −0.7109

[!visual-conversion] Figure 7.7 — Log probability (logprob) computation of a single token ("this") in the LLM’s generated answer (printed p. 236, scan page-248.png). The LLM returns the logits of the token, which are then converted to softmax probability values via torch.softmax() or logprob values via torch.log_softmax(). Print annotations: “Logits corresponding to the next token, generated by the model”, “We can get log probabilities from logits via torch.log(torch.softmax(logits)) or torch.log_softmax(logits) directly”, “The largest logit corresponds to the largest probability”, “The largest probability corresponds to the largest log probability”, and, across the bottom, “One generated answer step” spanning 'This is the prompt' → 'this is the LLM response'. The three bar panels share the structure of figure 5.14; individual bar heights are not recoverable at scan resolution, though the marked value −0.7109 matches the log-softmax maximum of that example.

In figure 7.7, instead of using real logits generated by prompting the base model, we use example logits assuming a vocabulary size of 7 (otherwise, with the original 151,000 token vocabulary, it would be impossible to visualize this concept in a plot):

logits = torch.tensor([
0.6667, -2.0000, 1.3333, -0.0000, -0.6667, 2.0000, -1.3333
])

The following code implements the calculation shown in figure 7.7:

logprobs = torch.log_softmax(logits, dim=-1)
print("All token logprobs:", logprobs)
selected_token = torch.argmax(logprobs)
selected = logprobs[selected_token]
print("Selected token ID:", selected_token)
print("Selected token logprob:", selected)

These are the outputs:

All token logprobs: tensor([-2.0442, -4.7109, -1.3776,
-2.7109, -3.3776, -0.7109, -4.0442])
Selected token ID: tensor(5) Selected token logprob: tensor(-0.7109)

In short, torch.log_softmax() computes all logprobs, torch.argmax() returns the index (token ID) of the largest logprob (here, 5), and logprobs[selected_token] returns the logprob value of that token ID (-0.7109).

Entropy is closely related to the logprobs. We compute it by multiplying each probability by its logprobs and then summing these products, as illustrated in figure 7.8. In principle, we could also track simpler quantities than entropy during training, such as the sum of probabilities or logprobs, but entropy is a widely used and easy-to-interpret measure of uncertainty in a probability distribution.

Figure 7.8 shows an entropy of 1.37. As a rough rule of thumb,

  • Very low entropy (≈ 0–0.5) means that one token dominates the distribution. The model is highly confident and behaves almost deterministically.
  • Moderate entropy (≈ 1–2) means the probabilities are shared across a reasonably small set of tokens, which is typical during stable training.
  • High entropy (approaching [log × vocabulary size]; here, log(7) = 1.9459) means the probabilities are spread across many tokens. In this case, the model is highly uncertain and behaves almost randomly.

In code, we can calculate entropy as follows.

Listing 7.4 Calculating entropy

probs = torch.softmax(logits, dim=-1)
logprobs = torch.log_softmax(logits, dim=-1)
<!-- page: 250 (printed 238) -->
entropy = torch.sum(-(probs * logprobs))
print("Probs:", probs)
print("Entropy:", entropy)
Token indexLogitstorch.softmax(logits)torch.log_softmax(logits)
0–5example logit valuesprobability per tokenlog probability per token
entropy=∑i−(pi⋅log⁡pi)=1.37\text{entropy} = \sum_i -\bigl(p_i \cdot \log p_i\bigr) = 1.37

[!visual-conversion] Figure 7.8 — The entropy term is calculated by multiplying the token probabilities by the token logprobs (printed p. 238, scan page-250.png). The print shows three bar charts side by side — logits, softmax(logits) and log_softmax(logits) — in the same layout as figure 5.14, with the entropy computed from the elementwise product of the middle and right panels. The body text supplies the resulting value: an entropy of 1.37. The individual bar heights are not recoverable at scan resolution. This figure’s placeholder had been misfiled as a code annotation during triage and is restored here.

These are the resulting outputs:

Probs: tensor([0.1295, 0.0090, 0.2522, 0.0665, 0.0341, 0.4912, 0.0175]) Entropy: tensor(1.3700)

As mentioned earlier, entropy quantifies how spread out the model’s probability distribution is over the vocabulary. In this specific example, the entropy of 1.37 indicates a moderate level of uncertainty. One token (with probability 0.4912) clearly dominates, but other tokens still have meaningful probabilities.

In listing 7.4, we compute the probs and logprobs separately using torch.softmax() and torch.log_softmax(), respectively. The torch.log_softmax() function combines two separate function calls: torch.log(torch.softmax()). The torch.exp() function is the inverse of torch.log(). This means that if we only had the logprobs, we could still calculate the probs by applying torch.exp(logprobs), as follows:

print("Probs:", torch.exp(logprobs))

This outputs the same probs values as before:

Probs: tensor([0.1295, 0.0090, 0.2522, 0.0665, 0.0341, 0.4912, 0.0175])

Building on this idea, we can extend the sequence_logprob function from the previous chapter to a sequence_logprob_and_entropy function that returns both the logprobs and the entropy.

Listing 7.5 Calculating sequence logprob and average entropy

Logprob of the generated answer tokens (sum over answer steps)

To compute and track entropy during training, we can use this sequence_logprob_and_entropy function inside compute_grpo_loss in place of the sequence_logprob function.

Note that figure 7.8 illustrated the entropy computation for a single token in the rollout (step_entropy), whereas sequence_logprob_and_entropy returns the average entropy across all answer tokens; that is, entropy_all_steps = torch.mean(step_entropy). For the answer “this is the LLM response”, the step entropy refers to the entropy at a single token position (for instance, at “this”), while the average entropy is the mean across all answer tokens in “this is the LLM response”.

With this modified sequence_logprob_and_entropy function, we can now use entropy as a diagnostic for the model’s generation behavior during training. By tracking the average entropy of the generated answer tokens, we can monitor whether the model behaves randomly (high entropy), remains exploratory (moderate entropy), or becomes overly confident and deterministic (low entropy).

In particular, we expect entropy to gradually decrease as the model becomes more confident. A sudden collapse to very low entropy can be a warning sign of unstable training.

Let’s build on the earlier computation of advantage statistics and entropy by analyzing these quantities in a concrete training run. To do this, we could update compute_grpo_loss to use sequence_logprob_and_entropy and then print and log the entropy in train_rlvr_grpo, which calls compute_grpo_loss internally. To avoid duplicating a long code listing here, the full modified version is provided in the book’s supplementary materials. You can download it as follows:

download_from_github( “ch07/03_rlvr_grpo_scripts_advanced/7_3_plus_tracking.py” )

This code can be run in the same way as the training script we used earlier:

uv run 7_3_plus_tracking.py
—steps 500
—max_new_tokens 1024

Since training takes a long time, you can download the resulting CSV log file and plot the new advantage statistics and entropy as follows:

download_from_github( “ch07/02_logs/7_3_plus_tracking_metrics.csv” ) plot_grpo_metrics( “7_3_plus_tracking_metrics.csv”, columns=[“reward_avg”, “adv_avg”, “adv_std”, “entropy_avg”] )

We already looked at the average reward, but it’s included here again for comparison. The resulting plots are shown in figure 7.9. Here, moderate entropy should still be understood as exploratory behavior, just less random than the later high-entropy regime.

reward_avg adv_avg
1.00 | |||| |||||| 0.050 | 0.75 | |||||||||||||||||||| 0.025 | 0.50 | ~~--___--~~~~~~~~~~~ 0.000 |~~~~~~~~~~~~~~~~~~~~~~ 0.25 | |||||||||||||||||||| -0.025 | 0.00 +---------------------- -0.050 +----------------------
0 200 400 0 200 400
Step Step
adv_std entropy_avg
1.00 | 10.0 | |||||| 0.75 | _--~~~--__ 7.5 | |||||||| 0.50 | _- ~~--___ 5.0 | |||||||||| 0.25 | - 2.5 | __--~~~~~ 0.00 +---------------------- 0.0 +----------------------
0 200 400 0 200 400
Step Step

[!visual-conversion] Figure 7.9 — Visualizing advantage statistics and entropy tracked during the GRPO training run, next to the average reward tracked previously (printed p. 241, scan page-253.png). Print annotations: “The nonzero advantage standard deviation indicates that there is a good training signal throughout the training run” and “After an initial phase of moderate entropy, the model becomes much more random and higher entropy.” The body text supplies the readings the figure supports: the average advantage stays at zero throughout by design; the advantage standard deviation is initially high, then gradually decreases and stabilizes while remaining nonzero; entropy is low and flat early, then increases noticeably after roughly step 200; and MATH-500 evaluation accuracy stays in the 30%–40% range. Per-step values are not recoverable at scan resolution. The nonzero advantage standard deviation indicates that there is a good training signal throughout the training run. After an initial phase of moderate entropy, the model becomes much more random and higher entropy.

Let’s begin by analyzing the advantage shown in figure 7.9. As expected with GRPO-style normalization, the average advantage stays at zero throughout training. Since advantages are computed relative to the group mean, they sum to zero by design. As mentioned earlier, this metric mainly serves as a sanity check. If the advantage averages were to drift away from zero, that would point to a bug or a normalization issue.

The standard deviation of the advantages is more informative. Early in training, we see relatively high variance, which indicates that the model is producing rollouts with a wide range of quality. Over time, the advantage standard deviation gradually decreases and stabilizes, which means that the rollouts become more similar in quality. The key point is that as long as the advantage standard deviation remains nonzero and reasonably stable (meaning the value doesn’t vary much), there is still a usable learning signal, and training is still happening.

Next, let’s look at the entropy. Early in training, the entropy is relatively low and fairly flat, which indicates that the model behaves in a largely deterministic way. Increasing the sampling temperature would lead to more diverse rollouts, although it does not change the underlying entropy of the model itself.

Later in training, after roughly step 200, entropy increases quite noticeably. This means the next-token probabilities are more spread out and the model behaves more randomly. Very low entropy can also be a sign of collapse, where the model repeatedly produces the same or very similar outputs. In this run, the entropy and the increasing average reward and non-vanishing advantage standard deviation suggest somewhat healthy exploration rather than collapse. This is also consistent with the earlier MATH-500 evaluation accuracy, which stays in the 30%–40% range. That’s not great, but it is not near zero.

The main takeaway here is that each metric tells a slightly different part of the story, and they are most useful when considered together and in context.

7.4 Stabilizing sequence-level GRPO using clipped policy ratios

Section titled “7.4 Stabilizing sequence-level GRPO using clipped policy ratios”

So far, we have mainly focused on analyzing the GRPO training results. Next, we’ll start adding to the GRPO algorithm itself. The version we have used so far is a simplified form of GRPO, and in this section, we’ll introduce a clipped policy ratio in the GRPO loss, as illustrated in the overview in figure 7.10.

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.10 — We have plotted basic and advanced GRPO training metrics. Now we’ll modify the GRPO algorithm to add clipped policy ratios (printed p. 242, scan page-254.png). Topics 1 and 2 are ticked and topic 3 is highlighted, annotated “Next, we’ll compute clipped policy ratios to stabilize the training.” Next, we’ll compute clipped policy ratios to stabilize the training.

The clipped policy ratios will help limit overly large model weight updates and make training more stable, especially over longer runs. Ideally, we want to ensure that model performance doesn’t noticeably decline, as we saw previously.

The clipped policy ratio measures how much the current policy, that is, the LLM being trained, has changed relative to an earlier version of itself. It compares sequence logprobs computed before an update step with those computed after the update. You can think of it as asking, “If the LLM previously assigned a certain likelihood to this answer, how much more or less likely does it consider the same answer after we adjusted its weights?”

In the GRPO pipeline shown in figure 7.11, this corresponds to comparing the logprobs from step 4, which are computed using the old weight parameters, with the logprobs produced by the updated model (updated in step 6).

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"]
#RolloutRewardAdvantageLogprob
1\boxed{83}1.00.8659−7.9243
2”…The correct answer is \boxed{83}”1.00.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 7.11 — The GRPO overview from chapter 6 (printed p. 243, scan page-255.png). We’ll now use the sequence logprobs from step 4 to compute policy ratios and clipped policy ratios. Print annotations: “We’ll now use these sequence logprobs to compute the policy ratio” on step 4, and “We’ll now compute a ‘clipped’ version of the policy gradient loss” on step 5.

This will become clearer once we implement this concept in code. But first, to recap, in chapter 6 we computed the policy gradient loss as follows.

Listing 7.6 Computing the policy gradient

# Code to compute rollouts omitted for brevity
rewards = torch.tensor([1., 1., 0., 0.]) # Compute rewards.
logprobs = torch.tensor([-7.9243, -20.1546, -16.6130, -23.3677])
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4)
pg_loss = -(advantages.detach() * logprobs).mean() # Compute sequence logprobs.
print("Policy gradient loss:", pg_loss)

The resulting policy gradient value, also shown in figure 7.11, is −2.5764.

Next, we’ll compute the policy ratio and clipped policy ratio, as shown in figure 7.12. The policy ratio and clipped policy ratio are computed by comparing logprobs from a previous version of the policy (“old” logprobs) with those from the current policy (“new” logprobs). The mathematical derivation is outside the scope of this chapter, but if you’re interested, you can find more details in the “Proximal Policy Optimization Algorithms” paper (https://arxiv.org/pdf/1707.06347).

In the following code-based illustration of the calculation shown in figure 7.12, we reuse the logprobs from listing 7.6 as old_logps, assume that a model update has taken place, and then compute the corresponding new_logps using the updated model. In practice, both are computed using the same prompt to ensure a fair, apples-to-apples comparison between the old and current policies.

Listing 7.7 Computing policy ratios and clipped policy ratios

new_logps = logprobs
old_logps = torch.tensor([
-10.9243, # -7.9243
-20.3546, # -20.1546
-14.6130, # -16.6130
-23.3677, # -23.3677
])
log_ratio = new_logps - old_logps
ratio = torch.exp(log_ratio)
clip_eps = 10.0
clipped_ratio = torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps)
print("Ratio: ", ratio)
print("Clipped ratio:", clipped_ratio)
#RolloutAdvantageReward“New” logprob“Old” logprob
1\boxed{83}0.86591.0−7.9243−10.9243
2”…The correct answer is \boxed{83}”0.86591.0−20.1546−20.3546
3”…The final answer is 83”−0.86590.0−16.6130−14.6130
4”…We get \boxed{38}”−0.86590.0−23.3677−23.3677

Compute the exponentiated difference between new and old logprobs:

#CalculationRatioClipped ratio
1exp⁡(−7.9243−(−10.9243))\exp(-7.9243 - (-10.9243))20.08551.1000
2exp⁡(−20.1546−(−20.3546))\exp(-20.1546 - (-20.3546))1.22141.2214
3exp⁡(−16.6130−(−14.6130))\exp(-16.6130 - (-14.6130))0.13530.1353
4exp⁡(−23.3677−(−23.3677))\exp(-23.3677 - (-23.3677))1.00001.0000

[!visual-conversion] Figure 7.12 — Calculating the policy ratio (“ratio”) and clipped policy ratio (“clipped ratio”) we’ve added to the GRPO, from “new” and “old” logprobs (printed p. 245, scan page-257.png). Print annotations: “Logprobs for the current iteration are computed by passing the generated rollouts to the sequence_logprob function we defined in chapter 6”, “Additionally, we now also compute the logprobs by passing the rollouts to an older version of the model from a previous iteration”, and “Clip the ratio if it falls outside a certain range (here, if it is larger than 1.1 or smaller than 1/1.1).” All numeric values are transcribed from the figure.

The resulting unclipped and clipped policy ratios follow:

Ratio: tensor([20.0855, 1.2214, 0.1353, 1.0000]) Clipped ratio: tensor([11.0000, 1.2214, 0.1353, 1.0000])

The ratio tells us how different the old and new logprobs are. If they are identical, the ratio is 1.0.

The clipped_ratio, which we use to compute a clipped version of the policy gradient loss, limits how far the new policy can move away from the old one in a single update. If the new model suddenly assigns a much higher or much lower probability to a rollout than the old model, the raw ratio can become very large or very small. Without clipping, this would scale the advantage term substantially, which could lead to a very large gradient step that might destabilize training.

In practice, when using the clip_eps parameter from listing 7.7, it is common to clamp the ratio to the range 1 ± clip_eps. For example, DeepSeek-Rl used clip_eps = 10, which corresponds to very weak clipping. Other RL training setups, such as RLHF using the PPO algorithm, often use much smaller values, such as 0.1, which results in aggressive clipping and substantially smaller per-step policy changes.

As you can see, with this very generous clip_eps value of 10.0, only the first value is clipped from 20.0855 down to 11.0000.

NOTE The “eps” in clip_eps is short for epsilon (ε), a Greek letter commonly used in mathematics to denote a small positive quantity.

Next, we’ll apply the ratio and clipped_ratio in the loss computation. Previously, we multiplied the advantages directly by the logprobs. Now, we’ll instead scale the advantages by the policy ratios and use the clipped objective to limit how much each rollout can influence the update.

Listing 7.8 Computing the clipped policy gradient loss

adv = advantages.detach() # Treat advantages as fixed learning signals (no backprop through rewards). unclipped = ratio * adv clipped = clipped_ratio * adv
obj = torch.minimum(unclipped, clipped) # Limit overly large policy-ratio updates.
clipped_pg_loss = -torch.mean(obj)
policy_ratio = torch.mean(ratio)
print("Clipped policy gradient loss:", clipped_pg_loss)
print("Policy ratio:", policy_ratio)

The resulting clipped policy gradient loss is −2.3998-2.3998, which is slightly lower than the regular policy gradient loss we computed previously in this section (−2.5764-2.5764). This small difference makes sense because, in our example, only one of the policy ratios was effectively clipped by the generous clip_eps=10.0\texttt{clip\_eps} = 10.0 ratio. In general, this clipping can prevent overly aggressive updates that could destabilize training. Large, aggressive updates can move the policy too far in a single step, causing large shifts in token probabilities and leading to reward crashes, entropy collapses, or other related problems.

In addition, we compute the average policy ratio, policy_ratio=torch.mean(ratio)\texttt{policy\_ratio} = \texttt{torch.mean(ratio)}, which we can track and report during the training run. Here, the result is a relatively large 5.61065.6106. This large policy ratio means that the updated policy (model) assigns a much higher probability to the sampled tokens than the previous policy.

We can apply the clipped policy ratio and policy loss computations from listings 7.7 and 7.8 to see if they help stabilize training.

The modified code can be downloaded from the supplementary materials as follows:

download_from_github(
"ch07/03_rlvr_grpo_scripts_advanced/7_4_plus_clip_ratio.py"
)

And we can run it as before:

Terminal window
uv run 7_4_plus_clip_ratio.py \
--steps 500 \
--max_new_tokens 1024

As discussed in the previous section, the policy ratio compares logprobs computed under the current policy with those from a previous version of the policy. In practice, this means that we first need a batch of sampled responses whose old_logps\texttt{old\_logps} are measured under a fixed reference policy. We can then compare those same responses with the current model, which changes during optimization, to form the clipped policy ratio update.

DeepSeek-R1 does this at large scale by generating a large rollout pool once (8,192 responses), holding those responses fixed, and then stepping through them in 16 minibatches. At a high level, the process is as follows:

  1. Make a copy of the current model as the reference policy.
  2. Sample a big rollout pool using the reference policy.
  3. Split those fixed rollouts into minibatches.
  4. For each minibatch:

a Compute old_logs under the reference model. b Compute new_logs under the current model (which changes after each mini-batch update). c Update the current model. 5 Update the reference model.

Due to resource constraints, we cannot generate as many rollouts and minibatches as DeepSeek-R1 does, so we’ll use a smaller approximation. Instead of generating one huge fixed rollout pool and slicing it into minibatches, we’ll generate a small batch of rollouts, update the model on that batch, and then repeat the process with a fresh batch. The procedure in the 7_4_plus_clip_ratio.py script is as follows:

1 Make a copy of the current model as the reference policy. 2 Sample eight rollouts using the reference policy. 3 Then, a Compute old_logs under the reference model. b Compute new_logs under the current model. c Update the current model. 4 Repeat steps 2 and 3 (by default, one more time) with different rollouts instead of using minibatches. 5 Update the reference model.

In short, DeepSeek-R1 generates a huge rollout pool once and then reuses it across minibatches before refreshing the reference model. In our code, we mimic this idea more cheaply by generating a small batch of rollouts multiple times instead.

A log file from the 7_4_plus_clip_ratio.py training run can be downloaded and visualized as follows:

download_from_github( “ch07/02_logs/7_4_plus_clip_ratio_metrics.csv” ) plot_grpo_metrics( “7_4_plus_clip_ratio_metrics.csv”, columns=[“loss”, “reward_avg”, “avg_response_len”, “eval_acc”] )

loss reward_avg
0.050 | 1.00 | 0.025 | | | || | 0.75 | ~~~~~~~~~~~~~~~~~~ 0.000 |~~~~~~~~~~~~~~~~~~~~~~ 0.50 | /
-0.025 | 0.25 | /
-0.050 +---------------------- 0.00 +----------------------
0 200 400 0 200 400
Step Step
avg_response_len eval_acc 1000 | 40 |# # # # # # # # 750 | _--~~~~~~~~--__ 30 |# # # # # # # # 500 | / 20 |# # # # # # # # 250 | / 10 |# # # # # # # #
+---------------------- 0 +----------------------
0 200 400 0 200 400
Step Step

[!visual-conversion] Figure 7.13 — Metrics from a GRPO training run with clipped policy ratios (printed p. 248, scan page-260.png). The body text states what the figure shows: compared with the previous training runs, this run is more stable — there is no visible drop in the average reward or evaluation accuracy around the 400-step mark, in contrast to figures 7.4 and 7.16. Per-step values are not recoverable at scan resolution; the sketches reproduce each panel’s axes and the stability the text describes. The placeholder for this figure did not survive OCR and has been restored at its print location.

Figure 7.13 shows the resulting plot. Compared to the previous training runs, this training with clipped policy ratios is more stable, as there is no visible drop in the average reward or evaluation accuracy around the 400-step mark.

We could also plot and inspect the other metrics, such as policy_ratio, adv_avg, adv_std, and entropy_avg. I’ll leave that as an exercise for you to try.

7.5 Controlling how much the model changes with a KL term

In chapter 6, we skipped using the KL loss term in the GRPO algorithm to keep the presentation manageable. To complete the GRPO algorithm, we’ll now add the KL loss term, as outlined in figure 7.14.

NOTE If you’re familiar with reinforcement learning, you may recognize that what we implemented up to this point is essentially REINFORCE with group-normalized advantages. (See https://lilianweng.github.io/posts/2018-04-08-policy-gradient/ for information about the REINFORCE method.)

KL is short for Kullback–Leibler divergence, and it measures how much the current policy, that is, the LLM being trained, deviates from a reference policy, typically the original model at the start of training. The KL term acts as a constraint (technically called a regularizer) that discourages overly large updates and keeps the model close to its original behavior, preventing drastic or unstable changes.

This is closely related to the clipped policy ratios we introduced earlier. With clipped policy ratios, we limited how large individual update steps could be. The KL term is another mechanism for controlling how much the model can change. While clipped policy ratios focus on limiting changes between steps, the KL term is often used to control change over the longer training trajectory.

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.14 — Implementing a KL loss term, which is part of the original GRPO algorithm (printed p. 250, scan page-262.png). Topics 1 to 3 are ticked and topic 4 is highlighted, annotated “Now we’ll add a KL loss term to prevent drastic changes from a reference model.”

Figure 7.15 shows the KL loss term computation as part of the GRPO algorithm. The KL loss term calculation involves comparing logprobs and reference logprobs. It is computed by summing the differences between these corresponding logprobs.

A small KL loss term value indicates that the current model and the reference model output relatively similar logprobs, meaning the current model has not changed much compared to the reference model. This is generally desirable for stability, as it prevents large, abrupt shifts in behavior. If the KL loss term remains too small for too long, it may also indicate that learning is limited.

The resulting KL loss term is then added to the policy gradient loss to compute the total loss, so weight updates that greatly increase divergence from the reference model, even if they result in a high reward, are penalized during training.

In the clipped policy ratio section, we replaced the reference model in each iteration. For the KL loss term, the reference model used to compute the reference logprobs is the original model at the beginning of training, and it is either kept fixed or replaced relatively rarely (in the case of DeepSeek-R1, every 400 steps).

The following code illustrates how the compute_grpo_loss function can be modified to include this KL loss term. To avoid code duplication, listing 7.9 does not show the fully modified compute_grpo_loss_with_kl function. It instead focuses on the changes

Controlling how much the model changes with a KL term

we need to make to the compute_grpo_loss function. The new additions are marked with comments or are located inside the if kl_coeff blocks.

#RolloutAdvantageRewardLogprobReference logprob
1\boxed{83}0.86591.0−7.9243−7.6128
2”…The correct answer is \boxed{83}”0.86591.0−20.1546−20.6031
3”…The final answer is 83”−0.86590.0−16.6130−16.2687
4”…We get \boxed{38}”−0.86590.0−23.3677−23.6049
Loss componentValue
Policy gradient loss−2.5764
KL loss term−0.0075
Total loss−2.5839

[!visual-conversion] Figure 7.15 — Overview of the GRPO algorithm with the KL loss term calculation added to the right (printed p. 251, scan page-263.png). The reference logprobs are produced by a separate Reference LLM alongside the LLM to train. Print annotations: “We previously skipped the KL loss term computation”, “We used the policy gradient loss as the training loss in chapter 6”, and “Now, we’ll compute the total loss as the sum of the policy gradient loss and KL loss term.” All numeric values are transcribed from the figure and match figure 6.9.

Listing 7.9 Adding a KL term to the GRPO loss computation

import copy
kl_coeff = 0.0 # kl_coeff = 0.0 deactivates the KL term and the code is similar to before.
if kl_coeff:
ref_model = copy.deepcopy(model).to(device) # Make a copy of the original model and disable gradients so it isn't updated.
ref_model.eval()
for p in ref_model.parameters():
p.requires_grad = False
else:
ref_model = None
def compute_grpo_loss_with_kl(
model,
ref_model, # New: Pass the reference model.
# ...
kl_coeff=0.02, # New: Specify the KL strength.
):
roll_logs, roll_ref_logs, roll_rewards, samples = [], [], [], []
# ...
for _ in range(num_rollouts):
token_ids, prompt_len, text = sample_response(
# ...
)
if kl_coeff:
with torch.no_grad():
ref_logp = sequence_logprob(
ref_model, token_ids, prompt_len
)
else:
ref_logp = None
reward = reward_rlvr(text, example["answer"])
roll_rewards.append(reward)
roll_logs.append(logp)
if kl_coeff:
roll_ref_logs.append(ref_logp)
# ...
rewards = torch.tensor(roll_rewards, device=device)
advantages = (rewards - rewards.mean()) / (rewards.std() + 1e-4)
logs = torch.stack(roll_logs)
if kl_coeff:
ref_logs = torch.stack(roll_ref_logs).detach()
pg_loss = -(advantages.detach() * logs).mean()

Controlling how much the model changes with a KL term

if kl_coeff:
kl_loss = kl_coeff * torch.mean(logps - ref_logps)
else:
kl_loss = torch.tensor(0.0, device=logps.device)
loss = pg_loss + kl_loss # New: Add the KL loss term

to the policy gradient loss.

Note that adding the KL loss term increases resource use, since we now need to keep an additional copy of the original model. The strength of this penalty is controlled by kl_coeff. Larger kl_coeff values add a stronger constraint on how far the current policy is allowed to change from the reference model.

The setting kl_coeff = 0.0 at the top of listing 7.9 is included only so that this abbreviated code snippet won’t crash if we run it in a code environment. In practice, kl_coeff is typically a small value between 0.001 and 0.05.

The following script from the book’s supplementary materials implements the KL loss term code modification we’ve discussed:

download_from_github(
"ch07/03_rLvr_grpo_scripts_advanced/7_5_plus_kl.py"
)

As before, we can run it as follows:

uv run 7_5_plus_kl.py
—steps 500
—max_new_tokens 1024

Let’s take a look at the log files from a training run that was executed with the preceding settings:

download_from_github(
"ch07/02_logs/"
"7_5_plus_kl_metrics.csv"
)
plot_grpo_metrics(
"7_5_plus_kl_metrics.csv",
columns=["loss", "reward_avg", "avg_response_len", "eval_acc"]
)

The resulting plots are shown in figure 7.16.

As the accuracy graph at the bottom right shows, the first 50 steps improve the model’s performance noticeably from slightly above 15% accuracy to approximately 40%. We then see a total collapse where the loss values explode and the average reward goes toward 0. This is accompanied by a crash in the evaluation accuracy that also goes toward 0%.

loss reward_avg
30 | _____________ 1.00 |# 20 | __/ 0.75 |# 10 | _/ 0.50 |#
0 |____/ 0.25 |#\
+---------------------- 0.00 | \_________________
0 200 400 +----------------------
Step 0 200 400
Step
avg_response_len eval_acc 1000 |~~~~~~~~~~~~~~~~~~~~~~ 40 |# 750 | 30 |# 500 | 20 |# 250 | 10 |#
+---------------------- 0 |#______________________
0 200 400 +----------------------
Step 0 200 400
Step

[!visual-conversion] Figure 7.16 — Selected metrics from a GRPO training run after adding a KL loss term (printed p. 254, scan page-266.png). Here, loss (in the upper left) refers to the total GRPO loss, which is the sum of the policy gradient loss and the KL loss term. Print annotations: “Loss jumps to a very high value”, “Rewards completely collapse”, “The model fails to fit its response within the allowed token limit”, and “The model fails to answer anything correctly.” The body text confirms the failure mode: the model eventually started producing nonsensical text and random tokens. Per-step values are not recoverable at scan resolution — the sketches show each panel’s axes, range and the direction of the trend the annotations describe.

On manually inspecting the generated responses, we can see that the model eventually started producing nonsensical text and random tokens, such as “framework.raises Self profess(import)”. There are a couple of likely reasons for this behavior.

First, the KL term is computed using summed logprobs over the answer tokens, that is, kl_loss=kl_coeff∗mean(new_logps−ref_logps)\text{kl\_loss} = \text{kl\_coeff} * \text{mean}(\text{new\_logps} - \text{ref\_logps}). Here, new_logps\text{new\_logps} are computed under the current trainable policy, while ref_logps\text{ref\_logps} are computed under the reference policy, which is the original model at the beginning of training. This reference policy is not the same as the old rollout policy in later training steps. The old policy is a recent snapshot used to generate the sampled responses, whereas the reference policy remains fixed at the initial model.

KL direction versus rollout sampling

KL divergence is directional. If we sampled responses from the old rollout policy and wanted to measure how much the current policy differs from that old policy, the corresponding sample-level logprob difference would be old_logps−new_logps\text{old\_logps} - \text{new\_logps}.

However, the KL-style term here has a different purpose. It is intended to penalize the drift of the current policy from the fixed reference policy, so the corresponding logprob difference is new_logps−ref_logps\text{new\_logps} - \text{ref\_logps}.

The subtlety is that the responses are generated by the old rollout policy, not by the current policy after the update. Therefore, mean(new_logps−ref_logps)\text{mean}(\text{new\_logps} - \text{ref\_logps}) is a simplified sampled surrogate rather than an exact KL estimate. A more principled off-policy version would use an importance-sampling correction, which we’ll discuss in the next subsection.

Controlling how much the model changes with a KL term

Because the term is not length normalized, its magnitude grows with the length. This does not mean that longer outputs are always favored, since tokens can either increase or decrease the loss depending on the per-token difference between the current and reference policy. However, because these are sampled from the old policy, this simple sampled surrogate is not an exact mate for the current policy unless we either sample from the current policy or an importance-sampling correction. As a result, the objective becomes length sensitive, which can bias training toward longer outputs in some cases, as suggested by the following response length here, and can destabilize training.

Second, once rewards collapse to zero around step 200, the KL term becomes the only remaining source of gradient signal. When all rewards are zero, the advantages are also zero, so the policy gradient loss no longer contributes any gradient. The KL term is still active and starts to dominate the updates. In an exact KL-to-reference objective, this would pull the model back toward the reference policy. However, the simplified KL surrogate used here, kl_loss=kl_coeff∗mean(new_logps−ref_logps)kl\_loss = kl\_coeff * \text{mean}(new\_logps - ref\_logps), is evaluated only on sampled rollouts from the old policy, and ref_logpsref\_logps acts as a constant during optimization. On those fixed sampled tokens, minimizing the loss mainly pushes down the current model’s probability on the sampled actions, which can make the next-token distribution more spread out and raise entropy. The observed behavior is better understood as a failure mode of this sampled surrogate, which can lead to increasingly random outputs and the drop to 0.0% evaluation accuracy. If you want, you can plot the other evaluation metrics, such as policy_ratiopolicy\_ratio, adv_avgadv\_avg, adv_stdadv\_std, and entropy_avgentropy\_avg, and confirm that the entropy becomes very large.

While the KL term is a standard part of the GRPO algorithm, which is why I’ve introduced it here, several recent works report that models can train better without it. Examples include Dr. GRPO, Olmo 3, and DeepSeek-V3.2, all of which observe improved stability or performance when the KL term is reduced or omitted (see appendix A for more detailed references).

Improving training stability with a KL term

Alternatively, instead of removing the KL term, there are several ways to improve training stability. First, we can reduce kl_coeffkl\_coeff from 0.02 to a smaller value (for example, 0.001) to weaken the KL penalty, although this was not sufficient in my experiments.

Since we saw that the response length keeps growing until it hits the maximum, another option is to length normalize the sequence logprobs by dividing by the number of generated tokens, which approximates average per-token logprobs. This could reduce the incentive to increase response length to accumulate larger absolute logprob differences.

A third option is to use a reweighted KL term based on importance sampling, as proposed by DeepSeek-V3.2. This matters because the rollouts are generated by the old policy, while the KL term is intended to constrain the current policy relative to the reference policy. Instead of using

kl_loss=kl_coeff∗torch.mean(logps−ref_logps)kl\_loss = kl\_coeff * \text{torch.mean}(logps - ref\_logps)

(continued) we could use

kl_loss = (
kl_coeff * torch.mean(torch.exp(new_logps - old_logps)
* (new_logps - ref_logps)
)

Here, the importance weight torch.exp(new_logps - old_logps) corrects for rollouts being generated by the old policy, and it downweights samples that the current policy would rarely produce and upweights those it would.

Finally, we could add a small format reward to prevent advantages from collapsing to zero (we will revisit format rewards in the next section). That said, for math data, a common recommendation is to omit the KL term altogether (e.g., Dr. GRPO, Olmo 3, and DeepSeek-V3.2), which also simplifies the code and reduces resource requirements, since we don’t have to keep an additional reference model in memory.

So far, we’ve used only one type of verifiable reward, an answer-correctness reward, when training the model. In practice, this is sufficient to train reasoning models with RLVR. It is also common to use one or more auxiliary rewards, such as a format reward that checks whether the generated answer follows certain formatting guidelines (figure 7.17).

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.17 — Implementing a format reward that encourages the model to generate <think>...</think> tokens (printed p. 256, scan page-268.png). Topics 1 to 4 are ticked and topic 5 is highlighted, annotated “Adding a format reward to encourage the use of <think></think> tags.” The placeholder for this figure survived OCR only as an unlabeled comment and has been relabelled here. Chapter 6: Intro to RLVR and GRPO This chapter: Improving GRPO Adding a format reward to encourage the use of tags Figure 7.17 Implementing a format reward that encourages the model to generate … tokens

Specifically, we’ll focus on a format reward that encourages the model to us … tokens.

Some reasoning models, such as DeepSeek-R1 and Qwen3, use special and tokens. These are ordinary text tokens that mark the beginning and end of the model’s intermediate reasoning. We can prompt the model to write its step-by-step reasoning inside … and then provide the final answer outside these tags. This approach is optional, but it makes the output structure explicit and helps separate reasoning from the final result.

To illustrate this concept, we’ll start by loading the tokenizer for the base model we used earlier.

Listing 7.10 Loading the base model tokenizer

from reasoning_from_scratch.ch02 import get_device
from reasoning_from_scratch.ch03 import load_model_and_tokenizer
device = get_device()
model, tokenizer_base = load_model_and_tokenizer(
which_model="base",
device=device,
use_compile=False
)

Next, we’ll use the tokenizer to encode :

print(tokenizer_base.encode("<think>"))

The output is [13708, 766, 29], which means the tokenizer is breaking up the token into several subword tokens. This indicates that the token is not part of the tokenizer’s vocabulary.

Nowadays, when developing tokenizers and creating the embedding layers of LLMs, developers often leave unused placeholder token IDs that can be used for specific purposes when fine-tuning a model. The Qwen3 base model tokenizer has some empty placeholder slots that we can use to add :

tokenizer_base.tok.add_special_tokens(
["`<tool_response>`", "`</tool_response>`", "`<think>`", "`</think>`"]
)

Note that we are also adding the <tool_response> and </tool_response> tokens in the preceding code to match the tokenizer of the Qwen3 reasoning variant, which we’ll discuss shortly. But first, let’s check whether the modified base tokenizer now supports the newly added and tokens:

print(tokenizer_base.encode("<think>"))
print(tokenizer_base.encode("</think>"))

The outputs are single tokens [151667] and [151668], which indicates that the and tokens are now part of the vocabulary and are no longer broken into subword tokens.

These new tokens would also be supported by the base model, which supports token IDs from 0 to 151935, because it has a vocabulary size of 151936. We can confirm this by printing the size of the embedding layer:

print("Vocabulary size:", model.tok_emb.weight.shape[0])

Alternatively, instead of modifying the base tokenizer, we could use the reasoning model variant, whose tokenizer already supports these tokens natively. As in chapter 2, we can load the tokenizer separately.

Listing 7.11 Loading the reasoning model’s tokenizer

from reasoning_from_scratch.qwen3
import Qwen3Tokenizer
from reasoning_from_scratch.qwen3
import download_qwen3_small
download_qwen3_small(
kind="reasoning", tokenizer_only=True, out_dir="qwen3"
)
tokenizer_path = Path("qwen3") / "tokenizer-reasoning.json" tokenizer = Qwen3Tokenizer(tokenizer_file_path=tokenizer_path)

Now, let’s use the reasoning tokenizer (tokenizer) instead of tokenizer_base to encode the token IDs:

print(tokenizer.encode("<think>"))
print(tokenizer.encode("</think>"))

As when we used tokenizer_base, this returns [151667] and [151668].

Now that we have a tokenizer that supports these tokens, we can develop a reward function that checks whether the LLM uses them, and we’ll provide a nonzero reward if it does, as illustrated in figure 7.18. This means that we can develop a function that returns 1.0 if both and appear in the output in the correct order; otherwise, it returns 0.0.

Listing 7.12 Implementing a format reward function

def reward_format(
token_ids,
prompt_len,
start_think_id=151667,
end_think_id=151668,
):
try:
gen = token_ids[prompt_len:].tolist()
return float(
<!-- page: 271 (printed 259) -->
gen.index(start_think_id) < gen.index(end_think_id) ) except ValueError:
return 0.0

Previously, we used only one type of reward that focused on the correct answer being in \boxed{} context.

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

Correctness rewards

1.0 ← ” \boxed{83} ”

1.0 ← ” …The correct answer is \boxed{83} ”

0.0 ← ” …The final answer is 83”

0.0 ← ” …We get \boxed{38} ”

In addition to the answer correctness in \boxed{}, we now use a format reward that checks whether … tags are used correctly.

Prompt: “Half the value of 3x − 9 is x + 37. What is the value of x? When solving the problem, first write your reasoning inside <think> and </think> tags. Then, write the final result in \boxed{}”

Rollout from the LLM to trainCorrectness rewardFormat rewardTotal reward
<think>Solving 3x − 9 = 2(x + 37)...</think> \boxed{83}1.01.01.0
”…Rearranging the equation gives…correct answer is \boxed{83}.”1.01.01.0
<think>Solving the equation...</think>0.00.00.0
”…We get \boxed{38}”0.00.00.0

[!visual-conversion] Figure 7.18 — Using the previous correctness reward (left) and a correctness plus format reward (right) (printed p. 260, scan page-272.png). Print annotation: “The total reward is the sum of correctness and format rewards.” Rollout 1 earns both rewards; rollout 2 earns correctness and format credit despite its prose style; rollout 3 uses the tags but gives no boxed answer; rollout 4 gives a boxed answer but the wrong value and no tags. All values are transcribed from the figure. The placeholder for this figure did not survive OCR and has been restored at its print location.

Let’s give this a try on a simple text:

prompt = "Calculate ..."
rollout = "Let's ... `<think>` ... `</think>` ..."
token_ids = tokenizer.encode(prompt + rollout)
reward_format(
token_ids=torch.tensor(token_ids),
prompt_len=len(tokenizer.encode(prompt))
)

Running the reward_format function in the preceding code snippet returns 1.0 as expected, since the answer (rollout) contains both and .

Exercise 7.1: Testing the format reward Run the example and confirm it returns 1.0, since both and appear in the correct order.

Now modify the rollout text in the following ways:

  • Introduce a typo in one of the tags.
  • Reverse the tag order.
  • Remove one tag.

Verify that the reward becomes 0.0 in each case.

Now that we have this new reward_format function, we can use the format reward as an additional signal to train the model. For instance, we could convert compute_grpo_loss from chapter 6 into a compute_grpo_loss_plus_format_reward function, as follows (the changes are highlighted in the comments).

Listing 7.13 Updating the GRPO loss function with a format reward

def compute_grpo_loss_plus_format_reward(
# ...
format_reward_weight=1.0, <!-- A setting parameter that lets us regulate
): <!-- the magnitude of the format reward
# ... <!-- relative to the existing correctness reward
logp = sequence_logprob(model, token_ids, prompt_len)
rlvr_reward = reward_rlvr(text, example["answer"])
format_reward = reward_format(token_ids, prompt_len) <!-- NEW
reward = rlvr_reward + format_reward_weight * format_reward <!-- NEW
# ...
<!-- New format reward lines that modify the
previous reward to now consist of a
correctness and a format reward

In addition, we can modify render_prompt to direct the model to emit these and tokens explicitly.

Listing 7.14 Updated prompt rendering function for tokens

def render_prompt_with_think_tokens(prompt):
template = (
"You are a helpful math assistant.\n"
"When solving the problem, first write your reasoning inside `<think>`
and `</think>` tags.\n"
"Then write the final result on a new line in the exact format:\n"
"\\\\boxed{ANSWER}\n\n"
f"Question:\n{prompt}\n\nAnswer:"
)
return template

In theory, the modifications in code listings 7.11 through 7.14 should be sufficient to train a reasoning model with an additional format reward. Let’s now look at how it works in practice and discuss some additional caveats.

The modifications needed to train a reasoning model with a formatting reward implemented in a script that you can download:

download_from_github( “ch07/03_rlvr_grpo_scripts_advanced/7_6_plus_format_reward.py” )

There are a few caveats to keep in mind about this script. For instance, if we train the base model with the modified prompt to emit and tokens, as shown in listing 7.14, the results would be poor because the base model has never seen these tokens before. The proper way to introduce these new tokens would be to pretrain or instruction fine-tune the model on data that includes and tokens (instruction fine-tuning is covered in the next chapter).

In this chapter, where we are focusing on reinforcement learning, we’ll train the existing reasoning variant of the model, which is already familiar with tokens. This is the same reasoning variant we introduced in chapter 3.

You can run the script as follows:

uv run 7_6_plus_format_reward.py
—steps 500
—max_new_tokens 1024

Note that this script is already configured to use the reasoning model variant instead of the base model.

You can download a log file of this run for further analysis, because running the experiment can be resource intensive and expensive:

download_from_github( “ch07/02_logs/7_6_plus_format_reward_metrics.csv” ) plot_grpo_metrics( “7_6_plus_format_reward_metrics.csv”, columns=[“loss”, “reward_avg”, “avg_response_len”, “eval_acc”] )

The resulting plot is shown in figure 7.19. As you can see, the model improves at first but then gets worse in terms of evaluation accuracy, while the average reward stays approximately constant. The decline in evaluation accuracy appears to correlate with the shorter response lengths the model produces after that point.

loss reward_avg
0.050 | 2.0 | 0.025 | 1.5 | |||||||||||||||| 0.000 |~~~~~~~~~~~~~~~~~~~~~~ 1.0 | ~~~~~~~~~~~~~~~~~~
-0.025 | 0.5 | ||||||||||||||||
-0.050 | 0.0 +----------------------
+---------------------- 0 200 400
0 200 400 Step
Step
avg_response_len eval_acc 1000 |\ 40 |# # # # 800 | \__ 30 |# # # # # 600 | ~~--___ __--~~ 20 |# # # # # # 400 | ~~----~ 10 |# # # # # # # 200 +---------------------- 0 +----------------------
0 200 400 0 200 400
Step Step

[!visual-conversion] Figure 7.19 — Basic metrics from a GRPO training run with a format reward (printed p. 262, scan page-274.png). Print annotations: “The average response length steadily decreases before it recovers” and “Accuracy drops sharply.” The body text explains the flat loss trace: with the default settings (--kl_coeff 0.0 and --inner_epochs 1), the policy ratio starts at 1 and the advantages are normalized to a mean of 0, so the logged loss is exactly 0 throughout — a computational artifact rather than a real signal. Per-step values are not recoverable at scan resolution. The average response length steadily decreases before it recovers.

To investigate this further, let’s look at some additional metrics:

plot_grpo_metrics( “7_6_plus_format_reward_metrics.csv”, columns=[“reward_avg”, “format_reward_avg”, “adv_std”, “entropy_avg”], )

The results are shown in figure 7.20. One possible explanation for the declining model performance is that the model receives too much reward simply for following the tag format, as shown in the format_reward_avg plot. In other words, the model does not focus enough on answer correctness (as reflected by the drop in eval_acc despite the high reward_avg).

One way to address this is to reduce the strength of the format reward, such as by lowering the default format_reward_weight from 1.0 to 0.1. Another option is to make the format reward conditional so it is applied only when the answer is also correct. In the current setup, the format reward is granted regardless of correctness.

A note on loss and kl_loss This experiment used 7_6_plus_format_reward.py with the default settings —kl_coeff 0.0 and —inner_epochs 1. Because —kl_coeff is set to 0.0, the KL penalty is disabled, so the logged kl_loss remains 0 throughout the run.

If you want to enable KL regularization with the same settings used in section 7.5, run this:

uv run 7_6_plus_format_reward.py
—steps 500
—max_new_tokens 1024
—kl_coeff 0.001
—inner_epochs 2

The logged loss (figure 7.19) is also 0 with the default 7.6 settings. This happens because the run uses only one inner update (—inner_epochs 1) and compares the model against a copy of itself from the same step. As a result, the policy ratio starts at 1, and because the advantages are normalized to have a mean of 0, the scalar policy loss evaluates to 0.

So in this case, loss = 0 is a computational artifact caused by the default settings. It mainly reflects that the run uses a single inner epoch and no KL term, which makes the logged scalar loss uninformative.

The more useful quantities to monitor here are metrics such as reward_avg, format_reward_avg, adv_std, and entropy_avg.

reward_avg format_reward_avg
2.0 | 1.00 | ______-------- 1.5 | ~~~~~~~~~~~~~~~~~~ 0.75 | ___/ 1.0 | / 0.50 | _/ 0.5 | / 0.25 | / 0.0 +---------------------- 0.00 +----------------------
0 200 400 0 200 400
Step Step
adv_std entropy_avg
1.00 | 8 | |||||| 0.75 | __--~~~--__ 6 | |||||||| 0.50 | _-~ ~~--_ 4 | |||||||||| 0.25 | -~ 2 | ________ 0.00 +---------------------- 0 +----------------------
0 200 400 0 200 400
Step Step

[!visual-conversion] Figure 7.20 — Additional metrics from a GRPO training run with a format reward (printed p. 263, scan page-275.png). Print annotations: “The overall reward stays relatively constant”, “The format average grows”, and “The average entropy (randomness) increases after the first 200 steps.” The body text draws the conclusion the figure supports: the model receives too much reward simply for following the <think> tag format, as shown in the format_reward_avg plot, so it does not focus enough on answer correctness — reflected in the drop in eval_acc despite the high reward_avg. Per-step values are not recoverable at scan resolution.

Exercise 7.2: Making the format reward conditional Modify the format reward calculation, reward = rlvr_reward + format_reward_weight * format_reward so that the format reward is given only if the correctness reward (rlvr_reward) is non-zero. Repeat the training run with the conditional format reward. Does conditioning the format reward change training behavior and final accuracy?

Note: Because running these experiments can be resource intensive, reference results are provided in appendix B.

3 More GRPO modifications, tips, and tricks In chapter 6, we implemented a version of GRPO without the KL loss term, with clipped policy ratios, and with a format reward for introductory purposes. Then we added these concepts to build a solid foundation for understanding the original GRPO algorithm, which underlies most modern reasoning training frameworks. Figure 7.21 outlines this next step, where we’ll discuss additional modifications, tips, and tricks.

graph LR
    subgraph P ["Chapter 6: Intro to RLVR and GRPO"]
        direction TB
        A["Reinforcement learning with verifiable rewards (RLVR)"]
        B["Implementing a GRPO training loop"]
        C["Loading and evaluating the trained model"]
    end
    subgraph Q ["This chapter: Improving GRPO"]
        direction TB
        D1["1 - Plotting and analyzing basic training metrics"]
        D2["2 - Tracking more advanced training metrics"]
        D3["3 - Adding clipped policy ratios"]
        D4["4 - Adding a KL loss term"]
        D5["5 - Adding a format reward"]
        D6["6 - Additional GRPO tips and tricks"]
    end
    P --> Q

[!visual-conversion] Figure 7.21 — Flowchart showing progression from RLVR and GRPO basics to the advanced techniques of this chapter (printed p. 264, scan page-276.png). All six topics are complete: we plotted basic and advanced training metrics, added clipped policy ratios and a KL loss term, added a format reward, and collected additional GRPO tips and tricks. The next chapter turns from reinforcement learning to distillation. recently.

As far as RLVR with GRPO goes, we learned that there are many knobs to tune. Besides changing the basic settings, such as the learning rate, maximum response length, and prompt format, there is a nearly infinite number of settings and modifications to try. Exploring a single modification, or a small handful of modifications, thoroughly could become a month- or year-long research project for a small research team.

Algorithms are expected to keep changing and evolving. It is important, though, to understand the fundamentals and the general ideas behind them so you can understand and appreciate these improvements.

In the months following the success of DeepSeek-R1, many researchers propose changes to the original GRPO algorithm that improved both training stability and final performance. The following selection of suggested improvements comes from DAPO, Dr. GRPO, DeepSeek-V3.2, and others (you can find a full list of references and links in appendix A):

  1. Filter out zero-gradient examples (DAPO): Skip prompts where all sampled responses receive the same reward, because these groups produce no useful advantage signal.

  2. Use active sampling (DAPO): Oversample or prioritize prompts that produce a mix of correct and incorrect responses, because these provide a stronger learning signal.

  3. Switch from sequence-level to token-level loss (DAPO): Compute the loss over individual tokens rather than whole responses, which can reduce length-related bias.

  4. Omit the KL loss term (DAPO and Dr. GRPO): Remove the KL penalty when it hurts stability or performance, especially in math reasoning settings.

  5. Use a larger clipping range (DAPO): Relax the clipping threshold so the policy can make larger updates when the reward signal is reliable.

  6. Truncate importance-sampling ratios (verl): Cap very large importance weights so a few off-policy samples cannot dominate the update.

  7. Remove standard-deviation normalization of advantages (Dr. GRPO): Normalize rewards relative to the group mean but avoid dividing by the reward standard deviation.

  8. Tune the KL strength by domain (DeepSeek-V3.2): Use different KL coefficients for different data types, including zero KL for math tasks.

  9. Reweight the KL term with importance sampling (DeepSeek-V3.2): Correct the KL estimate when rollouts are sampled from an older policy rather than the current policy.

  10. Mask unsuitable off-policy sequences (DeepSeek-V3.2): Exclude rollout sequences that are too unlikely under the current policy.

  11. Preserve the sampling mask for top-p or top-k sampling (DeepSeek-V3.2): Compute probabilities only over the token set that was actually available during sampling.

12 Keep the original GRPO advantage normalization (DeepSeek-V3.2): Retain the standard group-based advantage normalization when it works well empirically.

13 Normalize each reward component before aggregation (GDPO): Normalize different reward types separately before combining them into a total reward.

14 Apply sequence-level importance sampling and clipping (GSPO): Correct and clip updates at the whole-sequence level instead of only at the token level.

15 Clip importance-sampling weights rather than token updates (CISPO): Limit the importance weights directly, so off-policy corrections remain stable.

Detailed explanations, code examples, and training run results for those modifications are outside the scope of this chapter. If you’re interested, you can find them in the book’s supplementary materials at https://mng.bz/nZVv.

Summary

  • Training reasoning models with GRPO can become unstable over longer runs, even when the implementation is correct and rewards initially improve.

  • Interpreting GRPO training requires tracking multiple metrics jointly (average rewards, response length, evaluation accuracy, advantage statistics, and entropy):

    • Basic metrics such as loss mainly serve as sanity checks in GRPO and should not be overinterpreted in isolation.

    • Advantage statistics provide useful diagnostics: the mean should remain near zero by design, while the standard deviation reflects the strength and stability of the learning signal.

    • Entropy measures how uncertain the model is during generation. Very low entropy can signal collapse, and very large entropy can indicate unstable updates and randomness in the model responses.

  • Clipped policy ratios limit how much the policy can change between updates and can substantially improve training stability over longer runs.

  • Adding a KL divergence term constrains long-term drift from a reference model but can destabilize training when the rewards collapse.

  • For math reasoning tasks, several recent systems report better stability and performance by omitting the KL term altogether.

  • Auxiliary format rewards can improve the response structure, such as encouraging the use of and tokens.

  • Beyond the original GRPO algorithm, many recent extensions modify advantage normalization, importance sampling, clipping strategies, and KL handling to improve stability and efficiency.