Reinforcement Learning
So far, training has usually started with examples and targets. A language model sees a prefix and the token that followed it. But some tasks are easier to evaluate than to demonstrate. We can check whether generated code passes a test, whether a game was won, or whether a robot stayed upright without supplying the best decision at every step.
Reinforcement learning uses this feedback to improve a decision rule. The difficulty is that a decision changes both the immediate result and what happens next. A move that looks good now may leave the agent in a poor situation later, and a successful outcome may depend on many earlier choices.
We’ll describe how a policy produces experience, combine rewards across time into an objective, and see why learning also depends on which actions the policy tries.
States and Actions
At each integer time \(t\geq0\), an agent observes a state \(s_t\in\mathcal S\), chooses an action \(a_t\in\mathcal A\), and receives a scalar reward \(r_t\) and next state \(s_{t+1}\) from the environment. The sets \(\mathcal S\) and \(\mathcal A\) contain the possible states and actions.
Consider a cart that moves left or right to keep a pole balanced. The state can include the cart’s position and velocity, the pole’s angle, and its angular velocity. The action chooses a push direction. A reward can count time spent balanced. A push changes both the pole’s current motion and the state from which the next decision will be made. The reward evaluates the outcome of the chosen action. The agent must learn which choices lead to higher rewards. Assigning delayed outcomes to earlier decisions is the credit-assignment problem.
This loop is formalized as a Markov decision process. Besides the state and action spaces, it has a joint distribution \(P(r_t,s_{t+1}\mid s_t,a_t)\) for the reward and next state. This notation denotes a probability law. The Markov property says that the current state contains the past information needed to predict what happens next: once \(s_t\) and \(a_t\) are known, earlier history adds nothing to the reward and next-state distribution. The property states what the word “state” must contain for this model.
An episode is one run from an initial state until termination. Unlike a fixed dataset, the collection of episodes depends on the agent’s behavior. If it never tries an action, it gathers no direct evidence about that action’s consequences.
An observation is not automatically a sufficient state. Two carts can occupy the same position while moving in opposite directions, so position alone does not determine their next-state distributions. We may need velocity or a history of observations. The analysis here assumes that the state contains the needed information.
For a language model generating a response, the available prefix can serve as the state and the next token as the action. Appending that token gives the next prefix. A reward might arrive only after the complete response is evaluated. The same mathematical framework covers this case even though the state is text and the action changes a sequence rather than a physical object.
Policies and Trajectories
The agent’s decision rule is a policy \(\pi\). For each state, it gives a distribution over actions, \[ a_t\sim\pi(\cdot\mid s_t). \] A deterministic policy chooses one action in each state. A stochastic policy assigns probabilities to the alternatives and samples from them. A neural network can implement the latter by mapping the state to action logits and applying softmax, just as our classifiers map features to class probabilities. The difference is that we sample an action and observe its consequences instead of comparing the output with a supplied correct label.
Running a policy in an environment produces a trajectory \[ \tau=(s_0,a_0,r_0,s_1,a_1,r_1,\ldots). \] The trajectory is one sampled outcome, but its components are dependent because each action affects later states and decisions.
Both the policy and the environment may be random. Thus even a fixed policy induces a distribution over trajectories. We optimize expected performance under that distribution. If \(G_0\) denotes the total return from the start, \[ J(\pi)=\mathbb E_{\tau\sim\pi}[G_0]. \] Here \(\tau\sim\pi\) means that we sample actions from \(\pi\) and transitions from the fixed environment. Averaging returns over independent episodes estimates this expectation, using the same Monte Carlo principle as before. One successful episode is evidence about performance, but repeated runs are needed to assess the expected result.
Discounted Return
For an episode with \(T\geq1\) decisions, suppose the rewards are \(r_0,\ldots,r_{T-1}\). The return from time \(t\) combines the rewards still to come. With a discount factor \(0\leq\gamma\leq1\), define
\[ G_t=\sum_{k=0}^{T-t-1}\gamma^k r_{t+k},\qquad t=0,\ldots,T. \]
A sum over an empty range is zero, so \(G_T=0\). The current reward receives weight one, the next receives weight \(\gamma\), and a reward \(k\) steps later receives weight \(\gamma^k\). We use \(\gamma^0=1\), including when \(\gamma=0\).
Setting \(\gamma=1\) counts all rewards equally. A smaller value makes later rewards count less. This is a choice about the objective: an agent can prefer a smaller reward that arrives sooner over a larger reward that arrives much later. When \(\gamma=0\), only the immediate reward matters.
We can compute every return by working backward through the episode:
\[ G_T=0,\qquad G_t=r_t+\gamma G_{t+1}\quad\text{for }t=T-1,\ldots,0. \]
The recurrence reuses the future total instead of summing the remaining rewards from scratch at every step.
The return at time t sums rewards from that time onward, with successive powers of γ. Splitting off the first reward gives G(t) = r(t) + γ G(t + 1).
Each bar shows one observed reward’s contribution to the selected return. Rewards before the decision do not enter it. A later reward appears in several earlier returns, with a different discount for each distance.
Some tasks continue without a fixed endpoint. For \(0\leq\gamma<1\), we can instead define
\[ G_t=\sum_{k=0}^{\infty}\gamma^k r_{t+k}. \]
Discounting can keep this sum finite. It also gives us a precise way to measure how much weight remains far into the future.
Claim: If a finite constant \(R_{\max}\geq0\) bounds every reward as \(|r_t|\leq R_{\max}\) for all \(t\geq0\), and \(0\leq\gamma<1\), the discounted return is finite and obeys \[ G_t=r_t+\gamma G_{t+1}. \] The discount weights have total mass \(1/(1-\gamma)\), which defines their rough effective horizon, and for every integer \(H\geq0\) the fraction of that mass assigned at least \(H\) steps ahead is \(\gamma^H\).
Proof
For an integer \(H\geq1\), define the finite geometric sum \(S_H=\sum_{k=0}^{H-1}\gamma^k\). Multiplication and subtraction give \[ (1-\gamma)S_H =(1+\gamma+\cdots+\gamma^{H-1}) -(\gamma+\gamma^2+\cdots+\gamma^H) =1-\gamma^H. \] At \(H=0\), the same identity holds with \(S_0=0\), using the convention that a sum over an empty index range is zero. Because \(0\leq\gamma<1\), \(\gamma^H\to0\), so \(\sum_{k=0}^{\infty}\gamma^k=1/(1-\gamma)\). Bounded rewards then give \[ \sum_{k=0}^{\infty}|\gamma^kr_{t+k}| \leq R_{\max}\sum_{k=0}^{\infty}\gamma^k =\frac{R_{\max}}{1-\gamma}, \] which proves absolute convergence and finiteness of \(G_t\).
Now split the convergent series after its first term: \[ G_t=r_t+\sum_{k=1}^{\infty}\gamma^kr_{t+k}=r_t+\gamma\sum_{j=0}^{\infty}\gamma^jr_{t+1+j}=r_t+\gamma G_{t+1}, \] where \(j=k-1\). Finally, normalize the weights to \(w_k=(1-\gamma)\gamma^k\) for integers \(k\geq0\). Their mass from any integer lag \(H\geq0\) onward is \[ \sum_{k=H}^{\infty}w_k =(1-\gamma)\gamma^H\sum_{j=0}^{\infty}\gamma^j =\gamma^H. \] Thus \(1/(1-\gamma)\) is the total undiscounted-equivalent weight and \(\gamma^H\) gives the exact remaining fraction beyond lag \(H\), proving the effective-horizon statements.
When \(\gamma>0\), rewards beyond the effective horizon still contribute. The exact tail fraction \(\gamma^H\) tells us how strongly the objective weights rewards at least \(H\) steps away. A larger \(\gamma\) keeps more of that distant future in the objective, including its uncertainty.
Return makes a later outcome available as feedback for earlier decisions. It does not prove that every earlier action caused that outcome. We still need a learning rule that turns these observations into a useful update. That will be the policy gradient.
Exploration
At any state, the agent can exploit the action currently believed best or explore an action whose consequences are less certain. Each choice changes which observations the agent collects for training.
Suppose an early accident makes one action look poor. A deterministic policy may stop selecting it and never collect the evidence needed to revise that conclusion. A stochastic policy with positive probability on alternatives continues to generate corrective experience. Exploration can cost reward in the current episode, but it can reveal a better decision rule for later episodes. Putting positive probability on every action does not by itself guarantee enough useful exploration: a long sequence of unlikely choices may still be almost impossible to observe.
The trajectory distribution changes with the policy, so a poor update can also steer the agent away from useful data.
The demo compares two cart-pole policies under matched starting seeds. Changing the decision rule changes the trajectories and returns we observe, even though the environment is the same.
To evaluate a new policy directly, we run that policy and average its returns. Simply averaging trajectories from an older policy estimates the older policy’s performance. This dependence of the data on the decision rule will matter when we derive an update.
We compare actions through the future rewards they lead to under a policy. Discounted return states how those rewards count, and repeated episodes let us estimate their expectation. The remaining task is to change the policy so that better trajectories become more likely.