Skip to content
Physical AI
All experiments

Learning to balance a cart-pole

An untrained policy improving through repeated interaction with a simulated environment, the training curve that interaction produces, and the difference between random actions and the learned policy once training stops.

Loading simulation…

What it demonstrates

An untrained policy improving through repeated interaction with a simulated environment, the training curve that interaction produces, and the difference between random actions and the learned policy once training stops.

How it works

The environment is the classic cart-pole: a cart on a 4.8 m track carries a hinged 1 m pole. The equations of motion and constants match the Gymnasium CartPole-v1 reference implementation (cart 1 kg, pole 0.1 kg, explicit Euler at 20 ms per step). Each step the policy picks push left or push right with 10 N. The reward is +1 for every step the pole stays within ±12° and the cart within ±2.4 m. Episodes end on failure (terminated) or after 500 steps (truncated).

The policy is linear in five features: the scaled cart position, cart velocity, pole angle, pole angular velocity and a constant. Two real learners are available. REINFORCE (a policy-gradient method) uses a stochastic logistic policy P(push right) = σ(w · φ), collects a batch of episodes, computes discounted returns-to-go, normalises them as a baseline, and takes one gradient-ascent step. The cross-entropy method (a derivative-free policy search) samples a population of weight vectors from a Gaussian, runs one episode with each, keeps the best fraction and refits the Gaussian to them.

Watch mode freezes a snapshot of the learned weights and runs it side by side with a uniformly random policy in real time. The Evaluate button runs 100 fresh episodes of each and reports the mean number of steps survived.

Adjustable parameters

  • Mode: train, or watch random vs learned
  • Algorithm: REINFORCE or cross-entropy method (switching resets learning)
  • Training speed (0.1–2500 environment steps per frame)
  • REINFORCE step size α (0.2–20), discount γ (0.9–0.999), episodes per update (1–20)
  • CEM population size (6–60) and elite fraction (0.1–0.5)

Known limitations

  • Cart-pole is a toy. A linear policy is enough here; a walking robot needs a neural network with tens of thousands of weights or more and millions to billions of simulated steps.
  • One environment at a time. Locomotion training typically runs thousands of environments in parallel on a GPU.
  • REINFORCE has high-variance gradients. PPO, discussed in this chapter, adds a learned critic, generalised advantage estimation and a clipped objective to make updates more stable.
  • The learned policy is evaluated on the same simulator it was trained on. There is no sim-to-real gap to cross.

Equations

πw(right∣s)=σ(w⊤ϕ(s))\pi_w(\text{right}\mid s) = \sigma\big(w^\top \phi(s)\big)
Gt=∑k=0T−t−1γkrt+k+1,A^t=Gt−mean⁡(G)std⁡(G)G_t = \sum_{k=0}^{T-t-1} \gamma^k r_{t+k+1}, \qquad \hat A_t = \frac{G_t - \operatorname{mean}(G)}{\operatorname{std}(G)}
w←w+α 1N∑t∇wlog⁡πw(at∣st) A^t,∇wlog⁡πw=(at−σ(w⊤ϕt)) ϕtw \leftarrow w + \alpha\, \frac{1}{N}\sum_t \nabla_w \log \pi_w(a_t\mid s_t)\, \hat A_t, \qquad \nabla_w \log \pi_w = (a_t - \sigma(w^\top\phi_t))\,\phi_t
CEM: wi∼N(μ,diag⁡σ2),  (μ,σ)←fit(top ρ fraction by return)\text{CEM: } w_i \sim \mathcal N(\mu, \operatorname{diag}\sigma^2),\; (\mu, \sigma) \leftarrow \text{fit}(\text{top } \rho \text{ fraction by return})

Core update rule

// REINFORCE update after a batch of episodes (lib/sim/ch07-cartpole.ts)
for (const ep of batch) {
  let G = 0;
  for (let t = ep.length - 1; t >= 0; t--) {
    G = 1 + gamma * G;            // reward +1 per step survived
    ep[t].G = G;                  // discounted return-to-go
  }
}
// normalise returns (baseline), then ascend the log-likelihood gradient
for (const { phi, a, p, G } of allSteps) {
  const adv = (G - meanG) / stdG;
  for (let i = 0; i < 5; i++) grad[i] += (a - p) * phi[i] * adv;
}
for (let i = 0; i < 5; i++) w[i] += lr * grad[i] / allSteps.length;

Explained in Chapter 7: RL Fundamentals