A warehouse robot moves from the dock into an aisle and pays a step cost. It does not know the transition probabilities of the warehouse, so it cannot solve the Bellman equations directly, yet this one observed step already says something about the value of the dock. Temporal-difference learning turns each observed transition into an update of a value table, and Q-learning does the same for action values in order to find good actions. This lesson computes such updates by hand, separates on-policy from off-policy targets, handles transitions into a terminal state correctly and states the conditions under which tabular updates converge. The warehouse and its numbers are constructed for illustration.
Key terms
Temporal-difference learning
Definition Temporal-difference learning estimates values from sampled transitions instead of from a known model. In tabular TD(0) policy evaluation, a fixed policy acts in an MDP whose transition probabilities and rewards need not be known, and the learner keeps a table with one estimate per state. After each observed transition from to with reward , it changes only the entry of ,
where the step size, or learning rate, satisfies , and is taken as when is terminal. The quantity is the TD target. For a finite MDP with bounded rewards and , the estimates converge to with probability if every state is updated infinitely often and the step sizes used at the th update of each state satisfy
In plain words TD learning updates after every step instead of waiting for an episode to end. It moves the estimate for the current state part of the way toward a target built from the reward just observed and the current estimate for the next state. Unlike the Bellman updates of a known model, it needs no transition probabilities, because the environment supplies one sampled next state at a time. The step size sets how much of each discrepancy is absorbed. With the old estimate is replaced by the target, and a smaller blends old and new evidence. A constant step size such as fails the second condition, so the convergence result does not cover it, and in a random environment the estimates keep fluctuating with each new sample.
Example A constructed warehouse has the states dock and aisle and a terminal state exit. Under the policy being evaluated, the robot moves from the dock to the aisle with reward , a modeled step cost. With , and the current estimates and , the TD target is , and the update gives
The estimate for the aisle stays at , since only the state that was left is updated. The starting estimates are chosen for the arithmetic and are not claimed to be correct values.
TD error
Definition For a value table and an observed transition, the TD error is
the TD target minus the current estimate, with when is terminal. The TD(0) update is . If equals the true value function and the transitions follow , the Bellman expectation equation gives for every state . Single TD errors are still generally nonzero, because rewards and next states are random.
In plain words The TD error says how much better or worse a step turned out than the current estimate predicted. A positive error raises the estimate and a negative error lowers it. The sign of the error need not match the sign of the reward, since a negative reward can still give a positive error when the next state’s estimate is high. Small TD errors during training show only that the estimates agree with their own targets. They do not show that the values are correct or that a policy behaves well, which needs an evaluation of its returns on separate episodes.
Example For the transition from the dock, , and the update adds . The reward was , yet the error is positive, because the aisle’s estimate of outweighs the step cost. If the aisle’s estimate were instead, the target would be , the error would be , and the dock’s estimate would fall to .
Bootstrapping
Definition An update bootstraps when its target contains current estimates, as the TD target contains . The Monte Carlo alternative waits until the episode ends and uses the observed return , the discounted sum of all remaining rewards, as its target. In an episodic task that follows , the return is an unbiased sample of . The TD target has expected value given when the estimates of the next states equal their true values, and it is generally biased otherwise, but it depends on only one random reward and transition and so usually varies less than .
In plain words Bootstrapping learns a guess from a guess. It lets learning start before an episode ends and works in tasks that never end, but an error in one estimate passes into the targets of others, and every change to the table changes later targets. When bootstrapping is combined with function approximation and off-policy data, the updates can even diverge, so guarantees proved for tables do not carry over automatically.
Example Suppose the episode continues from the aisle into the exit with reward . The Monte Carlo target for the dock is the observed return , available only after the episode has ended, and it would move the dock’s estimate from to . The TD target was available right after the first step, because it used the aisle’s estimate in place of the rest of the episode.
Q-learning
Definition Q-learning keeps a table of action-value estimates . In state it chooses with a behavior policy, often epsilon-greedy with respect to , observes and , and forms the target
with when is terminal. It then changes only the entry of the pair it used,
The target is a sampled form of the Bellman optimality equation for the optimal action values . For a finite MDP with bounded rewards and , the table converges to with probability if every state-action pair is updated infinitely often and, for each pair, the step sizes lie in and satisfy the two sum conditions of TD learning, for example at the th update of the pair. A policy that is greedy with respect to is then optimal.
In plain words Q-learning aims each update at the value of acting as well as possible from the next state on, whatever the behavior policy actually does next. That is why it can learn optimal action values while it explores. Exploration is still necessary, because an action that is never taken never has its entry updated, and its estimate stays wherever it started. The theorem needs all of its conditions. A constant step size such as fails the second sum condition, and when a neural network replaces the table, as in deep Q-learning, the tabular guarantee does not apply and training can be unstable.
Example At the dock the robot takes the action right, pays and reaches the aisle, whose actions forward and back have estimates and . With , and , the target is , and the entry becomes
This matches the state-value example only because the numbers were chosen alike. The two updates estimate different things, the value of a state under a fixed policy and the value of an action followed by optimal behavior. Every other entry of the table, such as the dock’s other action, stays as it was.
On-policy and off-policy learning
Definition The behavior policy is the policy that chooses the actions and so generates the data. The target policy is the policy whose values are being learned. A method is on-policy when the two are the same, so that it learns the values of the policy that is acting, exploration included, and off-policy when they differ. SARSA, named after the sequence , is the on-policy counterpart of Q-learning. Its target uses the next action actually chosen by the behavior policy,
again with when is terminal, and the same update of . Q-learning uses the maximum over next actions instead, so it learns about the greedy policy while behaving differently, which makes it off-policy.
In plain words The two methods differ in one place, the continuation term of the target. A sampled next action makes the target follow the exploring policy, so the values SARSA learns include the cost of the exploration it actually does. A maximum makes the target follow the best estimated action, whatever is done next. An off-policy method can also learn from transitions recorded under other policies, including older versions of its own, provided the records are real transitions of the same task and include the actions the target policy would take.
Example Take the same transition from the dock, with , reward , and , and suppose the exploring behavior policy next chooses back, whose estimate is . The SARSA target is , so the entry becomes
Q-learning uses the maximum instead and moves the same entry to . One observed transition gives two different updates, because the two targets answer different questions.
Terminal state
Definition In an episodic task, a terminal state ends the episode. No actions are taken in it and no rewards follow it, so its value is defined as , both and , and the target of a transition into a terminal state is the reward alone. The reward of that final transition still counts. A time limit that stops recording while the process would go on is a truncation, not a terminal state, and there the target keeps the discounted estimate for the next state.
In plain words Two different mistakes happen at the end of an episode. Bootstrapping past the end adds a continuation value that does not exist, for example a leftover number in the terminal row of a table. Dropping the final reward loses the one payoff that the last transition really had. Treating a time limit as a true ending makes the states near the limit look as if nothing could follow them, which biases their values.
Example From the aisle the robot moves forward into the exit with reward , and with . The target is , the TD error is , and the new estimate is . If the exit row of the table held a leftover value of and the update used it, the target would become and the estimate , which is too high. Dropping the reward instead would give the target and the estimate . The function below checks the terminal flag before it takes any maximum, and it reproduces the Q-learning update at the dock and this terminal update.
def q_update(Q, s, a, r, s_next, terminal, alpha, gamma):
"""One tabular Q-learning update of the entry (s, a)."""
if terminal:
target = r # nothing follows a terminal state
else:
if not Q[s_next]:
raise ValueError("a nonterminal state needs at least one action")
target = r + gamma * max(Q[s_next].values())
Q[s][a] += alpha * (target - Q[s][a])
Q = {"dock": {"right": 2.0, "left": 7.0},
"aisle": {"forward": 4.0, "back": 1.0},
"exit": {"stale": 3.0}} # leftover entry, never used
q_update(Q, "dock", "right", -1, "aisle", False, alpha=0.25, gamma=0.9)
q_update(Q, "aisle", "forward", 5, "exit", True, alpha=0.25, gamma=0.9)
print(Q["dock"], Q["aisle"]) # {'right': 2.15, 'left': 7.0} {'forward': 4.25, 'back': 1.0}Check yourself
- An entry is updated with and after a transition with reward into a terminal state. The terminal row of the table still holds the value from its initialization. Find the correct Q-learning update, and the result of a mistaken update that bootstraps from that row.
Show the answer
The next state is terminal, so the target is the reward alone. The TD error is , and the new value is
The mistaken update uses the target , with error , and gives . The leftover is not the value of anything, because no rewards follow a terminal state.
- Another entry with , and sees reward and a nonterminal next state whose two actions have estimates and . The behavior policy then chooses the action with estimate . Find the Q-learning update and the SARSA update, and say which policy each one learns about.
Show the answer
Q-learning uses the largest next estimate. Its target is , the error is , and the new value is .
SARSA uses the next action actually chosen. Its target is , the error is , and the new value is .
Q-learning learns about the greedy policy, which would take the action with estimate , while the data come from a policy that explored, so it is off-policy. SARSA learns about the behavior policy itself, exploration included, so it is on-policy. In both cases a continuation term appears because the next state is not terminal, which the terminal flag decides, not the size of the reward.
- A robot runs Q-learning with the constant step size and a purely greedy behavior policy, and its training TD errors become small. A colleague cites the tabular convergence theorem to claim that the table now holds the optimal action values. Which conditions of the theorem fail, what would satisfy them, and what else is needed before the learned policy can be trusted?
Show the answer
Two conditions fail. With a constant step size the squares add up to , which is infinite, so the square-summability condition fails. A purely greedy policy can stop trying some actions altogether, and their entries are then never updated again, so not every state-action pair is updated infinitely often.
Step sizes such as at the th update of each pair satisfy both sum conditions, and a behavior policy that keeps trying every action in every state, for example epsilon-greedy with in a task where every state keeps being visited, supplies the updates. Even then the theorem describes the limit and promises nothing after a fixed number of steps.
Small TD errors show only that the estimates agree with their own bootstrapped targets. Trusting the learned policy needs an evaluation of the greedy policy on separate episodes, with its returns and their spread, together with checks of which actions were actually tried, of terminal handling and of whether the reward measures what matters.