Skip to content
Physical AI
Chapter 07 30 min read

Reinforcement Learning Fundamentals

Agents, rewards, policies and value functions from first principles — with algorithms that actually learn in your browser.

Nobody writes down the equations a learned walking policy follows. An engineer specifies what good behaviour looks like as a number, the reward, and an optimisation algorithm searches for a controller that earns a lot of it. The search happens by trial and error: the controller acts, the world responds, and the algorithm adjusts the controller so that actions which led to high reward become more likely. This chapter builds that idea from first principles. It defines the vocabulary precisely, works through the mathematics of returns, values and the Bellman equation, and runs four real learning algorithms in your browser so you can watch an agent go from random flailing to competent behaviour.

What reinforcement learning is

Reinforcement learning (RL) is the study of agents that learn to choose actions by interacting with an environment and receiving a numerical reward signal. Three features separate it from other kinds of machine learning:

  • No labelled answers. Supervised learning is given the correct output for every input. An RL agent is never told the correct action. It is only told, sometimes much later, how well things went.
  • Actions change the data. What the agent sees next depends on what it did. A robot that falls over collects data about lying on the floor, not about walking. The agent controls its own training distribution, for better and worse.
  • Delayed consequences. A foot placed badly now may cause a fall half a second later. The agent must work out which of its many earlier actions deserve credit or blame. This is the credit assignment problem.

A useful one-line summary: RL turns "what should the robot do?" into "what should the robot be rewarded for?", and hands the rest to an optimiser.

General principle

The formal framework in this chapter follows Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition (2018), which is freely available online. Notation varies between textbooks and papers; this chapter uses ss for state, oo for observation, aa for action, rr for reward, π\pi for policy and γ\gamma for the discount factor.

The core vocabulary

Every RL problem, from a board game to a humanoid, is described with the same small set of terms. Getting them precise now saves confusion in the next two chapters.

Agent and environment

The agent is the decision-maker: the thing that learns and acts. In robot locomotion, the agent is the policy, a function running on the robot's computer. It is not the whole robot.

The environment is everything outside the agent that it interacts with. For a walking robot this includes the floor and gravity, and also the robot's own body, motors, gearboxes, sensors and communication bus. The boundary is drawn where the agent's direct control ends. The policy outputs a number, and everything that happens to that number afterwards (actuator delay, torque limits, friction) is part of the environment. This is why actuator modelling matters so much in simulation: it is part of the world the agent must learn to act in.

State and observation

The state sts_t is a complete description of the environment at time tt: everything needed to predict what happens next, given the action. For a rigid-body robot, that means every body's position, orientation and velocity, plus contact conditions, motor internal states, pending messages on the bus and so on.

The observation oto_t is what the agent actually receives. It is usually a small, noisy, possibly delayed subset of the state. A robot measures its joint angles with encoders and its rotation rate with an IMU. It does not directly measure its linear velocity, the friction coefficient of the floor, or the exact moment its foot made contact.

When observation and state are the same, the problem is fully observable. When they differ, it is partially observable, discussed below.

Action

The action ata_t is the agent's output at time tt. Actions can be discrete (push left or push right, move up or down) or continuous (a vector of 12 real-valued joint targets). Robot locomotion uses continuous actions.

Reward

The reward rt+1r_{t+1} is a single real number the environment returns after each action. It is the only signal the agent has about what you want. A large positive reward means "more of this", a negative one means "less of this". Rewards are usually designed by an engineer as a weighted sum of terms: track the commanded velocity (positive), keep the torso upright (penalise tilt), use little energy (penalise torque), do not fall (large one-off penalty).

The indexing convention matters later. The agent observes sts_t, takes ata_t, and the environment responds with rt+1r_{t+1} and st+1s_{t+1}. The reward belongs to the transition, not to the state alone.

Episode

An episode is one run from a starting state until it ends. Episodes end in one of two ways, and RL code must treat them differently:

  • Termination: the task reached a natural end, such as the robot falling or reaching a goal. There is no future after this point, so its value is zero.
  • Truncation: the episode was cut off by a time limit. The robot was still upright and could have kept going. Its future value is not zero; the clock simply ran out.

Treating a time-out as if the robot had fallen teaches the agent that the world ends at an arbitrary step count. Gymnasium's API returns separate terminated and truncated flags for exactly this reason.

Policy

The policy π\pi is the agent's behaviour: a mapping from what it observes to what it does. A deterministic policy outputs one action, at=π(ot)a_t = \pi(o_t). A stochastic policy outputs a probability distribution over actions, at∼π(⋅∣ot)a_t \sim \pi(\cdot \mid o_t). During training, locomotion policies are usually stochastic: a neural network outputs the mean of a Gaussian distribution for each joint, and actions are sampled around that mean. The randomness is how the agent explores.

Value function

A value function predicts how much reward the agent will collect from now on. The state-value function Vπ(s)V^\pi(s) is the expected return when starting in state ss and following policy π\pi afterwards. The action-value function Qπ(s,a)Q^\pi(s, a) is the expected return when taking action aa in state ss first, then following π\pi.

Values are the agent's answer to "how good is my situation?". Rewards are immediate; values are long-term. A robot mid-stride with its torso leaning badly may still be collecting positive reward this instant, but its value is low because a fall is coming.

Expected cumulative reward: the return

The agent does not try to maximise the next reward. It tries to maximise the total reward over the future, called the return. For a task that could run indefinitely, adding up rewards forever could give an infinite sum, so future rewards are discounted by a factor γ\gamma between 0 and 1:

Gt=rt+1+γ rt+2+γ2rt+3+⋯=∑k=0∞γk rt+k+1G_t = r_{t+1} + \gamma\, r_{t+2} + \gamma^2 r_{t+3} + \dots = \sum_{k=0}^{\infty} \gamma^k\, r_{t+k+1}

The return is random, because the environment and a stochastic policy are random. The agent's objective is the expected return:

J(π)=Eπ[ G0 ]J(\pi) = \mathbb{E}_{\pi}\left[\, G_0 \,\right]

The discount factor has two readings, and both are useful:

  • Mathematical convenience. With γ<1\gamma < 1 and bounded rewards, the sum is finite.
  • A horizon. A reward kk steps away is weighted by γk\gamma^k. The weights fall to about 1/e1/e after roughly 1/(1−γ)1/(1-\gamma) steps, the effective horizon. With γ=0.99\gamma = 0.99 and a 50 Hz policy, that is 100 steps, or 2 seconds. The agent effectively plans about two seconds ahead.

