Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbook~15 min readIntermediate
Deep Dive

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.

01

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 interaction loop
Agent
picks an action
→
Environment
returns reward + new state
↻
No labeled "correct action" — only rewards that say how good the outcome was. The agent must figure out what to do.

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.

02

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₃ + …

03

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.

→ The intuition

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.

04

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.

→ Bellman in one line

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:

Q(s,a) ← Q(s,a) + α·( r + γ·maxa′ Q(s′,a′) − Q(s,a) )

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.

05

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)
LearnsValue of states/actionsThe policy directly
Best forDiscrete actionsContinuous / stochastic actions
ExamplesQ-learning, DQNREINFORCE, PPO (+ actor-critic)
06

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.

→ The reward-hacking law

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.

07

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.

08

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.

RUN IT YOURSELF

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.

CPython · WebAssembly
By the numbers

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 episodeQ(3,→)Q(2,→)Q(1,→)Q(0,→)
10.500000
20.7500.22500
30.8750.4500.1010
40.9380.6190.2530.046
50.9690.7310.4050.137
100.9990.8900.7660.604
201.0000.9000.8100.728
limit10.90.810.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.

Trade-offs

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.

CaseTimeSpaceWhy
Tabular Q-learningO(|A|) per update, for the max over actionsOne number per state-action pair: 5 × 2 = 10 hereExact, but it must visit every state. Go has up to 3^361 ≈ 10^172 board configurations, so no table can exist.
DQNA forward and backward pass per minibatchNetwork weights plus a replay buffer of past transitionsGeneralises to unseen states. Replay and a frozen target network are what keep the deadly triad from diverging.
REINFORCEOne gradient step per finished episodePolicy parameters onlySimple, but the return of one episode is a noisy estimate, so it needs many episodes.
Actor-critic / PPOSeveral epochs of clipped updates per batch of rolloutsAn actor and a critic, often sharing layersThe 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 decisionModel, network and search treeFar fewer real interactions, paid for with compute per move.
RLHF with PPOGenerate and score responses every stepFour models: policy, frozen reference for the KL penalty, reward model, value modelThis 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.

Watch for

Common mistakes

  • Bootstrapping past the end

    At a terminal state the target is just r, not r + γ·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 max returns the first of equal items. With every Q at 0, the greedy choice in the runnable is always action 0, left. Set eps=0 and 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.

Self-check

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.

Frequently asked

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.

Finished this one? 0 / 209 Handbooks done
NextThe Diffusion Models Handbook Next on the “How models actually work” ladder · rung 7 of 11

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks