GSPO
Code source and cost
- The complete implementation comes from
datawhalechina/agentic-rl-lab/experiments/gspo. This page was checked against commitec51068; the source links and commands below refer to that revision.- The 100-step training run had a measured PyTRIO cost of ¥155.80 (
96.42Kprefilling /17.75Mtrain /15.84Msample tokens), averaging about 85 seconds per step for roughly 2 hours 22 minutes total. These are measurements from one reference run, not fixed pricing.- See the SwanLab 100-step run for full curves. Because this example spans multiple data, rollout, custom-loss, training, and evaluation modules, this page explains the core logic and complete loop while the source repository remains the runnable reference.

Introduction
GSPO (Group Sequence Policy Optimization), introduced by the Qwen team in 2025, keeps the group rollout, outcome reward, and group-relative advantage of GRPO without requiring a separate value model. Its core change moves importance ratio calculation and clipping from the token level to the sequence level:
GRPO: ratios and clipping decisions per completion. GSPO: 1 ratio and 1 clipping decision per completion.

| Stage | GRPO | GSPO |
|---|---|---|
| Group rollout | Sample completions per prompt | Same |
| Reward | One outcome reward per completion | Same |
| Advantage | Within-group normalization, one per completion | Same |
| Importance ratio | One per token | One per completion |
| Clipping | Keep / clip per token | One decision per completion |
| Loss | Aggregate token objectives | Aggregate sequence objectives directly |
This example uses Qwen/Qwen3.5-4B and PyTRIO's forward_backward_custom() custom loss API to run 100 steps of LoRA training on DAPO-Math-17K, then evaluates the Base Model alongside checkpoints at Steps 20, 40, 60, 80, and 100 on AIME25.
Objective
GRPO computes a policy probability ratio for every generated token:
A completion of length produces ratios and clipping decisions.
GSPO instead averages the token log-ratios across the completion before exponentiating, yielding a single length-normalized sequence ratio:
The normalization keeps sequence ratios on a comparable scale across different response lengths. The entire completion then shares one ratio and one clipping decision:
The paper's default clipping thresholds are:
epsilon_low = 3e-4
epsilon_high = 4e-4This range is much tighter than typical GRPO clipping thresholds because it constrains the length-normalized geometric mean ratio over the full sequence rather than individual token ratios. Because rewards are assigned at the full-completion level, sequence-level importance sampling aligns the optimization unit with the reward unit and reduces variance from long sequences.
The math verifier uses math_verify on the final \boxed{} answer (1 if correct, 0 if wrong or missing) and standardizes rewards within each prompt group:
When all completions in a group are correct or all are wrong, every advantage is 0. This reproduction follows the base GSPO objective without adding Dynamic Sampling or resampling; zero-gradient degenerate groups are skipped before the remote forward/backward call while keeping their zero objectives in the original denominator.
Configuration
| Item | Configuration |
|---|---|
| Base model | Qwen/Qwen3.5-4B |
| Training method | PyTRIO LoRA, rank 32 |
| Training data | DAPO-Math-17K, 17,126 cleaned training problems |
| Training steps | 100 steps |
| Batch per step | 8 prompt groups × 8 completions = 64 rollouts |
| Token budgets | max prompt 2,048 tokens · max completion 4,096 tokens |
| Sampling | temperature=1.0, top_p=1.0, top_k=-1 |
| Reward | Final \boxed{} + math_verify, binary 0/1 outcome reward |
| Loss | Local custom GSPO sequence-level loss (forward_backward_custom), clip 3e-4 / 4e-4 |
| Optimizer | Adam, lr 4e-5, β (0.9, 0.95) |
| Checkpoints | state + sampler weights every 20 steps |
Project layout
experiments/gspo/
├── prepare_data.py # Download, clean, deduplicate, and pin DAPO-Math and AIME25
├── data.py # Load training JSONL, deterministic shuffle, wrap-around cursor
├── reward.py # Extract \boxed{}, math_verify equivalence check, 0/1 reward
├── rollout.py # Prompt building, concurrent group rollout, token/logprob alignment, advantage
├── loss.py # Datum construction, GSPOMeta, sequence ratio and clipping loss
├── train.py # Main loop, PyTRIO calls, SwanLab logging, and checkpoints
├── eval.py # Base / LoRA AIME25 evaluation and JSONL output
├── analyse.py # Aggregate checkpoint metrics and plot 1×2 figure
└── start.md # Quick-start command checklistSee the full source at experiments/gspo.
Environment and data
Requires Python >=3.13. The local machine handles data loading, reward scoring, local GSPO loss computation, and loop orchestration; PyTRIO handles model sampling, LoRA forward/backward passes, optimizer updates, and checkpoint storage remotely.
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout ec51068085d647775915a91ce8441cb3441e4ccf
uv sync
trio login
swanlab loginDownload and validate the pinned DAPO-Math-17K training set and the 30-problem AIME25 evaluation set:
uv run python experiments/gspo/prepare_data.pyCore logic
The end-to-end GSPO × PyTRIO loop is shown below (the diagram illustrates the default 4 prompt groups; the 100-step run sets --groups-per-step 8):