The return can be written recursively, which is how code computes it, walking backwards from the end of an episode:

Gt=rt+1+γ Gt+1G_t = r_{t+1} + \gamma\, G_{t+1}

Experiment: rewards, penalties and discounting

The next experiment makes this concrete. Three fixed controllers (nothing learns here) drive the same simulated cart-pole from the same start: random pushes, a "pole-only" controller that balances the pole but ignores where the cart is (and has a small angle-sensor offset, so it slowly drifts off the track), and a full-state controller that balances and re-centres. Every 20 ms step earns a reward built from five terms, and the charts show each term, the discounted return GtG_t at every moment, and how much weight γ\gamma gives to future rewards.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How a per-step reward is built from several weighted terms, how the discount factor γ turns a sequence of rewards into the return G_t, and how the choice of γ can change which behaviour looks best.

How it works

Three fixed (not learned) controllers drive the same cart-pole simulation from the same initial state: uniformly random force, a pole-only PD controller that ignores cart position and has a 0.01 rad angle-sensor offset (so it drifts off the track after a few seconds), and a full-state linear controller that balances and re-centres the cart.

Every 20 ms step yields a reward made of five terms: an alive bonus, an upright penalty proportional to (θ/θmax)², a centring penalty proportional to (x/xmax)², an effort penalty proportional to (F/Fmax)², and a one-off failure penalty on the step the episode terminates. The discounted return is computed backwards with G_t = r_{t+1} + γ G_{t+1}. The table compares G₀ for all three controllers at the current γ.

Adjustable parameters

  • Controller: random, pole-only or full-state
  • Discount γ (0–0.999)
  • Alive bonus, upright, centre and effort weights
  • Failure penalty (0–100)
  • New initial state

Known limitations

  • Nothing learns in this experiment; it shows what a learner would be optimising. The reward terms are illustrative, loosely modelled on the kinds of terms used in locomotion rewards.
  • Real locomotion rewards have many more terms (velocity tracking, foot air time, joint limits, action rate). Menlo's reward design is in a guide page not yet reviewed for this site.

Equations

rt=walive−wθ (θ/θmax)2−wx (x/xmax)2−wu (F/Fmax)2−wfail 1[fell]r_t = w_{alive} - w_{\theta}\,(\theta/\theta_{max})^2 - w_x\,(x/x_{max})^2 - w_u\,(F/F_{max})^2 - w_{fail}\,\mathbb 1[\text{fell}]
Gt=∑k=0∞γkrt+k+1=rt+1+γ Gt+1G_t = \sum_{k=0}^{\infty} \gamma^k r_{t+k+1} = r_{t+1} + \gamma\, G_{t+1}
effective horizon≈11−γ steps\text{effective horizon} \approx \frac{1}{1-\gamma} \text{ steps}

Core update rule

// lib/sim/ch07-reward.ts
r.total = w.alive
        - w.upright * (th / thMax) ** 2
        - w.center  * (x / xMax) ** 2
        - w.effort  * (F / Fmax) ** 2
        - (fell ? w.failure : 0);

// discounted return, computed backwards over the episode
let G = 0;
for (let k = rewards.length - 1; k >= 0; k--) {
  G = rewards[k] + gamma * G;
  returns[k] = G;
}

Explained in Chapter 7: RL Fundamentals

Things to try:

  • Select Pole-only and set γ=0.9\gamma = 0.9. The effective horizon is 10 steps (0.2 s). In the table, the pole-only controller's G0G_0 is practically the same as the full-state controller's, even though it falls off the track six seconds later. The failure is invisible from the start.
  • Raise γ\gamma to 0.999. Now the late failure penalty and the lost alive bonuses count, and the full-state controller wins clearly. The discount factor decides how far ahead the agent cares. Too short, and it learns behaviours that fail slowly.
  • Set the Alive bonus and the Failure penalty to 0, leaving only the penalties. Every reward is now zero or negative, so a short episode accumulates fewer penalties than a long one. In the table, the random controller, which falls within a second or two, now scores higher than the pole-only controller, which balances for six seconds. An agent that cannot yet balance perfectly would learn from this reward that falling over quickly is its best option. This is a classic reward-design mistake.

The Markov decision process

The standard mathematical model of an RL problem is the Markov decision process (MDP). An MDP is a tuple (S,A,P,R,γ)(\mathcal{S}, \mathcal{A}, P, R, \gamma):

