Agent Environment action state, reward
Tier 3 · Deep Learning & Neural Networks

Reinforcement
Learning Basics

A different learning paradigm: no labeled examples, just trial, error, and reward. From the agent-environment loop through Q-learning to policy gradients — and the RLHF technique that makes modern chat models helpful and aligned.

📚 5 Lessons 🎮 Game-based Examples 🤖 RLHF Preview ⏱ ~3.5 hours
Lesson 10.1

Agents, Environments, Rewards, Policies

Reinforcement learning (RL) is a fundamentally different paradigm from everything in this tier so far. Supervised learning trains on (input, correct-output) pairs. RL trains an agent that takes actions in an environment, receives rewards, and learns a policy — a strategy for choosing actions — that maximizes cumulative reward over time, without ever being told the "correct" action directly.

🤖

Agent

The learner/decision-maker. Observes the environment's state, chooses an action according to its policy. Could be a game-playing AI, a robot, a recommendation system, or a chatbot being fine-tuned.

🌍

Environment

Everything the agent interacts with. Receives the agent's action, transitions to a new state, returns a reward signal. Could be a video game, a physical robot's surroundings, or a simulated market.

🎯

Reward

A scalar signal indicating how good the last action was. Often sparse and delayed — in chess, you only get a reward (win/lose) at the very end, not after each move. This is the credit assignment problem.

🧭

Policy π(a|s)

The agent's strategy — a (possibly probabilistic) mapping from states to actions. The entire goal of RL is to find the policy that maximizes expected cumulative reward. This is what gets "learned."

The exploration-exploitation tradeoff

A core tension in RL: should the agent exploit what it already knows works well, or explore to discover potentially better strategies? Always exploiting risks getting stuck in a mediocre local strategy. Always exploring wastes opportunities to use known-good actions. Balancing these is a central RL design challenge, often handled with strategies like ε-greedy (mostly exploit, occasionally explore randomly) or more sophisticated approaches.

🎮
Why RL is different from supervised learning In supervised learning, the "correct answer" (label) is given directly. In RL, the agent only learns whether an action sequence was good or bad eventually — and must figure out which of its many actions deserve credit or blame. This delayed, indirect feedback makes RL fundamentally harder and noisier to train than supervised learning.
Lesson 10.2

Markov Decision Processes

The Markov Decision Process (MDP) is the formal mathematical framework underlying almost all of RL. It defines precisely what "states," "actions," "rewards," and "transitions" mean, and crucially makes the Markov assumption: the future depends only on the current state, not on the history of how you got there.

MDP = (S, A, P, R, γ)

