CS 285 HW3: DQN and Soft Actor-Critic

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.

Pick a target, watch the bias

10

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.

Workbook progress
0 / 28 exercises (0%)
0
Day streak
Best: 0
28 exercises in five kinds: Derive, Trace, Build, Debug, Design. Build exercises run as JavaScript in your browser; the matching Python is shown beside them.

Chapter 0

The Map: What You Build

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.

Set the speed of each loop

Dots are transitions flowing into the buffer. Choose a preset, then drag the updates per environment step.

1

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.

UTD = K / N
Say it aloud

U-T-D equals K over N.

UTD
U-T-D the update-to-data ratio: gradient steps per environment step.
K
K gradient steps on minibatches from the buffer, per round.
N
N new environment steps added to the buffer, per round.
In plain words

Count the gradient steps K. Divide by the new environment steps N. Classic DQN takes one of each.

With numbers

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.

The road

  1. DQN: replay, a frozen target and the done flag. The hero's max target.
  2. Double DQN: why the max overrates, and the fix. The hero's double.
  3. One knob at a time: a fair sweep with seeds.
  4. The SAC critic: a' from the actor, hard and Polyak copies.
  5. Entropy and the actor: the tanh-Gaussian and the reparameterised gradient.
  6. Auto-temperature and the min of two: alpha by dual descent. The hero's min of two.
  7. Field guide: what you can build now, and where next.
In DQN, which process runs much slower than the other two?

Workbook

Exercise 0.1: Read a UTD ratio Derive
An agent adds 2 environment steps to the buffer, then takes 6 gradient steps with batches of 64. What is its update-to-data ratio?
updates per step
Show derivation
UTD = K / N = 6 / 2 = 3
The batch size does not enter. It changes how many samples each gradient step sees, not how many steps there are.
Exercise 0.2: Order one DQN step Design
Tap the chips in the order one DQN step runs them.
?
→
?
→
?
→
?
→
?
compute y with the frozen copy act epsilon-greedy copy weights if the step count says so sample a minibatch store (s, a, r, s′, d)
Exercise 0.3: Name the loop Trace
Fitted Q-iteration collects a big dataset, then fixes a target and runs many regression steps, then refits. How do its three processes nest?

Chapter 1

DQN: Replay, a Frozen Target, the Done Flag

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.

Run DQN on a corridor

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 = r + γ (1 − d) maxa′ Q̄(s′, a′)
Say it aloud

y equals r plus gamma, times one minus d, times the max over a-prime of Q-bar of s-prime and a-prime.

y
y the target that Q(s, a) regresses onto. No gradient flows into it.
r
r the reward of this move.
γ
gamma the discount, 0.9 on our corridor.
(1 − d)
one minus d 0 if the episode ended here, so nothing comes after; 1 otherwise.
maxa′ Q̄(s′, a′)
the max over a-prime of Q-bar the best value the frozen copy gives at the next state.
In plain words

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.

With numbers

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.

The trap: no done mask with auto-reset

symptom
Q at the start climbs past every return you can earn. On the corridor it settles at 1.26, not 0.59.
see it
Log Q next to the best possible return. After the goal, the stored next state is the reset state, so the target adds its value to the final reward.
fix
Multiply the bootstrap by (1 - done). A time limit that cuts an episode is not a done.
With a copy period of N = 100, why does the start cell's value stay at 0 for the first 200 updates?

Workbook

Exercise 1.1: One target by hand Derive
A transition has r = 0, d = 0 and γ = 0.9. The frozen copy gives Q̄(s′, ·) = [0.4, 0.73]. What is y?
target
Show derivation
max over a′ = max(0.4, 0.73) = 0.73
y = 0 + 0.9 × (1 − 0) × 0.73 = 0.657
Exercise 1.2: Targets for a batch Build
A neighbouring version on plain arrays. Each row of qNext holds the frozen copy's values at one next state.
  1. For each sample i, take the largest value in qNext[i].
  2. Multiply it by gamma and by 1 − d[i].
  3. Add r[i]. Return the array of targets.
