Unit 7 of 10 · about 4 hours · derive, implement

DQN targets, action gathering, gradient detachment and fixed-batch tests

Three one-line bugs (online net in the target, a missing terminal mask, a wrong gather index) each train something, just not DQN. Frozen-batch tests catch all three in seconds on CPU.

You'll be able to

  • Derive the masked DQN target and implement gathering plus no-gradient target computation.
  • Explain what detaching the target removes from the computation graph.
  • Write fixed-batch differential tests that catch online-target swaps, missing masks and wrong gathers.

Covers

DQN targets, action gathering and gradient detachmentFixed-batch differential tests for DQN updates
1

Read

In this order, only the parts listed

0 of 3 done

  1. The update method line by lineHands-on Modern RL - From Q-Learning to DQN

    The update method: gather for the taken action, torch.no_grad() around the masked target, mean squared error, and clip_grad_norm_ with max_norm=10 (page read 2026-10-14)

  2. The mask authorityGymnasium - Time Limits and Vector Autoreset

    Importance in learning code and Solution (page read 2026-10-14): bootstrap on truncation, cut on termination, with target vf_target = rew + gamma * (1 - terminated) * vf_next_state

  3. The single-file update to test againstCleanRL DQN

    The ALGO LOGIC block at commit fe8d8a0 (lines 197 to 218): with torch.no_grad() target with .max(dim=1), .gather(1, ...) prediction, mean squared error, and the Polyak-form target copy

2

Focus on

  • The mask multiplies by with as terminated only. Truncation keeps the bootstrap; the tutorial's Solution section is explicit.
  • Detachment makes targets constants: gradients flow only through . Without it, backpropagation also pulls the label.
  • gather on stored actions selects visited pairs; max over next-state values selects the bootstrap action. Swapping them trains the wrong pairing.
  • Frozen batches with frozen nets give bit-reproducible targets. Any mismatch after a code change is a bug, not noise.
Common mistakes · 3
  • Masking with terminated-or-truncated. Time-limit states lose their bootstrap and their values collapse near the cutoff.
  • Detaching the prediction instead of the target. No gradient then reaches , so the online net never learns from the loss. The target expression is the constant and the prediction is the only gradient path.
  • Testing with live sampling. Randomness hides systematic target bugs; freeze the batch first, then test.
3

Try it yourself

Closed-book, before checking anything

Closed-book, compute the two-transition hand targets from the replay unit (3.97 and -1.0, mean squared error 3.06545) and write the frozen-batch assertion your update must satisfy to four decimals.
4

Quiz yourself

Answer first, then mark it. Missed ones go to Review.

0 got · 0 missed

  1. 1.Your mask uses terminated-or-truncated. Which states lose value and why?Answer

    States near the time limit. Their targets drop the bootstrap term, so values ignore everything past the cutoff although the task continues.

  2. 2.Loss falls on live samples but the policy stays random. What is the next test?Answer

    Freeze one batch with hand targets. A falling live loss can come from shrinking target scale while the policy stays poor.

  3. 3.What exactly changes when torch.no_grad() is removed from the target?Answer

    The target joins the computation graph. With a separate target net whose parameters are outside the optimizer, backward only fills unused gradients on those parameters, wasting memory and compute. If the target is computed with the online net, as in a no-copy implementation, backward also moves the label toward the prediction and the update chases its own label.

  4. 4.The gather uses argmax over current Q instead of stored actions. What does the loss train?Answer

    Values of greedy actions rather than visited pairs. Off-policy data is misread as on-policy greedy data.

You're done when

Your frozen-batch test fails on each of the three injected bugs and passes on the clean update, all on CPU.

Only when you can do this without notes.

Leads to

Notes

