Unit 4 of 10 · about 4 hours · implement
Neural action-value functions and replay-buffer semantics
Replay and frozen targets turn an unstable neural Q-learner into something trainable. This unit builds the running baseline that every later unit instruments.
You'll be able to
- Implement a Q-network, a replay buffer and the DQN loss from a blank file.
- Explain why replay breaks correlation and why targets use frozen parameters.
- Train CartPole on CPU and separate training exploration from greedy evaluation.
Covers
Read
In this order, only the parts listed
0 of 4 done
- Why tables break and why naive networks failHands-on Modern RL - From Q-Learning to DQN
Sections Where Q-Tables Break through Why the Naive Replacement Still Fails: the bin-counting blowup, correlated samples, and moving targets (page read 2026-10-14)
The TD-target formula on this page omits the terminal mask. Take the masked form from the next item.
- Q-network, loss and replayHands-on Modern RL - From Q-Learning to DQN
Q-Network and Loss through Experience Replay: the masked loss , the symbol-by-symbol table, and the five-tuple buffer (page read 2026-10-14)
- Target network and training loopHands-on Modern RL - From Q-Learning to DQN
Target Network through Learning vs. Inference: periodic hard copies, exploratory collection in the training loop, and greedy evaluation with (page read 2026-10-14)
- Deep Q-learning with experience replayPlaying Atari with Deep Reinforcement Learning
Algorithm 1 and Section 4 in arXiv:1312.5602v1 (the three replay advantages: data efficiency, decorrelation, behavior averaging). Read Section 5 as reported Atari protocol, not as reproduction targets. Note this version has no target network: targets use the previous iterate.
Focus on
- One forward pass outputs every discrete-action value, and
argmaxselects among them. Continuous actions need a different method entirely. - The loss compares the prediction selected by
gatheragainst a target built undertorch.no_grad()from the frozen network. Gradients must touch only the prediction. - The workshop paper fixes targets with the previous iterate, not a periodic copy. The frozen-network copy used in code is the later stabilization of the same idea.
- Training explores while evaluation acts greedy. A test score measured with exploration mixes luck with learning.
Common mistakes · 3
- Copying the first page's target verbatim. It omits the terminal mask, so terminal transitions bootstrap phantom future value.
- Reusing the online network for targets. That reintroduces the moving-target loop the frozen network exists to slow.
- Judging training by episode return alone. The paper's Section 5.1 shows return is noisy under shifting visitation, so track average predicted Q on a fixed state set too.
Try it yourself
Closed-book, before checking anything
Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.Why output all action values at once instead of one value per forward pass?Answer
One pass plus
argmaxscores every discrete action. Per-action passes would multiply inference cost by the action count.2.What does
gatherdo in the update?AnswerIt selects, for each batch row, the Q-value of the action actually taken, so the loss touches only visited state-action pairs.
3.The workshop target uses the previous iterate. What breaks if targets use freshly updated weights every step?Answer
Prediction and target share parameters, so each update moves the label it just chased. The loss has no fixed label inside the step.
4.A CartPole agent scores 500 in testing but 200 in training. Is it broken?Answer
No. Training mixes random exploratory actions while the test is greedy. Compare greedy with greedy.
Practice
- Hands-on Modern RL: CartPole DQN (
code/chapter04_dqn/dqn_cartpole.py)Train CartPole on CPU per the file's training loop, then evaluate with
epsilon=0.0. The file'supdatealready showsgather,torch.no_grad()targets, the terminal mask and gradient clippingKeep this run. Later units add diagnostics, defect tests and checkpoints to it, and the section mini-project extends it with replay and target state.
- Deep-ML 537: Experience Replay Implementation
Implement the
ReplayBufferclass. The tests check size tracking, circular overwrite at capacity, and that a full sample after overwrite returns only the newest three
You're done when
Your blank-file DQN trains CartPole on CPU, greedy evaluation beats the training average, and the two-transition hand loss matches to four decimals.
Only when you can do this without notes.
Leads to
Notes
Resources · 2 for this unit, 10 more in the section
- 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.
- 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.pytrains 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; itscode/chapterNNfolders do not follow the site chapter numbers.
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 pinsgym==0.25.2, which fails on NumPy 2, so port it to Gymnasium (terminatedandtruncated) or pinnumpy<2in 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. - 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.
- 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_infoandfinal_observationkeys of older Gymnasium releases; on Gymnasium 1.x (next-step autoreset) it logs no episode returns and raisesKeyErrorat truncation, so run it in an environment withgymnasium==0.29.1or patch those lines and say so. - 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 - 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.
- Gymnasium - Env.reset and seedingFarama Foundation · reference
Read the
Env.resetentry for the seeding contract: an integer seed resets the environment PRNGnp_random, and a laterresetwithseed=Nonecontinues it, so seed once right after creation.