Advanced⏱ 30 min⚡ 110 XP🧩 5-question quiz

Reinforcement Learning Fundamentals

The agent-environment loop, Markov decision processes, returns and discounting, value functions, and the exploration-exploitation trade-off through multi-armed bandits.


Every model you have studied so far learned from a fixed dataset of examples. In Module 08, a diffusion model learned from millions of images; in Module 07, LLM pretraining used a fixed corpus of text. But many problems do not come with a dataset of right answers. How should a robot move its joints to walk? Which move wins a game of Go? Which of an LLM's possible answers will a person find most helpful? Nobody can label the correct action at every step, yet we can tell, eventually, whether things went well.

Reinforcement learning (RL) is the study of learning from that kind of signal: an agent acts, the world responds, and a reward says how good the outcome was. It powered superhuman game-playing systems, it controls real robots, and it is a central ingredient in training today's LLM assistants and reasoning models (Module 07's Fine-Tuning and Alignment lesson introduced RLHF and DPO as recipes; lesson 4 of this module opens them up as RL algorithms). This module builds RL from the ground up and finishes with exactly those modern uses.

The agent-environment loop

Rendering diagram…

The diagram shows the loop that defines RL: at each step the agent observes a state, chooses an action using its policy, and the environment returns a reward and the next state. The agent's goal is to choose actions that maximize total reward over time, not just the next reward.

Key vocabulary:

  • State s: what the agent observes (a board position, joint angles, a conversation so far).
  • Action a: what it can do (a move, motor torques, the next token).
  • Reward r: a scalar signal from the environment. The reward defines the task; designing it well is half the battle.
  • Policy π(a∣s)\pi(a \mid s): the agent's behaviour, a mapping from states to (probabilities of) actions. This is what we learn.
  • Episode: one run from a start state to a terminal state (one game, one conversation). Some tasks are continuing, with no natural end.

Three features make RL harder than supervised learning:

  1. Evaluative, not instructive, feedback. A reward of 3 says nothing about whether another action would have earned 10.
  2. Delayed consequences. A chess move's value may only become clear 40 moves later. Working out which earlier actions deserve credit is the credit assignment problem.
  3. The agent controls its data. What the agent experiences depends on how it acts. A bad policy sees a biased slice of the world, which is why exploration matters.

Markov decision processes

