Part III · Ch. 12 — Learning by Doing

Part III · Chapter 12 of 13

Learning by Doing

Reinforcement learning in one chapter


Review prerequisite concepts
  • Learning from Data
  • The Math Toolkit
  • Teaching the Network

Learning by consequence

Learning Go through self-play means starting with the game’s rules, playing millions of games, and adjusting toward moves that lead to wins. The rules tell you what is legal; they do not supply a labeled “best move here.” The strategy has to come from the consequences.

In learning from data we named three families. Reinforcement learning (RL) is the one where a learner acts and uses rewards to improve its behavior. It does collect data, namely experience from those actions, but the feedback need not say which action was correct.

Learning familyWhat teaches it
SupervisedExamples paired with correct answers.
UnsupervisedStructure in examples without output labels.
ReinforcementThe consequences of choices, scored by rewards.

The difference is what the feedback tells us. A labeled example names the answer to match. A reward scores what happened after a choice, often leaving us uncertain which earlier choice deserves credit. The learner must connect the outcome to its behavior across time.

Training a puppy gives us the picture. It tries things, sitting on command earns a treat, and over time it does more of what earns treats. The puppy is the learner, your kitchen is the world it acts in, sitting is a choice, and the treat supplies feedback. The rest of the chapter makes that loop precise.

  1. Try a behavior. The puppy sits.
  2. Receive feedback. Sitting earns a treat.
  3. Learn from it. Rewarded behavior becomes more likely.

The loop: state, action, reward

The agent chooses actions. The environment is everything outside it: the world that responds. A game, simulator, or physical system can play that role.

An agent sends an action to the environment, which returns the next state and reward.
Actions change the world; the next state and reward guide the next choice.

A state describes the current situation. An action is a choice that can change it. A reward is the number scoring the outcome. The agent receives the new situation as well as the reward; the reward is its objective’s teaching signal, not a label naming the correct move.

  1. Observe. Read the state: the board position or current measurements.
  2. Choose. Take an action using the current strategy.
  3. Receive. Record the next state and reward from the environment.
  4. Repeat. Use experience to improve the strategy over training, then act again.

Learning need not happen after every individual action. An agent may gather a whole episode or reuse stored transitions before updating its rule. “Repeat” describes interaction with the environment; adjusting weights is a training operation using that experience. Keeping those two rhythms separate helps when a reward arrives only after many choices.

InteractionTraining
Changes the state by taking actionsChanges the policy or value estimates using collected experience.

The goal is the largest total future reward, not the next reward alone. A chess agent can sacrifice a piece for checkmate later. If a score is delayed, acting now for a later payoff requires learning how present choices influence later situations. One favorable immediate outcome is not enough to tell us an action was wise.

That cuts both ways. RL can try situations nobody thought to label, and bad early choices can restrict the very experience it learns from. Stored experience can be reused, so “learning by doing” does not mean throwing away every past attempt.

Source of experienceConsequence
A learner acts in the worldIts choices determine which situations it visits and which evidence it collects.
An early strategy avoids an unfamiliar actionThe learner may never discover that action’s better payoff without exploration.
No answers, only consequences: the agent walks the grid, the values fill in from the goal backwards, and its arrows become a plan. (2:53)

Policy and value: a plan, and what each square is worth

A policy, written $\pi$ (Greek pi, meaning strategy, nothing to do with $3.14$), maps states to actions. A state’s value estimates future reward under that policy, even when standing there earns nothing.

ObjectQuestion it answersCorridor example
PolicyWhat action should I take?Step right
ValueHow much reward lies ahead?Larger nearer the goal
RewardWhat did this transition pay?Zero until entering the goal

Take four corridor squares, $s_1$, $s_2$, $s_3$, and goal. Our policy always steps right. Steps pay $0$ except entering the goal, which pays $+1$ and ends the episode. The discount factor $\gamma$, Greek gamma, is $0.9$: near enough to one to preserve the goal’s influence, and easy to do by hand.

A horizontal corridor of four equal squares. The first three, outlined in gray, are labeled inside 's1', 's2', 's3'. The fourth is faintly amber with an amber border, labeled 'GOAL' with a smaller '+1 reward'. A small mint agent dot sits in the first square, labeled 'agent'. Between consecutive squares, small mint arrows point right, each labeled 'step (0)', except the arrow into the goal which is labeled '+1' in amber. Below each square a violet value tag reads, left to right, 'V = 0.81', 'V = 0.90', 'V = 1.00', and 'V = 0' under the goal. Above the row a muted dashed arrow arcs from right to left, labeled 'value flows backward from the reward, dimming by times 0.9 each step (gamma = 0.9)'.
With a rightward policy and discount 0.9, the corridor values are 0.81, 0.90, 1.00, and terminal 0; entering the goal pays +1.

