Compute the DQN loss with a target network and Huber loss

Why it matters The target network plus Huber loss is the recipe that made deep Q-learning stable on Atari.

A DQN learns from a frozen copy of itself: targets come from a target network, and the loss on the chosen action's Q value uses the Huber function so a few big errors do not explode the gradients.

Write dqn_loss(q, actions, rewards, dones, q_target_next, gamma, delta=1.0).
- q: (B, A) online Q values for the current states; actions: (B,) ints taken.
- q_target_next: (B, A) target network Q values for the next states.
- y = rewards + gamma * (1 - dones) * max over actions of q_target_next.
- td = q[b, actions[b]] - y.
- Huber per element: 0.5 * td^2 if |td| <= delta else delta * (|td| - 0.5 * delta).
Return (mean Huber loss as a float, td as an array).

Signaturedef dqn_loss(q, actions, rewards, dones, q_target_next, gamma, delta=1.0)

Example

dqn_loss([[1, 2]], [1], [1], [0], [[0, 3]], 0.5) gives (0.125, array([-0.5])).

Understand the idea

Q-learning with a neural network chases a moving target: change the weights and the targets change too. DQN fixes this by computing targets with a separate target network that is only copied from the online network every few thousand steps. It also uses the Huber loss, which acts like squared error for small mistakes and like absolute error for large ones, so rare big rewards cannot cause huge gradient spikes.

Example: online Q for the taken action is 2, reward 1, gamma 0.5, best next target value 3. Target y = 1 + 0.5 * 3 = 2.5, error = -0.5, Huber = 0.5 * 0.25 = 0.125.

Rule: y = r + gamma * (1 - done) * max_a Q_target(s', a); loss = mean(huber(Q(s, a_taken) - y)).

Every value-based deep RL agent, from Atari players to recommendation bandits, starts from this loss.

Shapes and data flow

q: (B, A) -> gather -> (B,); q_target_next: (B, A) -> max -> (B,); td: (B,) -> loss scalar
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: exampledqn_loss([[1, 2]], [1], [1], [0], [[0, 3]], 0.5)
  • Sample 2: not greedydqn_loss([[5, 1], [0, 2]], [1, 0], [0, 1], [0, 1], [[1, 2], [9, 9]], 0.9)