Skip to content

Batched Rollout and GRPO

Full source in examples/grpo.rs. Run it with cargo run --release --example grpo.

What This Shows

  • Static-shape multi-layer nn::rl::RolloutKvCache supporting prompt prefill, repeat_for_group expansion (prompts x group_size), and in-place dynamic_update_slice updates
  • Batched autoregressive Rollout compiled into a single XLA for_loop via nn::rl::batched_rollout_loop and nn::rl::kv_cache_attention
  • Group-relative normalized advantages (nn::rl::grpo_advantages) and clipped policy-gradient optimization with Schulman's unbiased k3 KL penalty (nn::rl::grpo_loss)
  • Configurable CLI dimensions (--layers, --hidden, --heads, --kv-heads, --prompts, --group, --prompt-len, --rollout-len, --bf16, --rollout-only) for benchmarking batched Rollout throughput on GPUs

Batched Rollout and GRPO Update

let group_cache = prefill_cache.repeat_for_group(group_size);
let (gen_toks, old_lps, _final_cache) = batched_rollout_loop(
    rollout_len,
    first_tok,
    group_cache,
    start_pos,
    |tok, pos, c| {
        let (step_logits, next_c) = m.forward_with_cache(&cfg_r, &rope_r, tok, pos, c);
        let step_2d = step_logits.squeeze(1);
        let sampled = step_2d.sample_temperature(1.0);
        let lp = gather_token_log_probs(&step_2d, &sampled);
        (sampled.unsqueeze(1), lp.unsqueeze(1), next_c)
    },
);

let adv = grpo_advantages(&rewards, group_size, 1e-6).unsqueeze(1);
let loss = grpo_loss(&pi_lp, &old_lp, &ref_lp, &adv, None, 0.2, 0.04);

Running

# Fast CPU smoke test (batched rollout + 4 GRPO steps)
JACOBI_BACKEND=cpu cargo run --release --example grpo

# GPU batched Rollout benchmark in BF16 (64 sequences x 256 rollout tokens)
cargo run --release --example grpo -- --bf16 --rollout-only \
  --layers 24 --hidden 2048 --heads 16 --kv-heads 4 --head-dim 128 --ffn 5632 \
  --vocab 32768 --prompts 8 --group 8 --prompt-len 128 --rollout-len 256 --runs 5