AI Wiki中文/EN

Target networks: hold the answer still while updating the predictor

目标网络

Compare hard copies and soft averages, derive the coefficient convention, and verify independent parameter storage.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

What if improving a prediction also moves its target?

Suppose a network predicts 0.4 for taking an action now. Its learning target is 0.8, partly because the same network predicts a valuable next state. An update raises the current prediction—but shared parameters may also raise the next-state prediction. The answer it was trying to approach has moved. This feedback can complicate bootstrapped learning.

A target network introduces a delay. Keep an independently stored copy of the predictor for constructing targets, while the online network receives gradient updates. Occasionally replace the copy, or move it partway toward the online parameters. The target is not an oracle: it can still be wrong. The mechanism controls when changes in the predictor feed back into its own training targets. The 2015 DQN Methods describes this separate-network modification explicitly. Original method

Read Q-learning and backpropagation first. DQN explains the complete small learner, and experience replay explains its sampled data. Here we isolate parameter storage, update timing and the meaning of “fixed.”

Hard-copy timing separates the target used now from the target ready next. The prescribed scalar sequence is not a learning curve; the network example takes one real gradient step.
Hard-copy timing separates the target used now from the target ready next. The prescribed scalar sequence is not a learning curve; the network example takes one real gradient step.

Two parameter sets, two update rules

Let θ be the online parameters and θ⁻ the target parameters. For a discrete-action transition, r is the immediate reward, x′ the actual next input, gamma the discount and d the task-termination flag. Define a bootstrap target with a stopped gradient:

