Skip to content

Actor-Critic PPO with GAE

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

What This Shows

  • Joint Actor-Critic module producing discrete policy logits and scalar state values over batched horizons [B, T]
  • Reverse-scan Generalized Advantage Estimation via nn::rl::gae_advantages
  • Multi-epoch clipped PPO surrogate updates inside a compiled for_loop using nn::rl::ppo_clipped_loss, value MSE loss, and policy entropy regularization

GAE Rollout and Multi-Epoch Clipped PPO

let (adv, ret) = gae_advantages(&rewards, &values.detach(), &dones, &bootstrap, 0.99, 0.95);
let adv_norm = (&adv - adv.mean()) / (adv.std() + 1e-6);

let ppo_update = jit(|(m, o, obs, actions, old_lp, adv, ret): ...| {
    for_loop(ppo_epochs, (m, o, Tensor::scalar(0.0)), |_, (mut m, mut o, _)| {
        let (loss, grads) = value_and_grad(
            |p: ActorCritic| {
                let (logits, values) = p.forward(&obs);
                let lp = gather_token_log_probs(&logits, &actions);
                let pg_loss = ppo_clipped_loss(&lp, &old_lp, &adv, None, 0.2);
                let vf_loss = mse_loss(&values, &ret);
                let all_lp = log_softmax_axis(&logits, 2);
                let entropy = -(&all_lp.exp() * &all_lp).sum_axis(2).mean();
                pg_loss + vf_loss * 0.5 - entropy * 0.01
            },
            &m,
        );
        o.step(&mut m, &grads);
        (m, o, loss)
    })
});

Running

cargo run --release --example ppo
JACOBI_BACKEND=cpu cargo run --release --example ppo