- Formulate a sequential decision problem as an MDP and compute discounted returns.
- Derive the Bellman expectation and optimality equations and explain how dynamic programming solves them.
- Compare Monte Carlo, TD learning and Q-learning updates, and carry out Q-learning updates by hand.
- Implement tabular Q-learning with epsilon-greedy exploration and verify the learned values against the optimal return.
- Explain DQN, REINFORCE, actor-critic and PPO's clipped objective, and how RLHF and verifiable rewards apply RL to language models.
Before this: Probability and Statistics for AI, Calculus and Gradients: How Networks Learn, Neural Networks and Backpropagation
Reinforcement learning (RL) is learning by trial and error to maximise a reward signal over time. It produced the first systems to learn Atari games from pixels and to beat a top professional at Go, and it now trains robots, tunes data-centre cooling, and plays a central role in post-training large language models, from reinforcement learning from human feedback (RLHF) to the reasoning models trained against verifiable rewards. Unlike supervised learning, nobody tells the agent the right action. It has to discover which actions lead, often much later, to good outcomes.
Intuition: training a dog, playing a long game
Think of teaching a dog a trick with treats. The dog tries things; some actions earn a treat; over time it repeats what worked. Now make it harder: the treat only comes at the end of a long sequence, like winning a chess game after 60 moves. Which of those moves deserves the credit? That is the credit assignment problem, and it is the core of RL. The second core tension is exploration versus exploitation: should the dog repeat the trick it knows earns one treat, or try something new that might earn three?
The formal setup: agents, environments and MDPs
At each time step the agent observes a state , chooses an action , and the environment returns a reward and a next state . This is formalised as a Markov decision process (MDP), a tuple :
- : the set of states; : the set of actions.
- : the probability of reaching state with reward after taking action in state .
- : the discount factor.
The Markov property says the next state and reward depend only on the current state and action, not on earlier history. When the agent sees only part of the state (a robot's camera, a poker hand), the problem is a partially observable MDP, and agents use memory (recurrent networks, frame stacks) to compensate.
A policy gives the probability of taking action in state . The goal is to find a policy that maximises expected return.
Returns and discounting
The return from time is the discounted sum of future rewards:
Discounting does three jobs. It keeps infinite sums finite when , it encodes a preference for sooner rewards, and it reduces variance. A useful rule of thumb: the effective horizon is about steps, so looks roughly 100 steps ahead. Returns obey a simple recursion, which everything else builds on:
Worked example. An episode gives rewards and then ends. With : . Using the recursion backwards: , , .
Value functions and Bellman equations
The state-value function of policy is the expected return starting from and following : . The action-value function is , the expected return of taking first and then following .
Substituting the return recursion gives the Bellman expectation equation:
In words: the value of a state is the expected immediate reward plus the discounted value of where you land. The optimal value functions and satisfy the Bellman optimality equations:
Once you know , acting optimally is trivial: choose . Most of RL is about estimating these quantities when is unknown and the state space is huge.
Dynamic programming
If the model is known and the state space is small, dynamic programming (DP) solves the Bellman equations by iteration. Policy evaluation repeatedly applies the expectation equation as an update until stops changing. Policy improvement makes the policy greedy with respect to . Alternating the two is policy iteration. Value iteration folds them together by applying the optimality equation as an update, , which converges to for because the update is a contraction. DP is exact but needs the model and sweeps the whole state space, which Bellman called the curse of dimensionality.
Learning from experience: Monte Carlo and TD
When the model is unknown, the agent learns from sampled experience.
Monte Carlo (MC) methods run complete episodes and move the value estimate toward the observed return:
where is the step size. MC is unbiased but high-variance, and it must wait until the episode ends.
Temporal-difference (TD) learning updates after a single step by bootstrapping, using its own current estimate of the next state's value in place of the rest of the return:
The bracketed quantity is the TD error . TD learning works online, handles continuing tasks, and usually learns faster than MC because of its lower variance, at the price of bias from the bootstrapped estimate. -step returns and TD() interpolate between the two.
Q-learning
Q-learning (Watkins, 1989) applies TD learning to action values with a max in the target:
It is off-policy: it learns the value of the greedy policy while behaving with an exploratory one. Under standard conditions (every state–action pair visited infinitely often and suitably decaying step sizes), tabular Q-learning converges to . Its on-policy cousin SARSA uses the action actually taken next, , instead of the max, which makes it more cautious when exploration is risky.
Worked gridworld update
A robot in a gridworld is at cell (2,1). It moves right to cell (2,2) and receives reward (a step cost). Current estimates: , and the best action value at the new cell is . Take , .
- TD target: .
- TD error: .
- Update: .
Next, from (3,2) the robot moves right into the goal (3,3), receiving ; the episode ends, so there is no bootstrap term. If : target , error , new value . Repeated over many episodes, the goal reward propagates backwards through the grid one step at a time.
Exploration: epsilon-greedy and beyond
With -greedy exploration the agent picks a uniformly random action with probability and the greedy action otherwise. It is simple and surprisingly effective; is usually decayed from 1.0 toward a small value such as 0.01 or 0.05. Alternatives include softmax (Boltzmann) exploration, optimism in the face of uncertainty (optimistic initial values, upper confidence bounds), and intrinsic-motivation bonuses for novel states, which matter in sparse-reward problems where random actions almost never reach a reward.
A tabular Q-learning implementation
import numpy as np
ROWS, COLS = 4, 4
START, GOAL, PITS = (0, 0), (3, 3), {(1, 1), (2, 3)}
ACTIONS = [(-1, 0), (1, 0), (0, -1), (0, 1)] # up, down, left, right
def step(s, a):
r, c = s[0] + ACTIONS[a][0], s[1] + ACTIONS[a][1]
s2 = (min(max(r, 0), ROWS - 1), min(max(c, 0), COLS - 1)) # walls block
if s2 == GOAL: return s2, 10.0, True
if s2 in PITS: return s2, -10.0, True
return s2, -1.0, False
rng = np.random.default_rng(0)
Q = np.zeros((ROWS, COLS, len(ACTIONS)))
alpha, gamma, eps = 0.5, 0.9, 0.1
for episode in range(2000):
s, done = START, False
while not done:
a = int(rng.integers(4)) if rng.random() < eps else int(np.argmax(Q[s]))
s2, r, done = step(s, a)
target = r if done else r + gamma * np.max(Q[s2])
Q[s][a] += alpha * (target - Q[s][a]) # TD update
s = s2
s, path = START, [START]
for _ in range(20): # greedy rollout
s, _, done = step(s, int(np.argmax(Q[s])))
path.append(s)
if done: break
print("path:", path)
print("V(start) = %.3f" % Q[START].max())
The environment is a 4×4 grid with a goal worth , two pits worth and a step cost of . After 2,000 episodes the greedy policy walks a six-move shortest path around the pits, and . That matches the true optimal return: five step costs and then the goal, .
Deep RL: DQN
Tables fail when states are images. Deep Q-Networks (Mnih et al., 2013 preprint; Nature, 2015) replace the table with a convolutional network that maps stacked Atari frames to one value per action. Naive Q-learning with neural networks is unstable, so DQN added two ideas:
- Experience replay: store transitions in a buffer and train on random minibatches, which breaks correlations between consecutive samples and reuses data.
- Target network: compute targets with a periodically copied set of weights , minimising , so the target does not shift with every gradient step.
The Nature paper reported a single architecture and hyperparameter set learning 49 Atari 2600 games from pixels and score, reaching a level comparable to a professional human games tester across the set. Successors fixed known weaknesses: Double DQN reduces the overestimation caused by the max, and dueling networks, prioritised replay and distributional RL were combined in Rainbow.
Policy gradients: REINFORCE
Value-based methods struggle with continuous actions (a robot joint torque) and only learn deterministic greedy policies. Policy-gradient methods parameterise the policy directly, , and do gradient ascent on expected return . The policy gradient theorem gives
REINFORCE (Williams, 1992) estimates this by sampling episodes: increase the log-probability of actions in proportion to the return that followed them. Intuitively, it is supervised learning on your own actions, weighted by how well things went. The estimator is unbiased but very noisy, so we subtract a baseline that does not depend on the action, which keeps it unbiased while cutting variance: use instead of .
Actor-critic
Use a learned value function as the baseline and you get actor-critic: the actor is the policy , and the critic estimates values. The weight on each action becomes the advantage, (the TD error), which says how much better the action was than expected. Generalised advantage estimation (GAE) blends multi-step advantages with a parameter to trade bias against variance. A2C and A3C run many environment copies in parallel to decorrelate data.
PPO in one section
Policy-gradient updates are fragile: one step that is too large can collapse the policy, and the data needed to recover is then never collected. Proximal Policy Optimization (Schulman et al., 2017) limits how far each update moves the policy. With the probability ratio and advantage estimate , PPO maximises the clipped surrogate
with typically 0.1 to 0.2. When an action was good (), the objective stops rewarding increases in its probability beyond times the old one; when bad, it stops rewarding decreases below . This lets PPO run several epochs of minibatch updates on each batch of rollouts safely. In practice the loss also includes a value-function term and an entropy bonus. PPO's robustness made it the default on-policy algorithm for robotics, games and, for several years, RLHF. Off-policy actor-critics such as SAC and TD3 are common alternatives for continuous control when sample efficiency matters.
RL for language models: RLHF and verifiable rewards
A language model can be framed as a policy: the state is the prompt plus the text so far, an action is the next token, and an episode ends at the end of the response. RLHF, popularised by InstructGPT (Ouyang et al., 2022), has three stages: supervised fine-tuning on demonstrations; training a reward model on human preference comparisons between responses; and optimising the policy with PPO against the reward model, plus a KL-divergence penalty that keeps it close to the supervised model so it does not exploit reward-model errors (reward hacking). Preference-optimisation methods such as DPO skip the explicit RL loop.
For reasoning, a different reward is available: in maths and code you can check the answer. Reinforcement learning with verifiable rewards (RLVR), a term used in AI2's Tülu 3 report (2024), rewards the model when a final answer matches the reference or the code passes tests. DeepSeek-R1 (2025) showed that large-scale RL with such rule-based rewards, using the GRPO algorithm (which replaces the critic with advantages computed relative to a group of sampled answers to the same prompt), can produce long chain-of-thought reasoning. The lesson on post-training and alignment covers these pipelines in depth.
Famous results
| Year | System | What it showed |
|---|---|---|
| 1992 | TD-Gammon (Tesauro) | TD learning plus a neural network and self-play reached strong backgammon play |
| 2015 | DQN (DeepMind, Nature) | One network learned 49 Atari games from pixels and score |
| 2016 | AlphaGo | Beat Fan Hui 5–0 (October 2015, published January 2016), then Lee Sedol 4–1 in March 2016, using policy and value networks with Monte Carlo tree search, trained from human games and then self-play |
| 2017 | AlphaGo Zero | Learned Go from self-play alone, without human game data, and surpassed earlier AlphaGo versions |
| 2018 | AlphaZero (Science) | One algorithm mastered chess, shogi and Go from self-play, given only the rules |
Common pitfalls
- Reward hacking. The agent maximises the reward you wrote, not the one you meant: boat-racing agents circling to collect points, language models padding answers that a reward model likes. Inspect behaviour, not just reward curves.
- Sparse rewards. With reward only at success, random exploration may never find it; use reward shaping carefully (potential-based shaping preserves optimal policies), curricula or demonstrations.
- Seed sensitivity. Deep RL results vary hugely across random seeds; report several seeds with confidence intervals.
- Wrong discount or horizon. A that is too low makes the agent myopic; one that is too high slows learning.
- Non-stationary targets. Forgetting the target network, or not stopping gradients through targets, destabilises DQN.
- Evaluating with exploration on. Measure the greedy (or deterministic) policy separately from the exploring behaviour policy.
- Simulator exploits. Agents find physics bugs; a policy that exploits them will not transfer to the real world.
In practice
Ask first whether you need RL at all. If you can collect labelled decisions, supervised or imitation learning is cheaper and more stable; if the problem is one-step with feedback (ad selection, recommendations), contextual bandits may suffice. When RL fits (sequential decisions, a simulator or a safe way to interact, a clear reward), start with well-tested implementations from libraries such as Stable-Baselines3, CleanRL or TorchRL and environments with the Gymnasium API. Use PPO as a robust on-policy default, SAC for continuous control with costly samples, and DQN variants for discrete actions. Normalise observations and advantages, log episode returns across several seeds, and watch videos of the agent. For language models, RL now sits inside post-training pipelines: preference-based reward models for helpfulness and style, verifiable rewards for maths and code, always with a KL penalty or reference model and an eye on reward hacking.
Key takeaways
- RL learns from reward rather than labels, which creates two core problems: credit assignment over time and exploration versus exploitation.
- The Bellman equations express a value as immediate reward plus discounted future value; almost every RL algorithm is a way of solving them approximately.
- TD methods such as Q-learning bootstrap from their own estimates, which allows learning online after every step.
- DQN made Q-learning work with deep networks through experience replay and a target network.
- Policy-gradient methods optimise the policy directly; actor-critic reduces their variance and PPO keeps updates within a safe trust region.
- RLHF and RL with verifiable rewards bring the same machinery to language-model post-training, where reward hacking is the central risk.
Terms in this lesson
- Markov decision process (MDP)
- A formal model of sequential decisions defined by states, actions, transition probabilities, rewards and a discount factor.
- Return
- The discounted sum of future rewards from a time step onward.
- Discount factor
- A number between 0 and 1 that weights a reward k steps in the future by its k-th power.
- Policy
- A mapping from states to a probability distribution over actions.
- Action-value function
- The expected return from taking a given action in a given state and following a policy afterwards.
- Bellman optimality equation
- The recursive condition that the optimal value of a state equals the best action's expected reward plus discounted optimal next-state value.
- Temporal-difference error
- The difference between the bootstrapped target r + gamma V(s') and the current estimate V(s).
- Off-policy learning
- Learning about one policy, such as the greedy policy, from data generated by a different behaviour policy.
- Advantage
- How much better an action is than the policy's average action in that state: Q(s,a) minus V(s).
- Reward hacking
- An agent achieving high reward through behaviour that exploits flaws in the reward signal rather than doing the intended task.
Check your understanding
- 1.
An episode yields rewards 2, 0, 4 and then terminates. With gamma = 0.5, what is the return from the first step?
- 2.
Q(s, a) = 4, the agent receives r = 1 and lands in s' where max Q(s', a') = 10. With alpha = 0.1 and gamma = 0.9, what is the updated Q(s, a)?
- 3.
What makes Q-learning off-policy while SARSA is on-policy?
- 4.
You need to control a robot arm with 7 continuous joint torques, with a fast simulator available. Which is the most sensible starting algorithm?
- 5.
In PPO, an action has advantage +2, epsilon = 0.2, and the new policy makes it 1.5 times as likely as the old policy. What is that sample's clipped objective term?
Exercises
Work each problem before opening the solution.
- Exercise 1Core
Verify analytically that the optimal value of the start state in the lesson's gridworld is about 1.810. The shortest safe path takes 6 moves: five steps with reward -1 and a final step into the goal with reward +10, with gamma = 0.9. Then explain why a path that goes through the pit is never preferred.
Show solution
Return = -1 - 0.9 - 0.81 - 0.729 - 0.6561 + 0.9^5 x 10.
Step costs: the sum of 0.9^k for k = 0..4 is (1 - 0.9^5)/(1 - 0.9) = (1 - 0.59049)/0.1 = 4.0951, so the cost is -4.0951. Goal: 0.9^5 = 0.59049, times 10 = 5.9049. Total = 1.8098, which matches the learned Q value of 1.810.
Entering a pit ends the episode with -10. A path that falls into a pit after k earlier steps returns -(1 - 0.9^k)/0.1 - 10 x 0.9^k = -10 exactly (with gamma = 0.9, 1/(1 - gamma) = 10, so the discounted step costs and the discounted penalty always sum to -10). That is far below 1.81, so the greedy policy avoids pits. A 4x4 grid needs at least 6 moves from (0,0) to (3,3), so no shorter safe path exists.
- Exercise 2Core
Run value iteration by hand on this 3-state chain with gamma = 0.9. States A, B, C, where C is terminal (V = 0). In A, action 'right' goes to B with reward 0 and 'stay' stays in A with reward 0.5. In B, 'right' goes to C with reward 10 and 'left' goes to A with reward 0. Start with V = 0 everywhere and use synchronous updates (each sweep uses the previous sweep's values). Do sweeps until the values stop changing, and give the optimal policy.
Show solution
Sweep 1 (from V0 = 0):
- V1(A) = max(right: 0 + 0.9 x 0 = 0, stay: 0.5 + 0.9 x 0 = 0.5) = 0.5.
- V1(B) = max(right: 10 + 0 = 10, left: 0 + 0.9 x 0 = 0) = 10.
Sweep 2 (from V1):
- V2(A) = max(right: 0.9 x 10 = 9, stay: 0.5 + 0.9 x 0.5 = 0.95) = 9.
- V2(B) = max(10, 0.9 x 0.5 = 0.45) = 10.
Sweep 3 (from V2):
- V3(A) = max(0.9 x 10 = 9, 0.5 + 0.9 x 9 = 8.6) = 9.
- V3(B) = max(10, 0.9 x 9 = 8.1) = 10.
The values are unchanged, so V*(A) = 9 and V*(B) = 10. The optimal policy is A: right, B: right. Note that after sweep 1 the greedy action in A was 'stay': the goal reward had not yet propagated back to A. Check: staying in A forever is worth 0.5/(1 - 0.9) = 5, which is less than 9, so 'right' is indeed optimal.
- Exercise 3Core
Modify the lesson's Q-learning code to use SARSA instead, keeping everything else the same. Show the changed loop and explain any difference you would expect in the learned path when epsilon stays at 0.1.
Show solution
for episode in range(2000): s, done = START, False pick = lambda st: int(rng.integers(4)) if rng.random() < eps else int(np.argmax(Q[st])) a = pick(s) while not done: s2, r, done = step(s, a) a2 = None if done else pick(s2) # next action from the same eps-greedy policy target = r if done else r + gamma * Q[s2][a2] Q[s][a] += alpha * (target - Q[s][a]) s, a = s2, a2SARSA learns the value of the epsilon-greedy policy it actually follows. Paths that pass next to a pit are penalised, because 10% of the time a random move might fall in. SARSA may therefore prefer a route that keeps a margin from the pits even if it is longer: the classic cliff-walking result. Q-learning learns the optimal greedy path alongside the pits. In this small grid both often find a 6-move path, but SARSA's values for cells adjacent to pits are noticeably lower.
- Exercise 4Challenge
Implement REINFORCE with a baseline for a 2-armed bandit using numpy only. Arm 0 pays 1 with probability 0.3; arm 1 pays 1 with probability 0.7. Use a softmax policy over two logits, learning rate 0.1, and a running-average baseline. Show the gradient of log pi for a softmax and report the final probability of choosing arm 1 after 2,000 pulls.
Show solution
For a softmax policy pi(a) = exp(theta_a)/sum_b exp(theta_b), the gradient of log pi(a) with respect to theta_k is 1[k = a] - pi(k). In vector form: onehot(a) - pi.
import numpy as np rng = np.random.default_rng(0) p_pay = np.array([0.3, 0.7]) theta, lr, baseline = np.zeros(2), 0.1, 0.0 for t in range(2000): pi = np.exp(theta - theta.max()); pi /= pi.sum() a = rng.choice(2, p=pi) r = float(rng.random() < p_pay[a]) grad_logp = -pi.copy(); grad_logp[a] += 1.0 # onehot(a) - pi theta += lr * (r - baseline) * grad_logp # REINFORCE with baseline baseline += 0.01 * (r - baseline) # running average reward pi = np.exp(theta - theta.max()); pi /= pi.sum() print('P(arm 1) = %.3f' % pi[1])The probability of arm 1 climbs close to 1 (typically above 0.97 after 2,000 pulls). The baseline matters: without it, every reward of 1 pushes up whichever arm was pulled, and learning is noisier. With it, rewards are compared with the average (about 0.7 once the policy is good), so only better-than-average outcomes increase an action's probability. The baseline does not depend on the action, so the gradient estimate stays unbiased.
- Exercise 5Challenge
In RLHF with PPO, the per-response reward is often r = RM(x, y) - beta * KL(pi_theta || pi_ref). Explain (a) why the KL term is needed, (b) what happens when beta is too small or too large, and (c) why verifiable rewards for maths reduce but do not remove reward hacking.
Show solution
(a) The reward model is a learned approximation of human preferences, trained on a limited distribution of responses. Optimising hard against it pushes the policy into regions where the reward model is wrong, producing reward hacking (for example, verbose, sycophantic or oddly formatted text that scores high). The KL penalty keeps the policy near the reference (supervised) model, where the reward model is more reliable, and it preserves fluency and diversity.
(b) Beta too small: the policy drifts far, reward climbs while true quality falls (over-optimisation), and outputs can degenerate. Beta too large: the policy barely moves from the reference, so RL adds little. Practitioners tune beta or use an adaptive controller that targets a KL budget.
(c) A verifier (exact-match answer checking, unit tests) is far harder to fool than a learned reward model, because it checks the real objective for that task. Hacking still occurs: the model can exploit weak tests (special-casing test inputs), answer-format loopholes in the parser, or guess when answers are multiple choice. And the reward says nothing about the quality of the reasoning text itself. Defences include stronger and hidden test suites, strict output parsing, penalties for format abuse, and evaluating on held-out problems.
Further reading
- bookRichard S. Sutton and Andrew G. Barto, Reinforcement Learning: An Introduction, 2nd ed. (2018)
- paperVolodymyr Mnih et al., Human-level control through deep reinforcement learning (2015)
- paperJohn Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford, Oleg Klimov, Proximal Policy Optimization Algorithms (2017)
- paperDavid Silver et al., Mastering the game of Go with deep neural networks and tree search (2016)
- paperLong Ouyang et al., Training language models to follow instructions with human feedback (2022)
- courseOpenAI, Spinning Up in Deep RL
Go further
Sources
- Sutton & Barto, Reinforcement Learning: An Introduction (2nd ed.)
- Mnih et al., Nature 518 (2015)
- Silver et al., Nature 529 (2016)
- Silver et al., Mastering Chess and Shogi by Self-Play with a General Reinforcement Learning Algorithm (arXiv 1712.01815)
- DeepSeek-AI, DeepSeek-R1 (arXiv 2501.12948)
- Lambert et al., Tülu 3 (arXiv 2411.15124)
Fact-checked and last reviewed 2026-11-05