numpyy = r + gamma * (1 - d) * q_next.max(axis=1)   # the same idea on arrays
Show solution
javascriptfunction tdTargets(r, d, qNext, gamma) {
  return r.map((ri, i) => ri + gamma * (1 - d[i]) * Math.max(...qNext[i]));
}
Exercise 1.3: Values that never stop growing Debug
A neighbouring corridor agent. Its environment resets on its own after the goal. Q at the start settles at 1.26 instead of 0.59. Click the buggy line.
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
Show why
Line 4 bootstraps past the end of the episode. After the goal, s2 is the reset state, so the corridor turns into a loop. Write r + gamma * (1 - done) * q_next.
Exercise 1.4: Epsilon on a schedule Derive
Epsilon falls in a straight line from 1.0 to 0.01 over the first 50,000 environment steps, then stays at 0.01. What is epsilon at step 15,000? Give 3 decimals.
epsilon
Show derivation
fraction = 15,000 / 50,000 = 0.3
epsilon = 1.0 + 0.3 × (0.01 − 1.0) = 1.0 − 0.297 = 0.703
Early on the buffer fills with near-random moves. That is why the first stretch of a DQN curve can look no better than random.

Chapter 2

Overestimation and Double DQN

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.

Take the max of noisy guesses

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.

10

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.

E[maxi Xi] ≥ maxi E[Xi]
Say it aloud

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.

E[maxi Xi]
the expected value of the max take the largest estimate, then average over many draws. This is what the DQN target does.
maxi E[Xi]
the max of the expected values the true best value. Here it is 0.
In plain words

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 numbers

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 = r + γ (1 − d) Q̄(s′, arg maxa′ Q(s′, a′))
Say it aloud

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.

y
y the double DQN target. r, gamma and d are as in Chapter 1.
arg maxa′ Q(s′, a′)
the arg max over a-prime of Q the action the online network likes best at s-prime. An index, not a value.
Q̄
Q-bar the frozen copy. It scores the chosen action.
In plain words

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 numbers

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.

The trap: both roles on one network

symptom
Double DQN behaves like plain DQN. Logged Q drifts above the returns of greedy rollouts.
see it
Check which network feeds the argmax. If it is the target network, the same noise picks and scores.
fix
Take the argmax with the online network, under no gradient, and index the target network with it.
Why does the max target overestimate even when every single estimate is unbiased?

Workbook

Exercise 2.1: The max of two coins Derive
Two actions both have true value 0. Each estimate is +1 or −1 with equal chance, independently. What is the expected value of the larger estimate?
value
Show derivation
four equal cases: (+1, +1), (+1, −1), (−1, +1), (−1, −1)
their max: 1, 1, 1, −1
E[max] = (1 + 1 + 1 − 1) / 4 = 0.5
Each estimate averages 0, but the max averages 0.5. Only the case where both are low pulls it down.
Exercise 2.2: More actions, more bias Trace
Ten actions, true value 0, noise with standard deviation 1. About what does the max target report on average?
Exercise 2.3: The double target Build
A neighbouring version on arrays. qOn holds the online values at each next state, qTg the frozen copy's.
  1. For each sample i, find the index of the largest value in qOn[i]. On a tie, take the first.
  2. Read qTg[i] at that index.
  3. Return r + gamma × (1 − d) × that value, for each sample.
numpya_star = q_online_next.argmax(axis=1)
y = r + gamma * (1 - d) * q_target_next[np.arange(len(r)), a_star]
Show solution
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];
  });
}
Exercise 2.4: Double in name only Debug
A neighbouring tabular agent claims to use double Q-learning, but its values drift up like plain Q-learning. Click the buggy line.
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
Show why
Line 2 chooses with the target table, which also scores on line 4. That is the plain max. Choose with q_online[s2].argmax(axis=1).

Chapter 3

One Knob at a Time

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.

Sweep one knob, eight seeds each

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.

vk = v0 · (v3 / v0)k/3
Say it aloud

v-k equals v-zero times, v-three over v-zero, to the power k over three.

vk
v-k setting number k, for k = 0, 1, 2, 3.
v0
v-zero the smallest value you try.
(v3 / v0)k/3
v-three over v-zero, to the k over three the growth factor, applied k times in equal steps.
In plain words

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 numbers

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.

The trap: a sweep that changes two things

symptom
The best setting wins on one plot and loses when you rerun it.
see it
Diff the configs. A shorter copy period that also gets a new seed, or a bigger network that also gets a new learning rate, confounds the result.
fix
Change one knob. Fix the seeds per setting. Plot against environment steps, with every setting on one axis.
You sweep the copy period over four values, one seed each. Two curves cross twice. What do you conclude?