Resources · 3 for this unit, 9 more in the section
  • CleanRL DQNCleanRL · support

    Read the single-file DQN implementation and documented benchmark details after the blank-file update passes. Trace replay, target, seeding, termination and evaluation semantics. The script expects the final_info and final_observation keys of older Gymnasium releases; on Gymnasium 1.x (next-step autoreset) it logs no episode returns and raises KeyError at truncation, so run it in an environment with gymnasium==0.29.1 or patch those lines and say so.

  • Hands-on Modern RL - From Q-Learning to DQNWalking Labs · support

    Use Sections 5.1 to 5.4, with the masked target on the components page (the formula on the first page omits the terminal mask). code/chapter04_dqn/dqn_cartpole.py trains CartPole on CPU in about two minutes. Treat score claims as hypotheses requiring local seed and version evidence. Pin commit 9231bab of walkinglabs/hands-on-modern-rl; its code/chapterNN folders do not follow the site chapter numbers.

  • Gymnasium - Time Limits and Vector AutoresetFarama Foundation · reference

    Read Termination, Truncation, Importance in learning code and Solution in the time-limits tutorial, plus the vector autoreset note at https://farama.org/Vector-Autoreset-Mode. Next-step autoreset is the default for Gymnasium 1.x vector environments; on Gymnasium 1.4.0 the step after an episode ends returns reward 0 with both flags false and is not a transition.

Also in this section

  • Berkeley CS 185/285 Deep Reinforcement Learning (Spring 2026) - Value-Based RL and Q-Learning in PracticeUC Berkeley · primary

    Slides are public at https://rail.eecs.berkeley.edu/deeprlcourse/static/slides/lec-N.pdf; current videos are not, and the public Fall 2023 playlist numbers lectures differently. Study Lecture 7 (value-based RL) and Lecture 8 (Q-learning in practice: replay, target networks, double Q-learning). Work the DQN part of Homework 3 (src/agents/dqn_agent.py, CartPole then LunarLander with double DQN) on CPU or one small GPU; the Atari run is optional. The homework pins gym==0.25.2, which fails on NumPy 2, so port it to Gymnasium (terminated and truncated) or pin numpy<2 in its own environment, and turn off its forced WandB logging.

  • Reinforcement Learning: An Introduction (2nd ed.) - Chapters 9 and 11Richard Sutton and Andrew Barto · required

    The authors post the full second edition free at incompleteideas.net; cite the printed page numbers. Study Sections 9.1 to 9.4 (value error, semi-gradient TD, linear methods) and Sections 11.1 to 11.3 and 11.6 (off-policy divergence, the deadly triad, why the Bellman error is not learnable). Reproduce Baird's counterexample (Section 11.2, Figure 11.1) and show the weights diverge under off-policy semi-gradient TD.

  • Stanford CS224R Spring 2026 - Q-Learning and Off-Policy MethodsStanford University · support

    Use Lecture 06 (Q-learning) and the TA Q-learning tutorial (material/CS224R_Tutotial_Max.pdf) as a second derivation of fitted Q-iteration, targets and overestimation. Its homeworks run on cloud GPUs; follow the Stanford honor code for course materials.

  • Playing Atari with Deep Reinforcement LearningDeepMind · required

    Read the algorithm, replay and target-network design plus experimental protocol. Reproduce DQN on a small discrete environment, then ablate replay and target networks rather than attempting an Atari score reproduction.

  • Deep Reinforcement Learning with Double Q-LearningDeepMind · required

    Derive the action-selection and action-evaluation split, construct a noisy maximization example and compare DQN with Double DQN using identical samples and tuning budgets.

  • Dueling Network Architectures for Deep Reinforcement LearningWang et al. (ICML 2016) · support

    Read the dueling architecture and its aggregation equations (the mean-subtracted form). Implement it as an optional head and test that the value and advantage streams are identifiable only up to the stated constraint.

  • Deep-ML - Function Approximation and DQN ProblemsDeep-ML · support

    Use named problems as closed-book checks after your own implementation passes: 530 (semi-gradient TD(0)), 556 (deadly-triad instability), 557 (Baird's counterexample), 537 (experience replay) and 477 (double Q-learning). Read each problem's tests before trusting its statement.

  • Reinforcement Learning Control Laboratory - Deep Value CoreRoadmap-Final · required

    Implement DQN and Double DQN with replay and target state, fixed-batch target tests, checkpoint and resume, overestimation evidence and injected online-target, detach, action-gather and replay defects.

  • Gymnasium - Env.reset and seedingFarama Foundation · reference

    Read the Env.reset entry for the seeding contract: an integer seed resets the environment PRNG np_random, and a later reset with seed=None continues it, so seed once right after creation.