SymbolNameMeaningGrid-world example
S\mathcal{S}State spaceAll possible statesEvery non-wall cell
A\mathcal{A}Action spaceAll possible actionsUp, right, down, left
P(s′∣s,a)P(s' \mid s, a)Transition dynamicsProbability of landing in s′s' after taking aa in ssMove one cell, or stay if blocked. With slip, sometimes a random direction
R(s,a,s′)R(s, a, s')Reward functionExpected reward for that transition−1 per step, +20 at the goal, −20 in a pit
γ\gammaDiscount factorHow much future reward counts0.95

The word Markov names the key assumption: the next state depends only on the current state and action, not on the history of how you got there. Formally, P(st+1∣st,at)=P(st+1∣s0,a0,…,st,at)P(s_{t+1} \mid s_t, a_t) = P(s_{t+1} \mid s_0, a_0, \dots, s_t, a_t). If the state is complete, this holds by definition. Physics behaves this way: given every position and velocity, the past adds nothing.

The agent does not know PP or RR. It can only sample them by acting. Methods that learn without ever building an explicit model of PP are called model-free. Everything in this chapter, and PPO, is model-free.

The Bellman equations

Values satisfy a recursive consistency condition. The value of a state is the expected immediate reward plus the discounted value of wherever you land next. For a policy π\pi:

Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a) [ R(s,a,s′)+γ Vπ(s′) ]V^\pi(s) = \sum_{a} \pi(a \mid s) \sum_{s'} P(s' \mid s, a)\,\big[\,R(s, a, s') + \gamma\, V^\pi(s')\,\big] Qπ(s,a)=∑s′P(s′∣s,a) [ R(s,a,s′)+γ∑a′π(a′∣s′) Qπ(s′,a′) ]Q^\pi(s, a) = \sum_{s'} P(s' \mid s, a)\,\Big[\,R(s, a, s') + \gamma \sum_{a'} \pi(a' \mid s')\, Q^\pi(s', a')\,\Big]

In words: "how good is it here" equals "what I expect to get right now" plus "how good it is where I expect to end up", discounted. Terminal states have value zero.

The optimal value functions, the best achievable by any policy, satisfy the Bellman optimality equations, where the average over the policy's actions becomes a maximum:

V∗(s)=max⁡a∑s′P(s′∣s,a) [ R(s,a,s′)+γ V∗(s′) ]V^*(s) = \max_{a} \sum_{s'} P(s' \mid s, a)\,\big[\,R(s, a, s') + \gamma\, V^*(s')\,\big] Q∗(s,a)=∑s′P(s′∣s,a) [ R(s,a,s′)+γmax⁡a′Q∗(s′,a′) ]Q^*(s, a) = \sum_{s'} P(s' \mid s, a)\,\Big[\,R(s, a, s') + \gamma \max_{a'} Q^*(s', a')\,\Big]

Once you know Q∗Q^*, acting optimally is trivial: in every state, pick arg⁡max⁡aQ∗(s,a)\arg\max_a Q^*(s, a). That observation is the basis of Q-learning.

Partial observability

A walking robot's policy does not receive the state. It receives observations, which leave out quantities such as linear velocity, contact forces and terrain properties. The correct model is then a partially observable MDP (POMDP): the same tuple plus an observation model O(o∣s)O(o \mid s) describing what the agent sees in each state.

Under partial observability, the current observation alone may not be Markov. Two situations can look identical to the sensors yet require different actions. Standard remedies are:

  • Include history. Stack recent observations, or feed back the previous actions. A robot that knows what it commanded last step can partly infer how its body is moving.
  • Use memory. A recurrent network (for example an LSTM or GRU) carries an internal summary of the past.
  • Estimate the missing state. Train a separate estimator, or learn one implicitly.
  • Give the critic more information than the actor. During simulated training, the value function can use privileged quantities (true velocity, contact forces) that will not exist on the real robot, because the critic is thrown away at deployment. This is the subject of Chapter 8.

Asimov's actor receives a 45-dimensional observation: base angular velocity (3), projected gravity (3), the velocity command vx,vy,ωzv_x, v_y, \omega_z (3), joint positions (12), joint velocities (12) and the previous actions (12). Base linear velocity is deliberately excluded. The critic receives those 45 values plus 19 privileged ones, including base linear velocity, foot contact and contact forces, and the passive toe joint states, for 64 in total.

The previous actions in that list are a direct answer to partial observability: they give the policy a short memory of its own commands.

How an untrained robot learns

At the start of training, the policy is a neural network with random weights. Its actions are essentially noise: legs twitch, the robot collapses within a fraction of a second, and the episode terminates. Nothing about walking is built in. Training proceeds as a loop, repeated millions of times:

  1. Observationo_t: sensor vector
  2. Actor policyπ_θ(a | o_t)
  3. Actiona_t: joint targets
  4. Environmentphysics simulator steps
  5. New observation and rewardo_t+1, r_t+1, done
  6. Learning algorithme.g. PPO, from a batch of rollouts
  7. Updated policy weightsθ ← θ + Δθ

Loops back: Updated policy weights → Observation

The RL training loop. The inner cycle (observation → action → environment) runs every control step. The learning algorithm runs only after a batch of experience has been collected, then the updated weights are used for the next batch.
  1. Collect experience. The current policy controls the robot in simulation for a fixed number of steps. Every step records the observation, the action, the probability the policy assigned to it, the reward and whether the episode ended. When a robot falls, its environment resets and it starts again.
  2. Evaluate. The learning algorithm works out which actions turned out better or worse than expected. Actions followed by high returns get credit; actions followed by falls get blame.
  3. Improve. The policy's weights are nudged to make the better-than-expected actions more probable in those situations.
  4. Repeat with the improved policy.

Early on, the only behaviour that earns reward might be staying upright a little longer before falling. The policy shifts toward that. Then it learns to take a step without falling, because stepping keeps it upright longer when pushed by its own momentum. Gradually, tracking the commanded velocity starts to pay, and a gait emerges. No one designed the gait. It is whatever pattern of joint commands the optimiser found to maximise the reward in that simulator.

The policy produces actions, not animations

A common mental picture is that a trained policy "plays back" a walking motion, like an animation clip. It does not. At every control step, 50 times a second on Asimov, the policy reads the current observation and outputs the next action. Then it forgets that it did so, except through whatever history is in the observation.

On Asimov, physics runs at 200 Hz and the policy runs at 50 Hz, producing commanded joint targets from the latest available IO state.

The gait is an emergent property of repeating that observation-to-action mapping in a closed loop with the body and the floor. This is why a good policy recovers from a push: it does not need a "recovery animation". The push changes the observation, and the policy responds to the new observation the same way it responds to every observation, with whatever action its training found best there.

Experiment: learning to balance from scratch

The next experiment shows the whole loop on a problem small enough to train in seconds: balancing a pole on a cart. The dynamics and constants match the standard Gymnasium CartPole-v1 environment. The policy is linear: it weights five numbers (cart position, cart velocity, pole angle, pole angular velocity and a constant) and pushes left or right. The reward is +1 for every 20 ms step the pole stays up, so the return is simply how many steps it survived, up to 500.

Two real learners are available. REINFORCE is the simplest policy-gradient algorithm: it samples actions from a stochastic policy, waits until episodes finish, and makes actions that preceded long survival more likely. PPO, discussed below, is a more refined member of the same family. The cross-entropy method is a simpler, gradient-free search: try a population of random weight vectors, keep the best few, and sample the next population around them.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

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

Things to try:

  • Press play with REINFORCE at the default settings. The first episodes last about 20 steps, the same as random actions. Within a few hundred episodes the curve climbs, noisily, towards 500. Every point on that chart is a real episode run by the current policy.
  • Switch to Watch: random vs learned and compare the two carts side by side. The learned policy is a frozen snapshot: no learning happens while you watch. That is inference.
  • Press Evaluate 100 episodes each early in training and again later, to see the improvement measured on fresh episodes.
  • Set the step size α\alpha to its maximum and reset. Training may speed up, then collapse as one bad update destroys a good policy. Unstable updates are exactly the problem PPO's clipping addresses.
  • Try the cross-entropy learner. On this tiny problem it is faster than REINFORCE, because searching five weights directly is easy. Gradient-free search scales poorly to the tens of thousands of weights in a locomotion network, which is why gradient-based methods dominate there.

Exploration versus exploitation

An agent that always takes the action it currently believes is best (exploitation) can get stuck: if its early estimates are wrong, it never tries the alternatives that would reveal the mistake. An agent that keeps trying alternatives (exploration) gathers information but wastes reward on actions that are known to be poor. Balancing the two is a central problem of RL, and it does not arise in supervised learning, where the dataset is fixed.

The simplest setting that isolates this trade-off is the multi-armed bandit: a row of slot machines, each paying out with a hidden probability. There is only one state, so there is no credit assignment, only the question of which arm to pull. Common strategies are:

  • Greedy: always pull the arm with the highest estimated payout. Fast to exploit, and prone to locking onto a mediocre arm.
  • ε-greedy: be greedy, except with probability ε\varepsilon pull a random arm. Simple and robust, but it explores forever at the same rate, including arms that are clearly bad.
  • Upper confidence bound (UCB): add a bonus to each estimate that is large for rarely-tried arms, Q(a)+cln⁡t/N(a)Q(a) + c\sqrt{\ln t / N(a)}. This is "optimism in the face of uncertainty". The classic UCB1 algorithm uses c=2c = \sqrt 2.
  • Thompson sampling: keep a probability distribution over each arm's payout rate, draw one plausible value from each, and pull the arm whose draw is highest. Uncertain arms sometimes produce high draws, so they get tried in proportion to the chance they are actually best.
Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Why an agent must sometimes try actions that currently look worse, and how greedy, ε-greedy, UCB and Thompson sampling trade exploration against exploitation, measured by regret and by how often the best action is chosen.

How it works

A bandit is RL with a single state: each of k slot machines (arms) pays 1 with a hidden probability and 0 otherwise. The probabilities are drawn uniformly from [0.05, 0.95] when you press New machines.

Five strategies play the same machines. Each strategy runs 100 independent learners with their own random draws, and the charts average over them. All learners keep a sample-average estimate Q(a) per arm. Random ignores it. Greedy always takes the best estimate. ε-greedy explores at random with probability ε. UCB adds an exploration bonus c·√(ln t / N(a)) that shrinks as an arm is tried more. Thompson sampling keeps a Beta posterior per arm, samples one plausible success rate from each, and pulls the arm with the highest sample.

Regret is the expected reward lost compared with always pulling the best arm, computed from the true probabilities (which the learners never see).

Adjustable parameters

  • ε for ε-greedy (0–0.5)
  • UCB bonus scale c (0–3)
  • Pulls per frame (1–20)
  • 5 or 10 arms
  • Restart learners / new machines

Known limitations

  • A bandit has no state transitions: actions do not affect future situations. Full RL adds that credit-assignment problem on top of exploration.
  • Robot RL with continuous actions usually explores by adding Gaussian noise to the policy's actions (Menlo documents an initial policy noise std of 1.0), not by ε-greedy or UCB.

Equations

Qn+1(a)=Qn(a)+1N(a)(r−Qn(a))Q_{n+1}(a) = Q_n(a) + \tfrac{1}{N(a)}\big(r - Q_n(a)\big)
at=arg⁡max⁡a[Q(a)+cln⁡tN(a)](UCB)a_t = \arg\max_a \Big[Q(a) + c\sqrt{\tfrac{\ln t}{N(a)}}\Big] \quad \text{(UCB)}
p~a∼Beta⁡(1+Sa, 1+Fa),  at=arg⁡max⁡ap~a(Thompson)\tilde p_a \sim \operatorname{Beta}(1 + S_a,\, 1 + F_a),\; a_t = \arg\max_a \tilde p_a \quad \text{(Thompson)}
Regret(T)=∑t=1T(p∗−pat)\text{Regret}(T) = \sum_{t=1}^{T} \big(p^* - p_{a_t}\big)

Core update rule

// lib/sim/ch07-bandit.ts
switch (strategy) {
  case "epsilon-greedy":
    return rng() < eps ? randInt(rng, k) : argmax(Q);
  case "ucb":
    return argmax(Q.map((q, a) => q + c * Math.sqrt(Math.log(t + 1) / N[a])));
  case "thompson":
    return argmax(S.map((s, a) => betaSample(rng, 1 + s, 1 + N[a] - s)));
}
// after pulling arm a and observing reward r ∈ {0, 1}:
N[a] += 1;  S[a] += r;  Q[a] += (r - Q[a]) / N[a];

Explained in Chapter 7: RL Fundamentals

Things to try:

  • Watch the Greedy curve in the "% best arm" chart. It often plateaus well below 100%. Many of its 100 learners locked onto whichever arm paid out first.
  • Set ε=0\varepsilon = 0. ε-greedy becomes greedy. Then set ε=0.5\varepsilon = 0.5: it finds the best arm quickly but keeps wasting half its pulls, and its regret grows in a straight line.
  • Compare UCB and Thompson. Their regret curves bend over, because they stop exploring arms once those arms are confidently worse.

Robot RL with continuous actions explores differently: the policy outputs a Gaussian distribution, and the spread (standard deviation) of that Gaussian controls exploration. Training typically starts with a wide spread and the algorithm learns to narrow it as the policy improves.

Menlo lists an initial policy noise standard deviation of 1.0 for Asimov's actor.

Learning action values: Q-learning

The Bellman optimality equation for Q∗Q^* suggests an algorithm. If the agent's estimate Q(s,a)Q(s, a) were correct, then after any transition (s,a,r,s′)(s, a, r, s') it would satisfy Q(s,a)≈r+γmax⁡a′Q(s′,a′)Q(s, a) \approx r + \gamma \max_{a'} Q(s', a'). When it does not, nudge it towards that target:

Q(s,a)←Q(s,a)+α [ r+γmax⁡a′Q(s′,a′)⏟TD target−Q(s,a) ]Q(s, a) \leftarrow Q(s, a) + \alpha\,\big[\,\underbrace{r + \gamma \max_{a'} Q(s', a')}_{\text{TD target}} - Q(s, a)\,\big]

This is Q-learning (Watkins, 1989). The bracket is the temporal-difference (TD) error: the surprise between what the agent predicted and what one step of experience plus its own next estimate suggests. The learning rate α\alpha sets how far each update moves. Using its own estimate of the next state's value inside the target is called bootstrapping. It lets the agent learn from every single step without waiting for the episode to end.

Q-learning is off-policy: the target uses the best next action, regardless of which action the exploring agent actually takes next. SARSA is the on-policy variant: its target uses Q(s′,a′)Q(s', a') for the action a′a' the agent really will take, exploration included. SARSA therefore learns the value of its actual, exploring behaviour, and tends to prefer safer routes when random exploratory steps are dangerous.

With a table holding one number per state-action pair, Q-learning provably converges to Q∗Q^* if every pair keeps being visited and the learning rate decays appropriately.

Experiment: grid-world Q-learning

The agent below starts with a table of zeros and no knowledge of the grid. It explores ε-greedily, earns −1 per step, and ends episodes in the goal or a pit. Each cell is coloured by its learned value V(s)=max⁡aQ(s,a)V(s) = \max_a Q(s, a), and the arrow is the greedy action. The chart below it is the real return of every training episode.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

How a tabular agent with no prior knowledge learns action values Q(s, a) from rewards alone, how its greedy policy emerges from those values, and how α, γ, ε, slip and the reward design change what it learns.

How it works

The environment is an 8 × 6 grid: a small Markov decision process. The state is the agent's cell, the four actions move up, right, down or left, walls block movement, and every move earns the step reward. Entering the goal or a pit adds the goal reward or pit penalty and ends the episode. Episodes are also cut off after 100 steps; that cut-off is a truncation, not a terminal state, so the update still bootstraps from the next state. With slip > 0, the chosen action is replaced by a uniformly random one with that probability.

The agent stores one number per (state, action) pair in a table, initialised to zero. Each step it chooses an action ε-greedily, observes the reward and next state, and applies one temporal-difference update. Q-learning bootstraps from the best next action (off-policy). SARSA bootstraps from the action it will actually take next (on-policy). The value colour of each cell is V(s) = max_a Q(s, a), and the arrow is the greedy action.

The readouts compare the current greedy policy (evaluated from the Q-table without exploration) with a uniformly random policy evaluated over 300 episodes. The training curve plots the real return of every training episode, exploratory actions included.

Adjustable parameters

  • Algorithm: Q-learning or SARSA
  • Learning on/off (off = frozen greedy policy, i.e. inference)
  • Speed (0.1–2500 environment steps per frame)
  • Learning rate α (0.01–1)
  • Discount γ (0–0.99)
  • Exploration ε (0–1)
  • Slip probability (0–0.5)
  • Step, pit and goal rewards
  • Click cells to add or remove walls and pits

Known limitations

  • A table needs one entry per state–action pair. A walking robot's state is continuous and high-dimensional, so real locomotion uses neural-network function approximation instead.
  • The state is fully observed (the agent knows its cell). Robots see only partial, noisy observations.
  • Editing the grid keeps the old Q-table, so the agent must unlearn stale values; this is deliberate, to show adaptation.

Equations

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)](Q-learning)Q(s,a) \leftarrow Q(s,a) + \alpha\big[r + \gamma \max_{a'} Q(s',a') - Q(s,a)\big] \quad \text{(Q-learning)}
Q(s,a)←Q(s,a)+α[r+γ Q(s′,a′)−Q(s,a)],  a′∼ε-greedy(SARSA)Q(s,a) \leftarrow Q(s,a) + \alpha\big[r + \gamma\, Q(s',a') - Q(s,a)\big],\; a' \sim \varepsilon\text{-greedy} \quad \text{(SARSA)}
π(s)=arg⁡max⁡aQ(s,a),V(s)=max⁡aQ(s,a)\pi(s) = \arg\max_a Q(s,a), \qquad V(s) = \max_a Q(s,a)

Core update rule

// One environment step + one TD update (lib/sim/ch07-gridworld.ts)
const a = ag.a;                                       // chosen ε-greedily
const { next, reward, terminated } = envStep(grid, s, a, rewards, slip, rng);
let bootstrap = 0;
if (!terminated) {
  nextA = epsilonGreedy(Q, next, epsilon, rng);
  bootstrap = algorithm === "sarsa"
    ? Q[next * 4 + nextA]                              // on-policy
    : maxQ(Q, next);                                   // off-policy
}
const td = reward + gamma * bootstrap - Q[s * 4 + a];
Q[s * 4 + a] += alpha * td;

Explained in Chapter 7: RL Fundamentals

Things to try:

  • Watch how value spreads backwards from the goal. The cells next to the goal learn first, then their neighbours, one bootstrapped step at a time. This is the Bellman equation being solved by experience.
  • Set γ\gamma to 0.5. Values far from the goal become almost zero and the arrows there become arbitrary: the goal lies beyond the agent's horizon.
  • Set slip to 0.2 and compare Q-learning with SARSA. With random slips, routes that pass next to a pit become risky, and the learned path shifts.
  • Turn Learning off. The agent now follows its greedy policy with a frozen table: this is inference, and the training curve stops.
  • Click to add a wall across the learned path. The old values are now wrong, and you can watch the agent unlearn them.
  • Set the step reward to 0 and the goal reward to 0. The table stays at zero and nothing is learned. With no reward signal, there is nothing to learn from.

From tables to neural networks

A table works for 48 cells. A walking robot's observation is a vector of 45 real numbers, so a table is impossible: there are infinitely many states, and the robot will never visit the same one twice. Deep RL replaces the table with a neural network that maps an observation to an action (the actor) and, usually, to a value estimate (the critic). The network generalises: states that look similar get similar outputs, so experience in one state informs behaviour in states never seen. Function approximation also removes the convergence guarantees that tabular methods enjoy, which is one reason deep RL needs careful engineering.

Policy gradients and PPO

Q-learning picks actions by maximising over QQ, which is awkward when the action is a continuous 12-dimensional vector. Policy-gradient methods instead parameterise the policy directly, πθ(a∣o)\pi_\theta(a \mid o), and adjust θ\theta by gradient ascent on the expected return. The policy-gradient theorem gives an estimator that needs only sampled experience:

∇θJ(θ)=E[ ∑t∇θlog⁡πθ(at∣st)  A^t ]\nabla_\theta J(\theta) = \mathbb{E}\Big[\, \sum_t \nabla_\theta \log \pi_\theta(a_t \mid s_t)\; \hat A_t \,\Big]

Here A^t\hat A_t is an estimate of the advantage: how much better action ata_t turned out than the policy's average behaviour in that state, A(s,a)=Q(s,a)−V(s)A(s, a) = Q(s, a) - V(s). The gradient pushes up the log-probability of actions with positive advantage and pushes down those with negative advantage. REINFORCE, in the cart-pole experiment above, uses the normalised return as a crude advantage.

Actor-critic

Using raw returns makes the gradient very noisy, because a return mixes the effect of one action with the luck of everything afterwards. Actor-critic methods train a second network, the critic, to estimate V(s)V(s), and use it to compute lower-variance advantages. The actor chooses actions; the critic judges them. At deployment, only the actor is kept. Chapter 8 covers this architecture in detail, including Asimov's asymmetric actor and critic.

Generalised advantage estimation

With a critic, the simplest advantage estimate is the one-step TD error:

δt=rt+1+γ V(st+1)−V(st)\delta_t = r_{t+1} + \gamma\, V(s_{t+1}) - V(s_t)

It has low variance but is biased whenever the critic is wrong. The full Monte Carlo return minus V(st)V(s_t) is unbiased but noisy. Generalised advantage estimation (GAE) (Schulman et al., 2015) blends them with a second parameter λ\lambda:

A^tGAE=∑l=0∞(γλ)l δt+l\hat A_t^{\text{GAE}} = \sum_{l=0}^{\infty} (\gamma \lambda)^l\, \delta_{t+l}

With λ=0\lambda = 0, GAE is the one-step TD error. With λ=1\lambda = 1, it is the Monte Carlo advantage. Values around 0.95 are a common compromise. Intuitively, GAE asks "how much better than expected did things go?", trusting the critic more for the distant future and actual rewards more for the near future.

The clipped surrogate objective

Policy-gradient updates are fragile. One overly large step can move the policy into a region where it falls immediately, and then the data it collects is useless for recovering. Proximal Policy Optimization (PPO) (Schulman et al., 2017) limits how far each update can move the policy. It compares the new policy with the one that collected the data through the probability ratio

ρt(θ)=πθ(at∣st)πθold(at∣st)\rho_t(\theta) = \frac{\pi_\theta(a_t \mid s_t)}{\pi_{\theta_\text{old}}(a_t \mid s_t)}

and maximises the clipped surrogate objective

LCLIP(θ)=Et[ min⁡(ρt(θ) A^t,  clip⁡(ρt(θ), 1−ϵ, 1+ϵ) A^t)]L^{\text{CLIP}}(\theta) = \mathbb{E}_t\Big[\, \min\big(\rho_t(\theta)\, \hat A_t,\; \operatorname{clip}(\rho_t(\theta),\, 1-\epsilon,\, 1+\epsilon)\, \hat A_t\big) \Big]

with ϵ\epsilon typically 0.1 to 0.3. If an action had a positive advantage, the objective stops rewarding increases in its probability once the ratio passes 1+ϵ1 + \epsilon. If the advantage was negative, it stops rewarding decreases past 1−ϵ1 - \epsilon. The policy can still change, but there is no incentive to change it by more than about ϵ\epsilon per batch. This makes it safe to run several epochs of minibatch gradient descent on the same batch of data, which improves sample use. In practice the total loss also includes a value-function (critic) loss and often a small entropy bonus that discourages the policy from becoming deterministic too early.

Why PPO suits massively parallel simulation

PPO is on-policy: each batch must be collected by the current policy, used for a few epochs, then discarded. That sounds wasteful, and on a real robot it would be. In a GPU simulator, experience is cheap. Thousands of robots can be simulated in parallel, so a large, fresh batch is available in seconds. PPO also has few sensitive hyperparameters, handles continuous actions naturally through a Gaussian policy, and its clipping keeps training stable over thousands of updates.

General principle

Rudin et al. (2022), "Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning," trained a quadruped's locomotion policy with PPO and thousands of simulated robots on a single GPU, reaching flat-terrain walking in minutes of wall-clock time. That work popularised the parallel-simulation recipe now common in legged-robot RL.

PPO is our example, not a documented Asimov fact

Menlo's documentation does not name the RL algorithm used to train Asimov, nor the training library, number of parallel environments or hyperparameters. PPO is introduced here because it is a widely used actor-critic algorithm for locomotion that fits the documented actor/critic setup. Treat any statement on this site that Asimov "uses PPO" as an error.

Training versus inference

The same policy network lives two very different lives.

TrainingInference (deployment)
WhereSimulator, usually on a GPUThe robot's onboard computer
PolicyStochastic: actions sampled for explorationUsually deterministic: the mean action
WeightsUpdated after every batchFrozen
CriticUsed to compute advantagesNot present
RewardsComputed every stepNot computed: there is no reward on the real robot
Privileged informationAvailable to the criticNot available
CostHours of GPU time, millions to billions of stepsOne small network evaluation per control step
TimingCan run faster or slower than real timeMust finish every control period, every time

Inference is cheap. The documented Asimov actor network (45 inputs, hidden layers of 512, 256 and 128 units, 12 outputs) has about 190,000 weights. Evaluating it costs about 190,000 multiply-adds, which typically takes well under a millisecond on embedded-class hardware. All the expensive work happened during training.

Where the data comes from and what it looks like

RL has no dataset at the start. The agent generates its data by acting, and the data format follows directly from the loop.

  • Observation vector: a fixed-length array of floats, for example float32[45] for Asimov's actor. Each entry has a documented meaning and units. Most pipelines normalise observations, either with fixed scales or running mean and standard deviation statistics. Menlo documents that observation normalisation is enabled for Asimov.
  • Action vector: float32[12] for 12 actuated joints. What those numbers mean physically is part of the environment definition. Menlo documents them as commanded joint targets, but does not publish whether they are absolute angles or offsets from a default pose, or how they are scaled.
  • Reward: a single float32 per step, usually the weighted sum of many terms.
  • Done flags: terminated and truncated booleans per step.
  • Policy outputs at collection time: the log-probability log⁡πθold(at∣ot)\log \pi_{\theta_\text{old}}(a_t \mid o_t) and the critic's V(st)V(s_t), both needed by PPO.

These records are stored in a rollout buffer, an array indexed by time step and environment. With NN parallel environments each collecting TT steps, a buffer holds tensors such as:

Illustrative example
obs          [T, N, 45]   float32     actor observations
critic_obs   [T, N, 64]   float32     actor obs + privileged values
actions      [T, N, 12]   float32
log_probs    [T, N]       float32     log π_old(a | o)
values       [T, N]       float32     critic V(s)
rewards      [T, N]       float32
dones        [T, N]       bool        terminated (and truncation handled separately)
text

For example, N=4096N = 4096 environments and T=24T = 24 steps give about 98,000 transitions per batch. These sizes are illustrative, not Asimov's.

A trajectory (or rollout) is one environment's sequence o0,a0,r1,o1,a1,r2,…o_0, a_0, r_1, o_1, a_1, r_2, \dots. After each batch, advantages and return targets are computed from the buffer, the networks are updated, and the buffer is cleared.

A walking robot as an MDP

Here is how the abstract definitions map onto a legged robot such as Asimov. Documented items are marked; the rest are typical choices, shown for illustration.

  • State ss: the full simulator state: base position and orientation, base linear and angular velocity, all joint positions and velocities, including the passive toes, contact states and forces, actuator internal states and any delay buffers. The simulator knows all of it. The real robot knows only part.
  • Observation oo (documented): the 45 actor inputs listed earlier. Note what is missing: base linear velocity, contact forces, toe states and terrain.
  • Action aa (documented in part): 12 commanded joint targets at 50 Hz. How those targets become motor commands, and whether they are absolute angles or offsets, is not documented on the pages reviewed.
  • Reward rr (illustrative): a weighted sum such as positive terms for tracking the commanded forward, sideways and turning velocity, and penalties for torso tilt, vertical bouncing, joint torques, rapid changes between consecutive actions and joint-limit violations. Asimov's actual reward terms are described in a Menlo guide page this site has not yet reviewed.
  • Termination (illustrative): the base drops below a height threshold, the torso tilts past a limit, or a non-foot body touches the ground.
  • Truncation (illustrative): a time limit, for example 20 s, which is 1,000 policy steps at 50 Hz.
  • Initial state distribution (illustrative): a nominal standing pose with small random perturbations, plus a randomly sampled velocity command.
  • Discount (illustrative): γ=0.99\gamma = 0.99, an effective horizon of about 2 s at 50 Hz, long enough to cover a few steps of a gait cycle.

Code

Tabular Q-learning with Gymnasium

This is the grid-world algorithm in Python, on Gymnasium's built-in FrozenLake environment (a 4 × 4 grid with holes). Note the Gymnasium API: reset() returns (observation, info), and step() returns five values with separate terminated and truncated flags.

q_learning_frozenlake.py
import numpy as np
import gymnasium as gym
 
env = gym.make("FrozenLake-v1", is_slippery=False)
n_states = env.observation_space.n
n_actions = env.action_space.n
 
Q = np.zeros((n_states, n_actions))
alpha, gamma, epsilon = 0.5, 0.95, 0.1
rng = np.random.default_rng(0)
 
for episode in range(2000):
    obs, info = env.reset(seed=episode)
    done = False
    while not done:
        # epsilon-greedy action selection
        if rng.random() < epsilon:
            action = env.action_space.sample()
        else:
            best = np.flatnonzero(Q[obs] == Q[obs].max())
            action = int(rng.choice(best))           # random tie-break
 
        next_obs, reward, terminated, truncated, info = env.step(action)
 
        # TD target: no bootstrap from a terminal state,
        # but DO bootstrap if the episode was merely truncated
        target = reward if terminated else reward + gamma * Q[next_obs].max()
        Q[obs, action] += alpha * (target - Q[obs, action])
 
        obs = next_obs
        done = terminated or truncated
 
env.close()
print("greedy policy:", Q.argmax(axis=1).reshape(4, 4))
python

The interaction loop

Every RL system, however large, reduces to this loop. Here a placeholder policy controls CartPole and the loop records a trajectory.

rollout.py
import gymnasium as gym
 
env = gym.make("CartPole-v1")
obs, info = env.reset(seed=0)
 
trajectory = []          # list of (obs, action, reward, terminated, truncated)
episode_return = 0.0
 
for t in range(1000):
    action = env.action_space.sample()       # replace with policy(obs)
    next_obs, reward, terminated, truncated, info = env.step(action)
    trajectory.append((obs, action, reward, terminated, truncated))
    episode_return += reward
    obs = next_obs
 
    if terminated or truncated:
        print(f"episode ended at t={t}, return={episode_return}")
        obs, info = env.reset()
        episode_return = 0.0
 
env.close()
python

GAE and the PPO loss in PyTorch

A compact sketch of PPO's core for a continuous-action policy. A full implementation adds observation normalisation, minibatching, several epochs per batch, learning-rate schedules and gradient clipping. Spinning Up and the original paper are good references for the details.

ppo_core.py
import math
 
import torch
import torch.nn as nn
from torch.distributions import Normal
 
 
class Actor(nn.Module):
    def __init__(self, obs_dim: int, act_dim: int, init_std: float = 1.0):
        super().__init__()
        self.mean = nn.Sequential(
            nn.Linear(obs_dim, 256), nn.ELU(),
            nn.Linear(256, 128), nn.ELU(),
            nn.Linear(128, act_dim),
        )
        self.log_std = nn.Parameter(torch.full((act_dim,), math.log(init_std)))
 
    def dist(self, obs: torch.Tensor) -> Normal:
        return Normal(self.mean(obs), self.log_std.exp())
 
 
@torch.no_grad()
def compute_gae(rewards, values, dones, last_value, gamma=0.99, lam=0.95):
    """rewards, values, dones: [T, N]; last_value: [N]. Returns advantages, returns."""
    T = rewards.shape[0]
    advantages = torch.zeros_like(rewards)
    gae = torch.zeros_like(last_value)
    for t in reversed(range(T)):
        next_value = last_value if t == T - 1 else values[t + 1]
        not_done = 1.0 - dones[t].float()
        delta = rewards[t] + gamma * next_value * not_done - values[t]
        gae = delta + gamma * lam * not_done * gae
        advantages[t] = gae
    return advantages, advantages + values
 
 
def ppo_loss(actor, critic, obs, actions, old_log_probs, advantages, returns,
             clip_eps=0.2, value_coef=0.5, entropy_coef=0.01):
    dist = actor.dist(obs)
    log_probs = dist.log_prob(actions).sum(dim=-1)          # joint log-prob over action dims
    ratio = torch.exp(log_probs - old_log_probs)
 
    adv = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
    surrogate = torch.min(ratio * adv,
                          torch.clamp(ratio, 1.0 - clip_eps, 1.0 + clip_eps) * adv)
    policy_loss = -surrogate.mean()
 
    # an asymmetric critic would take privileged critic_obs here instead of obs
    value_loss = (critic(obs).squeeze(-1) - returns).pow(2).mean()
    entropy = dist.entropy().sum(dim=-1).mean()
    return policy_loss + value_coef * value_loss - entropy_coef * entropy
python

The dones mask in compute_gae stops value from leaking across episode boundaries. A careful implementation treats truncation differently, by bootstrapping from the critic's estimate of the state at which the episode was cut off rather than zeroing it.

Limitations and common misconceptions

“The network memorises a gait.”

A locomotion policy stores a mapping from observations to actions, not a sequence of poses. The gait appears only when that mapping runs in closed loop with a body and the ground. Put the same policy on a robot with different leg masses or a slower actuator, and the "gait" changes or collapses, because the loop it was trained in has changed.

“The reward tells the robot how to walk.”

The reward only scores outcomes. It says nothing about how to achieve them. The optimiser will find any behaviour that scores well, including ones you did not intend.

Reward hacking. Because the optimiser maximises exactly what you wrote, not what you meant, it exploits loopholes. A velocity-tracking reward without an orientation penalty can produce a robot that slides forward on its knees. A penalty-only reward (as in the discounting experiment with the alive bonus and failure penalty at zero) can make falling immediately the optimal strategy. Simulator bugs are loopholes too: if contact is slightly wrong, a policy may learn to vibrate its feet to "skate". Careful reward design and watching the trained behaviour, not just the return curve, are essential.

Sample inefficiency. Model-free RL needs enormous amounts of experience. The tiny cart-pole above needs tens of thousands of steps. Locomotion policies are typically trained on hundreds of millions to billions of simulated steps. That is only practical because simulation is fast and parallel, and it is the main reason RL for robots is done in simulation and transferred, rather than trained directly on hardware.

Sensitivity and instability. Results can depend strongly on hyperparameters, network initialisation and random seed. A curve that rose for one seed may plateau for another. Robust claims need several seeds.

Exploits of the simulator. A policy is only as good as the environment it was trained in. It will exploit any unrealistic physics, perfect sensors or zero-latency timing it is given. This is the sim-to-real problem from Chapter 1, and the reason Menlo models actuator delay, saturation, friction and CAN timing in Asimov's simulator.

Partial observability is easy to forget. If the critic or the reward relies on information the actor never sees, the actor can only act on its best guess. Training succeeds when the actor's observations contain enough information to infer what it needs.

A high training return is not a deployed result. Training returns include exploration noise and are measured in the training simulator. What matters is the deterministic policy's performance on fresh episodes, ideally in a differently-randomised simulator, and ultimately on hardware.

How this connects to the rest of the site

  • Chapter 1 introduced the perception–action loop. RL is a way of learning the controller block in that loop.
  • Chapter 6 describes the environment Asimov's policy is trained in: the physics, actuator models, sensor timing and observation pipeline.
  • Chapter 8 develops the actor-critic architecture, including Asimov's documented asymmetric actor (45 inputs) and critic (64 inputs).
  • Chapter 9 follows a trained locomotion policy from observations to joint targets on the robot.

Key takeaways

Key takeaways

  • RL learns behaviour from a scalar reward through trial and error. The agent is never told the correct action.
  • An MDP (S,A,P,R,γ)(\mathcal S, \mathcal A, P, R, \gamma) formalises the problem. A robot sees observations, not states, so it is really partially observable.
  • The agent maximises the expected discounted return Gt=∑kγkrt+k+1G_t = \sum_k \gamma^k r_{t+k+1}. The discount sets an effective horizon of about 1/(1−γ)1/(1-\gamma) steps.
  • Value functions predict long-term return and satisfy the Bellman equations. Q-learning solves them from experience with TD updates.
  • Exploration is necessary because the agent's own actions determine what it learns about.
  • A locomotion policy maps each observation to the next action, 50 times a second on Asimov. The gait emerges from that loop; it is not stored as an animation.
  • PPO is a common actor-critic algorithm for locomotion: GAE advantages, a clipped objective for stable updates, and on-policy batches from massively parallel simulation. Menlo does not document which algorithm Asimov uses.
  • Training is expensive, stochastic and happens in simulation. Inference is a cheap, frozen, deterministic forward pass on the robot.

References and further reading

  • R. S. Sutton and A. G. Barto, Reinforcement Learning: An Introduction, 2nd ed. (MIT Press, 2018). Free online.
  • J. Schulman, F. Wolski, P. Dhariwal, A. Radford and O. Klimov, "Proximal Policy Optimization Algorithms," 2017. arXiv:1707.06347.
  • J. Schulman, P. Moritz, S. Levine, M. Jordan and P. Abbeel, "High-Dimensional Continuous Control Using Generalized Advantage Estimation," 2015. arXiv:1506.02438.
  • N. Rudin, D. Hoeller, P. Reist and M. Hutter, "Learning to Walk in Minutes Using Massively Parallel Deep Reinforcement Learning," CoRL 2021 (PMLR 164, 2022). arXiv:2109.11978.
  • OpenAI, Spinning Up in Deep RL, an introduction to policy gradients, PPO and the surrounding concepts.
  • Farama Foundation, Gymnasium documentation, including the reset/step API and the CartPole and FrozenLake environments.
  • R. J. Williams, "Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning," Machine Learning 8, 229–256 (1992). The REINFORCE algorithm.
  • A. G. Barto, R. S. Sutton and C. W. Anderson, "Neuronlike Adaptive Elements That Can Solve Difficult Learning Control Problems," IEEE Transactions on Systems, Man, and Cybernetics 13(5), 1983. The original cart-pole learning task.
  • P. Auer, N. Cesa-Bianchi and P. Fischer, "Finite-time Analysis of the Multiarmed Bandit Problem," Machine Learning 47, 235–256 (2002). The UCB1 algorithm.
  • Menlo, Reinforcement Learning for Locomotion, the Asimov actor and critic specification used in this chapter.