Week 09 · Deep Q-networks
Compare replay and target networks on a small controlled environment.
← Week 8 · Subject contents · Week 10 →
Compare replay and target networks on a small controlled environment.
Work through the problem
A DQN represents Q(s,a) with a neural network. Train toward r+γ maxₐQ_target(s′,a) on nonterminal transitions. A lagging target network holds the target fixed over several updates. Replay draws previous transitions to reuse data and mix experience from different times.
Use a five-state chain with two actions. Moving right reaches reward 1 after four steps from state 0. At γ=0.9 its optimal start value is 0.9³. Compare the full setup with runs that remove one mechanism. This environment tests implementation, and may be too easy to show a reliable benefit.
Run the Python lab
import random
import torch
from torch import nn
torch.set_num_threads(1)
def train(replay, delayed):
rng = random.Random(3)
torch.manual_seed(3)
net = nn.Sequential(nn.Linear(5,16),nn.ReLU(),nn.Linear(16,2))
target = nn.Sequential(nn.Linear(5,16),nn.ReLU(),nn.Linear(16,2))
target.load_state_dict(net.state_dict())
opt = torch.optim.Adam(net.parameters(),lr=.015)
states = torch.eye(5)
buffer,s = [],0
for step in range(700):
a = rng.randrange(2) if rng.random()<.3 else net(states[s]).argmax().item()
t = min(4,max(0,s+(1 if a else -1)))
done = t==4
buffer.append((s,a,t,done))
batch = rng.sample(buffer,min(len(buffer),16)) if replay else buffer[-1:]
i,b,j,end = map(torch.tensor,zip(*batch))
with torch.no_grad():
expected = end.float()+.9*(~end)*(target if delayed else net)(states[j]).max(1).values
opt.zero_grad()
nn.functional.smooth_l1_loss(net(states[i]).gather(1,b[:,None])[:,0],expected).backward()
opt.step()
if step%35==0:
target.load_state_dict(net.state_dict())
s = 0 if done else t
q = net(states[0]).detach()
return q.argmax().item(),q.max().item()
for replay, delayed in [(True,True),(False,True),(True,False)]:
action,q = train(replay,delayed)
print(replay,delayed,"start action",action,"Q",round(q,3))
print("Optimal start value:",round(.9**3,3))
Output from the lab
True True start action 1 Q 0.742
False True start action 1 Q 0.731
True False start action 1 Q 0.726
Optimal start value: 0.729
Practice
- Why exclude the terminal state’s estimated value from the target?
Check your reasoning
- Termination ends future rewards. The observed final reward already completes the return.