1. Concurrent group rollout and degenerate groups
rollout.py samples 8 completions concurrently per prompt using the latest LoRA sampler weights and enforces strict length matching between completion_tokens and sampling_logprobs. reward.py extracts the final complete \boxed{} answer and verifies equivalence via math_verify (no length penalty or extra format reward), then standardizes rewards within each group. Degenerate groups with zero advantages are filtered out in train.py to avoid wasted remote compute.
2. Autoregressive shift and local GSPO loss
build_datum() in loss.py shifts prompt and completion tokens for autoregressive prediction:
model_input = prompt_tokens + completion_tokens[:-1]
target_tokens = [0] * (len(prompt_tokens) - 1) + completion_tokensDatum.loss_fn_inputs carries only target_tokens, while local GSPOMeta stores rollout sampling_logprobs, sequence advantage, and completion_tokens length. forward_backward_custom() returns differentiable logprobs under the current policy for each target token, and make_gspo_loss_fn() computes the sequence ratio and clipping over the completion slice:
for meta, current_values in zip(metas, logprobs_list, strict=True):
current = current_values.float().reshape(-1)
current_completion = current[-meta.completion_tokens :]
sampling = torch.as_tensor(
meta.sampling_logprobs,
dtype=torch.float32,
device=current.device,
)
# Geometric mean of per-token probability ratios
log_ratio = (current_completion - sampling).mean()
seq_ratio = torch.exp(log_ratio)
# Single sequence-level clipping decision
clipped_ratio = torch.clamp(
seq_ratio,
min=1.0 - config.clip_ratio_low,
max=1.0 + config.clip_ratio_high,
)
unclipped_objective = seq_ratio * meta.advantage
clipped_objective = clipped_ratio * meta.advantage
sequence_objectives.append(
torch.minimum(unclipped_objective, clipped_objective)
)
# Equal weight per sequence; degenerate groups remain in normalization_sequences
gspo_loss = -torch.stack(sequence_objectives).sum() / normalization_sequencesSkipping degenerate groups saves remote forward/backward compute while keeping their zero objectives in normalization_sequences, preventing gradient inflation on the remaining active sequences.
3. One update per rollout batch
train.py connects the stages into a synchronous on-policy loop:
Load and shuffle dataset
→ Create LoRA TrainingClient and fetch tokenizer once
→ Refresh sampler from latest LoRA weights each step
→ Concurrent group rollout
→ Filter zero-advantage degenerate groups
→ forward_backward_custom
→ optim_step
→ Log to SwanLab and save periodic checkpointsThe client does not split rollout batches into mini-batches; each rollout batch runs one backward pass and one optim_step, leaving backend sharding and gradient accumulation to PyTRIO.
Running training
Run the 100-step training command from the repository root:
uv run python experiments/gspo/train.py \
--max-steps 100 \
--groups-per-step 8 \
--group-size 8 \
--max-prompt-tokens 2048 \
--max-tokens 4096 \
--save-every 20 \
--swanlab-mode onlineDuring training, gspo/normalization_sequences stays fixed at 64 sequences per step while gspo/train_sequences varies with the number of degenerate groups. Across the 100 steps, mean gspo/sequence_clip_fraction was 13.11% (6.25% on the final step). The SwanLab rollout/reward and GSPO loss curves are shown below:


AIME25 evaluation
Both the Base Model and all checkpoints are evaluated under identical settings (30 AIME25 problems × 12 samples = 360 generations, temperature=1.0, top_p=1.0, top_k=-1, max_tokens=8192):
# Evaluate Base Model
uv run python experiments/gspo/eval.py
# Evaluate a checkpoint (replace with the sampler weights path printed during training)
uv run python experiments/gspo/eval.py \
--model-path 'trio://RUN_ID/sampler_weights/GSPO_WEIGHTS_NAME' \
--output experiments/gspo/eval-results/aime25-gspo-step100.jsonl
# Aggregate summaries and generate the comparison chart
uv run python experiments/gspo/analyse.pyMetric definitions:
- Average@12: fraction of correct generations out of 360;
- Pass@12: fraction of the 30 problems solved at least once in 12 samples;
- Format: fraction of responses from which a valid
\boxed{}answer is extracted.
Reference results:
| Checkpoint | Average@12 | Pass@12 | Format | Correct generations | Solved problems | Mean completion tokens |
|---|---|---|---|---|---|---|
| Base (Run 1) | 41.11% | 56.67% | 46.67% | 148/360 | 17/30 | 6489.8 |
| Base (Run 2) | 40.56% | 66.67% | 47.50% | 146/360 | 20/30 | 6442.5 |
| Step 20 | 41.11% | 73.33% | 62.22% | 148/360 | 22/30 | 5775.4 |
| Step 40 | 37.78% | 60.00% | 87.22% | 136/360 | 18/30 | 4785.8 |
| Step 60 | 35.00% | 63.33% | 92.50% | 126/360 | 19/30 | 4438.7 |
| Step 80 | 34.72% | 73.33% | 97.78% | 125/360 | 22/30 | 3886.9 |
| Step 100 | 33.89% | 66.67% | 99.44% | 122/360 | 20/30 | 3358.1 |

Three observations stand out:
- Peak single-run Pass@12 gain: Steps 20 and 80 reach 73.33% Pass@12 (22/30), up 6.66 percentage points from Base Run 2 (66.67%). However, the two independent Base evaluations themselves differ by 10 percentage points; with only 30 problems in AIME25, single-run Pass@12 is sensitive to sampling variance.
- Average@12 declines after Step 20: Step 20 matches Base Run 1 at 41.11% (148/360), after which Average@12 trends downward to 33.89%.
- Clear, steady shift in output behavior: Format adherence rises continuously from 47.50% to 99.44%, while mean completion length drops from 6442.5 to 3358.1 tokens (roughly a 48% reduction).
The most solid takeaway from this run is that the custom GSPO training loop works end to end and strongly shifts output formatting and conciseness, whereas stable accuracy gains require additional seeds and repeated evaluations to confirm.
Metrics to watch
| Metric | Meaning |
|---|---|
reward/accuracy / reward/format_rate | Online rollout accuracy and \boxed{} formatting rate |
rollout/degenerate_groups | Number of all-correct or all-wrong zero-gradient groups |
gspo/loss | Sequence-level GSPO loss |
gspo/seq_ratio_mean | Mean sequence importance ratio (expected near 1.0) |
gspo/sequence_clip_fraction / gspo/token_clip_fraction | Fraction of sequences and tokens clipped at sequence level |
gspo/active_sequence_fraction | Share of non-degenerate sequences entering the gradient update |
Reproduction boundaries
- Algorithmic pipeline rather than paper-scale replication: The original GSPO paper fine-tunes from a cold-start
Qwen3-30B-A3B-Basemodel, splits each rollout batch into 4 optimizer mini-batches, and evaluates on AIME 2024, LiveCodeBench, and CodeForces. This example usesQwen/Qwen3.5-4BLoRA with one optimizer update per rollout batch on AIME25 and does not test MoE stability. - No matched GRPO baseline: Without a matched GRPO run on the same model, data, and compute budget, these numbers should not be interpreted as evidence that GSPO outperforms GRPO.
For full discussion and notes, see the upstream GSPO README.