Workbook

Exercise 3.1: Plan a fair sweep Design
Tap the chips in the order you should do them.
?
→
?
→
?
→
?
→
?
run each value with 3 or more seeds pick one knob and say why plot every value on one axis vs env steps choose 4 values on a log scale fix every other setting
Exercise 3.2: Two curves, one agent Trace
Early in a DQN run, the training return sits far below the evaluation return. Later they meet. Why?
Exercise 3.3: The second setting Derive
You sweep the copy period over four log-spaced values from 500 to 20,000 updates. What is the second value, v1? Round to the nearest whole update.
updates
Show derivation
ratio = 20,000 / 500 = 40
step = 401/3 = 3.420
v1 = 500 × 3.420 = 1,710
The four settings are 500, 1,710, 5,848 and 20,000. Equal ratios give each setting the same share of the range.

Chapter 4

The SAC Critic and Its Slow Copy

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 = r + γ (1 − d) Q̄(s′, a′),   a′ ~ π(· | s′)
Say it aloud

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.

y
y the critic's target. r, gamma and d are as in Chapter 1.
Q̄(s′, a′)
Q-bar of s-prime and a-prime the frozen critic's value of one next action.
a′ ~ π(· | s′)
a-prime drawn from pi given s-prime a new action from the current actor, not the action stored in the buffer.
In plain words

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 numbers

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.

Watch the copy trail the critic

The teal line is one critic weight as it learns. The yellow line is its copy. Choose hard or soft, then drag the knob.

0.005

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.

φ̄ ← φ̄ + τ (φ − φ̄)
Say it aloud

Phi-bar becomes phi-bar plus tau times, phi minus phi-bar.

φ̄
phi-bar the target critic's weights.
φ
phi the online critic's weights, just updated.
τ
tau the share of the gap closed per step, 0.005 here.
In plain words

Find the gap between phi and phi-bar. Close a share tau of it. Do this after every critic step.

With numbers

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.

The trap: tau in the wrong slot

symptom
The critic is as jumpy as with no target at all. Its Q values swing with every batch.
see it
Lecture 8 writes the same rule as φ̄ ← τφ̄ + (1 − τ)φ with τ = 0.999. Put 0.005 into that form and the copy jumps 99.5% of the way each step.
fix
Pick one form and test it: after one step with τ = 0.005 from φ̄ = 0 and φ = 1, the copy must read 0.005.
You train the SAC critic with no actor updates yet. Which sign says the critic code is wrong?

Workbook

Exercise 4.1: A soft update Build
A neighbouring version on plain arrays of weights.
  1. For each index i, find the gap online[i] − target[i].
  2. Return a new array: target[i] plus tau times the gap.
numpyphi_bar = phi_bar + tau * (phi - phi_bar)   # one line per weight array
Show solution
javascriptfunction polyak(target, online, tau) {
  return target.map((t, i) => t + tau * (online[i] - t));
}
Exercise 4.2: The half-life of a copy Derive
The online weights stop moving. With τ = 0.01, after how many soft updates has the copy closed half the gap? Round to the nearest step.
steps
Show derivation
each step keeps (1 − τ) of the gap: 0.99
solve 0.99n = 0.5: n = ln 0.5 / ln 0.99 = 68.97
Doubling tau from 0.005 to 0.01 halves the half-life, from 138 to 69 steps.
Exercise 4.3: Which copy lags more? Trace
The critic's weights climb at a steady rate. Compare a hard copy every 10,000 steps with Polyak at τ = 0.005.
Exercise 4.4: A terminal critic target Derive
A SAC transition has r = 2, d = 1 and γ = 0.99. The actor samples a′ and the frozen critic scores it at 7.5. What is y?
target
Show derivation
y = 2 + 0.99 × (1 − 1) × 7.5 = 2 + 0 = 2
The sampled action and its score do not matter here. You may still compute them for the whole batch; the mask zeroes them.

Chapter 5

Entropy and the Reparameterised Actor

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.

Train a tanh-Gaussian actor

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.

0.05

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 π(a | s) = log N(u; μ, σ) − log(1 − tanh² u)
Say it aloud