The standard mathematical model of this loop is a Markov decision process (MDP), defined by:

  • a set of states S and actions A;
  • transition probabilities P(s′∣s,a)P(s' \mid s, a);
  • a reward function R(s,a,s′)R(s, a, s') (or its expectation);
  • a discount factor γ∈[0,1]\gamma \in [0, 1].

The defining assumption is the Markov property: the next state and reward depend only on the current state and action, not on how you got there. "The state is a sufficient summary of the past." A chess board is Markov (well, plus castling and repetition rules); a single frame of a video game where a ball's velocity is not visible is not, which is why DQN stacked several frames as its state. When the agent sees only partial observations, the problem is a POMDP, and agents typically use memory (recurrent networks, or the full context window in an LLM) to compensate.

Returns and discounting

The agent maximizes the return, the (discounted) sum of future rewards from time t:

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

Why discount?

  • Mathematical: in continuing tasks, an infinite sum of rewards could diverge. With γ < 1 and bounded rewards, G_t is finite.
  • Practical: near-term rewards are more certain; the further ahead we predict, the noisier it gets.
  • Behavioural: γ sets the agent's planning horizon. A rough rule of thumb is that the effective horizon is about 1/(1−γ)1/(1-\gamma) steps (the sum ∑kγk\sum_k \gamma^k): γ = 0.9 looks about 10 steps ahead, γ = 0.99 about 100.

Worked example. An agent gets rewards 0, 0, 10, then the episode ends. With γ = 0.9: G₀ = 0 + 0.9·0 + 0.81·10 = 8.1. With γ = 0.5: G₀ = 0.25·10 = 2.5. A small γ makes the agent short-sighted: given a choice between 3 now and 10 in two steps, it would take the 3.

Returns also satisfy a simple recursion that the whole next lesson builds on:

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

Value functions and policies

Because the environment and policy can both be random, we work with expected returns:

Vπ(s)=Eπ[Gt∣st=s],Qπ(s,a)=Eπ[Gt∣st=s, at=a]V^\pi(s) = \mathbb{E}_\pi\big[ G_t \mid s_t = s \big], \qquad Q^\pi(s, a) = \mathbb{E}_\pi\big[ G_t \mid s_t = s,\, a_t = a \big]
  • State value Vπ(s)V^\pi(s): how good is it to be in state ss if I follow π\pi from here?
  • Action value Qπ(s,a)Q^\pi(s, a): how good is taking action aa in state ss and then following π\pi?

If you knew the optimal action values Q∗(s,a)Q^*(s, a), acting optimally would be trivial: pick arg⁡max⁡aQ∗(s,a)\arg\max_a Q^*(s, a). This suggests two broad families of methods, which the next two lessons cover:

FamilyLearnsActs byExamples
Value-basedQ(s, a)argmax over actionsQ-learning, DQN
Policy-basedπ(a | s) directlysampling from πREINFORCE, PPO
Actor-criticbothsampling from π, guided by a value estimateA2C, PPO with a critic
Model-baseda model of P and Rplanning with the modelMCTS in AlphaZero and MuZero, Dreamer

Bandits: exploration in its purest form

Before tackling sequential decisions, isolate the hardest conceptual piece: exploration versus exploitation. A multi-armed bandit is an MDP with one state. You repeatedly choose one of k slot-machine arms; each pays a random reward from an unknown distribution. There is no future state to worry about, just the tension between:

  • exploiting: pulling the arm that currently looks best, and
  • exploring: pulling other arms to learn whether they are better.

Bandits are not just a toy. They run real systems: choosing which headline or layout to show, adaptive clinical trials, ad selection and recommendation (often as contextual bandits, where the best arm depends on features of the user).

Performance is measured by regret: how much reward you lost compared with always pulling the best arm. Three strategies:

  • Greedy: always pick argmax Q(a). Fails when early noise makes the best arm look bad.
  • ε-greedy: with probability ε pick a random arm, otherwise greedy. Simple and robust, but keeps exploring uniformly forever.
  • UCB (upper confidence bound): pick at=arg⁡max⁡a[Q(a)+cln⁡t/N(a)]a_t = \arg\max_a \big[ Q(a) + c \sqrt{\ln t / N(a)} \big]. Arms with few pulls get a large bonus. This is optimism in the face of uncertainty: treat an under-explored arm as possibly great until data says otherwise. Its regret grows only logarithmically in time under standard assumptions.

A fourth classic, Thompson sampling, keeps a posterior distribution over each arm's mean, samples one value per arm and picks the best sample; it is popular in production for its strong performance and natural handling of uncertainty.

import numpy as np

def run(strategy, true_means, steps=2000, eps=0.1, c=1.0, seed=0):
    rng = np.random.default_rng(seed)
    k = len(true_means)
    Q = np.zeros(k)          # estimated value of each arm
    N = np.zeros(k)          # times each arm was pulled
    total = 0.0
    for t in range(1, steps + 1):
        if strategy == "greedy":
            a = int(np.argmax(Q))
        elif strategy == "eps-greedy":
            a = int(rng.integers(k)) if rng.random() < eps else int(np.argmax(Q))
        elif strategy == "ucb":
            if t <= k:
                a = t - 1                                    # try every arm once
            else:
                a = int(np.argmax(Q + c * np.sqrt(np.log(t) / N)))
        r = rng.normal(true_means[a], 1.0)
        N[a] += 1
        Q[a] += (r - Q[a]) / N[a]                            # incremental mean
        total += r
    regret = steps * max(true_means) - total
    return total / steps, regret

true_means = np.array([0.2, 0.5, 0.1, 0.9, 0.4])           # arm 3 is best
for s in ["greedy", "eps-greedy", "ucb"]:
    res = np.array([run(s, true_means, seed=k) for k in range(20)])
    print(f"{s:10s} avg reward/step={res[:, 0].mean():.3f}  avg regret={res[:, 1].mean():7.1f}")

Averaged over 20 runs you should see roughly: greedy about 0.51 reward per step with regret near 770; ε-greedy about 0.83 with regret near 140; UCB about 0.87 with regret near 66. Greedy often locks onto a mediocre arm. Notice the update Q[a] += (r - Q[a]) / N[a]: a running average written as "old estimate + step size × (target − old estimate)". That error-correcting update is the pattern behind almost every RL algorithm in this module.

From bandits to full RL

Bandits have exploration but no state and no delayed consequences. Full RL adds both: your action changes the state, and rewards may arrive long after the action that earned them. You will need value functions that propagate credit backward through time (next lesson) and policies that can be improved by gradient ascent (the lesson after).

Pitfalls and misconceptions

  • "Reward = what I want." The agent optimizes the reward you wrote, not your intention. A boat-racing agent famously learned to circle forever collecting bonus targets instead of finishing the race. Lesson 4 returns to this as reward hacking.
  • Choosing γ carelessly. Too low and the agent ignores long-term consequences; too close to 1 and learning becomes high-variance and slow.
  • Ignoring non-stationarity. In real bandit problems, arm values drift (user tastes change). Use a constant step size instead of a pure average so recent data counts more.
  • Confusing the reward with the return. The agent maximizes the long-run return; a policy that sacrifices immediate reward can be optimal.

Hands-on exercise

  1. Run the bandit code. Vary ε in {0.01, 0.1, 0.3} and c in {0.5, 1, 2}. Which settings minimize regret, and why does a very large ε hurt?
  2. Implement Thompson sampling for Gaussian rewards: keep a normal posterior per arm (mean = sample mean, standard deviation = 1/√(N+1)), sample one value per arm, pick the largest. Compare its regret with UCB.
  3. Make the problem non-stationary: every 500 steps, swap the best arm with a random other arm. Compare the sample-average update with a constant step size of 0.1.
  4. On paper: for γ = 0.95, compute the return of receiving +1 every step forever. Then explain why an agent with γ = 0.95 would prefer +1 forever over a one-off +15.

Expected outcome: moderate exploration wins; Thompson sampling performs comparably to or better than UCB; the constant step size adapts after each swap while the sample average lags badly; and +1 forever is worth 1/(1 − 0.95) = 20 > 15.

Key takeaways

  • RL learns from rewards, not labels, with delayed consequences and data shaped by the agent's own actions.
  • An MDP formalizes states, actions, transitions, rewards and a discount γ; the Markov property says the state summarizes the past.
  • The agent maximizes the discounted return Gt=∑kγkrt+k+1G_t = \sum_k \gamma^k r_{t+k+1}; γ\gamma sets the effective horizon.
  • Value functions V and Q estimate expected returns; acting greedily on Q* is optimal.
  • Bandits isolate exploration: greedy fails, ε-greedy and UCB (optimism under uncertainty) and Thompson sampling succeed.

Next, we add states and delayed rewards and learn optimal action values with the Bellman equation, Q-learning and its deep-learning extension, DQN.

Further reading

  • "Reinforcement Learning: An Introduction" (2nd edition), Richard Sutton and Andrew Barto (2018), chapters 1–3. Freely available from the authors.
  • "Bandit Algorithms", Tor Lattimore and Csaba Szepesvári (2020).
  • "A Contextual-Bandit Approach to Personalized News Article Recommendation", Li et al. (2010).
  • OpenAI "Spinning Up in Deep RL", Part 1: Key Concepts in RL (spinningup.openai.com).

Save your progress and earn XP

Create a free account to take the quiz, track progress and unlock badges.

Reinforcement Learning Fundamentals · AI Everything