The Complete Guide to Reinforcement Learning
From the Bellman equation to PPO and RLHF — a structured, visual walkthrough of how agents learn to make sequential decisions by trial, error, and reward. Built for engineers and researchers who want the full map, not just the highlights.
Core Concepts
Reinforcement learning (RL) is the branch of machine learning concerned with how an agent ought to take actions in an environment to maximize cumulative reward. Unlike supervised learning, there are no labeled examples — only a scalar feedback signal, delayed consequences, and the agent's own experience.
Agent
The learner and decision-maker. It observes state, selects actions via a policy, and updates that policy from experience.
Environment
Everything the agent interacts with. It responds to actions with a new state and a reward signal.
State & Action
The state sₜ captures everything relevant at time t; the action aₜ is the choice the agent makes from it.
Reward
A scalar signal rₜ the agent seeks to maximize in expectation, summed (and discounted) over time.
Policy, Value, and Return
A policy π maps states to actions (deterministic) or to a probability distribution over actions (stochastic). The agent's goal is to find the policy that maximizes expected return — the discounted sum of future rewards.
Two quantities anchor almost every RL algorithm: the state-value function Vπ(s), the expected return from state s under policy π, and the action-value function Qπ(s,a), the expected return from taking action a in state s and then following π.
Markov Decision Processes & the Bellman Equations
Almost all of RL is formalized as a Markov Decision Process (MDP) — a tuple ⟨S, A, P, R, γ⟩ of states, actions, transition dynamics, reward function, and discount factor. The Markov property assumes the future depends only on the current state, not the full history.
When P and R are fully known, dynamic programming (value iteration, policy iteration) can solve small MDPs exactly. Most real problems don't expose P and R directly — the agent must learn from sampled experience instead, which is where model-free RL begins.
Exploration vs. Exploitation
An agent that only exploits its current knowledge may get stuck in a suboptimal routine; one that only explores never capitalizes on what it has learned. Balancing the two is a defining challenge of RL.
ε-Greedy
Acts greedily with probability 1−ε, and picks a uniformly random action with probability ε. Simple, still a strong baseline in discrete action spaces.
ClassicSoftmax / Boltzmann
Samples actions proportionally to exponentiated value estimates, giving smoother exploration than ε-greedy's hard random switch.
Value-WeightedUCB & Thompson Sampling
Upper Confidence Bound favors actions with high uncertainty; Thompson Sampling draws from a posterior over value estimates. Both give principled, regret-bounded exploration.
Bandit TheoryEntropy Regularization
Adds an entropy bonus to the objective so the policy stays stochastic longer, common in policy-gradient methods like SAC and PPO.
Policy-BasedIntrinsic Motivation
Curiosity-driven bonuses (e.g. prediction error, novelty, count-based bonuses) reward the agent for visiting unfamiliar states — crucial in sparse-reward tasks.
Sparse RewardsNoisy Networks
Injects learnable noise directly into network weights, letting exploration behavior itself be learned end-to-end rather than hand-tuned.
Deep RLValue-Based Methods
Value-based methods learn V(s) or Q(s,a) and derive a policy implicitly (e.g. act greedily with respect to Q). They form the historical and conceptual backbone of RL.
Dynamic Programming
Policy Iteration alternates policy evaluation (compute Vπ) and policy improvement (act greedily w.r.t. Vπ) until convergence. Value Iteration merges both steps by directly applying the Bellman optimality backup. Both require a known model and are typically limited to small, discrete state spaces.
Monte Carlo Methods
Estimate value functions by averaging complete episode returns, with no bootstrapping and no model required. Simple and unbiased, but high-variance and only applicable to episodic tasks.
Temporal-Difference (TD) Learning
TD methods combine the best of both worlds: like Monte Carlo, they learn directly from raw experience without a model; like dynamic programming, they bootstrap — updating estimates based on other learned estimates rather than waiting for a final outcome.
Q-Learning & SARSA
The two workhorse TD control algorithms differ in one crucial way: Q-learning is off-policy (it learns the optimal Q* regardless of the behavior policy), while SARSA is on-policy (it learns the value of the policy actually being followed, including its exploration).
Deep Q-Networks & Value-Function Approximation
Tabular Q-learning breaks down once state spaces become continuous or astronomically large (e.g. raw pixels). Deep Q-Networks (DQN), introduced by DeepMind in 2013–2015, replaced the Q-table with a neural network Q(s,a;θ) and proved it could learn to play Atari games directly from pixels.
# sample a minibatch of transitions from replay buffer s, a, r, s_next, done = replay_buffer.sample(batch_size) # target uses a separate, periodically-synced target network target = r + (1 - done) * gamma * max(target_net(s_next), dim=-1) # minimize temporal-difference error q_values = policy_net(s).gather(a) loss = huber_loss(q_values, target.detach()) loss.backward() optimizer.step()
Experience Replay
Stores past transitions in a buffer and samples them randomly, breaking harmful correlations between consecutive updates and improving sample efficiency.
Target Network
A slowly-updated copy of the Q-network used to compute TD targets, stabilizing training by decoupling the target from the network being optimized.
Double DQN
Decouples action selection from action evaluation to reduce the systematic overestimation bias inherent in standard Q-learning's max operator.
Dueling DQN
Splits the network into separate value and advantage streams, learning which states are valuable independent of the effect of each action.
Prioritized Experience Replay
Samples transitions with probability proportional to their TD error, focusing learning on the most surprising or informative experiences.
Rainbow DQN
Combines six DQN improvements — double Q, dueling, prioritized replay, multi-step returns, distributional RL, and noisy nets — into one strong baseline.
Policy Gradient & Actor-Critic Methods
Instead of learning values and deriving a policy indirectly, policy-gradient methods parameterize the policy πθ(a|s) directly and optimize it via gradient ascent on expected return. This handles continuous action spaces naturally and can learn genuinely stochastic policies.
| Algorithm | Year | Key Idea | Action Space |
|---|---|---|---|
| REINFORCE | 1992 | Monte Carlo policy gradient using full-episode returns; high variance, unbiased. | Discrete / Continuous |
| A2C / A3C | 2016 | Actor-critic with a learned baseline (critic) to reduce variance; A3C adds asynchronous parallel workers. | Discrete / Continuous |
| TRPO | 2015 | Constrains each policy update within a KL-divergence trust region for monotonic improvement guarantees. | Continuous |
| PPO | 2017 | Clips the probability ratio between new and old policies — TRPO's stability with far simpler implementation. | Discrete / Continuous |
| DDPG | 2015 | Off-policy actor-critic for continuous control, combining deterministic policy gradients with DQN-style replay and target networks. | Continuous |
| TD3 | 2018 | Twin critics, delayed policy updates, and target-action noise fix DDPG's overestimation and instability. | Continuous |
| SAC | 2018 | Maximum-entropy actor-critic that jointly maximizes reward and policy entropy for robust exploration and stability. | Continuous |
PPO is the closest thing modern RL has to a default choice — it is the algorithm behind OpenAI Five, much of robotic locomotion research, and the reinforcement-learning stage of RLHF used to align large language models.
Model-Based Reinforcement Learning
Model-based methods learn (or are given) a model of the environment's dynamics p(s′,r|s,a), then use it to plan — simulating rollouts internally instead of relying solely on real interaction. This can dramatically improve sample efficiency.
Dyna-Q
Interleaves real experience with simulated updates from a learned model, blending model-free and model-based learning in one loop.
Monte Carlo Tree Search
Builds a search tree by simulating rollouts, balancing exploration and exploitation of tree branches. Central to AlphaGo and AlphaZero.
World Models / MuZero
Learn a latent, learned dynamics model directly optimized for planning rather than pixel-accurate prediction — MuZero mastered Go, chess, and Atari without knowing the rules in advance.
The trade-off is model bias: an imperfect learned model can compound errors over long planning horizons, so most production systems either use short planning horizons or fall back to model-free fine-tuning.
Multi-Agent Reinforcement Learning
Many real settings involve multiple learning agents interacting — cooperatively, competitively, or both. This breaks the single-agent MDP assumption, since the environment becomes non-stationary from any one agent's perspective as others also learn.
Centralized Training, Decentralized Execution
Agents share information (like a joint critic) during training but act on local observations only at execution time — used in MADDPG and QMIX.
Self-Play
An agent trains against copies or past versions of itself, driving an automatic curriculum of increasing difficulty — the approach behind AlphaZero and OpenAI Five.
Value Decomposition
Methods like QMIX and VDN factor a joint action-value function into per-agent components, enabling scalable cooperative learning.
Game-Theoretic Equilibria
In competitive settings, the learning target shifts from an optimal policy to a Nash or correlated equilibrium, since no single fixed best response exists.
Key Dichotomies
Three axes classify almost every RL algorithm discussed above. Knowing where a method sits on each tells you a lot about its sample efficiency, stability, and applicability.
On-Policy
- Learns about the policy currently being executed
- Must discard old data after each update
- Generally more stable, less sample-efficient
- Examples: SARSA, REINFORCE, PPO, TRPO, A2C
Off-Policy
- Learns about a target policy using data from a different behavior policy
- Can reuse old data via replay buffers
- More sample-efficient, can be less stable
- Examples: Q-learning, DQN, DDPG, TD3, SAC
Model-Based
- Learns or is given environment dynamics
- Can plan via simulated rollouts
- Very sample-efficient when the model is accurate
- Examples: Dyna-Q, MCTS, MuZero, World Models
Model-Free
- Learns purely from trial-and-error interaction
- No explicit dynamics model required
- Simpler to implement, typically needs more data
- Examples: Q-learning, DQN, PPO, SAC, A3C
Milestones in Reinforcement Learning
A field shaped by decades of theory before an explosive decade of deep-learning-powered breakthroughs.
Real-World Applications
RL has moved well beyond games and simulated benchmarks into domains where sequential decisions under uncertainty carry real consequences.
Games & Simulation
Atari, Go, chess, StarCraft II, Dota 2 — the proving ground where most modern algorithms were first validated at scale.
Robotics & Control
Locomotion, dexterous manipulation, and autonomous navigation, often trained in simulation and transferred to physical hardware.
LLM Alignment (RLHF)
Human preference models act as the reward signal; PPO-style updates fine-tune language models to be more helpful and safe.
Recommendation Systems
Framing recommendations as sequential decisions lets systems optimize long-term engagement rather than single-click metrics.
Finance & Trading
Portfolio allocation and execution strategies modeled as MDPs, balancing risk-adjusted return against transaction costs.
Data Center & Chip Design
RL agents optimize cooling schedules, network routing, and even chip floorplanning — tasks with enormous combinatorial search spaces.
Healthcare
Treatment-policy optimization and adaptive clinical trial design, where actions today affect outcomes far in the future.
Autonomous Driving
Behavior planning and decision-making layers that must balance safety, efficiency, and interaction with other unpredictable agents.
Energy Systems
Grid balancing and building climate control, where RL agents learn to minimize cost while respecting hard operational constraints.
Tools & Frameworks
A modern RL stack typically layers a simulation environment, an algorithm library, and an experiment-tracking layer.
Gymnasium
The community-maintained successor to OpenAI Gym — the standard API for RL environments.
Stable-Baselines3
Reliable, well-tested PyTorch implementations of PPO, SAC, TD3, DQN, and more.
RLlib (Ray)
Distributed, production-grade RL library supporting multi-agent training at scale.
CleanRL
Single-file, research-friendly reference implementations that prioritize readability over abstraction.
MuJoCo & Isaac Gym
High-fidelity, GPU-accelerated physics simulators for continuous-control and robotics research.
PettingZoo
The multi-agent counterpart to Gymnasium's API, standardizing cooperative and competitive environments.
Weights & Biases
Experiment tracking, hyperparameter sweeps, and reward-curve visualization for iterating on training runs.
JAX-based Libraries
Frameworks like PureJaxRL push RL throughput further with end-to-end compiled, vectorized training on accelerators.
Glossary of Key Terms
Quick definitions for terms used throughout this guide.
- Agent
- The decision-making learner that interacts with an environment.
- Policy (π)
- A mapping from states to actions or action probabilities.
- Value Function
- Expected return from a state (V) or state-action pair (Q).
- Reward Shaping
- Modifying the reward signal to make learning faster without changing the optimal policy.
- Discount Factor (γ)
- Weight applied to future rewards, between 0 (myopic) and 1 (far-sighted).
- Episode
- One complete sequence of interaction from an initial state to a terminal state.
- Bootstrapping
- Updating an estimate using other learned estimates rather than only real outcomes.
- Advantage Function
- A(s,a) = Q(s,a) − V(s); how much better an action is than the state's average.
- Credit Assignment
- Determining which past actions were responsible for a later reward.
- Sample Efficiency
- How much environment interaction an algorithm needs to reach a given performance level.
- Partial Observability
- When the agent cannot directly observe the true underlying state (formalized as a POMDP).
- Reward Hacking
- An agent exploiting unintended loopholes in a reward function rather than solving the intended task.
- Curriculum Learning
- Training on a sequence of increasingly difficult tasks or environments.
- Sim-to-Real Transfer
- Applying a policy trained in simulation to a physical, real-world system.
- Regret
- The cumulative gap between an agent's rewards and those of an optimal strategy.
- RLHF
- Reinforcement Learning from Human Feedback — using a learned reward model built from human preferences.