Log pi of a given s equals log N of u, mu, sigma, minus the log of one minus tanh squared of u.

log π(a | s)
log pi of a given s the log-probability of the action a = tanh(u).
log N(u; μ, σ)
log N of u the Gaussian log-density of u before the squash.
log(1 − tanh² u)
log of one minus tanh squared u the log of the slope of tanh at u. A flat slope piles density up.
In plain words

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 numbers

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π = Eε[ α log π(ã | s) − Q(s, ã) ],   ã = tanh(μ + σε)
Say it aloud

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.

Lπ
L-pi the actor loss. Lower is better.
Eε
the average over epsilon over draws of standard normal noise; one draw per state works well.
α
alpha the temperature: how much one unit of entropy is worth.
Q(s, ã)
Q of s and a-tilde the critic's score of the sampled action.
ã = tanh(μ + σε)
a-tilde the action as a function of mu and sigma, so gradients reach them.
In plain words

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 numbers

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.

The trap: no tanh correction

symptom
With entropy as the only term, logged entropy climbs past 0.69 and keeps going, while σ grows.
see it
Run the entropy-only check. A uniform spread on −1 to 1 has entropy log 2 = 0.693, and nothing on that interval has more. A tanh-Gaussian peaks near 0.684, at σ about 0.87.
fix
Subtract log(1 − tanh² u), or use a distribution class that applies the tanh transform for you. Sample with rsample(), not sample(), or no gradient reaches the actor.
Why does SAC write the action as tanh(μ + σε) instead of drawing it straight from the distribution?

Workbook

Exercise 5.1: A squashed log-probability Derive
μ = 0, σ = 1, and the draw gives u = 1.0. What is log π(a | s) for a = tanh(1.0)? Give 3 decimals.
nats
Show derivation
log N(1; 0, 1) = −0.5 × 1 − 0.919 = −1.419
tanh 1.0 = 0.762; 1 − 0.762² = 0.420; log 0.420 = −0.868
log π = −1.419 + 0.868 = −0.551
Further from the centre, the tanh slope shrinks and the correction grows. The density of a rises even though u is less likely.
Exercise 5.2: Read the entropy check Trace
You run the actor with only the entropy term, on a one-dimensional action squashed by tanh. Logged entropy passes 1.4 and is still rising. What is wrong?
Exercise 5.3: A reparameterised actor loss Build
A neighbouring one-dimensional version. Q is a function of the action; eps is an array of fixed noise draws.
  1. For each draw e, set u = mu + sigma × e and a = tanh(u).
  2. Compute log π = −0.5((u − mu)/sigma)² − log sigma − 0.5 log(2π) − log(1 − a²).
  3. Return the mean over draws of alpha × log π − Q(a).
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))
Show solution
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;
}
Exercise 5.4: The entropy ceiling Derive
An action lives on the interval −1 to 1. The most spread-out density there is uniform, with height 1/2. What is its entropy, −∫ p log p? Give 3 decimals.
nats
Show derivation
p = 1/2 on an interval of length 2
H = −2 × (1/2) × log(1/2) = log 2 = 0.693
A tanh-Gaussian cannot be exactly uniform. Its best is about 0.684, which is why the handout says "approximately log 2".

Chapter 6

Auto-Temperature and the Minimum of Two

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(α) = E[ −α ( log π(a | s) + H̄ ) ]
Say it aloud

L of alpha equals the average of minus alpha times, log pi of a given s plus H-bar.

L(α)
L of alpha the temperature loss. Gradient descent on it moves alpha.
E
the average over states from the buffer and actions from the actor.
α
alpha the temperature, kept positive as exp of log alpha.
log π(a | s)
log pi of a given s minus one sample of the entropy. Hold it fixed: no gradient into the actor.
H̄
H-bar the target entropy, −1 for one action dimension.
In plain words

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 numbers

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.

Let alpha find the target

Purple is alpha; blue is the entropy, with the target line at −1. Press Run. Then sharpen the reward, or flip the sign.

1

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 = r + γ (1 − d) ( mini=1,2 Q̄i(s′, a′) − α log π(a′ | s′) )
Say it aloud

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.

