GSPO
GSPO: Group Sequence Policy Optimization Zheng et al. (Qwen Team) arXiv
GSPO makes one clipping decision for the whole answer when individual token probabilities are noisy.
Why it mattered
When training Mixture-of-Experts models with token-level GRPO, tiny router flips between sampling and training cause individual token importance ratios to explode, destabilizing entire runs. The Qwen team discovered that lifting importance sampling to the sequence level — matching the sequence-level reward — makes MoE RL rock solid.
Core insightCompute one length-normalized geometric-mean importance ratio per response: Clip with a tight sequence-scale range (, ) and multiply by sequence advantage .
grad's catalog includes single-GPU 80 GB MoE bases (qwen/qwen3.6-35b-a3b at 76 GB and google/gemma-4-26b-a4b-it at 68 GB), and every Datum carries exact 1:1 weights and sampling_logprobs so grad.masked_mean() computes the exact sequence geometric mean in 10 lines of losses.CustomLoss.
When to use
Use GSPO when running RL on sparse Mixture-of-Experts (MoE) models such as qwen/qwen3.6-35b-a3b or google/gemma-4-26b-a4b-it, where minor expert-routing flips make token-level PPO ratios explode. On dense models, standard GRPO or DAPO is usually sufficient.
Step-by-step walkthrough
- 01
Open a single-GPU MoE Trainer
qwen/qwen3.6-35b-a3b(76 GB) andgoogle/gemma-4-26b-a4b-it(68 GB) both fit LoRA RL on a single 80 GB H100. Using a native MoE checkpoint lets you test sequence-level ratio stability directly against real expert routing.client.trainers.create(model='qwen/qwen3.6-35b-a3b', adapter=adapters.LoRA(rank=32), ...) - 02
Compute the sequence-level geometric mean ratio
Use
grad.masked_mean(lp - old_lp, mask)strictly over generated tokens (prompt and tool tokens stay masked to0.0), then exponentiate. Taking the geometric mean over generated tokens smooths out single-token expert switches without needing routing-replay buffers.s = torch.exp(grad.masked_mean(lp - old_lp, mask)) - 03
Apply tight sequence clipping inside CustomLoss
Clip to against sequence advantage
a_seqand send exact token gradients back to the trainer. Tight sequence-level clipping bounds keep step sizes safe even though the ratio is averaged across hundreds of tokens.trainer.forward_backward(batch, loss=GSPOLoss(eps_low=3e-4, eps_high=4e-4))
Implementation
import torch
import grad
from grad import Environment, Grad, Rubric, Scorer, Task, adapters, advantages, losses, optim, validators
class GSPOLoss(losses.CustomLoss):
def __init__(self, eps_low: float = 3e-4, eps_high: float = 4e-4):
self.eps_low, self.eps_high = eps_low, eps_high
def compute(self, data, out):
terms = []
for i, d in enumerate(data):
lp, mask = out.logprobs[i], out.mask(i)
old_lp = torch.tensor(d.sampling_logprobs, dtype=torch.float32)
adv = torch.tensor(d.advantages, dtype=torch.float32)
s = torch.exp(grad.masked_mean(lp - old_lp, mask))
a_seq = grad.masked_mean(adv, mask)
terms.append(-torch.minimum(s * a_seq, s.clamp(1.0 - self.eps_low, 1.0 + self.eps_high) * a_seq))
return torch.stack(terms).mean()
client = Grad()
ds = client.datasets.from_hf("openai/gsm8k", config="main", split="train", prompt="question", answer="answer", limit=2560)
tasks = [Task(id=str(i), prompt=r["messages"][0]["content"], expected_output=r["expected_output"]) for i, r in enumerate(ds.records())]
env = Environment(
rubric=Rubric([Scorer("math", fn=validators.MathEquivalence())]),
max_turns=1,
system_prompt="Solve step by step and end with \\boxed{...}.",
)
total_steps = 80
with client.trainers.create(
model="qwen/qwen3.6-35b-a3b",
name="gspo-moe",
adapter=adapters.LoRA(rank=32),
total_steps=total_steps,
max_cost_usd=15.0,
) as trainer:
for step in range(1, total_steps + 1):
chunk = tasks[((step - 1) * 32) % len(tasks) : ((step - 1) * 32) % len(tasks) + 32]
groups = env.rollout_groups(trainer, tasks=chunk, group_size=8, max_tokens=1024, temperature=1.0)
batch = grad.with_advantages(groups, advantages.GroupStd())
if not batch:
continue
fb = trainer.forward_backward(batch, loss=GSPOLoss(eps_low=3e-4, eps_high=4e-4))
opt = trainer.optim_step(optim.AdamW(lr="auto", objective="rl"))
fb_res, opt_res = fb.result(), opt.result()
trainer.log_metrics(opt_res.step, {"reward": grad.mean_reward(groups), "loss": fb_res.loss})
artifact = trainer.export(name="gspo-moe").result().artifactBenchmarks
Reported results from the original paper compared against its baseline.
Models & datasets
| Model | Duration | Est. cost |
|---|---|---|
Qwen3.6 35B A3BMoE (recommended)qwen/qwen3.6-35b-a3b | ~42 min | ~$4.20 |
Gemma 4 26B A4B ITMoEgoogle/gemma-4-26b-a4b-it | ~36 min | ~$3.40 |
Qwen3 8Bdense smoke runqwen/qwen3-8b | ~20 min | ~$1.60 |
| Dataset | Source | Size |
|---|---|---|
| GSM8K Math | Hugging Face | 7,473 train / 1,319 test |
| MATH-500 | Hugging Face | 500 competition problems |
Practical gotchas
- Sequence-level ratios have far tighter variance than per-token ratios — start with tight clipping (
eps_low=3e-4,eps_high=4e-4) on MoE models. - Always use
out.mask(i)so prompt tokens and index0never dilute the geometric mean. - For multi-minibatch updates on MoE, call
grad.recompute_logprobs(trainer, batch)before the first minibatch if sampling and training kernels differ slightly.