AI State of the Art
Fundamentals/Machine Learning: The Basics/25 min
Section 6

Reinforcement Learning: Fundamental Principles

Listen as a podcast →

Introduction: Learning by Trial, Error, and Reward

Your child wants to learn to walk. Nobody programs their muscles. They try, fall (ouch, negative), get back up, succeed in taking a step (yes, positive!). Little by little, they learn the sequence of muscles they need to contract.

This is Reinforcement Learning (RL). An agent interacts with an environment. It tries an action. The environment says "well done, here's a reward" or "missed, penalty." After thousands of attempts, the agent finds the strategy that maximizes cumulative reward.

It's not supervised, it's real feedback

Supervised: "Here's the right answer." RL: "Here's a reward, figure out on your own where it came from."

The Actors of RL

Agent

The entity that learns. It's the "brain" being trained. Can be a robot, an AI playing chess, a chatbot.

Environment

Everything the agent interacts with. Reacts to actions. Determines rewards.

The Interaction Loop

  1. Agent observes the state (position, situation)
  2. Agent chooses an action
  3. Environment changes and produces a reward
  4. Back to step 1

Think of AlphaGo: agent = the AI, environment = the Go board. AlphaGo plays a move. The environment validates whether it's legal and produces a reward (better position? eventual victory?)

Diagram of the agent-environment cycle in reinforcement learning
This diagram illustrates the fundamental cycle of reinforcement learning: the agent interacts with the environment by taking actions, receives a state and a reward, then updates its model to improve its policy. A concrete example is AlphaGo playing on a board.Source : GeeksforGeeks

Key Concepts

State

The current description of the situation.

Examples:

  • Chess: position of all pieces
  • Walking robot: positions and velocities of its joints
  • Video game: screen pixels, or player position + enemies + items

Action

What the agent can do.

Discrete: go left, right, jump, shoot (video games)

Continuous: apply a continuous force on a motor (robotics)

Reward

The environment's immediate response: a single number, positive when things went well, negative when they did not.

Examples:

  • Chess: +1 for a win, -1 for a loss, 0 otherwise
  • Walking robot: +1 for each meter advanced, -100 for a fall
  • Pac-Man: +10 for eating a pellet, -10 for getting caught
Designing the Reward is an Art

A bad reward = weird agent. Classic example: agent tasked with "picking up objects." It learns to spin in circles next to the item respawn point instead of exploring. This is called reward hacking: the agent faithfully maximizes the number you gave it, but that number was not measuring what you wanted.

Policy

The agent's strategy. A function that says "in this state, take this action."

Deterministic: same state = same action always.

Stochastic: same state = probability distribution over different actions.

The goal of RL: find the optimal policy that maximizes the long-term reward.

Value Function

Answers: "How much is this state worth in the long run?"

