Skip to content

RL

GSPO

Code source and cost

  • The complete implementation comes from datawhalechina/agentic-rl-lab/experiments/gspo. This page was checked against commit ec51068; the source links and commands below refer to that revision.
  • The 100-step training run had a measured PyTRIO cost of ¥155.80 (96.42K prefilling / 17.75M train / 15.84M sample 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.

PyTRIO usage for the 100-step GSPO training run

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: TT ratios and TT clipping decisions per completion. GSPO: 1 ratio and 1 clipping decision per completion.

Sequence-level importance ratio comparison between GSPO and GRPO

StageGRPOGSPO
Group rolloutSample GG completions per promptSame
RewardOne outcome reward per completionSame
AdvantageWithin-group normalization, one A^i\hat{A}_i per completionSame
Importance ratioOne wi,tw_{i,t} per tokenOne sis_i per completion
ClippingKeep / clip per tokenOne decision per completion
LossAggregate token objectivesAggregate 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:

wi,t(θ)=πθ(yi,t∣x,yi,<t)πθold(yi,t∣x,yi,<t)w_{i,t}(\theta) = \frac{\pi_\theta(y_{i,t} \mid x, y_{i,\lt t})}{\pi_{\theta_{\mathrm{old}}}(y_{i,t} \mid x, y_{i,\lt t})}

A completion of length TT produces TT ratios and TT clipping decisions.

GSPO instead averages the token log-ratios across the completion before exponentiating, yielding a single length-normalized sequence ratio:

si(θ)=exp⁡(1∣yi∣∑t=1∣yi∣log⁡πθ(yi,t∣x,yi,<t)πθold(yi,t∣x,yi,<t))s_i(\theta) = \exp\left(\frac{1}{|y_i|}\sum_{t=1}^{|y_i|} \log \frac{\pi_\theta(y_{i,t} \mid x, y_{i,\lt t})}{\pi_{\theta_{\mathrm{old}}}(y_{i,t} \mid x, y_{i,\lt t})}\right)

The 1/∣yi∣1 / |y_i| normalization keeps sequence ratios on a comparable scale across different response lengths. The entire completion then shares one ratio and one clipping decision:

JGSPO(θ)=1G∑i=1Gmin⁡(siA^i,  clip⁡(si,  1−εlow,  1+εhigh)A^i)\mathcal{J}_{\mathrm{GSPO}}(\theta) = \frac{1}{G}\sum_{i=1}^{G} \min\left(s_i \hat{A}_i,\; \operatorname{clip}\left(s_i,\; 1 - \varepsilon_{\mathrm{low}},\; 1 + \varepsilon_{\mathrm{high}}\right)\hat{A}_i\right)

The paper's default clipping thresholds are:

text
epsilon_low  = 3e-4
epsilon_high = 4e-4

This 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:

A^i=ri−mean⁡(r)std⁡(r)+10−8\hat{A}_i = \frac{r_i - \operatorname{mean}(r)}{\operatorname{std}(r) + 10^{-8}}

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 ​

ItemConfiguration
Base modelQwen/Qwen3.5-4B
Training methodPyTRIO LoRA, rank 32
Training dataDAPO-Math-17K, 17,126 cleaned training problems
Training steps100 steps
Batch per step8 prompt groups × 8 completions = 64 rollouts
Token budgetsmax prompt 2,048 tokens · max completion 4,096 tokens
Samplingtemperature=1.0, top_p=1.0, top_k=-1
RewardFinal \boxed{} + math_verify, binary 0/1 outcome reward
LossLocal custom GSPO sequence-level loss (forward_backward_custom), clip 3e-4 / 4e-4
OptimizerAdam, lr 4e-5, β (0.9, 0.95)
Checkpointsstate + sampler weights every 20 steps

Project layout ​

text
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 checklist

See 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.

bash
git clone https://github.com/datawhalechina/agentic-rl-lab.git
cd agentic-rl-lab
git checkout ec51068085d647775915a91ce8441cb3441e4ccf

uv sync
trio login
swanlab login

Download and validate the pinned DAPO-Math-17K training set and the 30-problem AIME25 evaluation set:

bash
uv run python experiments/gspo/prepare_data.py

Core 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):

End-to-end GSPO and PyTRIO training loop

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:

text
model_input   = prompt_tokens + completion_tokens[:-1]
target_tokens = [0] * (len(prompt_tokens) - 1) + completion_tokens

Datum.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:

python
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_sequences

Skipping 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:

text
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 checkpoints

The 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:

bash
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 online

During 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:

Rollout and reward curves across the 100-step GSPO run

GSPO loss, sequence ratio, and clip fraction curves across 100 steps

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):

bash
# 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.py

Metric 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:

CheckpointAverage@12Pass@12FormatCorrect generationsSolved problemsMean completion tokens
Base (Run 1)41.11%56.67%46.67%148/36017/306489.8
Base (Run 2)40.56%66.67%47.50%146/36020/306442.5
Step 2041.11%73.33%62.22%148/36022/305775.4
Step 4037.78%60.00%87.22%136/36018/304785.8
Step 6035.00%63.33%92.50%126/36019/304438.7
Step 8034.72%73.33%97.78%125/36022/303886.9
Step 10033.89%66.67%99.44%122/36020/303358.1

AIME25 evaluation progress across Base and GSPO checkpoints

Three observations stand out:

  1. 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.
  2. 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%.
  3. 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 ​

MetricMeaning
reward/accuracy / reward/format_rateOnline rollout accuracy and \boxed{} formatting rate
rollout/degenerate_groupsNumber of all-correct or all-wrong zero-gradient groups
gspo/lossSequence-level GSPO loss
gspo/seq_ratio_meanMean sequence importance ratio (expected near 1.0)
gspo/sequence_clip_fraction / gspo/token_clip_fractionFraction of sequences and tokens clipped at sequence level
gspo/active_sequence_fractionShare 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-Base model, splits each rollout batch into 4 optimizer mini-batches, and evaluates on AIME 2024, LiveCodeBench, and CodeForces. This example uses Qwen/Qwen3.5-4B LoRA 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.