y=stopgrad⁡ ⁣[r+γ(1−d)max⁡a′Qθ−(x′,a′)].y=\operatorname{stopgrad}\!\left[r+\gamma(1-d)\max_{a'}Q_{\theta^-}(x',a')\right].

The stop-gradient notation is an instruction about differentiation. We still compute the number inside it, but gradient descent on the online loss does not train θ⁻ through that branch. In this NumPy implementation the target is simply a separate computed array; there is no automatic differentiation graph. In the fixed Spinning Up implementation, separate storage, disabled target gradients and a no-gradient target calculation make the same separation explicit. Implementation comparison

Take a batch of B transitions and optimize its half-squared error with respect to θ only:

L(θ;θ−)=12B∑i=1B(Qθ(xi,ai)−yi)2,∇θL=1B∑i(Qθ(xi,ai)−yi)∇θQθ(xi,ai).L(\theta;\theta^-)=\frac1{2B}\sum_{i=1}^{B}(Q_\theta(x_i,a_i)-y_i)^2,\qquad \nabla_\theta L=\frac1B\sum_i(Q_\theta(x_i,a_i)-y_i)\nabla_\theta Q_\theta(x_i,a_i).

Holding θ⁻ fixed holds the target for a particular stored transition fixed. It does not mean that every sampled transition has the same target, or that a changing minibatch has an unchanged loss. If preprocessing includes additional randomness, that randomness would also have to be controlled for an exactly repeatable target.

For hard updates, initialize an independent copy. Let u count completed online gradient updates, and let C be the positive copy interval. Synchronize after each multiple of C:

θ0−=copy⁡(θ0),θu−={copy⁡(θu),u mod C=0,θu−1−,otherwise.\theta^-_0=\operatorname{copy}(\theta_0),\qquad \theta^-_u=\begin{cases}\operatorname{copy}(\theta_u),&u\bmod C=0,\\\theta^-_{u-1},&\text{otherwise}.\end{cases}

Update u uses the previous target parameters, then may replace them for update u+1. With C=1, every update gets a fresh copy afterward; its target remains fixed during the update itself. Increasing C changes the delay, not an intrinsic guarantee of stability. If a program counts environment frames instead, report that convention rather than assuming it is equivalent. The DQN Methods’ delayed-copy mechanism motivates this rule; our clock is defined explicitly in gradient updates. Copy mechanism

Soft updates average parameter values after every online update. Here tau is the weight on the new online parameters:

θu−=(1−τ)θu−1−+τθu,0≤τ≤1,ρ=1−τ.\theta^-_u=(1-\tau)\theta^-_{u-1}+\tau\theta_u,\qquad 0\leq\tau\leq1,\qquad \rho=1-\tau.

Some implementations instead call the old-target weight rho or polyak. Spinning Up uses that convention. Tau 0 leaves the target unchanged; tau 1 copies the online values. With old value 2, new value 10 and tau 0.25, the result is 4, not 8. Always read which parameter each coefficient multiplies. Fixed Polyak update

Unrolling the recurrence shows what averaging means:

θu−=(1−τ)uθ0−+τ∑k=1u(1−τ)u−kθk.\theta^-_u=(1-\tau)^u\theta^-_0+\tau\sum_{k=1}^{u}(1-\tau)^{u-k}\theta_k.

Older parameter vectors receive exponentially decreasing weight. This is an average in parameter space: because a neural network is nonlinear in its parameters, evaluating the averaged network is generally not the same as averaging the predictions of the historical networks. The formula does not promise that a particular tau is best for a task.

One further distinction protects the derivation. With a fixed target network, let Y be a random one-step target at a fixed state-action pair and q the online prediction. Expanding around the conditional mean gives:

E[(Y−q)2∣s,a]=(E[Y∣s,a]−q)2+Var⁡(Y∣s,a).\mathbb E[(Y-q)^2\mid s,a]=(\mathbb E[Y\mid s,a]-q)^2+\operatorname{Var}(Y\mid s,a).

The cross term has mean zero. While the target network is fixed, the variance term does not depend on the online parameters, so these two objectives have the same online gradient. For Y equally likely 1 or 3 and q=1, the left side is 2: squared mean error 1 plus variance 1. The 2015 printed decomposition and gradient notation should not be copied without this check; this article uses the identity and derivative stated above. Methods derivation

Inspect the target before and after copying

The standalone Python 3.12/NumPy 1.26.4 example has two parts. First, a prescribed scalar sequence 1 through 6 stands for online parameters after successive updates. It is a timing illustration, not a learned trajectory. The target starts at 0; hard copies happen every third update, and soft averaging uses tau 0.25.

Second, the original two-hidden-layer tanh network from the DQN teaching environment takes one real gradient step. We compare four fixed transition targets before that step, after the online update, and after copying the updated network. Only the latter operation should change the nonterminal targets.

"""Original NumPy teaching network, not an Atari reproduction."""
import math
import random
import numpy as np


def integer(value, minimum=0):
    if isinstance(value, bool) or not isinstance(value, (int, np.integer)) or value < minimum:
        raise ValueError('Expected an integer within the documented range')
    return int(value)


def network(seed=0):
    rng = np.random.default_rng(integer(seed))
    return {name: value for name, value in [
        ('w1', rng.normal(0, .5, (1, 8))), ('b1', np.zeros(8)),
        ('w2', rng.normal(0, .3, (8, 8))), ('b2', np.zeros(8)),
        ('w3', rng.normal(0, .3, (8, 2))), ('b3', np.zeros(2))]}


def forward(p, x):
    x = np.asarray(x, dtype=float)
    if x.ndim != 2 or x.shape[1] != 1 or not np.isfinite(x).all():
        raise ValueError('Expected finite input with shape (batch, 1)')
    h1 = np.tanh(x @ p['w1'] + p['b1'])
    h2 = np.tanh(h1 @ p['w2'] + p['b2'])
    return h2 @ p['w3'] + p['b3'], (x, h1, h2)


def loss_gradient(p, x, actions, targets):
    q, (x, h1, h2) = forward(p, x)
    a = np.asarray(actions)
    y = np.asarray(targets, dtype=float)
    n = len(x)
    if not n or a.shape != (n,) or a.dtype.kind not in 'iu' or np.any((a < 0) | (a >= 2)):
        raise ValueError('One integer action 0 or 1 is required per row')
    if y.shape != (n,) or not np.isfinite(y).all():
        raise ValueError('One finite fixed target is required per row')
    error = q[np.arange(n), a] - y
    dq = np.zeros_like(q)
    dq[np.arange(n), a] = error / n
    d2 = (dq @ p['w3'].T) * (1 - h2 * h2)
    d1 = (d2 @ p['w2'].T) * (1 - h1 * h1)
    g = {'w1': x.T @ d1, 'b1': d1.sum(0), 'w2': h1.T @ d2,
         'b2': d2.sum(0), 'w3': h2.T @ dq, 'b3': dq.sum(0)}
    return float(.5 * np.mean(error * error)), g


def copy_network(p):
    return {k: v.copy() for k, v in p.items()}


def update_target(target, online, tau=1.):
    # tau weights the NEW online parameters; Spinning Up's rho = 1 - tau.
    if not math.isfinite(tau) or not 0 <= tau <= 1 or target.keys() != online.keys():
        raise ValueError('Invalid target update')
    for k in target:
        if target[k].shape != online[k].shape or np.shares_memory(target[k], online[k]):
            raise ValueError('Target must be a separate, shape-compatible network')
    for k in target:
        target[k][...] = (1 - tau) * target[k] + tau * online[k]


def targets(target, rewards, next_x, terminated, gamma=.9):
    r = np.asarray(rewards, dtype=float)
    x = np.asarray(next_x, dtype=float)
    done = np.asarray(terminated)
    if not math.isfinite(gamma) or not 0 <= gamma <= 1:
        raise ValueError('Discount must be in [0, 1]')
    if r.ndim != 1 or x.shape != (len(r), 1) or done.shape != r.shape or done.dtype.kind != 'b':
        raise ValueError('Mismatched batch or non-boolean terminal flags')
    if not np.isfinite(r).all():
        raise ValueError('Finite rewards required')
    y = r.copy()
    live = ~done
    # Do not evaluate a terminal placeholder (which may be NaN).
    if live.any():
        y[live] += gamma * forward(target, x[live])[0].max(axis=1)
    return y


def transition(state, action):
    s, a = integer(state), integer(action)
    if s > 3 or a > 1:
        raise ValueError('Four states and two actions only')
    if a == 0:
        return .2, 0, True
    return (1., 0, True) if s == 3 else (0., s + 1, False)


def encode(states):
    return (np.asarray(states, dtype=float).reshape(-1, 1) - 1.5) / 1.5


def evaluate(p, gamma=.9):
    policy = forward(p, encode(range(4)))[0].argmax(axis=1).tolist()
    state, discount, total = 0, 1., 0.
    for _ in range(4):
        reward, state, done = transition(state, policy[state])
        total += discount * reward
        if done:
            return policy, total
        discount *= gamma
    raise AssertionError('This acyclic environment ends within four steps')


def scalar_trace(values, period=3, tau=.25):
    period = integer(period, 1)
    online = {'value': np.array([0.])}
    hard, soft = copy_network(online), copy_network(online)
    rows = []
    for count, value in enumerate(values, 1):
        if not math.isfinite(value):
            raise ValueError('Finite scalar required')
        # Values stand for online parameters AFTER this gradient update.
        online['value'][0] = value
        hard_before = float(hard['value'][0])
        soft_before = float(soft['value'][0])
        if count % period == 0:
            update_target(hard, online)
        update_target(soft, online, tau)
        rows.append(dict(update=count, online=value, hard_used=hard_before,
                         soft_used=soft_before, hard_next=float(hard['value'][0]),
                         soft_next=float(soft['value'][0])))
    return rows


def demo():
    online = network(4)
    target = copy_network(online)
    x = encode([0, 1, 2, 3])
    a, r, d = [1, 1, 1, 1], [0., 0., 0., 1.], [False, False, False, True]
    nx = encode([1, 2, 3, 0])
    fixed = targets(target, r, nx, d)
    before = forward(online, x)[0]
    loss, g = loss_gradient(online, x, a, fixed)
    for k in online:
        online[k] -= .05 * g[k]
    still_fixed = targets(target, r, nx, d)
    update_target(target, online)
    copied = targets(target, r, nx, d)
    return dict(scalar_trace=scalar_trace([1., 2., 3., 4., 5., 6.]),
                gamma=.9, tau_new_weight=.25, equivalent_rho_old_weight=.75,
                predictions_before=before.tolist(), predictions_after=forward(online, x)[0].tolist(),
                targets_before=fixed.tolist(), targets_after_online_step=still_fixed.tolist(),
                targets_after_copy=copied.tolist(), half_squared_loss_before=loss,
                half_squared_loss_after=loss_gradient(online, x, a, fixed)[0],
                terminal_target=float(copied[-1]))


if __name__ == '__main__':
    import json
    print(json.dumps(demo(), indent=2, allow_nan=False))

For the scalar example, the hard target used by updates 1–6 is[0,0,0,3,3,3]. The target left ready for the next update is[0,0,3,3,3,6]. With soft averaging, the successive ready values are 0.25,0.6875,1.265625,1.94921875,2.7119140625,3.533935546875. The distinction between “used now” and “ready next” prevents an off-by-one explanation of the copy interval.

For the network step, the four targets are unchanged after updating only the online network. After a hard copy, the three nonterminal targets change; the final terminal target stays 1. The half-squared loss against the original fixed targets falls from about 0.229677 to 0.204274. This is evidence about one step on one fixed batch, not convergence over continued training.

Tests compare all scalar averages with exact fractions, verify the hard-copy schedule, reject shared storage, check tau endpoints, and ensure that an invalid shape does not cause a partial update. Independent copies add O(P) persistent storage for P parameters; each synchronization costs O(P). Computing batch targets adds a target-network forward pass, roughly O(BP) for this small dense architecture. The scalar trace and printed network arrays add diagnostic storage only.

A slower mistake is still a mistake

Setting target = online copies a reference, not the arrays. Updating one then updates what both names see. A shallow dictionary copy has the same problem for its array values. The example copies each array and checks for same-parameter shared memory before synchronizing. Architecture, parameter shapes and ordering must agree as well.

A target that changes too slowly may keep stale estimates; a very rapid update can preserve much of the feedback the delay was intended to reduce. Neither hard copying nor averaging prevents errors from missing data, inappropriate rewards or bad state representations. Replay capacity, exploration, learning rate and target timing interact; tuning one knob does not prove that the others are sound. Scope of the original modification

Termination remains a separate issue. An actual terminal transition has no bootstrap contribution, regardless of target-network accuracy. A collector cutoff while the task continues should retain the actual next observation and allow bootstrapping; a genuinely finite-horizon task instead ends according to its own state and horizon. The code evaluates only nonterminal next inputs. Modern termination semantics

Finally, using a separate target network is not Double DQN by itself. The target here uses a maximum evaluated entirely by the target network. Selecting an action with the online network and evaluating that action with the target network is a different modification, which belongs in its own article.

Which value is used on this update?

  1. Old target=2, new online parameter=10, tau=0.25 weights the online value. Compute the next target and the equivalent old-weight coefficient rho.

Answer: The next target is 0.75×2+0.25×10=4 and rho=0.75. Using tau as the old weight would instead give 8, demonstrating why the symbol alone is insufficient.

  1. The target starts at 0. Online parameters after updates 1,2,3,4 are 1,2,3,4, with a hard copy after every third update. What targets are used by updates 3 and 4?

Answer: Update 3 uses 0 and then copies 3. Update 4 uses 3. Saying update 3 used 3 would move the synchronization before the update, contradicting the stated schedule.

  1. A target dictionary is made with dict(online), where the values are NumPy arrays. Why is the target not frozen?

Answer: The new dictionary still points to the same arrays. In-place changes to online parameters appear through both dictionaries. Copy array contents into independent storage; merely disabling a target gradient would not fix shared memory.

  1. For Y equally likely 1 or 3 and q=1, compare expected squared sample error with squared expected-target error. What does the difference imply for a fixed target network?

Answer: Expected sample error is(0²+2²)/2=2; squared expected-target error is(2−1)²=1. Their difference is variance 1. With the target distribution fixed, this variance does not depend on q, so both have the same derivative with respect to the online prediction. The identity does not make their loss values equal.

Read copying, differentiation and data separately

The 2015 DQN Methods provides the delayed-copy motivation and update, not a universal nonlinear convergence guarantee. The fixed Spinning Up implementation makes the soft-update coefficient, separate storage and stopped target gradients inspectable; our reading was limited to the recorded replay/target sections, with no full DDPG reproduction. The Farama article addresses the distinct question of when a transition should bootstrap. These sources answer different implementation questions and should not be reduced to one generic instruction to “stabilize training.”

Make a prediction, then check

An old target parameter is2, the new online value is10, and tau0.25 weights the new value. What is the updated target?

Choose one answer

Learning objectives

  • Separate the online gradient update from target synchronization and interpret the update clock.
  • Compute hard and soft target trajectories without aliasing the online network.

Prerequisites & connections

Explore related knowledge →

References

  1. Human-level control through deep reinforcement learning — scoped Methods reading
    Volodymyr Mnih; Koray Kavukcuoglu; David Silver; Andrei A. Rusu; Joel Veness; Marc G. Bellemare; Alex Graves; Martin Riedmiller; Andreas K. Fidjeland; Georg Ostrovski; Stig Petersen; Charles Beattie; Amir Sadik; Ioannis Antonoglou; Helen King; Dharshan Kumaran; Daan Wierstra; Shane Legg; Demis Hassabis · 2015
  2. Spinning Up: replay and target-network mechanisms at fixed commit
    OpenAI; Joshua Achiam and contributors · 2020
  3. Deep Dive: Gymnasium Step API
    The Farama Foundation · 2023

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 identity/abstract,6 left-column Methods and right-column evaluation,7; viewed7. Separate target network, uniform replay and stated training conditions only; score/extended tables not audited. Printed variance decomposition and gradient sign require independent correction; no general convergence claim or benchmark replication. Fixed2020-02-07 commit; read code1–52,145–230,255–280, full readme.md/MIT LICENSE, docs Q-learning-side section. Ring storage, replacement sampling, deepcopy, no_grad and Polyak convention. Old length-based done heuristic not copied. No upstream execution, source reuse or DDPG benchmark audit. Read full2023-10-27 article on API motivation, alternatives and theory. Terminal versus collection truncation and time-remaining state for finite-horizon tasks. No current installation or third-party tutorial audit performed. 6 paired equations and four explained exercises. Checked independent parameter storage, online-only semi-gradient, hard-copy after-update clock, tau/rho convention, Fraction-based Polyak recurrence, terminal target and variance identity. Prescribed scalar path is not a learning curve; one fixed-batch descent step is not a convergence proof.

  • Checked independent parameter storage, online-only semi-gradient, hard-copy after-update clock, tau/rho convention, Fraction-based Polyak recurrence, terminal target and variance identity. Prescribed scalar path is not a learning curve; one fixed-batch descent step is not a convergence proof.
  • Four computed SVG variants per topic;11 numeric/geometry tests and18 responsive cases passed. All six selected current captures directly viewed. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • Human-level control through deep reinforcement learning — scoped Methods reading · Read PDF1 identity/abstract,6 left-column Methods and right-column evaluation,7; viewed7. Separate target network, uniform replay and stated training conditions only; score/extended tables not audited. Printed variance decomposition and gradient sign require independent correction; no general convergence claim or benchmark replication.
  • Spinning Up: replay and target-network mechanisms at fixed commit · Fixed2020-02-07 commit; read code1–52,145–230,255–280, full readme.md/MIT LICENSE, docs Q-learning-side section. Ring storage, replacement sampling, deepcopy, no_grad and Polyak convention. Old length-based done heuristic not copied. No upstream execution, source reuse or DDPG benchmark audit.
  • Deep Dive: Gymnasium Step API · Read full2023-10-27 article on API motivation, alternatives and theory. Terminal versus collection truncation and time-remaining state for finite-horizon tasks. No current installation or third-party tutorial audit performed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.