electronics engineering
Course handbook · Fifth year
Reinforcement and Imitation Learning
Reinforcement and imitation learning: Markov decision processes, Bellman equations, Q-learning, DQN, policy gradient and PPO, behaviour cloning and DAgger, Gymnasium, Stable-Baselines3 and PufferLib, simulation and Gaussian splatting, applications.
- 9Topics
- 0Solved exercises
- 22Formula sheet
Free handbook generated from the lessons of the site and updated often, every time a lesson or an exercise changes: the latest version is always at www.electronics-engineering.com/handbook/reinforcement-learning. Links work in the PDF too.
1Markov decision processes
In supervised learning someone provides the right answer for every example. In reinforcement learning (RL) nobody knows it: an agent tries actions in an environment, receives a numerical reward and must learn by itself which behaviour maximises it in the long run. This is how programs that play better than champions (AlphaGo), robots that walk, traffic controllers and the final stage of large language models (RLHF) are trained. This first lesson defines the mathematical language of the whole course: the Markov decision process, the return, the policy and the value functions.
The agent and the environment
At each instant
the agent observes the state
, chooses an action
, and the environment responds with a reward
and a new state
. The loop repeats. For a robot the state is the joint positions and velocities, the action the motor torques, the reward a number that rewards moving forward without falling. For CartPole, the example we will use often, the state is the cart position and velocity, the pole angle and angular velocity, the action is pushing left or right, and the reward is +1 for every step in which the pole stays up.