S = set of states
A = set of actions
P(s'|s,a) = transition probability — chance of reaching s' from s via action a
R(s,a,s') = reward received for this transition
γ ∈ [0,1) = discount factor — how much future reward is worth today
Markov property: P(sₜ₊₁ | sₜ, aₜ, sₜ₋₁, aₜ₋₁, ...) = P(sₜ₊₁ | sₜ, aₜ) — only the current state matters
The discount factor and return

The agent's goal is to maximize the return — the discounted sum of all future rewards. The discount factor γ controls how much to value future rewards versus immediate ones.

Gₜ = Rₜ₊₁ + γRₜ₊₂ + γ²Rₜ₊₃ + ... = Σ γᵏ Rₜ₊ₖ₊₁
γ close to 0: myopic, cares mostly about immediate reward. γ close to 1: farsighted, values long-term outcomes.
📊

Value function V(s)

Expected return starting from state s, following policy π thereafter. "How good is it to be in this state?" Used to evaluate states regardless of which action you're about to take.

🎯

Action-value function Q(s,a)

Expected return starting from state s, taking action a, then following policy π. "How good is it to take this specific action in this state?" This is what Q-learning estimates directly.

Optimal policy π*

The policy that maximizes expected return from every state. Once you have the optimal Q-function Q*(s,a), the optimal policy is simply: always pick the action with highest Q-value.

🔄

Bellman equation

The recursive relationship defining V and Q in terms of immediate reward plus discounted future value. This recursion is the mathematical foundation that makes Q-learning and value iteration possible.

Bellman equation for Q:
Q(s,a) = E[R + γ · max_{a'} Q(s', a')]
The Q-value of a state-action pair equals immediate reward plus the discounted best Q-value achievable from the next state
Lesson 10.3

Q-Learning

Q-learning is a classic, foundational RL algorithm that learns the optimal action-value function Q*(s,a) directly from experience, without needing to know the environment's transition probabilities in advance (model-free learning). It uses the Bellman equation as an iterative update rule.

Q(s,a) ← Q(s,a) + α · [R + γ·max_{a'}Q(s',a') − Q(s,a)]

α = learning rate. The term in brackets is the "TD error" —
difference between the current estimate and a better bootstrapped estimate
This is Temporal Difference (TD) learning: update toward a target computed from the next state's own estimate
Tabular Q-learning algorithm
  • 1Initialize a Q-table with one entry per (state, action) pair, typically zeros.
  • 2Observe the current state s.
  • 3Choose an action using ε-greedy: with probability ε pick a random action (explore), otherwise pick argmax_a Q(s,a) (exploit).
  • 4Execute the action, observe reward R and new state s'.
  • 5Update Q(s,a) using the Bellman update equation above.
  • 6Repeat until convergence — Q-values stabilize toward the true optimal values.
Pythontabular Q-learning — FrozenLake-style grid world
import numpy as np

# Simplified grid world: 4 states, 2 actions (left/right)
n_states, n_actions = 4, 2
Q = np.zeros((n_states, n_actions))

# Simulated environment transition (toy example)
def step(state, action):
    # action 0 = left, action 1 = right
    next_state = max(0, state - 1) if action == 0 else min(n_states-1, state + 1)
    reward = 1.0 if next_state == n_states - 1 else 0.0   # goal at last state
    done = (next_state == n_states - 1)
    return next_state, reward, done

# ── Q-learning hyperparameters ───────────────────────────────────────
alpha, gamma, epsilon = 0.1, 0.95, 1.0
epsilon_decay = 0.995

for episode in range(1000):
    state = 0
    done = False
    while not done:
        # ε-greedy action selection
        if np.random.rand() < epsilon:
            action = np.random.randint(n_actions)   # explore
        else:
            action = np.argmax(Q[state])              # exploit

        next_state, reward, done = step(state, action)

        # Bellman update — the core of Q-learning
        best_next_q = np.max(Q[next_state])
        td_target = reward + gamma * best_next_q
        td_error  = td_target - Q[state, action]
        Q[state, action] += alpha * td_error

        state = next_state

    epsilon = max(0.01, epsilon * epsilon_decay)   # decay exploration over time

print("Learned Q-table:")
print(Q.round(3))
# Optimal policy: argmax over each row → should favor "right" (action 1)
⚠️
Tabular Q-learning doesn't scale A Q-table needs one entry per (state, action) pair. For Chess (~10^47 states) or continuous state spaces (robotics, Atari from pixels), an explicit table is impossible. The solution: approximate Q(s,a) with a neural network instead of a table — this is Deep Q-Networks (DQN), the algorithm that famously learned to play Atari games from raw pixels.
Lesson 10.4

Policy Gradients (Conceptual)

Q-learning learns values and derives a policy indirectly (pick the action with the highest Q-value). Policy gradient methods take a more direct approach: parameterize the policy itself as a neural network, and directly optimize its parameters to maximize expected reward using gradient ascent.

Policy: πθ(a|s) — neural network with parameters θ, outputs action probabilities

Objective: J(θ) = E_π[Σ γᵗ Rₜ] (expected discounted return)

REINFORCE gradient: ∇θ J(θ) = E[∇θ log πθ(a|s) · Gₜ]
Gₜ = the return (cumulative future reward) following action a at state s
🎲

The intuition

If an action led to high reward, increase the probability of taking that action again in similar states. If it led to low reward, decrease that probability. The gradient ∇log π(a|s) tells you which direction in parameter space increases that action's probability.

📈

Continuous action spaces

Unlike Q-learning (which needs to maximize over discrete actions), policy gradients naturally handle continuous action spaces — useful for robotics (continuous joint torques) where Q-learning's argmax step is intractable.

📉

High variance

REINFORCE gradients are noisy — a single good or bad episode can swing the gradient estimate significantly. Variance reduction techniques (baselines, advantage estimation) are essential for stable training.

🏆

Actor-Critic methods

Combine policy gradients (the "actor") with a learned value function (the "critic") that reduces variance by estimating expected returns. PPO (Proximal Policy Optimization) — used in RLHF — is a modern, stable actor-critic method.

Q-learning vs Policy Gradients — when to use which Q-learning (and DQN): discrete action spaces, sample-efficient, off-policy (can learn from old data). Policy gradients (and PPO): continuous or large action spaces, naturally stochastic policies, on-policy (needs fresh data each update) but more stable for complex tasks like language model fine-tuning.
Lesson 10.5

Where RL Fits in Modern AI — RLHF Preview

Reinforcement Learning from Human Feedback (RLHF) is the technique that turns a raw pretrained language model (good at predicting next tokens) into an assistant that follows instructions, avoids harmful outputs, and feels genuinely helpful. It's RL applied to a domain very different from games or robotics: the "environment" is a conversation, and the "reward" comes from human preferences.

The three-stage RLHF pipeline
  • 1Supervised Fine-Tuning (SFT): Start with a pretrained language model. Fine-tune it on a dataset of high-quality human-written demonstrations (prompt → ideal response). This gives the model a baseline sense of "what a good response looks like."
  • 2Reward Model training: Collect human preference data — pairs of model responses where a human indicates which is better. Train a separate neural network (the reward model) to predict this human preference score for any given response.
  • 3RL fine-tuning (typically PPO): Use the reward model as the reward signal in an RL loop. The language model (now the "policy") generates responses, the reward model scores them, and PPO updates the language model's weights to generate higher-scoring responses — while a KL-divergence penalty keeps it from drifting too far from the SFT model (preventing reward hacking and gibberish).
RLHF objective:
max_θ E[Reward_model(response)] − β · KL(πθ || π_SFT)
The KL penalty prevents the policy from exploiting the reward model in degenerate ways far from sensible language
🗣️

The "environment" is conversation

Unusual compared to games: there's no simulator. The "environment dynamics" are just the model generating text token by token, and the episode ends when generation stops. The state is the conversation so far.

👥

Reward comes from humans

Instead of a hand-coded reward function (score in a game), the reward model is trained to imitate human judgments of response quality — helpfulness, harmlessness, honesty. This is what aligns the model with human preferences.

⚖️

Reward hacking risk

If the reward model has blind spots, the policy can learn to exploit them — e.g. generating overly long responses if the reward model slightly favors length. The KL penalty against the SFT model is a key safeguard against this drift.

🔄

Alternatives to PPO

DPO (Direct Preference Optimization) and other newer methods achieve similar alignment without a separate RL loop or reward model — directly optimizing the policy on preference pairs with a clever loss function. Simpler to implement, increasingly popular.

The big picture This module gave you the RL fundamentals — MDPs, Q-learning, policy gradients — that underpin everything from game-playing agents (AlphaGo) to robotics to the alignment techniques that shape how modern conversational AI systems behave. RLHF is one of the most consequential applications of RL today, directly responsible for the difference between a raw language model and a helpful assistant.