microGRPO
microGRPO copied to clipboard
đ A tiny single-file implementation of Group Relative Policy Optimization (GRPO) as introduced by the DeepSeekMath paper
microGRPO
A tiny single-file implementation of Group Relative Policy Optimization (GRPO) as introduced by the DeepSeekMath paper[^1][^2][^3].
đ microGRPO now implements the GRPO improvements introduced by Dr. GRPO[^4], Apple's LOOP[^5], and Mistral's Magistral[^6]:
- đĨ Remove per-group advantage normalization[^4]
- âŗī¸ Leave-one-out advantage[^5] (LOOP only)
- đĨ Eliminate KL divergence[^5]
- đĸ Normalize loss[^5]
- đ Add per-batch advantage normalization[^6] (Magistral only)
- đĻ Relax trust region bounds[^5]
- đ Eliminate non-diverse groups[^5]
[^1]: The DeepSeekMath paper [^2]: Yuge (Jimmy) Shi's blog post [^3]: Nathan Lambert's RLHF book [^4]: The Dr. GRPO paper [^5]: Apple's LOOP paper [^6]: Mistral's Magistral paper
Features
- đ Only ~300 lines of code
- đĻ In pure NumPy, with autograd to compute the gradient
- â Type annotated and linted
- âī¸ Easily swap out the default game and train on any other game or environment
Getting started
[!NOTE] You'll need to install uv to run the commands below.
To start teaching a policy to play a simplified version of Battleship, run:
uv run microgrpo.py
You should see that the policy learns to improve its average score from around 15% to about 50% over 2000 iterations:
Background
File structure
The file is structured into five sections:
- đšī¸ Game (~50 lines): An implementation of the Battleship board game
- đ Environment (~60 lines): The API with which an agent can interact with the game
- đ§ Policy (~30 lines): A model that produces action probabilities given the observed environment state
- đ¯ GRPO (~80 lines): The GRPO objective function and training data generator
- ⥠Train (~50 lines): The loop that collects training data and optimizes the GRPO objective with AdamW
GRPO config
Starting a training run only requires defining a GRPOConfig with your choice of environment (here, BattleshipEnv) and a function that evaluates the policy model given its parameters (here, neural_battleship_policy):
# Define the environment and the policy model to optimize.
grpo_config = GRPOConfig(environment=BattleshipEnv, policy=neural_battleship_policy)
# Train the policy model by maximizing the GRPO objective with AdamW.
θ_star, rewards_val = train_grpo(θ_init := neural_battleship_policy_init(), grpo_config)