Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path →
Reinforcement learning,
and learning by trying.
Supervised learning shows a model the right answers. Reinforcement learning gives no answers at all — just an agent, a world, and rewards for good outcomes. It learns to act by trial and error, and it's how machines mastered Go and how LLMs became helpful assistants. Here's the machinery.
The setup: agent, environment, reward
Reinforcement learning is learning to make decisions by trial and error. An agent interacts with an environment in a loop: it observes the current state, chooses an action, and the environment returns a reward (a number) and the next state. Repeat. The agent's goal is to learn a policy — a mapping from states to actions — that earns the most reward over time.
The defining difference from supervised learning: there are no labels. Nobody tells the agent the right action; it only gets a reward signal, often delayed (a move in chess isn't rewarded until you win or lose much later). Learning which actions lead to reward, through experience alone, is the whole challenge.
The objective: cumulative reward
The agent isn't maximizing the immediate reward — it's maximizing the return: the total reward accumulated over the whole future. That's what makes RL about strategy, not greed: sometimes a low-reward action now (sacrificing a piece) leads to far more reward later (winning the game).
Future rewards are usually discounted by a factor γ (gamma, between 0 and 1): a reward k steps away counts as γk times its value. This makes the infinite future sum finite and expresses "sooner is better," and γ tunes how far-sighted the agent is — near 1 is patient and long-term, near 0 is myopic. Formally, the agent maximizes the expected discounted return.
Return = r₀ + γr₁ + γ²r₂ + γ³r₃ + …
Exploration vs exploitation
Here's RL's defining dilemma. To earn reward the agent should exploit — do what it already knows works. But to find better strategies it must explore — try unfamiliar actions whose outcomes it doesn't yet know. These conflict: every step spent exploring is a step not exploiting, and vice versa.
Lean too far toward exploitation and the agent gets stuck repeating a mediocre habit, never discovering the better path (a local optimum). Explore too much and it wastes time on bad actions and never cashes in on what it learned. Good RL balances the two — a common simple scheme is ε-greedy (mostly exploit, occasionally act randomly), often exploring more early and exploiting more as it learns. This tradeoff has no free lunch, and managing it well is much of what separates an agent that learns from one that stalls.
It's the "new restaurant vs your favorite" problem. Always ordering your favorite (exploit) means you never find a better one; always trying new places (explore) means many bad meals. You need both, tilted toward exploring while you're still learning.
Value functions & Q-learning
One family of methods learns value functions: how much future reward to expect from a situation. A state value estimates the return from a state; an action value (the Q-value) estimates the return from taking a specific action in a state and acting well thereafter. If you knew the Q-values, acting optimally is trivial: in each state, pick the action with the highest Q-value.
Q-learning learns these values from experience using the Bellman idea: the value of an action is its immediate reward plus the discounted value of the best next action. The agent bootstraps — updating each estimate toward "reward now + best estimated future" — and the estimates converge toward the true values. Deep Q-Networks (DQN) use a neural network to approximate Q-values for huge state spaces (this is how RL first beat Atari games from raw pixels). Value methods shine when actions are discrete.
The value of a state equals the best immediate reward plus the discounted value of where you land next. Learn that consistency everywhere, and you've learned to act optimally.
The update itself is one line, and it's enough to learn an optimal policy from reward alone:
On a chain where you walk right to a goal, the learned values come out as γk−1 for a state k steps from the goal — 1.0 one step away, 0.9, 0.81, 0.73 — so the greedy policy is "go right" everywhere. The runnable version below trains it and rolls out to the goal.
Policy gradient methods
The other family skips value estimates and optimizes the policy directly. A policy gradient method parameterizes the policy (usually a neural network mapping states to a distribution over actions) and adjusts its parameters to make high-reward actions more likely — nudging up the probability of actions that led to good returns, down for bad ones. REINFORCE is the basic version; PPO (Proximal Policy Optimization) is the workhorse, adding a constraint that stops each update from changing the policy too drastically, which keeps training stable.
Policy methods handle continuous actions (robot joint torques) and naturally produce stochastic policies, where value methods struggle. In practice, actor-critic methods combine both worlds: an "actor" (policy) chooses actions while a "critic" (value function) evaluates them to reduce the noise in the policy's updates. PPO — a stable actor-critic-style method — is exactly what's used to fine-tune LLMs with human feedback (section 08).
| Value-based (Q-learning) | Policy-based (policy gradient) | |
|---|---|---|
| Learns | Value of states/actions | The policy directly |
| Best for | Discrete actions | Continuous / stochastic actions |
| Examples | Q-learning, DQN | REINFORCE, PPO (+ actor-critic) |
Why RL is hard
RL is powerful but notoriously finicky, and interviewers probe whether you know why. Three issues dominate. Instability: combining function approximation (neural nets), bootstrapping (updating estimates from other estimates), and off-policy learning — the "deadly triad" — can cause training to diverge. Sample inefficiency: RL often needs an enormous number of environment interactions to learn, because it learns only from sparse, delayed reward signals rather than dense labels.
And reward design is treacherous: the agent optimizes exactly what you reward, not what you meant. A poorly-specified reward invites reward hacking — the agent finds a degenerate way to score high that violates your intent (the classic: a boat-race agent that spins in circles hitting bonus targets instead of finishing). Specifying rewards that truly capture the goal is one of RL's deepest practical problems.
You get what you reward, not what you want. Any gap between the reward and the true goal will be found and exploited. Designing rewards that can't be gamed is as hard as the learning itself.
Model-free vs model-based
A final axis. Model-free RL (Q-learning, PPO) learns purely from experience without any model of how the environment works — simple and general, but sample-hungry because it can only learn from real interactions. Model-based RL additionally learns (or is given) a model of the environment — how states and rewards follow from actions — and can then plan or generate imagined experience, making it far more sample-efficient.
The tradeoff: a learned model can be wrong, and errors compound when you plan against it, so model-based methods add complexity and a source of bias. Landmark systems blend the ideas — AlphaGo/AlphaZero combine a learned value/policy network with explicit search (planning) over the game tree. Choose model-free for simplicity and when interactions are cheap; reach for model-based when real experience is expensive and a decent model is learnable.
RL in the real world — including LLMs
RL's headline wins are agents that learn superhuman play (Atari, Go, StarCraft) and control problems (robotics, resource scheduling). But its most consequential recent use is aligning large language models. RLHF (reinforcement learning from human feedback) is how a raw, capable base model becomes a helpful assistant: humans compare model outputs, a reward model is trained to predict which output people prefer, and the LLM is optimized with RL (usually PPO) to produce higher-reward responses.
Everything above shows up here. The reward model is an imperfect proxy, so unconstrained optimization leads to reward hacking — the model games the reward with degenerate outputs. The fix is a KL penalty keeping the policy close to the original model, exactly the "don't drift too far" idea PPO embodies. So RL isn't just for games: it's the mechanism that turned language models into the assistants we actually use. For the full pipeline, see Design an RLHF Pipeline.
Q-learning finds the path from reward alone
Give an agent nothing but a reward at the goal and the Bellman update, and it learns to act optimally. This runs Q-learning on a five-state chain where the only reward is reaching the far end. Watch the learned Q-values settle into γk−1 for a state k steps from the goal — 1.0 one step from the goal, then 0.9, 0.81, 0.73 further back — so the greedy policy becomes "go right" at every state, and a rollout walks straight to the goal. No map, no demonstrations, just trial and reward. Change the discount, learning rate, or exploration.
Worked example: Q-values by hand on the page’s chain
Take the runnable’s chain: states 0 to 4, goal at 4, reward 1 only for stepping onto it, α = 0.5, γ = 0.9, every Q starting at 0. Suppose the agent walks right on every step, as it does once ε-greedy has stumbled onto the goal. In episode 1 the first three updates have reward 0 and a next-state value of 0, so nothing moves. Only the last step pays: Q(3,→) = 0 + 0.5 × (1 + 0.9 × 0 − 0) = 0.5. The goal’s own Q-values are never updated and stay 0, which is what makes it terminal. Each column below is one state’s right-move value after that episode:
| After episode | Q(3,→) | Q(2,→) | Q(1,→) | Q(0,→) |
|---|---|---|---|---|
| 1 | 0.500 | 0 | 0 | 0 |
| 2 | 0.750 | 0.225 | 0 | 0 |
| 3 | 0.875 | 0.450 | 0.101 | 0 |
| 4 | 0.938 | 0.619 | 0.253 | 0.046 |
| 5 | 0.969 | 0.731 | 0.405 | 0.137 |
| 10 | 0.999 | 0.890 | 0.766 | 0.604 |
| 20 | 1.000 | 0.900 | 0.810 | 0.728 |
| limit | 1 | 0.9 | 0.81 | 0.729 |
Read it diagonally. Reward travels back one state per episode, because each update can only borrow value from a neighbour that already has some. Q(0,→) stays at zero until episode 4, four steps from the goal, and gets within 0.01 of its limit at episode 16. The limits are γ^(k−1), where k is the number of steps to the goal: 1.0 one step away, then 0.9, 0.81 and 0.729. That is section 04’s formula. Running the page’s code gives these right-move values, and left-move values one γ lower, because stepping left only delays the same reward.
Cost and trade-offs: what each method spends
Here Time is the compute or experience each method needs, and Space is what it keeps in memory.
| Case | Time | Space | Why |
|---|---|---|---|
| Tabular Q-learning | O(|A|) per update, for the max over actions | One number per state-action pair: 5 × 2 = 10 here | Exact, but it must visit every state. Go has up to 3^361 ≈ 10^172 board configurations, so no table can exist. |
| DQN | A forward and backward pass per minibatch | Network weights plus a replay buffer of past transitions | Generalises to unseen states. Replay and a frozen target network are what keep the deadly triad from diverging. |
| REINFORCE | One gradient step per finished episode | Policy parameters only | Simple, but the return of one episode is a noisy estimate, so it needs many episodes. |
| Actor-critic / PPO | Several epochs of clipped updates per batch of rollouts | An actor and a critic, often sharing layers | The critic cuts the noise; the clip stops any one update moving the policy far. The usual default. |
| Model-based with search (AlphaZero-style) | A tree search at every decision | Model, network and search tree | Far fewer real interactions, paid for with compute per move. |
| RLHF with PPO | Generate and score responses every step | Four models: policy, frozen reference for the KL penalty, reward model, value model | This memory bill is why preference methods such as DPO, which train on preference pairs with only the policy and a reference, became popular. |
The pattern: methods buy back sample efficiency with memory (a replay buffer, a model) or with compute per decision (search). None of them get it for free.
Common mistakes
- Bootstrapping past the end
At a terminal state the target is just
r, notr + γ·max Q(s′). The page’s code gets this right only because the goal’s Q-values are never updated and stay 0. The opposite bug is just as common: an episode cut off by a time limit has not terminated, so it should still bootstrap. - Ties on a zero table
Python’s
maxreturns the first of equal items. With every Q at 0, the greedy choice in the runnable is always action 0, left. Seteps=0and the agent sits at state 0 for every episode and every Q stays 0. Break ties at random, or keep some exploration. - Scoring the agent with exploration on
Training performance includes the random ε moves. To report how good the policy is, run it greedily (ε = 0) in separate evaluation episodes.
- Trusting one seed
RL results swing widely with the random seed, and one lucky run can look like a better algorithm. Run several seeds and report the spread, not the best curve.
- Picking γ without thinking about the horizon
γ sets how far ahead the agent looks, roughly 1/(1 − γ) steps: 10 for 0.9, 100 for 0.99. At γ = 0.5 a reward 10 steps away is weighed by 0.5^9 ≈ 0.002, so the agent effectively cannot see it.
Check yourself
Set GAMMA = 0.5 in the runnable. What does Q(0,→) converge to, and does the policy change?
It converges to 0.5^3 = 0.125 (four steps from the goal, so γ^(k−1) with k = 4). The policy stays “go right”: every left move only delays the same reward, so its value is one more factor of γ lower (0.0625 at state 0). Only the size of the values changes. A goal much farther away would be almost invisible.
You change the rewards to −1 per step and 0 at the goal. Does the agent still learn the shortest path?
Yes. Every extra step costs −1, so the shortest path has the highest return. As a bonus, Q-values that start at 0 are now optimistic: true values are negative, so untried actions look better than tried ones and the agent explores them on its own.
A DQN’s loss climbs and the Q-values blow up. Which part of the deadly triad is most likely biting, and what is the standard fix?
Bootstrapping toward a target computed by the same network you are updating. Every step moves the target too. A target network, a frozen copy updated only every so often, holds the target still. A replay buffer breaks up the correlation between consecutive transitions.
During RLHF the reward-model score keeps rising, but raters say answers are getting longer and more flattering, not better. What is happening, and which knob do you turn?
Reward hacking: the policy has found what the proxy over-rewards. Raise the KL coefficient so the policy stays closer to the reference model, stop at the checkpoint raters preferred, and retrain the reward model on examples of the exploit.
Quick answers
What is reinforcement learning?
Training an agent to make decisions by trial and error: it observes a state, takes an action, gets a reward and new state, and over many interactions learns a policy that maximizes cumulative reward. No labels — only rewards.
Exploration vs exploitation?
The agent must balance exploiting known-good actions to earn reward now against exploring unknown actions that might be better. Too much of either fails; good RL tilts toward exploring while still learning.
Value-based vs policy-based?
Value methods (Q-learning) estimate action values and pick the best; policy methods (policy gradient, PPO) optimize the policy directly. Value suits discrete actions, policy handles continuous/stochastic; actor-critic combines both.
How does RL train LLMs?
RLHF: humans compare outputs, a reward model predicts preferences, and the model is optimized with PPO toward higher reward, kept near the base model with a KL penalty to prevent reward hacking.
Explore the topic
See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.
More Handbooks
- The Diffusion Models HandbookHow AI images are really made — generation as iterative denoising, the forward noising and reverse denoising processes, the elegant noise-prediction training objective, sampling and the steps-vs-speed dial, conditioning and classifier-free guidance, latent diffusion (Stable Diffusion), and why diffusion beat GANs and VAEs.Read →
- The Synthetic Data HandbookUsing LLMs to generate training and eval data. Why quality filtering beats raw volume (effective size = generated × pass rate), what model collapse is and why recursive training on unfiltered self-generated data shrinks diversity (Var_k = s^k · Var_0 → 0), and a safe generate-filter-mix pipeline. With worked math and runnable code.Read →
- RL from Verifiable Rewards (RLVR)The training technique behind modern reasoning models: reinforcement learning where the reward comes from a programmatic check (a unit test passing, a math answer matching) instead of a gameable learned reward model. How it differs from RLHF, the GRPO/PPO loop, why reasoning behaviors emerge in DeepSeek R1-Zero, and where verifiable rewards run out.Read →
- World ModelsWhat it means for AI to learn a predictive model of an environment it can imagine inside — the basis of model-based RL, planning, and controllable simulation. The three families (latent control models like Dreamer, generative interactive video like Genie/Sora, and JEPA), how a latent world model learns and acts in imagination, and the debate over whether video generators really understand physics.Read →
- ML FundamentalsThe seven concept pairs every practitioner is expected to have straight — how machines learn, what they predict, the two ways they miss, which mistake you can live with, how you validate, how you ensemble, and what a model is really modelling. Worked confusion matrices, real fold scores, and the failure mode behind each one.Read →
- Rapid Prototyping for FDEsHow FDEs build a convincing prototype in days, not months: throwaway-first thinking, the smallest demoable vertical slice, choosing a boring fast stack, faking the non-core parts honestly (hardcode / stub / Wizard-of-Oz), demo-driven development, and knowing when to throw it away versus harden.Read →