Downloads · 30 days
16
8% of all-time downloads
lordChipotle/Llama3GRPOReasoning
Llama3GRPOReasoning is a reinforcement learning model from lordChipotle. Use it for the reinforcement learning task on the model card, and read the license before you ship it in a product.
Please visit our notebook for a full walkthrough on this project.
Downloads · 30 days
16
8% of all-time downloads
All-time downloads
212
Public
Parameters
8B
16.1 GB on disk
Likes
1
Public
Click a slice to open those files.
.safetensors16.1 GB · 100%
From the Hugging Face model README
Please visit our notebook for a full walkthrough on this project.
This model is a fine-tuned version of meta-llama/Meta-Llama-3.1-8B-Instruct trained using Group Relative Policy Optimization (GRPO) to enable autonomous mathematical reasoning capabilities. Unlike traditional supervised fine-tuning approaches, this model learned to reason through reinforcement learning without requiring pre-labeled reasoning examples or teacher model distillation.
<thinking> tags<answer> tagsWhile setting up a GRPO config is straightforward, understanding what each hyperparameter means and how the underlying training logic works is essential. This guide walks through the GRPO training loop, highlighting the key code paths in trl/trainer/grpo_trainer.py.
GRPO is built on top of the TRL Trainer class, but it customizes key parts of the training pipeline by overriding several critical methods:
compute_lossprepare_inputThese functions are the heart of GRPO's training logic.
In each train_step:
Trainer.train_step() in the parent class first calls prepare_input() in the GRPO trainercompute_loss() with the output of prepare_input()self.num_iterations to generate fresh completionsExample Configuration:
num_iterations = 4: generate completions every 4 global steps. Each global step can consist of k grad accumulation stepsgradient_accumulation_steps = 5: buffer stores 5 sets of completionsnum_iterations = 1, completions are not reused, and buffering may be unnecessary@profiling_decorator
def _prepare_inputs(self, inputs: dict) -> dict:
mode = "eval" if self.control.should_evaluate else "train"
if mode == "train":
if self.state.global_step % self.num_iterations == 0:
inputs = self._generate_and_score_completions(inputs)
self._buffered_inputs[self._step % self.args.gradient_accumulation_steps] = inputs
else:
inputs = self._buffered_inputs[self._step % self.args.gradient_accumulation_steps]
self._step += 1
else:
inputs = self._generate_and_score_completions(inputs)
return inputs
Conversations are stored in the "prompt" field. The apply_chat_template() function is used to convert this into a generation-ready string:
prompt = tokenizer.apply_chat_template(
example["prompt"],
tools=tools,
tokenize=False,
add_generation_prompt=True
)
For the non-vLLM implementation path:
max_prompt_lengthExample Output: The last 5 tokens for 6 generations made on GPU0. With batched inference, we append EOS (128009) for early completed answers:
prompt_completion_ids[:,-5:]
# Output tensor:
tensor([[128009, 128009, 128009, 128009, 128009],
[128009, 128009, 128009, 128009, 128009],
[128009, 128009, 128009, 128009, 128009],
[ 279, 1176, 220, 605, 14741],
[ 220, 430, 568, 11021, 220],
[128009, 128009, 128009, 128009, 128009]], device='cuda:0')
Note: You can check the code for vLLM path which is more efficient.
Completion masks identify valid (non-EOS) completions. Each rank computes completion masks based on the first occurrence of EOS.
Example Mask: The following is the mask for the completions shown above:
completion_mask[:,-5:]
# Output tensor:
tensor([[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1],
[0, 0, 0, 0, 0]], device='cuda:0', dtype=torch.int32)
Each rank performs the following operations:
Setup:
Total Prompts Processed per Iteration:
Prompt Distribution Example on GPU 0 (Rank 0):
Note: Other ranks may hold the remaining replicas of Prompt #2 and additional prompts.
Reward Normalization Process:
For Prompt #1:
For Prompt #2:
Important: That's why all-gather is needed so each rank has access to the required replicas.
step % G) during the first iterationnum_iterations windownum_iterations step (i.e., at global_step % num_iterations == 0)Key Points:
Note: Old and current policy logprobs will be identical when
num_iterations = 1.
$$\text{GRPO} = -\mathbb{E}{(s,a)}\left[\frac{\pi(a|s)}{\pi{\text{old}}(a|s)} A(s,a)\right] + \beta \cdot \text{KL}[\pi(\cdot|s) | \pi_{\text{ref}}(\cdot|s)]$$
Steps:
Concatenate prompt_ids + completion_ids
Run forward pass through old policy to compute \(\pi_{\text{old}}(a|s)\)
Run forward pass through ref policy to compute \(\pi_{\text{ref}}(a|s)\)
Run forward pass through current policy to compute \(\pi(a|s)\)
num_iterations > 1; otherwise the same as old policyCompute KL loss between \(\pi(a|s)\) and \(\pi_{\text{ref}}(a|s)\)
Compute advantage-weighted logprobs: \(\frac{\pi(a|s)}{\pi_{\text{old}}(a|s)} \times A(s,a)\)
| Component | What It Does | Why It Matters |
|---|---|---|
| GRPO Trainer Class | Extends the TRL Trainer, overrides prepare_input and compute_loss | Customizes the loss and input preparation for rollout reuse and reward learning |
| train_step | Calls prepare_input then compute_loss | Controls how and when rollouts and gradients are processed |
| prepare_input() | Generates and buffers rollouts once every num_iterations steps | Allows reuse of expensive rollouts across multiple updates |
| Prompt Construction | Uses apply_chat_template to create generation-ready input | Ensures the model sees correctly formatted conversational prompts |
| Inference | Uses on-device or vLLM backend to generate completions | Provides actions for which logprobs and rewards are computed |
| Completion Masking | Identifies valid (non-EOS) completions | Ensures reward/logprob computation only applies to meaningful tokens |
| Reward Normalization | Aggregates and normalizes rewards across GPUs for each prompt | Yields correct advantage estimates across distributed setup |
| Logprob Computation | Computes logprobs of old, ref, and current policy | Needed for KL and advantage-weighted loss; reused if num_iterations > 1 |
| compute_loss() | Combines KL divergence and advantage-weighted logprob ratio | Drives the optimization update direction for the policy |
trl/trainer/grpo_trainer.py to help understand the GRPO training workflow.*The model was trained using multiple custom reward functions:
<thinking> and <answer> tag structureThe model expects a specific system prompt to maintain the structured output format:
SYSTEM_PROMPT = """
Respond in the following format and make sure the entire response is wrapped in <reasoning> and <answer> tags with no other text outside of these tags:
<thinking>
your reasoning goes here and do not use newlines so that the entire reasoning becomes a single paragraph
</thinking>
<answer>
your answer goes here
</answer>
"""
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("your-username/llama3-grpo-math-reasoning")
tokenizer = AutoTokenizer.from_pretrained("your-username/llama3-grpo-math-reasoning")
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": "Mark is looking to buy a total of 12 pieces of fruit at the store. He has already chosen 3 apples. He has also selected a bunch of bananas containing 4 bananas. How many oranges does he need to pick out to have 12 total pieces of fruit?"}
]
input_text = tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=False)
inputs = tokenizer(input_text, return_tensors="pt")
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=128,
temperature=0.7,
top_p=0.9,
do_sample=True
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(response)
Expected Output:
<thinking>
Mark wants 12 total pieces of fruit. He already has 3 apples and 4 bananas, which gives him 3 + 4 = 7 pieces of fruit. To reach 12 total pieces, he needs 12 - 7 = 5 more pieces of fruit, which would be oranges.
</thinking>
<answer>
5
</answer>
If you use this model, please cite:
@misc{llama3-grpo-math-reasoning,
title={Llama 3.1-8B Mathematical Reasoning via Group Relative Policy Optimization},
author={[Your Name]},
year={2025},
howpublished={\\url{https://huggingface.co/your-username/llama3-grpo-math-reasoning}}
}
This model inherits the license from meta-llama/Meta-Llama-3.1-8B-Instruct. Please refer to the original model's license for usage terms.