y
y one target, shared by both critics.
mini=1,2 Q̄i(s′, a′)
the min over i of Q-bar-i the smaller of the two frozen critics' scores of a-prime.
α log π(a′ | s′)
alpha log pi of a-prime subtracted, so an unlikely a-prime adds an entropy bonus.
In plain words

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 numbers

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.

The trap: a sign error in the alpha loss

symptom
Alpha runs away: to 0, and the actor collapses; or to huge values, and the reward stops mattering.
see it
Plot alpha and entropy together. Entropy below target with alpha falling means the sign is wrong. The handout labels this expression a gradient; it is the loss you descend.
fix
Minimise −α(log π + H̄), with log π detached. Test: entropy below target must raise alpha.
The entropy estimate is −1.6 and the target is −1. What does one step on the alpha loss do?

Workbook

Exercise 6.1: The temperature loss Build
A neighbouring version on an array of log-probabilities from one batch.
  1. Set alpha = exp(logAlpha).
  2. For each log-probability lp, compute −alpha × (lp + targetEnt).
  3. Return the mean.
numpyalpha = np.exp(log_alpha)
loss = np.mean(-alpha * (logp + target_entropy))   # logp held fixed
Show solution
javascriptfunction alphaLoss(logAlpha, logps, targetEnt) {
  const alpha = Math.exp(logAlpha);
  return logps.reduce((s, lp) => s - alpha * (lp + targetEnt), 0) / logps.length;
}
Exercise 6.2: Alpha runs the wrong way Debug
A neighbouring one-dimensional toy. Its entropy sits far below the target, and alpha keeps falling. Click the buggy line.
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
Show why
The gradient of the loss in log alpha is alpha times (entropy minus target). Line 4 flips it, so the descent step on line 5 lowers alpha when the entropy is low. Write grad = alpha * (entropy - target_entropy).
Exercise 6.3: A clipped soft target Derive
r = 1, d = 0, γ = 0.99. The two frozen critics score a′ at 6.2 and 5.8. α = 0.2 and log π(a′|s′) = −1.5. What is y? Give 3 decimals.
target
Show derivation
min(6.2, 5.8) = 5.8
bonus = −0.2 × (−1.5) = 0.3
y = 1 + 0.99 × (5.8 + 0.3) = 1 + 6.039 = 7.039
Exercise 6.4: The target entropy Trace
A robot arm has 6 action dimensions. With the usual rule, what target entropy does the auto-temperature aim for?
Exercise 6.5: Read two Q curves Trace
You log the critic's Q on the actor's actions for a single-critic run and a clipped double-Q run. Fresh episodes earn about the same return in both. Which pattern points to overestimation?

Chapter 7

Field Guide: Where Next

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.

TermWhat it isNumber on this page
UTD ratiogradient steps per environment step1 for classic DQN
done maskstops the bootstrap at a real episode endcorridor: 0.59 with it, 1.26 without
overestimationthe max of noisy estimates sits above the truth10 actions, noise 1: +1.54
double targetonline network picks, frozen copy scoreshero: 90% to 14% wrong turns
Polyak τshare of the gap the copy closes per step0.005: half-life 138, lag 199
hard copycopy every N stepsN = 10,000: average lag 5,000
entropy ceilingmost spread on −1 to 1, one dimensionlog 2 = 0.693; tanh-Gaussian 0.684
target entropythe floor that auto-temperature holds−dim(A): −1 for one dimension

What you can build now

The core, on our toy

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

Experiments worth running next

  1. On the hero, set noisy actions to 1. The max has one guess, so all three targets agree.
  2. On the corridor, add n-step returns and count the updates until the start cell is right.
  3. On the actor toy, train with alpha 0 and watch the spread collapse onto the peak.
  4. On the alpha toy, sharpen the reward mid-run and time how fast alpha catches up.

Keep going

The lectures behind each part

The takeaway. A bootstrapped target is only as honest as its parts. Freeze it, end it where the episode ends, and never let one noisy estimate both choose and score.

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.

Workbook

Exercise 7.1: Order one SAC update Design
Tap the chips in the order one SAC update runs them, after a batch is sampled.
?
→
?
→
?
→
?
step log alpha on the alpha loss regress both critics onto the clipped soft target soft-update both target critics step the actor on the reparameterised loss

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.

CS 285 HW3: DQN and Soft Actor-Critic (UC Berkeley)
The course page · HW3 handout · Lecture 8 slides · Back to Gleams