The Markov decision process
An MDP (Markov decision process) is the five-tuple
:
the set of states,
that of actions;
the probability of moving to
by taking
in
;
the average reward obtained by taking
in
;
the discount factor.
The word Markov indicates the fundamental assumption: the future depends on the past only through the present state,
. If the observation does not contain everything needed (for example a single image of a ball, which does not tell its velocity), it is recovered by putting previous observations in the state too or by using networks with memory.
The return and discounting
The goal is not the immediate reward but the return, the sum of discounted future rewards:
![Rendered by QuickLaTeX.com \[ G_t = r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \dots = \sum_{k=0}^{\infty}\gamma^k r_{t+k+1} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-43887cd049e98ad9805b2e52080c65be_l3.png)
Discounting has three reasons. Mathematical: if rewards are bounded by
and
, the geometric series converges,
. Practical: a distant reward is more uncertain. Interpretive:
is the horizon over which the agent “looks”: with
about 100 steps. The recursive relation, the basis of the whole course, holds:
![]()
Policy and value functions
A policy
is the rule by which the agent chooses: the probability of taking
in state
(deterministic if it always gives the same action). To evaluate it one defines:
![]()
, the value of the state, is the average return starting from
and following
;
, the action value, is the average return taking
first and then following
. They are linked by
. The difference
is called the advantage: how much better than average action
is. All modern algorithms use it.
A policy
is optimal if
in every state, for every other
. In a finite MDP a deterministic optimal policy always exists (this is proved in the lesson on Bellman equations), and knowing
it is immediate:
.
A complete example: the gridworld
A 4×4 grid; the top-left and bottom-right cells are the exits. The agent moves one cell up, down, left or right (if it hits the border it stays put), and each step costs
: maximising the return means leaving as soon as possible. With
:
- for the optimal policy the value of each cell is minus the number of steps to the nearest exit: 0, −1, −2, −3;
- for the random policy (each direction with probability 1/4) the values are much more negative: −14 near the exits, −22 in the far corners, because the random walk wanders for a long time before leaving.

The fact that the random policy is worth −22 in a corner, and the optimal one −3, shows the central point of RL: from the same states and the same actions, the chosen behaviour changes the result radically. The next lesson shows how to compute these values, and from them the optimal policy, with the Bellman equations; the following lessons how to learn them when
and
are unknown and the state is too large for a table.
Where RL sits among control techniques
Those who have studied Control Systems will recognise the structure: the state, the input (action), the dynamics (
), a cost index to optimise (
). Optimal control (LQR, MPC) solves the same problem knowing the model; RL solves it learning from experience, even when there is no model or it is too complicated. The price is the number of trials: this is why RL is almost always done in simulation, and the speed of simulators (lesson on libraries) is decisive.
2Bellman equations
The Bellman equations are the mathematical heart of reinforcement learning: they turn the definition of value, an average over infinitely many possible futures, into an equation that links the value of a state to that of the next states. All algorithms come from them, from exact ones (value and policy iteration) to those that learn from experience (Q-learning, DQN, actor-critic). This lesson derives them, proves that they have one and only one solution and that the algorithms converge, and applies them to the gridworld of the previous lesson with Python code.
The Bellman equation for a policy
Theorem. For every policy
and every state
:
![]()
Proof. Start from the recursive relation of the return,
, and take the average conditioned on
:
![]()
The first term is the average reward:
is chosen with probability
and on average
is received. In the second one also conditions on the next state: by the Markov property, once
is known, the future does not depend on how it was reached, so
. Weighting with the probabilities
gives the equation. ∎
It is a linear system of
equations in
unknowns: in vector form
, with solution
(the matrix is invertible for
, because
has norm less than 1). For the gridworld with the random policy this gives the values −14, −20, −22 of the previous lesson.
The optimality equation
For the optimal policy the average over actions becomes a maximum:
![]()
It is no longer linear (because of the maximum), so it is not solved by inverting a matrix: it is solved by iteration. The result that makes this possible is the following.
The Bellman contraction
Define the optimal Bellman operator
, which turns a function
into another:
. The optimality equation says that
is a fixed point:
.
Theorem.
is a contraction of factor
in the max norm: for every
,
.
Proof. An elementary inequality is used: for two functions
of
,
(if the maximum of
is at
,
, and symmetrically). Then, for every
:
![]()
because the probabilities
sum to 1. ∎
Consequences (Banach fixed-point theorem):
- the fixed point exists and is unique:
is well defined; - starting from any
, the sequence
converges to
, and the error shrinks at least by the factor
at each step:
.
This is value iteration. On the gridworld with
and a deliberately wrong initial estimate (50 in every cell) the maximum error goes from 46.7 to 41.3, 36.5, 32.1, …: ratios between 0.87 and 0.88, always below 0.9 as guaranteed by the theorem.

Policy improvement
Theorem (policy improvement). Given a policy
, let
be the greedy policy with respect to
:
. Then
for every
.
Proof. By construction
. Expand
taking
at the first step, and apply the same inequality to
:
![]()
repeating to infinity (the residual terms
tend to zero). ∎
Alternating evaluation (computing
with the linear equation) and improvement (making the policy greedy) gives policy iteration: every step improves or leaves the policy unchanged, deterministic policies are finite in number, so in a finite number of steps one reaches a policy that no longer improves, i.e. that satisfies the optimality equation. This also proves that a deterministic optimal policy always exists. The “evaluate, then improve” scheme returns in all modern algorithms: in actor-critic the critic evaluates and the actor improves.
The code
import numpy as np
N = 4 # 4x4 gridworld, exits at 0 and 15, -1 per step
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
EXITS = {0, 15}
def step(s, a):
if s in EXITS:
return s, 0.0
r, c = divmod(s, N)
r = min(max(r + MOVES[a][0], 0), N - 1)
c = min(max(c + MOVES[a][1], 0), N - 1)
return r * N + c, -1.0
def bellman_optimal(V, gamma):
"""Optimal Bellman operator T: (TV)(s) = max_a [ r + gamma V(s') ]."""
return np.array([0.0 if s in EXITS else
max(r + gamma * V[s2] for s2, r in (step(s, a) for a in range(4)))
for s in range(N * N)])
# value iteration with gamma = 1
V = np.zeros(N * N)
for k in range(100):
V_new = bellman_optimal(V, 1.0)
if np.max(abs(V_new - V)) < 1e-10:
break
V = V_new
print("V* after", k, "sweeps:\n", V.reshape(N, N))
# evaluation of the random policy: average over the four actions instead of the maximum
Vr = np.zeros(N * N)
for _ in range(5000):
Vr = np.array([0.0 if s in EXITS else
np.mean([r + Vr[s2] for s2, r in (step(s, a) for a in range(4))])
for s in range(N * N)])
print("random policy:\n", np.round(Vr.reshape(N, N), 1))
# greedy policy with respect to V*: the best arrow in each cell
ARROWS = "↑↓←→"
pol = [" " if s in EXITS else ARROWS[int(np.argmax([r + V[s2] for s2, r in (step(s, a) for a in range(4))]))]
for s in range(N * N)]
print("\n".join(" ".join(pol[i * N:(i + 1) * N]) for i in range(N)))
# contraction: with gamma = 0.9 the error shrinks at least by 0.9 per sweep
Vs = np.zeros(N * N)
for _ in range(200):
Vs = bellman_optimal(Vs, 0.9)
U = np.where(np.isin(np.arange(N * N), list(EXITS)), 0.0, 50.0)
errors = []
for _ in range(6):
U = bellman_optimal(U, 0.9)
errors.append(np.max(abs(U - Vs)))
print("errors:", np.round(errors, 2), "ratios:", np.round(np.array(errors[1:]) / np.array(errors[:-1]), 3))Running it prints
after 3 sweeps plus the checking one (the values 0, −1, −2, −3), the values of the random policy (−14, −18, −20, −22), the grid of arrows towards the nearest exit and the errors 46.71, 41.31, 36.45, … with ratios 0.884, 0.882, 0.880, … On large problems the table
does not fit in memory and
is unknown: the next lessons replace the sum over
with experience (Q-learning) and the table with a neural network (DQN).
3Temporal differences, SARSA and Q-learning
The Bellman equations require knowing the transition probabilities
and the rewards
. They are almost never known: a robot has no formula for how it will slip on the floor, a game does not say in advance the opponent’s moves. One can however try and observe what happens. This lesson presents the methods that learn values from experience: Monte Carlo, which waits for the end of the episode, and temporal differences (TD), which update at every step. From these come SARSA and Q-learning, which we compare on the classic cliff example, with code and results.
Monte Carlo: the average of returns
Value is an average:
. The most direct way to estimate it is to play many episodes following
, compute the return
every time
is visited and average. In incremental form, after each observed return:
![]()
with
the learning rate. With
(n number of visits) it is exactly the arithmetic mean. Monte Carlo makes no assumptions about the environment, but it must wait for the end of the episode and its estimates have high variance:
sums many random rewards.
Temporal differences
Sutton’s idea (1988) is to replace the true return, known only at the end, with an estimate built from the Bellman equation:
. The TD(0) update is
![Rendered by QuickLaTeX.com \[ V(s_t) \leftarrow V(s_t) + \alpha\,\underbrace{\big(r_{t+1} + \gamma V(s_{t+1}) - V(s_t)\big)}_{\delta_t,\ \text{TD error}} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-c42998e7621b298ed39a5600685e8295_l3.png)
Learning happens at every step, even in tasks without an end. The estimate uses another estimate (it is said to bootstrap): it has less variance than Monte Carlo, because it depends on a single random reward, but it is biased as long as
is wrong. The bias-variance trade-off between Monte Carlo and TD is tuned with
-step returns and the parameter
(TD(
), and in its modern version the GAE used by PPO).
Convergence. With a table, if every state is visited infinitely often and the step sizes satisfy the Robbins-Monro conditions,
and
(for example
), TD(0) converges to
with probability 1. The idea of the proof: on average the update applies the Bellman operator, which is a contraction; the first condition allows reaching anywhere, the second switches off the noise.
From value to action: SARSA and Q-learning
To choose actions without a model
is needed, not
: with
one would need to know where each action leads. Exploring with an ε-greedy policy (best action according to
with probability
, random with probability
),
is updated after each transition
:
![]()
![]()
The only difference is the target. SARSA uses the action
the agent will actually take (exploration included): it learns the value of the policy it is following, and is called on-policy. Q-learning uses the maximum, i.e. the action the optimal policy would take: it learns
whatever the way it explores, and is called off-policy (Watkins, 1989). Being off-policy is precisely what allows reusing old experience or experience collected by others, and it is the basis of DQN.
The cliff example
A 4×12 grid: the start is at the bottom left, the exit at the bottom right, and the bottom cells between them are a cliff: falling in gives
and sends back to the start. Each step costs
. The shortest path runs along the edge of the cliff (13 steps); a safer one goes higher.

With
,
and 500 episodes (average over 20 random seeds):
| learned path | average return in the last 100 episodes | |
|---|---|---|
| SARSA | safe, 19 steps | −28.1 |
| Q-learning | optimal, 13 steps | −48.0 |
Q-learning finds the best path, but earns less while learning: walking on the edge, the 10 % random move makes it fall often. SARSA knows it will explore and prefers to stay away from the edge. It is a lesson that applies to real systems: a robot learning on a real plant must take its own exploration into account, and on-policy or “cautious” algorithms are often preferable; in simulation, where falling costs nothing, one can use Q-learning and then switch off exploration.

The code
import numpy as np
ROWS, COLS = 4, 12
START, EXIT = (3, 0), (3, 11)
MOVES = [(-1, 0), (1, 0), (0, -1), (0, 1)]
def step(pos, a):
r = min(max(pos[0] + MOVES[a][0], 0), ROWS - 1)
c = min(max(pos[1] + MOVES[a][1], 0), COLS - 1)
if r == 3 and 1 <= c <= 10: # cliff: -100 and back to the start
return START, -100.0, False
return (r, c), -1.0, (r, c) == EXIT
def learn(method, episodes=500, alpha=0.5, eps=0.1, seed=0):
rng = np.random.default_rng(seed)
Q = np.zeros((ROWS, COLS, 4))
def choose(p): # epsilon-greedy (tiny noise to break ties)
return rng.integers(4) if rng.random() < eps else int(np.argmax(Q[p] + 1e-9 * rng.random(4)))
returns = []
for _ in range(episodes):
p, tot = START, 0.0
a = choose(p)
for _ in range(1000):
p2, r, done = step(p, a)
tot += r
a2 = choose(p2)
if method == "sarsa":
target = r if done else r + Q[p2][a2] # action actually chosen
else:
target = r if done else r + np.max(Q[p2]) # best action
Q[p][a] += alpha * (target - Q[p][a])
p, a = p2, a2
if done:
break
returns.append(tot)
return np.array(returns), Q
for method in ("sarsa", "qlearning"):
curves = np.array([learn(method, seed=s)[0] for s in range(20)])
_, Q = learn(method, seed=0)
p, length, done = START, 0, False
while not done and length < 50: # final greedy path
p, _, done = step(p, int(np.argmax(Q[p])))
length += 1
print(f"{method:9s}: last 100 episodes {curves[:, -100:].mean():6.1f}, path of {length} steps")Running it prints
and 19 steps for SARSA,
and 13 steps for Q-learning. A table with one cell per state-action pair works as long as states number a few thousand; for CartPole (continuous states) or a video game (states made of pixels) an approximation is needed: the
table becomes a neural network, the DQN of the next lesson.
4Deep Q-Network
A table
works as long as states are few. CartPole has four continuous variables, an Atari video game has 210×160 pixel images: states are infinite or astronomically many. In 2015 DeepMind showed that a convolutional neural network, trained with Q-learning and two tricks, learns to play 49 Atari games starting only from pixels, surpassing human level in many. This is the Deep Q-Network (DQN). This lesson explains why Q-learning with a neural network is unstable, how the replay memory and the target network stabilise it, why the maximum overestimates values (and the remedy, double DQN), and applies it to CartPole with code that reaches the maximum score.
From tabular Q-learning to the network
The table is replaced by a function
with parameters
(the weights of a network): the state as input, one value per action as output. The Q-learning update becomes a gradient descent step on the loss
![Rendered by QuickLaTeX.com \[ L(\theta) = \Big(\underbrace{r + \gamma\max_{a'}Q_{\bar\theta}(s', a')}_{y,\ \text{target}} - Q_\theta(s, a)\Big)^2 \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-369bcf20c141e71679f29a45b30415f8_l3.png)
where the target
is treated as a constant (no derivative is taken with respect to it). It looks simple, but put together naively it often diverges.
Why it diverges: the deadly triad
Sutton and Barto call the deadly triad the combination of three ingredients that, together, can make learning diverge even in simple problems:
- function approximation: changing
to correct
also changes the values of similar states one did not want to touch; - bootstrapping: the target contains the estimate itself
, so an error propagates and feeds itself; - off-policy: the greedy policy is learned from data collected with another policy (the exploring one).
Deep Q-learning has all three. To these a statistical problem is added: consecutive steps of an episode are strongly correlated (the state at step
is almost equal to that at step
), while gradient descent assumes independent examples.
The two DQN tricks
Replay memory. Every transition
is stored in a buffer of a few tens of thousands of elements; at each training step a mini-batch is drawn at random. This breaks correlations, reuses every experience many times (which is legitimate because Q-learning is off-policy) and averages over many different situations.
Target network. The target
is computed with a copy of the weights,
, updated only every few hundred or thousand steps (
). Between two copies the problem becomes a supervised regression with fixed targets, and the network does not “chase its own tail”.

Overestimation of the maximum and double DQN
Theorem. If the estimates
are unbiased but noisy,
, then the maximum is overestimated:
.
Proof. For every
,
; taking the average,
, and this holds for every
, hence also for the one maximising
. ∎
Noise gets “selected”: the action that looks best is often the one estimated too high. The overestimation accumulates through bootstrapping. Double DQN (van Hasselt, 2016) separates choice from evaluation: the online network chooses the action, the target network evaluates it,
![]()
The errors of the two networks are largely independent, and the overestimation is greatly reduced.
True end and time limit. If the episode ends because the pole fell, there is no further reward and the target is just
. If instead it ends because time ran out (500 steps in CartPole), the state is not terminal: the target must still include
. Confusing the two cases is one of the most common mistakes; Gymnasium distinguishes them with the two values terminated and truncated.
The code on CartPole
import random, collections
import numpy as np
import torch, torch.nn as nn
import gymnasium
torch.manual_seed(0); random.seed(0); np.random.seed(0)
env = gymnasium.make("CartPole-v1")
def network():
return nn.Sequential(nn.Linear(4, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 2))
q, q_target = network(), network()
q_target.load_state_dict(q.state_dict())
opt = torch.optim.Adam(q.parameters(), lr=2.5e-4)
memory = collections.deque(maxlen=10000) # replay memory
STEPS, BATCH, GAMMA, COPY, EVERY, START = 200000, 128, 0.99, 500, 10, 10000
o, _ = env.reset(seed=0)
env.action_space.seed(0)
for t in range(STEPS):
eps = max(0.05, 1 - 0.95 * t / 100000) # decreasing exploration
if random.random() < eps:
a = env.action_space.sample()
else:
with torch.no_grad():
a = int(q(torch.tensor(o, dtype=torch.float32)).argmax())
o2, r, terminated, truncated, _ = env.step(a)
memory.append((o, a, r, o2, float(terminated))) # only a true end zeroes the future
o = o2
if terminated or truncated:
o, _ = env.reset()
if t >= START and t % EVERY == 0:
b = random.sample(memory, BATCH)
O, A, R, O2, D = (torch.tensor(np.array(x), dtype=torch.float32) for x in zip(*b))
with torch.no_grad(): # double DQN
a2 = q(O2).argmax(1, keepdim=True)
y = R + GAMMA * (1 - D) * q_target(O2).gather(1, a2).squeeze(1)
estimate = q(O).gather(1, A.long().unsqueeze(1)).squeeze(1)
loss = nn.functional.mse_loss(estimate, y)
opt.zero_grad(); loss.backward(); opt.step()
if t % COPY == 0:
q_target.load_state_dict(q.state_dict()) # target network update
# greedy evaluation over 20 episodes
scores = []
for e in range(20):
o, _ = env.reset(seed=1000 + e)
tot, done = 0.0, False
while not done:
with torch.no_grad():
o, r, te, tr, _ = env.step(int(q(torch.tensor(o, dtype=torch.float32)).argmax()))
tot += r; done = te or tr
scores.append(tot)
print("evaluation:", np.mean(scores))The hyperparameters are those of the CleanRL teaching library. During training the average return goes from 62 (after 40,000 steps) to 353, 370, 468 and 500; the final greedy evaluation is 500 over 20 episodes, the maximum possible. On an ordinary processor it takes less than a minute.

Beyond DQN
DQN works with few discrete actions (it must compute the maximum over all of them). For continuous actions, such as a robot’s torques or a car’s steering, actor-critic methods (DDPG, TD3, SAC) are used, which also learn a policy, together with the policy gradient methods of the next lesson. The DQN variants for games (Rainbow) add prioritised replay, “dueling” networks, multi-step returns and return distributions; the principle remains the one described here.
5Policy gradient and PPO
DQN learns values and derives the policy from them. One can also do the opposite: parameterise the policy directly
with a neural network and move its weights in the direction that increases the average return. These are policy gradient methods. They work with continuous actions (torques, steering, acceleration), learn stochastic policies and are the basis of PPO (Proximal Policy Optimization, Schulman et al., 2017), the most used algorithm today: from walking robots to language models trained with human feedback. This lesson proves the policy gradient theorem, derives REINFORCE, the baseline and actor-critic, explains the generalised advantage (GAE) and the “clipped” objective of PPO, and applies it to CartPole.
The policy gradient theorem
The objective is the average return
, where
is a trajectory and
its return.
Theorem.
, with
the return from
onwards.
Proof. The probability of a trajectory is
. The log-derivative trick is used,
:
![]()
In the logarithm the product becomes a sum, and the terms
and
do not depend on
: they vanish when differentiating. What remains is
. Finally the rewards received before
do not depend on
, and their contribution has zero mean (by the same argument as the baseline below):
can be replaced by
. ∎
The result is remarkable: to improve the policy the model of the environment is not needed, it is enough to be able to differentiate one’s own policy. The interpretation is intuitive: increase the probability of actions followed by a high return, decrease that of actions followed by a low return. Estimating the average with the played trajectories gives the REINFORCE algorithm (Williams, 1992).
The baseline and actor-critic
REINFORCE is correct but very slow:
has an enormous variance. A baseline
can be subtracted without changing the mean.
Lemma.
.
Proof.
. ∎
The natural choice is
: instead of
the advantage
is used, which says how much better than expected the action went.
is learned with a second network, the critic, while the policy is the actor: this is the actor-critic scheme, the “evaluate and improve” version of policy iteration.
Generalised advantage (GAE). As between Monte Carlo and TD, the advantage can be estimated with the TD error
(low variance, biased) or with the whole return (unbiased, high variance). GAE (Schulman, 2016) takes an exponential average:
![Rendered by QuickLaTeX.com \[ \hat A_t = \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l} = \delta_t + \gamma\lambda\,\hat A_{t+1} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-8a6902bdd9b730ee070efeb84ea5fd16_l3.png)
with
one gets the TD error, with
the Monte Carlo return minus
; usually
. The recursive form is computed backwards in one line of code.
PPO: big steps but not too big
A gradient step that is too long can change the policy so much as to ruin it, and the data collected with the old policy are no longer valid. PPO uses the probability ratio
between the new policy and the one that collected the data, and maximises the clipped objective:
![]()
with
. If an action was good (
) its probability is increased, but beyond 20 % more the objective becomes flat and the gradient vanishes; if it was bad (
) its probability is reduced, but not below 20 % less. The minimum guarantees that clipping acts only when it would improve the objective, never when it worsens it: it is a pessimistic bound on the gain. In this way several steps (epochs) can be taken safely on the same data. The critic error and a small entropy bonus, which keeps exploration alive, are added to the objective.

PPO on CartPole
The code collects 128 steps from 8 environments in parallel (1024 transitions), computes GAE, performs 4 update epochs with the clipped objective and repeats 100 times. The environments are vectorised with PufferLib, presented in the lesson on libraries; with Gymnasium (gymnasium.vector.SyncVectorEnv) the code would be almost identical.
import numpy as np
import torch, torch.nn as nn
import gymnasium
import pufferlib.emulation, pufferlib.vector
N_ENV, T, UPDATES = 8, 128, 100 # 8 environments, 128 steps each per update
GAMMA, LAM, CLIP, LR, EPOCHS = 0.99, 0.95, 0.2, 1e-3, 4
torch.manual_seed(0)
def make(buf=None, seed=0):
return pufferlib.emulation.GymnasiumPufferEnv(env=gymnasium.make("CartPole-v1"), buf=buf, seed=seed)
envs = pufferlib.vector.make(make, num_envs=N_ENV, backend=pufferlib.vector.Serial)
obs, _ = envs.reset(seed=0)
actor = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 2))
critic = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 1))
params = list(actor.parameters()) + list(critic.parameters())
opt = torch.optim.Adam(params, lr=LR)
for k in range(UPDATES):
for g in opt.param_groups:
g["lr"] = LR * (1 - k / UPDATES) # learning rate decreasing linearly to zero
O, A, LP, R, D, V = [], [], [], [], [], []
for t in range(T): # data collection with the current policy
o = torch.tensor(obs, dtype=torch.float32) # copy: PufferLib reuses the same buffer
with torch.no_grad():
dist = torch.distributions.Categorical(logits=actor(o))
a = dist.sample()
O.append(o); A.append(a); LP.append(dist.log_prob(a)); V.append(critic(o).squeeze(-1))
obs, r, term, trunc, _ = envs.step(a.numpy())
R.append(torch.tensor(r, dtype=torch.float32))
D.append(torch.tensor(np.logical_or(term, trunc), dtype=torch.float32))
with torch.no_grad():
v_end = critic(torch.tensor(obs, dtype=torch.float32)).squeeze(-1)
adv, last = torch.zeros(T, N_ENV), torch.zeros(N_ENV)
for t in reversed(range(T)): # GAE, computed backwards
v_next = v_end if t == T - 1 else V[t + 1]
delta = R[t] + GAMMA * v_next * (1 - D[t]) - V[t]
last = delta + GAMMA * LAM * (1 - D[t]) * last
adv[t] = last
returns = (adv + torch.stack(V)).reshape(-1)
O, A, LP = torch.stack(O).reshape(-1, 4), torch.stack(A).reshape(-1), torch.stack(LP).reshape(-1)
adv = adv.reshape(-1)
adv = (adv - adv.mean()) / (adv.std() + 1e-8)
for _ in range(EPOCHS): # clipped PPO objective
dist = torch.distributions.Categorical(logits=actor(O))
ratio = torch.exp(dist.log_prob(A) - LP)
loss_pi = -torch.min(ratio * adv, torch.clamp(ratio, 1 - CLIP, 1 + CLIP) * adv).mean()
loss_v = ((critic(O).squeeze(-1) - returns) ** 2).mean()
loss = loss_pi + 0.5 * loss_v - 0.01 * dist.entropy().mean()
opt.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(params, 0.5)
opt.step()
envs.close()
env, scores = gymnasium.make("CartPole-v1"), []
for e in range(10): # evaluation with the most likely action
o, _ = env.reset(seed=100 + e)
tot, done = 0.0, False
while not done:
with torch.no_grad():
o, r, te, tr, _ = env.step(int(actor(torch.tensor(o, dtype=torch.float32)).argmax()))
tot += r; done = te or tr
scores.append(tot)
print("evaluation over 10 episodes:", np.mean(scores))
torch.save(actor.state_dict(), "expert.pt") # will serve as the expert to imitateIn less than 10 seconds on a processor (about 100,000 steps) the average return of the last 20 episodes during training goes from 162 after 20 updates to 245, 201, 401 and 407 (during training actions are still random), and the evaluation with the most likely action gives 500 on all 10 episodes. Two tricks were decisive in the trials: the learning rate decreasing to zero and the gradient norm limit (0.5); without them, the policy reached 400 and then got worse. This is typical of RL: results change a lot with hyperparameters and with the random seed, and several seeds are always used to compare two methods. A simplification: the code also treats the time limit (500 steps) as terminal, which strictly would require continuing to bootstrap; for CartPole the effect is small.
Why PPO is everywhere
It is simple (a few lines beyond actor-critic), more robust to hyperparameters than many competitors, works with discrete and continuous actions and parallelises well over thousands of simulated environments. It is the algorithm with which OpenAI trained the robotic hand that solved the Rubik’s cube and the Dota 2 bots, and the one used in 2022 for InstructGPT, the language model that made training with human feedback (RLHF) famous, as shown in the lesson on applications.
6Imitation learning
Defining a reward that describes a task well is often harder than the task itself: how do you write as a number “drive like an expert”, or “fold the shirt neatly”? It is much easier to show how it is done. Imitation learning learns a policy from demonstrations by an expert: a driver, an operator remotely guiding a robot, a program that is already good. It is the basis of the first autonomous driving systems, of many manipulator robots and also of the first training stage of language models. This lesson presents behaviour cloning, proves why its errors accumulate, presents DAgger, which solves the problem, and outlines inverse reward learning. Experiments on CartPole show everything with numbers.
Behaviour cloning
The simplest idea: collect (state, expert action) pairs and train a network to predict the action from the state, as in a classification problem (discrete actions) or a regression problem (continuous actions). No reward, no exploration: it is supervised learning. In 1989 ALVINN drove a van by learning the steering angle from camera images and a driver’s manoeuvres; in 2016 NVIDIA did the same with a convolutional network (PilotNet).
Why errors accumulate
Behaviour cloning has a deep flaw: the network is trained on the states visited by the expert, but is used on the states visited by itself. A small error is enough to bring the agent to a state slightly different from those seen; there the network makes larger errors, and the state drifts further. Errors compound.

Theorem (Ross and Bagnell, 2010). If the cloned policy chooses the wrong action with probability at most
on the expert’s states, and an error can take it outside the expert’s distribution for the rest of the episode, the expected cost over a horizon of
steps can grow as
, instead of
.
Proof idea. As long as the agent has not yet made a mistake, it is in the expert’s states and errs with probability
per step. The probability of having already erred by step
is about
(for small
), and after the first error, in the worst case, a cost is paid at every following step. The expected cost is therefore
. If instead the policy were trained on the states that it itself visits, the error per step would stay
and the cost
. ∎
DAgger: asking the expert where things went wrong
DAgger (Dataset Aggregation, Ross, Gordon and Bagnell, 2011) cures the problem at the root: let the learned policy drive, record the states it visits, ask the expert which action it would have chosen in those states, add the new pairs to the data and retrain. Repeating, the data cover exactly the states where the agent ends up, including those where it needs to “recover”. The DAgger theorem guarantees a cost growing as
. The price: the expert must be available during training (a program, a simulator with an optimal controller, or a person correcting afterwards).
The experiments on CartPole
The expert is the PPO of the previous lesson, which keeps the pole up for all 500 steps. The imitating policy is a small network (one hidden layer of 32 neurons), trained to classify the action and evaluated over 20 episodes. With so little data the result depends a lot on chance (which states appear in the demonstrations, how the network starts), so each configuration is repeated with 10 random seeds and mean and standard deviation are reported.
| steps of data | behaviour cloning | DAgger |
|---|---|---|
| 20 | 82 ± 23 | 82 ± 23 (starting point) |
| 40 | 129 ± 103 | 164 ± 127 |
| 60 | 186 ± 140 | 232 ± 103 |
| 80 | 205 ± 121 | 313 ± 105 |
| 100 | 243 ± 146 | 321 ± 110 |
| 200 | 383 ± 130 |
For the same amount of data DAgger is always better, and with 80-100 steps it achieves what takes behaviour cloning about twice as many. The reason is the one in the theorem: the expert’s demonstrations show almost only the pole close to vertical, while DAgger adds precisely the “wrong” states the agent ends up in, with the right action to recover. Standard deviations are large: with a lucky seed even behaviour cloning can reach 500, with an unlucky one stay below 100. It is a general warning: in RL and imitation a single experiment proves nothing.

import numpy as np
import torch, torch.nn as nn
import gymnasium
expert = nn.Sequential(nn.Linear(4, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 2))
expert.load_state_dict(torch.load("expert.pt")) # saved by the code of the PPO lesson
expert_action = lambda s: int(expert(torch.tensor(s, dtype=torch.float32)).argmax())
def evaluate(policy, episodes=20):
env, scores = gymnasium.make("CartPole-v1"), []
for e in range(episodes):
o, _ = env.reset(seed=1000 + e)
tot, done = 0.0, False
while not done:
o, r, te, tr, _ = env.step(policy(o))
tot += r; done = te or tr
scores.append(tot)
return float(np.mean(scores))
def collect(policy, steps, seed):
"""States visited following policy, labelled with the expert's action."""
env, S, Y = gymnasium.make("CartPole-v1"), [], []
o, _ = env.reset(seed=seed)
for _ in range(steps):
S.append(o); Y.append(expert_action(o))
o, _, te, tr, _ = env.step(policy(o))
if te or tr:
o, _ = env.reset()
return S, Y
def train(S, Y, seed):
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(4, 32), nn.Tanh(), nn.Linear(32, 2))
opt = torch.optim.Adam(net.parameters(), lr=1e-2)
X, T = torch.tensor(np.array(S), dtype=torch.float32), torch.tensor(Y)
for _ in range(300): # classification of the action
loss = nn.functional.cross_entropy(net(X), T)
opt.zero_grad(); loss.backward(); opt.step()
return lambda s: int(net(torch.tensor(s, dtype=torch.float32)).argmax())
print("expert:", evaluate(expert_action))
bc = {n: [] for n in (20, 40, 60, 80, 100, 200)}
dag = {n: [] for n in (20, 40, 60, 80, 100)}
for seed in range(10):
for n in bc: # behaviour cloning with n steps
bc[n].append(evaluate(train(*collect(expert_action, n, 100 * seed), seed)))
S, Y = collect(expert_action, 20, 100 * seed) # DAgger: start from 20 steps
policy = train(S, Y, seed)
dag[20].append(evaluate(policy))
for it in range(1, 5):
S2, Y2 = collect(policy, 20, 100 * seed + it) # states visited by the learned policy
S += S2; Y += Y2
policy = train(S, Y, seed)
dag[20 * (it + 1)].append(evaluate(policy))
for n in bc:
row = f"{n:4d} steps: behaviour cloning {np.mean(bc[n]):6.1f} ± {np.std(bc[n]):5.1f}"
if n in dag:
row += f", DAgger {np.mean(dag[n]):6.1f} ± {np.std(dag[n]):5.1f}"
print(row)Beyond direct imitation
- Inverse reinforcement learning (inverse RL): instead of copying actions, one looks for the reward the expert seems to maximise, and then optimises it with RL. It is more robust outside the demonstrations, because the reward is valid also in never-seen states.
- GAIL (generative adversarial imitation learning, 2016): a discriminator learns to distinguish the expert’s trajectories from the agent’s, and the agent is trained with RL to “fool” it, as in generative adversarial networks.
- Imitation, then reinforcement: in practice one often starts with behaviour cloning (fast, stable) and improves with RL. This is the scheme of AlphaGo (first the masters’ games, then self-play) and of language models (first supervised training on answers written by people, then RL with human feedback).
- Modern robotics: diffusion policies and vision-language-action models learn from thousands of teleoperated demonstrations; error accumulation is mitigated by predicting chunks of future actions instead of a single one.
7Libraries: Gymnasium, Stable-Baselines3, PufferLib
The algorithms of the previous lessons can be written in a hundred lines, but real work uses libraries: for environments (a standard interface between agent and simulator), for algorithms (tested, comparable implementations) and for speed (simulating millions of steps per second). This lesson presents the most used Python ecosystem: Gymnasium, the standard for environments; Stable-Baselines3, to use reliable algorithms in a few lines; CleanRL, RLlib and TorchRL; and PufferLib, a recent library that bets everything on simulation speed, with a working example and measurements made for this lesson.
Gymnasium: the standard interface
In 2016 OpenAI released Gym, a set of environments with a common interface; since 2022 the project has been maintained by the Farama Foundation under the name Gymnasium. Every environment has an observation space and an action space, and two functions:
import gymnasium
env = gymnasium.make("CartPole-v1")
print(env.observation_space, env.action_space) # Box(4,) and Discrete(2)
obs, info = env.reset(seed=0) # initial state
total, done = 0.0, False
while not done:
action = env.action_space.sample() # the policy would go here
obs, reward, terminated, truncated, info = env.step(action)
total += reward
done = terminated or truncated # true end or time limit
print("return of a random episode:", total)terminated indicates a true end (the pole fell), truncated a time limit: as seen in the DQN lesson, they must be treated differently. Hundreds of environments rely on this interface: classic control, Atari games, MuJoCo physics simulation (walking robots), and third-party ones (autonomous driving, power grids, finance). PettingZoo is the equivalent for multi-agent environments.
Stable-Baselines3: ready-made algorithms
Stable-Baselines3 (SB3), based on PyTorch, offers tested implementations of PPO, A2C, DQN, SAC, TD3 and DDPG, with reasonable default hyperparameters. A few lines are enough to train PPO on CartPole:
import time
import gymnasium
from stable_baselines3 import PPO
from stable_baselines3.common.env_util import make_vec_env
from stable_baselines3.common.evaluation import evaluate_policy
envs = make_vec_env("CartPole-v1", n_envs=8, seed=0) # 8 environments in parallel
model = PPO("MlpPolicy", envs, seed=0, verbose=0) # default hyperparameters
t0 = time.time()
model.learn(total_timesteps=100_000)
mean, std = evaluate_policy(model, gymnasium.make("CartPole-v1"), n_eval_episodes=10, deterministic=True)
print(f"training {time.time() - t0:.1f} s, evaluation over 10 episodes: {mean:.1f} ± {std:.1f}")
model.save("ppo_cartpole")With SB3 2.9 training took 48 s and the evaluation gave 453.6 ± 60.7: a good result without touching anything, a little below the hand-written PPO of the previous lesson, whose hyperparameters had been chosen for CartPole. It is the typical trade-off: the library is slower and less tuned to the single problem, but it is reliable, documented and lets you change algorithm by changing one word (PPO → SAC).
The other libraries
- CleanRL: each algorithm in a single file of a few hundred lines, without abstractions. It is made for understanding and modifying, and it is the best to read after this course. The DQN hyperparameters of lesson 4 come from there.
- RLlib (Ray project): designed to scale on clusters of many machines, with many agents and many algorithms; more complex, suited to large projects.
- TorchRL: PyTorch’s official RL library, made of “building blocks” (buffers, data collectors, losses) to combine.
PufferLib: speed first
In RL almost all the time goes not into the neural network but into the simulator: for CartPole the network does a few thousand operations, while the agent needs hundreds of thousands of steps. PufferLib, developed by Joseph Suarez (PufferAI), starts from this observation and combines three things:
- emulation: it wraps any Gymnasium or PettingZoo environment and makes it look like a “flat” environment, with observations and actions in contiguous memory arrays, the same for all environments (even those with complicated, dictionary observations);
- vectorisation: it runs many environments in parallel with different backends (
Serialin the same process,Multiprocessingover several processes,Rayover several machines), writing results into shared buffers without copies; - Ocean: a collection of environments written in C, from simple games to large multi-agent simulations, that run hundreds of times faster than Python versions (and even more on the GPU).
Versions. On PyPI version 3.0 (June 2025, pip install pufferlib) offers the Python interface described here. Version 5.0, at the time this lesson is written, is installed from the PufferAI GitHub repository and goes even further: C and CUDA environments, training on the GPU with a modified PPO, command-line use (./build.sh breakout --cu, ./puffer train, ./puffer eval latest); training requires an NVIDIA GPU. The interface changes quickly between versions: always check the documentation on puffer.ai.
The example. The PPO of the previous lesson already uses PufferLib to vectorise: the Gymnasium environment is wrapped by GymnasiumPufferEnv and eight copies are created by pufferlib.vector.make. An instructive trap met while writing it: to avoid copying data, PufferLib rewrites the same buffer of observations and rewards at every step. Storing observations with torch.as_tensor, which does not copy, made all stored steps point to the last observation, and the agent learned nothing (return stuck around 25). With torch.tensor, which copies, the same code reaches 500. In general: with high-performance libraries, whatever you want to keep must be copied.
Measurements. Steps per second with random actions, on a PC with 16 logical processors (PufferLib 3.0, Gymnasium 0.29, Python 3.11):
| configuration | steps per second |
|---|---|
| Gymnasium, one environment at a time | 114,000 |
| PufferLib Serial, 8 environments | 126,000 |
| PufferLib Multiprocessing, 8 environments on 4 processes | 150,000 |
| PufferLib Ocean, CartPole in C, 1024 environments | 32,900,000 |

Repeating the measurements, the values of the first three rows change by 20-30 % (in another run: 120,000 and 118,000 steps per second), that of Ocean by 2-3 %. For an environment as simple as CartPole, parallel processes help little: the cost of communication between processes is similar to that of a step. The real jump comes from the environment written in C, which performs 1024 steps in a loop without ever returning to Python: almost 300 times faster. This is why modern libraries (PufferLib, GPU simulators such as Isaac Lab, MJX and Brax) rewrite environments in compiled languages or on the GPU: at 30 million steps per second, a training run that would take a day takes a few minutes.
import time
import numpy as np
import gymnasium
import pufferlib.emulation, pufferlib.vector, pufferlib.ocean
def make(buf=None, seed=0):
return pufferlib.emulation.GymnasiumPufferEnv(env=gymnasium.make("CartPole-v1"), buf=buf, seed=seed)
def measure(envs, n_env, steps=2000):
envs.reset(seed=0)
actions = np.random.randint(0, 2, size=(steps, n_env))
t0 = time.time()
for k in range(steps):
envs.step(actions[k])
return steps * n_env / (time.time() - t0)
envs = pufferlib.vector.make(make, num_envs=8, backend=pufferlib.vector.Serial)
print(f"Serial, 8 environments: {measure(envs, 8):,.0f} steps/s"); envs.close()
envs = pufferlib.vector.make(make, num_envs=8, num_workers=4, backend=pufferlib.vector.Multiprocessing)
print(f"Multiprocessing, 8 environments on 4 processes: {measure(envs, 8):,.0f} steps/s"); envs.close()
ocean = pufferlib.ocean.env_creator("puffer_cartpole")(num_envs=1024) # CartPole written in C
ocean.reset(seed=0)
actions = np.random.randint(0, 2, size=(500, 1024))
t0 = time.time()
for k in range(500):
ocean.step(actions[k])
print(f"Ocean, 1024 environments in C: {500 * 1024 / (time.time() - t0):,.0f} steps/s")Which to choose
For learning and small experiments: Gymnasium and your own code, or CleanRL. For a project that must work right away with standard algorithms: Stable-Baselines3. To train agents on complex or multi-agent environments, when simulation time dominates: PufferLib or GPU simulators. For systems distributed over several machines: RLlib. In all cases the Gymnasium interface is the meeting point: an environment written for Gymnasium can be used with all of them.
8Simulation and Gaussian splatting
An RL agent needs millions of trials, and no real robot or car can fall a million times. This is why almost all applied reinforcement learning happens in simulation: the agent is trained in a virtual world and then transferred to the real one. This lesson presents the most used physics simulators, the problem of the gap between simulation and reality (sim-to-real gap) and the techniques to bridge it, and finally Gaussian splatting, a 2023 technique that reconstructs photographed real scenes and renders them in real time, increasingly used to build photorealistic simulators for robots and autonomous vehicles.
Physics simulators
- MuJoCo (Multi-Joint dynamics with Contact): a physics engine for articulated bodies with contacts, born for robotics and become the RL standard for continuous control (Gymnasium’s locomotion environments use it). Acquired by DeepMind in 2021 and made open source in 2022. MJX is its JAX version, running on the GPU.
- Isaac Sim and Isaac Lab (NVIDIA): physics and sensor simulation on the GPU, with thousands of simulated robots in parallel in the same process. Training locomotion for a quadruped robot thus takes minutes instead of days.
- Brax (Google): differentiable physics written in JAX, very fast on the GPU.
- CARLA: an open-source simulator for autonomous driving, based on a video game engine, with cities, traffic, pedestrians, weather and sensors (cameras, LiDAR, radar).
The common principle is the one seen with PufferLib: speed comes from running many environments together in compiled code or on the GPU, without returning to Python at every step.
The gap between simulation and reality
A simulator is never perfect: masses, friction, motor delays, sensor noise and surface appearance are always slightly different. A policy optimised too well for the simulator exploits its defects (for example a friction slightly too high) and fails in the real world. The main techniques:
- system identification: measuring the parameters of the real robot (masses, inertias, friction, latencies) and putting them in the simulator, as is done for a classic controller;
- domain randomisation: at each episode the parameters are drawn at random (mass ±20 %, friction between 0.5 and 1.2, sensor delay, colours and lighting of images). The policy learns to work on a whole family of worlds, and the real world becomes “one of many”. OpenAI used it in 2019 to have a robotic hand trained only in simulation solve the Rubik’s cube, automatically widening the ranges as the agent improved;
- actuator networks: a model of the motors’ behaviour is learned from real data and inserted into the simulation (this was decisive in making ETH Zurich’s ANYmal quadruped robot run in 2019);
- online adaptation: the policy also receives an estimate of the parameters (or the recent history of states and actions) as input and adapts by itself.

Gaussian splatting
For tasks with cameras (autonomous driving, robots that see) the simulated images must also resemble the real ones. Modelling every building and every tree by hand takes a long time and the result never looks real. The alternative is to reconstruct the scene from real photos or video. In 2020 NeRFs (neural radiance fields) showed that a neural network can learn a scene from a few dozen photos, but rendering took seconds per image. In 2023 Kerbl, Kopanas, Leimkühler and Drettakis presented 3D Gaussian splatting: similar quality, real-time rendering.
The representation. The scene is a set of millions of three-dimensional Gaussians, small ellipsoidal “clouds”. Each has:
- a position
(the centre); - a covariance
giving its shape and orientation, written as
with
a rotation and
a diagonal matrix of the three scales: in this way it always stays symmetric and positive definite during optimisation; - an opacity
; - a colour that changes with the viewing direction (described with spherical harmonics, for reflections).
Rendering. Each Gaussian is projected onto the image: with
the view transformation and
the Jacobian of the perspective projection, its footprint on the screen is a two-dimensional Gaussian with covariance
. The Gaussians are sorted by depth and composited front to back, like overlapping semi-transparent sheets:
![]()
where
is the opacity of Gaussian
at the pixel (the opacity times the value of the Gaussian at that point) and the product is the light that reaches there without being absorbed by the previous ones. Everything is computed in parallel on the GPU, in tiles of pixels, at more than 100 images per second.
Training. One starts from the 3D points obtained from the photos with photogrammetry (structure from motion) and optimises all parameters with gradient descent, comparing rendered images with the real photos. The compositing formula is differentiable, so the pixel error can be “traced back” to the position, shape, colour and opacity of every Gaussian. During optimisation Gaussians that are too large are split, those in under-described areas are duplicated, transparent ones are removed.

Why it matters for RL. With a few tens of minutes of video of a junction, a warehouse or a stretch of road one obtains a navigable, photorealistic scene, from which images can be rendered from new viewpoints: those a vehicle making a manoeuvre different from the recorded one would see. Policies using cameras can thus be trained and tested in closed loop in the reconstructed “real” world, and the dangerous situations missing from recordings can be generated. It is one of the most active routes to reducing the gap between simulation and reality in perception.
A two-dimensional example
The following code applies the same ideas to a flat image: 150 two-dimensional Gaussians with position, two scales, rotation, colour and opacity, composited with the front-to-back formula and optimised with Adam to reproduce a 64×64 pixel image.
import torch
torch.manual_seed(0)
H = W = 64
yy, xx = torch.meshgrid(torch.linspace(0, 1, H), torch.linspace(0, 1, W), indexing="ij")
img = torch.zeros(H, W, 3) + torch.tensor([0.10, 0.15, 0.35]) # image to reconstruct
img[((xx - 0.35) ** 2 + (yy - 0.40) ** 2) < 0.18 ** 2] = torch.tensor([0.95, 0.55, 0.10])
u, v = (xx - 0.68) * 0.8 + (yy - 0.62) * 0.6, -(xx - 0.68) * 0.6 + (yy - 0.62) * 0.8
img[(u.abs() < 0.18) & (v.abs() < 0.08)] = torch.tensor([0.20, 0.75, 0.35])
img[(yy - 0.85).abs() < 0.03] = torch.tensor([0.95, 0.95, 0.95])
N = 150
pos = torch.rand(N, 2, requires_grad=True) # centres
log_s = torch.full((N, 2), -3.0, requires_grad=True) # scales (as logarithms: always positive)
rot = torch.zeros(N, requires_grad=True) # rotations
col = torch.rand(N, 3, requires_grad=True) # colours (before the sigmoid)
op = torch.zeros(N, requires_grad=True) # opacities (before the sigmoid)
def render():
c, s, S = torch.cos(rot), torch.sin(rot), torch.exp(log_s)
dx, dy = xx[None] - pos[:, 0, None, None], yy[None] - pos[:, 1, None, None]
u = (c[:, None, None] * dx + s[:, None, None] * dy) / S[:, 0, None, None] # coordinates in the
v = (-s[:, None, None] * dx + c[:, None, None] * dy) / S[:, 1, None, None] # Gaussian's axes
alpha = torch.sigmoid(op)[:, None, None] * torch.exp(-0.5 * (u ** 2 + v ** 2))
light = torch.cumprod(torch.cat([torch.ones(1, H, W), 1 - alpha[:-1]], 0), 0) # product of (1 - alpha_j)
return ((alpha * light)[..., None] * torch.sigmoid(col)[:, None, None, :]).sum(0)
psnr = lambda a, b: float(10 * torch.log10(1 / ((a - b) ** 2).mean()))
opt = torch.optim.Adam([pos, log_s, rot, col, op], lr=0.02)
print(f"initial: PSNR {psnr(render().detach(), img):.1f} dB")
for it in range(1, 1501):
loss = ((render() - img) ** 2).mean() # pixel error
opt.zero_grad(); loss.backward(); opt.step() # the gradient reaches every Gaussian
if it in (100, 500, 1500):
print(f"iteration {it}: PSNR {psnr(render().detach(), img):.1f} dB")The peak signal-to-noise ratio (PSNR, higher is better) rises from 10.8 dB at the start to 23.3 dB after 100 iterations, 29.5 after 500 and 31.0 after 1500, in about 40 seconds on a processor. In the three-dimensional case the perspective projection, depth sorting and the number of Gaussians (millions) change, but the principle is this one: a set of simple primitives, a differentiable rendering formula, gradient descent.
9Applications: robotics, driving, RLHF
Reinforcement learning left the laboratories in a few years: it has beaten the champions of Go and of complex video games, it makes robots walk and fly, it controls plants, and today it is an essential part of training large language models. This lesson reviews the most important applications, says honestly where RL works and where it does not, and proves the formulas of RLHF (reinforcement learning from human feedback) and of DPO, the method that simplified its last stage.
Games: where it all began
- AlphaGo (DeepMind) beat Lee Sedol 4 to 1 in March 2016: neural networks trained first by imitation on the masters’ games, then by self-play, together with a Monte Carlo tree search. AlphaZero (2017) removed imitation: only the rules and self-play, and it surpassed the best chess, shogi and Go programs.
- OpenAI Five beat the Dota 2 world champions in 2019, and AlphaStar reached Grandmaster level in StarCraft II: games with incomplete information, thousands of actions and long matches, tackled with PPO and variants on thousands of processors.
Games are the ideal case: the simulator is the game itself, perfect and very fast, and the reward (winning) is clear.
Robotics and control
- Locomotion: quadruped robots (such as ETH Zurich’s ANYmal) and humanoids walk on difficult terrain with policies trained in simulation with thousands of parallel copies and domain randomisation, then transferred to the real robot without further training.
- Drones: in 2023 the University of Zurich’s Swift system, trained with RL in simulation, beat human drone racing champions (a result published in Nature).
- Plants: DeepMind used RL for the cooling of Google’s data centres, reporting a reduction of up to 40 % in the energy used for cooling, and in 2022, with EPFL, to control the shape of the plasma in the TCV tokamak by acting on 19 magnetic coils.
The common problem is transfer from simulation to reality, discussed in the previous lesson, and safety: a learned controller is hard to certify, and it is almost always paired with a classic controller or a safety filter that prevents dangerous actions.
Autonomous driving and ADAS
In cars RL is used with caution. Production ADAS functions (emergency braking, lane keeping, adaptive cruise control) are based on classic control, like that of the Automation Systems Design course, and on supervised neural networks for perception. RL is studied mainly for decisions: when to change lane, how to merge into a flow, how to behave at junctions with other road users. “End-to-end” driving, from camera to steering, relies mostly on imitation of millions of kilometres of human driving, with RL used to correct rare and dangerous behaviours in simulation. The reason is safety: in a car you cannot explore, and validation requires demonstrating the behaviour in every situation.
Language models: RLHF
A pre-trained language model can continue a text, but does not necessarily know how to be helpful, honest and harmless. RLHF (reinforcement learning from human feedback), made famous by InstructGPT (OpenAI, 2022), trains it in three stages:
1. Imitation (supervised fine-tuning): the model learns from example answers written by people. It is behaviour cloning.
2. Reward model: for the same question
two answers are generated, and a person chooses the better one
over the other
. A network
learns to give a score consistent with the preferences, with the Bradley-Terry model:
, with
the sigmoid;
is minimised.
3. Reinforcement: the model (the policy
, which “acts” by choosing words) is optimised with PPO to maximise the reward, but without moving too far from the starting model
:
![]()
The Kullback-Leibler term prevents the model from finding strange answers that “fool” the reward model (which is only an approximation of the true preferences). In the InstructGPT work, the answers of a 1.3-billion-parameter model trained this way were preferred by people to those of the 175-billion GPT-3.

DPO: preferences without PPO
PPO on a model with billions of parameters is expensive and delicate. DPO (direct preference optimization, Rafailov et al., 2023) shows that the third stage can be done with a simple supervised loss.
Theorem. The policy that maximises
is
![Rendered by QuickLaTeX.com \[ \pi^*(y) = \frac{1}{Z}\,\pi_{ref}(y)\,e^{r(y)/\beta},\qquad Z = \sum_y\pi_{ref}(y)\,e^{r(y)/\beta} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-df04c563c0568cfd0601b221a58bddcf_l3.png)
Proof. Rewrite the objective by collecting
:
![Rendered by QuickLaTeX.com \[ \sum_y\pi(y)\Big[r(y) - \beta\log\frac{\pi(y)}{\pi_{ref}(y)}\Big] = -\beta\sum_y\pi(y)\log\frac{\pi(y)}{\pi_{ref}(y)e^{r(y)/\beta}} = -\beta\,\text{KL}(\pi\ \|\ \pi^*) + \beta\log Z \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-467bae636023ec80eb9fff3d9689c606_l3.png)
does not depend on
, and the KL divergence is non-negative and zero only if
(Gibbs’ inequality): the maximum is
. ∎
Inverting:
. The reward is determined by the optimal policy up to a constant, which in the Bradley-Terry model cancels out (only the difference
matters). Substituting gives a loss that trains the policy directly on preference pairs, without a reward model and without RL:
![]()
Numerical check. With four possible answers,
, rewards
and
, the formula gives
; gradient descent on the objective reaches the same values to the fourth decimal place, with objective 2.046 against 1.3 for the starting policy, and from
the reward differences
are reconstructed exactly.
import numpy as np
pi_ref = np.array([0.4, 0.3, 0.2, 0.1]) # reference policy over four answers
r = np.array([1.0, 2.0, 0.0, 3.0]) # rewards
beta = 0.5
pi_star = pi_ref * np.exp(r / beta) # closed form
pi_star /= pi_star.sum()
z = np.log(pi_ref).copy() # gradient descent on the logits
for _ in range(20000):
p = np.exp(z - z.max()); p /= p.sum()
f = r - beta * (np.log(p) - np.log(pi_ref))
z += 0.5 * p * (f - (p * f).sum())
p = np.exp(z - z.max()); p /= p.sum()
objective = lambda q: (q * r).sum() - beta * (q * np.log(q / pi_ref)).sum()
print("closed form:", np.round(pi_star, 4), " gradient:", np.round(p, 4))
print("objective:", round(objective(pi_star), 4), "against", round(objective(pi_ref), 4))
rr = beta * np.log(pi_star / pi_ref) # reward recovered from the policy
print("reward differences:", np.round(rr - rr[0], 4))Reasoning with verifiable rewards
Since 2024 RL has also been used to teach models to reason: on mathematics and programming problems the answer can be verified automatically (the result is right, the program passes the tests), and verification becomes the reward. The model generates many attempts, the correct ones are reinforced. DeepSeek-R1 (2025) showed that long chains of reasoning, with self-corrections, emerge this way, using a critic-free variant of PPO (GRPO, which estimates the advantage by comparing attempts within the same group).
When RL goes wrong: the wrong reward
An agent maximises the reward it is given, not the one intended. In a famous OpenAI example (2016), an agent trained on a boat racing game, rewarded for hitting targets, discovered that circling while hitting the same targets over and over paid more than finishing the race. In real systems this phenomenon (reward hacking, specification gaming) is the main concern: it is fought with carefully designed rewards, explicit constraints, limits on deviation from known behaviour (like the KL term of RLHF) and independent checks of the final behaviour.
Summary
| field | why it works | main difficulty |
|---|---|---|
| games | perfect and fast simulator, clear reward | huge action space |
| robotics | GPU simulators, domain randomisation | transfer to reality, safety |
| plants | abundant models and historical data | certification, constraints |
| autonomous driving | imitation on large data, RL in simulation | validation, rare events |
| language models | human preferences and automatic checks | approximate reward, reward hacking |
∑Formula sheet
Markov decision processes
The return and discounting
![Rendered by QuickLaTeX.com \[ G_t = r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \dots = \sum_{k=0}^{\infty}\gamma^k r_{t+k+1} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-43887cd049e98ad9805b2e52080c65be_l3.png)
![]()
Policy and value functions
![]()
Bellman equations
The Bellman equation for a policy
![]()
![]()
The optimality equation
![]()
The Bellman contraction
![]()
Policy improvement
![]()
Temporal differences, SARSA and Q-learning
Monte Carlo: the average of returns
![]()
Temporal differences
![Rendered by QuickLaTeX.com \[ V(s_t) \leftarrow V(s_t) + \alpha\,\underbrace{\big(r_{t+1} + \gamma V(s_{t+1}) - V(s_t)\big)}_{\delta_t,\ \text{TD error}} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-c42998e7621b298ed39a5600685e8295_l3.png)
From value to action: SARSA and Q-learning
![]()
![]()
Deep Q-Network
From tabular Q-learning to the network
![Rendered by QuickLaTeX.com \[ L(\theta) = \Big(\underbrace{r + \gamma\max_{a'}Q_{\bar\theta}(s', a')}_{y,\ \text{target}} - Q_\theta(s, a)\Big)^2 \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-369bcf20c141e71679f29a45b30415f8_l3.png)
Overestimation of the maximum and double DQN
![]()
Policy gradient and PPO
The policy gradient theorem
![]()
The baseline and actor-critic
![Rendered by QuickLaTeX.com \[ \hat A_t = \sum_{l=0}^{\infty}(\gamma\lambda)^l\,\delta_{t+l} = \delta_t + \gamma\lambda\,\hat A_{t+1} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-8a6902bdd9b730ee070efeb84ea5fd16_l3.png)
PPO: big steps but not too big
![]()
Simulation and Gaussian splatting
Gaussian splatting
![]()
Applications: robotics, driving, RLHF
Language models: RLHF
![]()
DPO: preferences without PPO
![Rendered by QuickLaTeX.com \[ \pi^*(y) = \frac{1}{Z}\,\pi_{ref}(y)\,e^{r(y)/\beta},\qquad Z = \sum_y\pi_{ref}(y)\,e^{r(y)/\beta} \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-df04c563c0568cfd0601b221a58bddcf_l3.png)
![Rendered by QuickLaTeX.com \[ \sum_y\pi(y)\Big[r(y) - \beta\log\frac{\pi(y)}{\pi_{ref}(y)}\Big] = -\beta\sum_y\pi(y)\log\frac{\pi(y)}{\pi_{ref}(y)e^{r(y)/\beta}} = -\beta\,\text{KL}(\pi\ \|\ \pi^*) + \beta\log Z \]](https://www.electronics-engineering.com/wp-content/ql-cache/quicklatex.com-467bae636023ec80eb9fff3d9689c606_l3.png)
![]()