Discounting values sooner rewards more and keeps infinite sums of bounded rewards finite when the factor is below one. The return $G$ adds rewards $r_1$, $r_2$, and so on, starting with the next step:

$$G = r_1 + \gamma\, r_2 + \gamma^2 r_3 + \cdots$$

In words: add all future rewards, shrinking each later one by another factor of gamma. The next reward $r_1$ counts fully; $r_2$ counts $0.9$ times as much; the third counts $0.9^2$. The dots mean keep going to the end: sooner rewards count more than later ones.

QuantityMeaning
RewardThe immediate score from a transition.
ReturnThe discounted sum along a run.
ValueExpected return from a state under the policy.
An unrewarded stateStanding one step from the goal pays nothing. Its value is high because the next action collects the reward. This separates a situation’s promise from the score we have already received: value looks forward under the policy we chose, rather than measuring how pleasant the current square is.

Write value as $V(s)$. For this deterministic corridor and fixed policy, let $s'$ (“s-prime”) mean the next state and $r$ the immediate reward:

$$V(s) = r + \gamma\, V(s')$$

In words: a state’s value is the reward you get now plus the discounted value of wherever you land next. Each state borrows from its neighbor, so we do not have to add the whole future again.

Worked example: values from right to left

  1. Goal. Terminal value is $0$: no future remains.
  2. One move away. Entering earns the reward now.
  3. Farther back. A zero-reward step discounts the next square’s value.
$$V(s_3) = 1.00$$

The next move pays one; nothing follows it.

$$V(s_2) = \gamma \times V(s_3) = 0.9 \times 1.00 = 0.90$$

One square farther back, discount again:

$$V(s_1) = \gamma \times V(s_2) = 0.9 \times 0.90 = 0.81$$

In words: the values are $0.81$, $0.90$, $1.00$, then terminal $0$; earlier squares inherit discounted reward.

Compare actions by immediate reward plus discounted next-state value; choosing the highest-valued neighbor alone fails at the terminal goal. With uncertain transitions, value averages over possible outcomes.

Why it's hard

RL must learn from outcomes while choosing which experiences to collect. Four difficulties shape that work.

DifficultyWhyWhat people do about it
Delayed creditA 40-move chess win pays +1 at the end: credit the good turn 12, not the turn-30 blunder it survived.Learn values and compare many outcomes; one win cannot identify every good move.
Explore or exploitThe known action pays +2; an untried one may pay more or less. Like ordering your usual dinner versus trying a new favorite.Balance reliable choices with deliberate trials; either extreme wastes opportunities.
Cost and instabilityMillions of attempts may be needed; changing behavior changes the data. You cannot crash ten thousand real cars for practice.Use safe simulators, reuse experience, and check performance beyond the training setting.
Wrong rewardThe score may omit the real goal; loud radio signals need not make a good operational link.Design and test rewards against the intended outcome, including ways to game the score.
Two panels split by a vertical hairline. The left panel is headed 'credit assignment — who won it?': a left-to-right chain of six small circles joined by thin arrows, ending in an amber star labeled 'win! +1'. Above the chain a curved amber dashed arrow sweeps back over all the moves, labeled 'which of these earned it?'. One middle circle is tagged in mint 'great move' and another in red 'blunder (got away with)'. A note reads 'one reward, many past actions'. The right panel is headed 'explore vs exploit': a mint agent dot faces two arrows — a solid one to a blue box 'known: +2 (reliable)' and a dashed one to a muted box 'untried: +? (maybe better, maybe worse)'. A note reads 'take the sure thing, or gamble on something better?'. A bottom italic line reads 'delayed reward and the explore/exploit dilemma are what supervised learning never has to face'.
Delayed credit asks which past moves earned the outcome; exploration asks whether an untried action beats the reliable known payoff.

These problems interact. An agent that never explores lacks the evidence for better value estimates, and a misspecified reward still produces the wrong behavior however well it is optimized. Reach for RL when sequential consequences require it and you have a practical way to collect useful experience.

How the learning works

In deep RL, the policy and value estimates are networks with adjustable weights. The optimizer is familiar from fitting a line and teaching the network; the learning signal now comes from experience and rewards. A value network takes a state as input and predicts its value. A policy network chooses actions, often by assigning each a probability.

  1. Try. Choose an action and collect what follows.
  2. Compare. Was its outcome better or worse than expected?
  3. Adjust. Make better-than-expected actions more likely in that state, and worse ones less likely.

That is the intuition behind policy learning, not a complete algorithm. Rewards are delayed and noisy, so a learned value estimate helps judge what was expected. The loss uses that comparison to guide changes to the policy’s weights. Value learning, in turn, uses rewards and estimates of what comes next to improve its predictions.

A lucky outcome proves nothing about the actions that preceded it. Repeated experience helps separate a useful choice from a blunder that happened to be followed by success. Comparing against an expectation asks whether the outcome was better than the agent had reason to predict, instead of treating every positive score as equally informative.

Method familyWhat it learnsHow it acts
Value-basedAction values; Q-learning is the classic example.Choose actions with high estimated return, allowing exploration.
Policy-basedThe strategy directly.Adjust action probabilities toward better outcomes.
Actor-criticAn actor (policy) paired with a critic (value estimate).The critic helps assess the actor’s choices.

Small problems can store values in a table rather than train a network. RL names the learning problem; gradient descent is one way to fit its functions. In either case, the difficult part is making useful updates from a stream of consequences instead of a fixed answer key.

From reward to an assistant’s behavior

A raw language model learns next-token prediction from text, which is the sister site’s prediction game. That objective alone does not specify the helpful behavior we want in a conversation. One way to shape it is reinforcement learning from human feedback, or RLHF.

A loop drawn with RL terms mapped onto a language model. A top box outlined in mint reads 'the LLM = the AGENT' with a small subnote 'policy = how it responds'. A mint down-arrow labeled 'action = write a response' leads to a small speech bubble tagged 'a candidate answer'. That answer feeds right into a box outlined in amber reading 'reward model', with a subnote 'learned from humans ranking answers'. An amber up-left arrow returns from the reward model to the LLM, labeled 'reward = preference score'. To the right of the reward model, a small cluster shows two stacked answer chips with 'A > B' between them and a tiny human glyph, labeled 'people ranked pairs, trained this'. In the center a muted italic note reads 'same loop as the puppy and the treat — at trillion-parameter scale'.
In RLHF, a model trained on human preferences scores responses, and reinforcement learning adjusts the language model toward higher-scoring behavior.
  1. Rank. People compare pairs of candidate answers.
  2. Fit a judge. Train a reward model to predict those preferences.
  3. Adjust the agent. Score generated responses, then train the language model toward higher-scoring behavior.

The reward model estimates preferences; its score does not guarantee truth or usefulness.

At enormous model scale, this is still the same action-and-feedback loop. The sister site’s from parrot to partner develops the story and covers direct preference optimization (DPO), a method that learns from preferred responses without a separate reward-model RL loop. Preference training can shape a model’s behavior through more than one recipe.

RL componentIn a conversation
Agent and policyThe language model and its strategy for responding.
StateThe conversation so far.
ActionWriting a response.
RewardThe preference score supplied by the learned reward model.

Where you'll meet this

WhereWhat it looks likeChapter link
Games and robotsLearn sequences of moves, walking, or grasping from outcomes.Choosing your tool
Operations and recommendationsTune data centers or chip layouts; choose what to show next when choices affect later results.Problem fit
Chat assistantsRLHF shapes responses with human-preference rewards: manners are a trained policy.From parrot to partner

What you now know

  • RL learns from consequences: an agent acts, observes a new state, and receives a reward.
  • A policy chooses actions; value estimates discounted future reward.
  • The corridor’s reward propagates backward as values 1.00, 0.90, and 0.81.
  • Delayed credit, exploration, costly experience, and misspecified rewards make learning difficult.
  • Deep RL uses familiar networks and optimizers with a learning signal built from experience.
  • RLHF reshapes a language model’s behavior using learned preference rewards.

Where we’re headed. We have three ways to learn and a toolbox spanning lines, trees, neural networks, generators, and agents. The last skill is looking at a problem you have never seen, deciding which tool its structure calls for, and defending that choice. The capstone puts the toolbox to work: what data is available, what answer is needed, and which mistakes matter?