V(s)=r+γ⋅V(s′)V(s) = r + \gamma \cdot V(s')

Symbol by symbol: ss is the current state ("where I stand"), V(s)V(s) the value we assign it, rr the reward collected right now, s′s' ("s prime") the state we land in immediately after, and γ\gamma ("gamma") a number between 0 and 1. In one sentence: a state is worth what it pays out now, plus whatever the next state is worth, slightly discounted.

The discount factor (γ\gamma, between 0 and 1) controls the importance of the future. It is exactly a financial discount rate: a dollar ten moves from now is worth less than a dollar today.

  • γ\gamma close to 0: the agent is short-sighted, focused on immediate reward
  • γ\gamma close to 1: the agent plans for the long term

Q-Function

A variant of the value function. Answers: "If I take this action in this state, what reward do I expect?"

Q(s,a)=r+γ⋅max⁡a′Q(s′,a′)Q(s, a) = r + \gamma \cdot \max_{a'} Q(s', a')

Same letters as above, plus two: aa is the action being considered now, and max⁡a′\max_{a'} means "try every action a′a' available from the next state and keep the best value". In one sentence: this action is worth the immediate reward plus the value of the best move playable afterwards, discounted.

If you know the optimal Q, the optimal policy is simple: in each state, take the action with the highest Q value.

Exploration vs Exploitation: The Fundamental Dilemma

You know a good restaurant (exploitation). But maybe there's a better one nearby (exploration). If you only exploit, you never discover the best one. If you only explore, you never enjoy your discoveries.

This is the central trade-off of RL.

Exploitation: do what you know to be good

Exploration: try new things to potentially discover something better

Explore vs Exploit diagram in AI
This diagram illustrates the fundamental trade-off between exploration (trying new actions) and exploitation (optimizing known actions) in reinforcement algorithms. It shows how these two strategies balance each other to maximize long-term rewards.Source : Strategyzer

Strategies:

Epsilon-greedy: with probability ϵ\epsilon (say 10%), draw an action at random, that is exploration. The rest of the time, take the best known action, that is exploitation. You shrink ϵ\epsilon over time, so you explore a lot early and barely at all late.

Softmax: draw the action at random, but with loaded dice, the higher an action's estimated Q value, the likelier it comes up. Bad actions keep a small chance, which maintains a trickle of exploration at all times.

Upper Confidence Bound (UCB): instead of picking the best-scoring action, pick the one whose score could be the best given what you still do not know. Rarely tried actions are therefore favored, until you have tried them enough to settle the question.

Q-Learning: The Foundational Algorithm

One of the most famous RL algorithms. Learns the optimal Q function without a model of the environment.

How it works:

  1. Observe current state s
  2. Choose action a (epsilon-greedy for example)
  3. Environment gives reward r and new state s'
  4. Update Q:
Q(s,a)←Q(s,a)+α[r+γ⋅max⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha \left[ r + \gamma \cdot \max_{a'} Q(s', a') - Q(s, a) \right]

The arrow ←\leftarrow means "replace the left-hand value with the right-hand result". α\alpha ("alpha") is the learning rate: the fraction of the correction you agree to apply each time, typically 0.1. What sits inside the bracket is the gap between what you just observed (r+γ⋅max⁡a′Q(s′,a′)r + \gamma \cdot \max_{a'} Q(s', a'), the revised value) and what you believed (Q(s,a)Q(s,a), the old estimate).

In one sentence: compare what you believed against what you just saw, and shift the estimate by a tenth of the difference. When the gap reaches zero nothing moves any more, which is the sign the estimate is consistent with itself.

Reinforcement learning diagram with feedback
Imagine a system that sees an apple but incorrectly says, 'It's a mango.' The system is told, 'Wrong! It's an apple.' It learns from this mistake. Next time, when shown the apple, it correctly says 'It's an apple.' This trial-and-error process, guided by feedback is like how Q-Learning works.Source : GeeksforGeeks

Deep Q-Network (DQN): When State Spaces are Huge

When the state space is infinite (the pixels of an Atari game = billions of states), a Q table doesn't work.

Solution: replace the Q table with a neural network that approximates Q(s, a).

DQN allowed an AI to learn Atari games at superhuman level. Two key innovations:

Experience replay: transitions actually lived (state, action, reward, next state) are stored in a pool, and training samples from that pool at random. Without it the network would learn from consecutive, therefore nearly identical, moments and would be dragged around by whatever it saw last.

Target network: keep a copy of the network, frozen for a few thousand steps, and use that copy to compute the value being aimed at. Otherwise the network chases a target it is itself moving at every step, and training runs away.

Playing Atari with Deep Reinforcement Learning (Mnih et al., 2013)
Diagram of a deep reinforcement learning agent
Structure of DQNSource : Medium

Policy Gradient: Optimizing the Policy Directly

Instead of learning Q and deriving the policy from it, optimize the policy directly.

Policy gradient theorem:

∇J(θ)=E[∇log⁡πθ(a∣s)⋅Q(s,a)]\nabla J(\theta) = \mathbb{E} \left[ \nabla \log \pi_\theta(a|s) \cdot Q(s, a) \right]

The formula looks forbidding but says something simple. The symbols, in order:

  • θ\theta ("theta"): the learned parameters of the policy, the settings of the neural network that picks actions.
  • J(θ)J(\theta): the total reward you expect to collect with those settings. This is the quantity to push up.
  • ∇\nabla ("nabla", the gradient): for each parameter, which way and how far to turn it in order to raise whatever follows.
  • πθ(a∣s)\pi_\theta(a|s) ("pi"): the policy. The probability that the model, with its current settings, picks action aa in state ss.
  • log⁡\log: the logarithm, present for a purely technical reason, it turns a product of probabilities into a sum, which keeps the arithmetic stable (see numerical stability).
  • E\mathbb{E}: the expectation, that is, "on average across many played episodes" (see expectation and variance).
  • Q(s,a)Q(s, a): the action value defined above.

In one sentence: for every action taken, nudge the settings in the direction that makes that action more likely, and nudge harder the better the action turned out to be. A mediocre action (low QQ) is barely reinforced; a bad one (negative QQ) is actively discouraged.

Variations:

REINFORCE: the barest version, applying the formula above as it stands.

Actor-critic: two networks instead of one. The actor is the policy and picks actions. The critic is the value function and scores situations. One learns to play better, the other to judge better, and each helps the other.

PPO (Proximal Policy Optimization): the most widespread variant today. Its idea: forbid each update from moving the new policy too far from the old one, which prevents sudden collapses. This is what RLHF uses.

Proximal Policy Optimization Algorithms (Schulman et al., 2017)

Spectacular Applications

Games

AlphaGo (2016): beat the world champion of Go, a feat that was considered humanly impossible for a machine. Combination of neural networks + tree search + RL.

Google's AlphaGo program was playing against Lee Se-dol in Seoul, in South Korea.
Google's AlphaGo program was playing against Lee Se-dol in Seoul, in South Korea.Source : BBC

AlphaZero (2017): learns chess from nothing, with no human games at all, and after a few hours of training beats the best traditional programs.

Playing level of AlphaZero and AlphaGo compared to other machines (source: DeepMind)
Playing level of AlphaZero and AlphaGo compared to other machines (source: DeepMind)Source : Creachess

OpenAI Five (2019): beat the best players of Dota 2 (complex, cooperative game).

OpenAI's bots defeated former professional Dota 2 players, in a match meant to test the bots' readiness to take on the world's top players later this month at the game's premier tournament
OpenAI's bots defeated former professional Dota 2 players, in a match meant to test the bots' readiness to take on the world's top players later this month at the game's premier tournamentSource : Quartz

Robotics

RL makes it possible to train robots to walk, grasp objects, and navigate their environment. Sim-to-real transfer is central here: you train the agent in simulation (fast, free, and where breaking the robot costs nothing) then install the learned policy on the physical machine.

RLHF: Aligning LLMs with Humans

RLHF (Reinforcement Learning from Human Feedback) is one of the most impactful applications of RL. ChatGPT, Claude, and Gemini all use it.

Training language models to follow instructions with human feedback (InstructGPT)

Process:

  1. Supervised pre-training: LLM trained classically on text (already useful)

  2. Reward model: humans compare pairs of responses, indicate which is better. Train a model to predict these preferences.

  3. PPO optimization: use PPO to optimize the LLM. Maximize the reward model score, while staying close to the original model (avoids "reward hacking").

Result: ChatGPT capable of following instructions, being helpful, avoiding harmful content.

DPO: A Modern Alternative to RLHF

DPO (Direct Preference Optimization) simplifies the process. No need for an explicit reward model or PPO (Proximal Policy Optimization). Just a direct classification problem on preference pairs. Simpler, often just as good.

Direct Preference Optimization (Rafailov et al., 2023)
Steps of Direct Preference Optimization
Overview of the RLHF learning processSource : AWS

The Challenges of RL

Sample efficiency: RL often needs millions of interactions before it knows anything at all. In simulation that is one night of compute. With a real robot that wears out and breaks, it is out of reach.

Stability: RL training is notoriously unstable. A slight hyperparameter change = collapse.

Reward design: translating what you actually want into a single number is very hard, and the agent will find the hole in your wording before you do.

Exploration vs exploitation: finding the right balance takes experience.

Generalization: an agent trained on one environment can fail if the environment changes slightly.

The Alignment Problem with LLMs

If you optimize an LLM to please an imperfect reward model, it can "hack" it. It then produces text no human would genuinely like but which scores well with the reward model. This is a central challenge of AI safety.

Why This Matters

RL is how modern systems learn from real interaction. AlphaGo, ChatGPT, autonomous vehicles, robots: everywhere you need to learn from real-world feedback (not just static data), RL dominates. It's also the most difficult paradigm, but the most powerful.

Check your understanding0 / 5

1. What fundamentally separates reinforcement learning from supervised learning?

2. An agent tasked with collecting items learns to circle next to the item respawn point instead of exploring. What is this phenomenon called?

3. In the value function, what is the discount factor gamma for?

4. What does the epsilon-greedy strategy do?

5. During RLHF, why is the optimized LLM forced to stay close to the original model?