A target that takes the max of noisy guesses rates its best guess too high. On our toy, a plain DQN target sends the agent down a losing path in 90% of episodes 21 to 50. A double target cuts that to 14%.
A lesson with a workbook. Each chapter explains one part of the homework, then gives you exercises on our own toy problems.
Choose a target and press Run. Watch how often the agent walks left into the noisy room. Drag noisy actions to give the max more guesses. Then we build DQN, then SAC, one piece at a time.
You need Q-learning and actor-critic. The exercises run JavaScript in your browser.
A workbook for Homework 3 of UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine (Spring 2026). It follows the HW3 handout (PDF), Lecture 8, Q-learning in practice (PDF) and Section 4, DQN and SAC (PDF). The words, toys and numbers here are our own.
Our toy, after the maximisation-bias example in Sutton and Barto. From A, right ends with 0; left leads to B, where each action pays a random reward with mean −0.1. Tabular, epsilon 0.1, learning rate 0.1, 400 runs. Illustrative.
Chapter 0
See the two agents you build and the three loops that run inside both
Homework 3 builds two off-policy agents. DQN learns one Q-value per action, for a small set of actions. SAC (soft actor-critic) learns a critic Q(s, a) and an actor for continuous actions. Both keep old transitions in a replay buffer: a fixed-size store of (s, a, r, s′, d) tuples, oldest out first.
Inside both agents, three loops run at their own speeds. Process 1 collects data with the current policy. Process 2 copies the online weights into a frozen target. Process 3 regresses Q onto targets drawn from the buffer.
Dots are transitions flowing into the buffer. Choose a preset, then drag the updates per environment step.
The three presets follow Lecture 8 (pp. 10 to 12). The drawing keeps the order of the speeds, not their scale.
How much learning does each new transition buy? Call the gradient steps per round K and the environment steps per round N.
U-T-D equals K over N.
Count the gradient steps K. Divide by the new environment steps N. Classic DQN takes one of each.
With made-up numbers: collect N = 4 steps, then take K = 8 gradient steps. UTD = 8 / 4 = 2. Higher UTD learns faster per sample but costs compute, and too high overfits the buffer.
Chapter 1
Regress Q onto a target that holds still, and stop the bootstrap where the episode ends
The first part fills in the critic update and epsilon-greedy action choice in the DQN agent. The idea is regression. Q(s, a) should match a target y: the reward now, plus the discounted value of the best next action.
If y comes from the same network you update, y moves with every step. You chase your own tail. DQN reads y from a target network Q̄: a frozen copy of the weights, refreshed every N updates. Between copies, each update is plain regression.
Teal bars are Q(s, right) in each cell. Yellow ticks are the frozen copy. Press Play, then turn off the done mask.
Our toy: 6 cells, a reward of 1 for stepping right off cell 5, discount 0.9. The buffer holds all 12 moves; each update samples 4. After the goal the environment resets, so the stored next state is cell 0.
What should Q(s, a) be? Call the reward r, the discount γ, and the done flag d: 1 if the episode ended on this move, else 0.
y equals r plus gamma, times one minus d, times the max over a-prime of Q-bar of s-prime and a-prime.
Look up the next state s-prime in the frozen copy Q-bar. Take its best action value. Zero it if d is 1. Discount by gamma and add r.
Corridor, cell 4, move right: r = 0, d = 0, the copy says 1.0 at cell 5. y = 0 + 0.9 × 1.0 = 0.9. At cell 5 the move ends the episode: y = 1 + 0 = 1.
The true value at cell 0 is 0.95 = 0.590. Each copy carries the reward back one cell, so with N = 100 the value needs about 6 × 100 updates to reach the start.
(1 - done). A time limit that cuts an episode is not a done.qNext holds the frozen copy's values at one next state.qNext[i].d[i].r[i]. Return the array of targets.numpyy = r + gamma * (1 - d) * q_next.max(axis=1) # the same idea on arrays
javascriptfunction tdTargets(r, d, qNext, gamma) {
return r.map((ri, i) => ri + gamma * (1 - d[i]) * Math.max(...qNext[i]));
}
def target(batch, q_target, gamma): s, a, r, s2, done = batch q_next = q_target[s2].max(axis=1) y = r + gamma * q_next return y
r + gamma * (1 - done) * q_next.Chapter 2
Let one network choose the next action and the other one score it
Ten actions all have a true value of 0. Your estimates of them are noisy. The target takes the largest estimate, and the largest of ten noisy numbers is almost always above 0. The max picks the action whose noise is highest, then reports that noise as value.
Each dot is one noisy estimate; the true value is the line at 0. Press Draw 200 to average many draws. Change the count of actions.
Our toy: each estimate is the true value 0 plus Gaussian noise with standard deviation 1. Double: table A picks the action, table B scores it.
Call the estimates X1 to Xn. On its own, each one has no bias.
The expected value of the max over i of X-i is at least the max over i of the expected value of X-i.
Averaging the maxima X-i gives more than the best average. The gap is the overestimation bias, and the bootstrap passes it back to earlier states.
With 10 estimates of true value 0 and noise of standard deviation 1, the average max is 1.54. The truth is 0.
The fix uses two networks with different noise. The online network Q picks the action. The frozen copy Q̄ scores it.
y equals r plus gamma, times one minus d, times Q-bar of s-prime at the arg max over a-prime of Q of s-prime and a-prime.
Ask Q which next action is best. Look up that action's value in Q-bar, not Q-bar's own best. Then discount and add r as before.
With made-up numbers: Q(s′) = [1, 3, 2], Q̄(s′) = [2, 1, 4], r = 0, γ = 0.9. Q picks action 1; Q̄ scores it 1, so y = 0.9. The plain target takes Q̄'s max, 4: y = 3.6.
argmax. If it is the target network, the same noise picks and scores.qOn holds the online values at each next state, qTg the frozen copy's.qOn[i]. On a tie, take the first.qTg[i] at that index.numpya_star = q_online_next.argmax(axis=1)
y = r + gamma * (1 - d) * q_target_next[np.arange(len(r)), a_star]
javascriptfunction doubleTarget(r, d, qOn, qTg, gamma) {
return r.map((ri, i) => {
let k = 0;
for (let j = 1; j < qOn[i].length; j++) if (qOn[i][j] > qOn[i][k]) k = j;
return ri + gamma * (1 - d[i]) * qTg[i][k];
});
}
def double_target(r, done, s2, q_online, q_target, gamma): a_star = q_target[s2].argmax(axis=1) rows = np.arange(len(r)) q_next = q_target[s2][rows, a_star] return r + gamma * (1 - done) * q_next
q_online[s2].argmax(axis=1).Chapter 3
Change one hyperparameter over four values, keep the rest fixed, and run seeds
The homework asks you to pick one hyperparameter and try four values on one plot. Lecture 8 warns that Q-learning results change a lot from one seed to the next. So one run per value tells you little. A fair sweep changes one knob, fixes the others, and runs several seeds per value.
Pick a knob with a reason. The copy period trades stability against speed. The learning rate trades speed against noise. The exploration schedule decides what lands in the buffer.
Each line is the mean error of Q at the start over 8 seeds; the band is the spread. Choose the knob.
Our corridor from Chapter 1, with Gaussian noise of standard deviation 0.5 on the goal reward. Error is |Q(0, right) − 0.590|. The other knobs stay at learning rate 0.5, copy period 10, batch 4. Illustrative.
Which values should the four settings take? Spread them on a log scale, so each is a fixed multiple of the last. Call the smallest value v0 and the largest v3.
v-k equals v-zero times, v-three over v-zero, to the power k over three.
Divide the largest value v-three by the smallest v-zero. Take the cube root: that is the step. Multiply v-zero by the step, one setting at a time.
With made-up numbers: learning rates from 0.0001 to 0.001. The step is 101/3 = 2.154, so the settings are 0.0001, 0.000215, 0.000464 and 0.001.
Chapter 4
Draw the next action from the actor, and let the target copy trail the critic
With continuous actions, the max over a′ is an optimisation problem inside every target. SAC drops it. The next action a′ comes from the actor at s′. The critic maps one (s, a) pair to one number, where the DQN critic gave one number per action.
What does the critic regress onto? Call the actor π, the frozen critic Q̄, and the next action a′, a fresh sample from π at s′.
y equals r plus gamma, times one minus d, times Q-bar of s-prime and a-prime; with a-prime drawn from pi given s-prime.
Sample a next action a-prime from the actor. Score it with the frozen critic Q-bar. Zero it if d is 1, discount by gamma, add r.
With made-up numbers: r = 0.5, d = 0, γ = 0.99, and Q̄ scores the sampled a′ at 4.0. y = 0.5 + 0.99 × 4.0 = 4.46.
The frozen copy can follow the critic in two ways. A hard update copies every N steps. A soft update (Polyak averaging) moves the copy a small fraction τ of the way after every step.
The teal line is one critic weight as it learns. The yellow line is its copy. Choose hard or soft, then drag the knob.
Section 4 lists hard N = 10,000 and Polyak τ = 0.005 as common values. The climbing weight is our toy; the lags are exact for a steady climb.
Phi-bar becomes phi-bar plus tau times, phi minus phi-bar.
Find the gap between phi and phi-bar. Close a share tau of it. Do this after every critic step.
At τ = 0.005, half of a fixed gap closes in ln 0.5 / ln 0.995 = 138 steps. On a steady climb the copy trails by 1 / τ − 1 = 199 steps. A hard copy every 10,000 steps trails by 0 to 9,999, about 5,000 on average.
online[i] − target[i].target[i] plus tau times the gap.numpyphi_bar = phi_bar + tau * (phi - phi_bar) # one line per weight array
javascriptfunction polyak(target, online, tau) {
return target.map((t, i) => t + tau * (online[i] - t));
}
Chapter 5
Pay the actor for staying random, and pass the critic's gradient through the sample
DQN explores with epsilon. SAC pays its actor for entropy: H = E[−log π(a|s)], large when the actor spreads its actions. A temperature α sets the price of one unit of entropy, counted in reward. The handout calls it β at first; we call it α throughout.
The actor outputs a mean μ and a spread σ. It draws noise ε from a standard normal, sets u = μ + σε, and squashes: a = tanh(u), inside −1 to 1. The action is now a smooth function of μ and σ, so the critic's gradient flows back through it. This is the reparameterisation trick.
Blue is the actor's density over actions; the warm dashed curve is Q. Press Train. Turn the reward off to see the entropy ceiling.
Our toy: Q(a) = 1 − 4(a − 0.5)², 32 samples per step, learning rate 0.05. The read-out computes entropy exactly on a grid. The log 2 ceiling is the handout's sanity value.
What is the log-probability of a squashed action? Call the Gaussian density of u N(u; μ, σ). The tanh squeezes the line into −1 to 1, which piles up density.
Log pi of a given s equals log N of u, mu, sigma, minus the log of one minus tanh squared of u.
Score u under the Gaussian. Then subtract the log of the tanh slope at u. Near the edges the slope is small, so the density of a rises.
With μ = 0, σ = 1, u = 0.5: log N = −0.125 − 0.919 = −1.044. tanh 0.5 = 0.462, and log(1 − 0.213) = −0.240. So log π = −1.044 + 0.240 = −0.804.
The actor minimises the temperature times the log-probability, minus Q, on a reparameterised sample ã.
L-pi equals the average over epsilon of, alpha times log pi of a-tilde given s, minus Q of s and a-tilde; where a-tilde is tanh of mu plus sigma epsilon.
Draw epsilon and build a-tilde from mu and sigma. Score it with Q. Add alpha times its log-probability. Lower this by gradient descent on mu and sigma.
With μ = 0, σ = 1, one draw ε = 0.5, α = 0.1 and a critic that scores every action 0: L = 0.1 × (−0.804) − 0 = −0.080.
rsample(), not sample(), or no gradient reaches the actor.Q is a function of the action; eps is an array of fixed noise draws.numpyu = mu + sigma * eps
a = np.tanh(u)
logp = -0.5 * eps**2 - np.log(sigma) - 0.5 * np.log(2 * np.pi) - np.log(1 - a**2)
loss = np.mean(alpha * logp - Q(a))
javascriptfunction actorLoss(mu, sigma, eps, alpha, Q) {
let t = 0;
for (const e of eps) {
const u = mu + sigma * e, a = Math.tanh(u);
const logp = -0.5 * e * e - Math.log(sigma) - 0.5 * Math.log(2 * Math.PI) - Math.log(1 - a * a);
t += alpha * logp - Q(a);
}
return t / eps.length;
}
Chapter 6
Let alpha find itself by dual descent, then take the smaller of two critics
A good fixed α differs per task and drifts during training. SAC states the goal as a constraint instead: earn the most reward, while the entropy stays at or above a target entropy H̄. For continuous actions H̄ is usually minus the number of action dimensions. Then α becomes the Lagrange multiplier of the constraint: the price that rises while the constraint is broken.
Its loss is short. Call the target entropy H̄ and the actor's log-probability of a fresh sample log π(a|s).
L of alpha equals the average of minus alpha times, log pi of a given s plus H-bar.
The slope of L in alpha is the entropy minus H-bar. If the entropy is below H-bar, the slope is negative, so descent raises alpha. If above, alpha falls.
With made-up numbers: log π samples −0.5 and 0.2, so the entropy estimate is 0.15. H̄ = −1 and α = 1. L = −1 × (−0.15 − 1) = 1.15. The entropy is above target, so the gradient on log α is +1.15 and α falls.
Purple is alpha; blue is the entropy, with the target line at −1. Press Run. Then sharpen the reward, or flip the sign.
Our toy: Q(a) = −c·a² with an unsquashed Gaussian actor, so the best actor for each alpha has variance alpha / 2c. Adam on log alpha, learning rate 0.05, start alpha 0.2.
The last part fights overestimation in SAC. One critic has the same max problem as DQN, because the actor climbs toward the critic's errors. Clipped double-Q trains two critics and builds one target from the smaller of their two frozen copies.
y equals r plus gamma, times one minus d, times the min over i of Q-bar-i of s-prime and a-prime, minus alpha log pi of a-prime given s-prime.
Sample a-prime. Score it with both frozen critics and keep the smaller. Add alpha times minus its log-probability. Mask, discount, add r.
With made-up numbers: r = 0.5, γ = 0.9, d = 0, the copies say 3.0 and 3.4, α = 0.1, log π(a′|s′) = −0.5. y = 0.5 + 0.9 × (3.0 + 0.05) = 3.245.
numpyalpha = np.exp(log_alpha) loss = np.mean(-alpha * (logp + target_entropy)) # logp held fixed
javascriptfunction alphaLoss(logAlpha, logps, targetEnt) {
const alpha = Math.exp(logAlpha);
return logps.reduce((s, lp) => s - alpha * (lp + targetEnt), 0) / logps.length;
}
def alpha_step(log_alpha, logp, target_entropy, lr): alpha = np.exp(log_alpha) entropy = -logp.mean() grad = alpha * (target_entropy - entropy) # d loss / d log_alpha return log_alpha - lr * grad
grad = alpha * (entropy - target_entropy).Chapter 7
Keep the targets, the numbers and the build list on one page
DQN regresses Q onto a target from a frozen copy and masks the end of each episode. Double DQN picks the next action with one network and scores it with the other. SAC swaps the max for a sample from the actor. It pays for entropy at a price α that tunes itself, and it takes the smaller of two critics.
| Term | What it is | Number on this page |
|---|---|---|
| UTD ratio | gradient steps per environment step | 1 for classic DQN |
| done mask | stops the bootstrap at a real episode end | corridor: 0.59 with it, 1.26 without |
| overestimation | the max of noisy estimates sits above the truth | 10 actions, noise 1: +1.54 |
| double target | online network picks, frozen copy scores | hero: 90% to 14% wrong turns |
| Polyak τ | share of the gap the copy closes per step | 0.005: half-life 138, lag 199 |
| hard copy | copy every N steps | N = 10,000: average lag 5,000 |
| entropy ceiling | most spread on −1 to 1, one dimension | log 2 = 0.693; tanh-Gaussian 0.684 |
| target entropy | the floor that auto-temperature holds | −dim(A): −1 for one dimension |
One SAC step for the one-dimensional bandit of Chapter 5, in numpy with hand-written gradients. It is our toy, not the homework's agent.
numpyimport numpy as np Q = lambda a: 1 - 4 * (a - 0.5)**2 # the critic, fixed for this toy dQ = lambda a: -8 * (a - 0.5) def sac_toy_step(mu, log_sig, log_alpha, rng, lr=0.05, target_ent=-1.0, n=32): sig, alpha = np.exp(log_sig), np.exp(log_alpha) eps = rng.standard_normal(n) u = mu + sig * eps; a = np.tanh(u); slope = 1 - a**2 logp = -0.5 * eps**2 - log_sig - 0.5 * np.log(2 * np.pi) - np.log(slope) # actor: minimise alpha*logp - Q(a), gradients through a = tanh(mu + sig*eps) g_mu = np.mean(alpha * (2 * a) - dQ(a) * slope) g_sig = np.mean(alpha * (-1 + 2 * a * sig * eps) - dQ(a) * slope * sig * eps) mu, log_sig = mu - lr * g_mu, log_sig - lr * g_sig # temperature: d/dlog_alpha of -alpha*(logp + target) = alpha*(entropy - target) log_alpha -= lr * alpha * (-logp.mean() - target_ent) return mu, log_sig, log_alpha
This workbook follows UC Berkeley CS 185/285, Deep Reinforcement Learning, Sergey Levine (Spring 2026): the course page, the Homework 3 handout and its starter code, Lecture 8 and Section 4. The words, toys and numbers here are our own.
The papers behind it: Mnih et al. (2015) for DQN, van Hasselt et al. (2016) for double DQN, and Fujimoto et al. (2018) for TD3. Haarnoja et al. (2018) wrote SAC and its automatic temperature.
Now press Teach. Explain from memory why the max overrates, what the done mask stops, and which way alpha moves when the entropy is low. Then go back to the hero, set noisy actions to 20, and say why the max target gets worse.