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.
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 for state, for observation, for action, for reward, for policy and 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 is a complete description of the environment at time : 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 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 is the agent's output at time . 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 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 , takes , and the environment responds with and . 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 is the agent's behaviour: a mapping from what it observes to what it does. A deterministic policy outputs one action, . A stochastic policy outputs a probability distribution over actions, . 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 is the expected return when starting in state and following policy afterwards. The action-value function is the expected return when taking action in state first, then following .
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 between 0 and 1:
The return is random, because the environment and a stochastic policy are random. The agent's objective is the expected return:
The discount factor has two readings, and both are useful:
- Mathematical convenience. With and bounded rewards, the sum is finite.
- A horizon. A reward steps away is weighted by . The weights fall to about after roughly steps, the effective horizon. With 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:
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 at every moment, and how much weight gives to future rewards.
Things to try:
- Select Pole-only and set . The effective horizon is 10 steps (0.2 s). In the table, the pole-only controller's 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 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 :
| Symbol | Name | Meaning | Grid-world example |
|---|---|---|---|
| State space | All possible states | Every non-wall cell | |
| Action space | All possible actions | Up, right, down, left | |
| Transition dynamics | Probability of landing in after taking in | Move one cell, or stay if blocked. With slip, sometimes a random direction | |
| Reward function | Expected reward for that transition | −1 per step, +20 at the goal, −20 in a pit | |
| Discount factor | How much future reward counts | 0.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, . 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 or . It can only sample them by acting. Methods that learn without ever building an explicit model of 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 :
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:
Once you know , acting optimally is trivial: in every state, pick . 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 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 (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:
- Observationo_t: sensor vector
- Actor policyπ_θ(a | o_t)
- Actiona_t: joint targets
- Environmentphysics simulator steps
- New observation and rewardo_t+1, r_t+1, done
- Learning algorithme.g. PPO, from a batch of rollouts
- Updated policy weightsθ ← θ + Δθ
Loops back: Updated policy weights → Observation
- 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.
- 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.
- Improve. The policy's weights are nudged to make the better-than-expected actions more probable in those situations.
- 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.
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 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 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, . This is "optimism in the face of uncertainty". The classic UCB1 algorithm uses .
- 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.
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 . ε-greedy becomes greedy. Then set : 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 suggests an algorithm. If the agent's estimate were correct, then after any transition it would satisfy . When it does not, nudge it towards that target:
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 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 for the action 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 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 , and the arrow is the greedy action. The chart below it is the real return of every training episode.
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 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 , which is awkward when the action is a continuous 12-dimensional vector. Policy-gradient methods instead parameterise the policy directly, , and adjust by gradient ascent on the expected return. The policy-gradient theorem gives an estimator that needs only sampled experience:
Here is an estimate of the advantage: how much better action turned out than the policy's average behaviour in that state, . 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 , 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:
It has low variance but is biased whenever the critic is wrong. The full Monte Carlo return minus is unbiased but noisy. Generalised advantage estimation (GAE) (Schulman et al., 2015) blends them with a second parameter :
With , GAE is the one-step TD error. With , 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
and maximises the clipped surrogate objective
with 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 . If the advantage was negative, it stops rewarding decreases past . The policy can still change, but there is no incentive to change it by more than about 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.
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.
| Training | Inference (deployment) | |
|---|---|---|
| Where | Simulator, usually on a GPU | The robot's onboard computer |
| Policy | Stochastic: actions sampled for exploration | Usually deterministic: the mean action |
| Weights | Updated after every batch | Frozen |
| Critic | Used to compute advantages | Not present |
| Rewards | Computed every step | Not computed: there is no reward on the real robot |
| Privileged information | Available to the critic | Not available |
| Cost | Hours of GPU time, millions to billions of steps | One small network evaluation per control step |
| Timing | Can run faster or slower than real time | Must 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
float32per step, usually the weighted sum of many terms. - Done flags:
terminatedandtruncatedbooleans per step. - Policy outputs at collection time: the log-probability and the critic's , both needed by PPO.
These records are stored in a rollout buffer, an array indexed by time step and environment. With parallel environments each collecting steps, a buffer holds tensors such as:
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)For example, environments and steps give about 98,000 transitions per batch. These sizes are illustrative, not Asimov's.
A trajectory (or rollout) is one environment's sequence . 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 : 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 (documented): the 45 actor inputs listed earlier. Note what is missing: base linear velocity, contact forces, toe states and terrain.
- Action (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 (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): , 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.
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))The interaction loop
Every RL system, however large, reduces to this loop. Here a placeholder policy controls CartPole and the loop records a trajectory.
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()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.
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 * entropyThe 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 formalises the problem. A robot sees observations, not states, so it is really partially observable.
- The agent maximises the expected discounted return . The discount sets an effective horizon of about 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/stepAPI 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.