Sign in

Networks

Shared neural network modules for reinforcement learning

The small networks most RL agents share: an MLP encoder, a plain or dueling Q head, a categorical policy head, a Gaussian policy head, and the Adam optimizer.

Overview

Most RL agents are built from the same few parts. An encoder turns an observation into features. A head turns the features into what the algorithm needs: one value per action, a probability per discrete action, or the mean of a continuous action. Keeping the parts separate lets one encoder design serve many algorithms. In this template each part is written in plain NumPy with the backward pass done by hand, so you can read exactly how a loss on the output becomes a change to each weight.

A short history

These are standard building blocks gathered from several sources, not one invention. The multilayer perceptron trained by backpropagation dates to the 1980s. The Q head that outputs one value per action comes from DQN in 2013 and 2015, and the dueling head from Ziyu Wang and colleagues in 2016. Gaussian policy heads follow Ronald Williams's 1992 work on policy gradients. Adam, the optimiser nearly all deep RL code uses, was published by Diederik Kingma and Jimmy Ba in 2014.

How it works

  1. MLP.forward passes a batch through each layer: multiply by the weights, add the bias, apply tanh or ReLU. It keeps every layer's input and output for the backward pass.
  2. MLP.backward takes the gradient of the loss with respect to the output and walks the layers in reverse, storing a gradient for each weight and returning the gradient with respect to the input.
  3. QNetwork puts a linear head on the encoder that gives one value per action. With dueling=True it has two heads, a state value and per-action advantages, and combines them.
  4. CategoricalPolicy outputs logits. probs, sample and log_prob read them through a softmax, and nll_loss returns the loss with its gradient on the logits.
  5. GaussianPolicy outputs the mean of a continuous action. Its log standard deviation is one learned vector shared by all states.
  6. Adam reads parameters() and gradients() from any of these and updates the arrays in place when you call step.

Watch out for

  • Each network keeps only the activations of its last forward. Calling backward after a different forward uses the wrong activations and gives wrong gradients without any error.
  • CategoricalPolicy.nll_loss returns a gradient that you must pass to backward, while GaussianPolicy.nll_loss backpropagates by itself. Mixing up the two leaves stale gradients for Adam to apply.
  • The Gaussian head has one standard deviation for all states, so it cannot be cautious in one state and bold in another. Tasks that need that require a state-dependent head.
  • The encoder is an MLP over flat vectors. On images it ignores which pixels are neighbours and needs far more data than a convolutional encoder would.

Use cases

When to use it

Use these as the function approximators of a NumPy agent on vector observations (DQN, policy gradient, actor-critic), or as a reference to check a framework's heads against. Choose the dueling head when many actions have similar values in most states.

In industry

Robotics
A small MLP with a Gaussian policy head maps joint readings to motor commands in most continuous control agents.
Games and simulation
An encoder followed by a Q head or a categorical policy head chooses among a fixed set of game actions.
Research and teaching
Reusing the same encoder and heads across DQN, A2C, PPO and SAC keeps comparisons between algorithms fair.

Choosing it: what must hold

  • Observations that are fixed-length vectors of modest size, which is what an MLP encoder expects.
  • A head that matches the action space: Q or categorical for discrete actions, Gaussian for continuous actions.
  • Inputs scaled to a sensible range, since unnormalised observations slow or break training.

When to choose something else

IfUse instead
Observations are imagesA convolutional encoder, or a VAE as in the World Models vision lesson
The agent needs memory of earlier stepsA recurrent model, as in the World Models memory lesson
The state space is tinyA table, as in Tabular Q-learning or SARSA

Math foundations

  1. One layer, forward

    hl=φ(hl−1Wl+bl)h_l = \varphi\big(h_{l-1} W_l + b_l\big)

    Each layer is a linear map followed by a nonlinearity. Rows of hh are batch items. Without φ\varphi a stack of layers would collapse into a single linear map.

  2. One layer, backward

    ∂L∂Wl=hl−1⊤ δl,∂L∂hl−1=δl Wl⊤,δl=∂L∂hl⊙φl′\frac{\partial L}{\partial W_l} = h_{l-1}^{\top} \, \delta_l, \qquad \frac{\partial L}{\partial h_{l-1}} = \delta_l \, W_l^{\top}, \qquad \delta_l = \frac{\partial L}{\partial h_l} \odot \varphi'_l

    The chain rule for one layer. δl\delta_l is the gradient arriving at the layer's output times the slope of the activation there: 1−hl21 - h_l^2 for tanh, and 1 or 0 for ReLU. The second expression is what gets handed to the layer below.

  3. Dueling Q head

    Q(s,a)=V(s)+A(s,a)−1∣A∣∑a′A(s,a′)Q(s, a) = V(s) + A(s, a) - \frac{1}{|\mathcal{A}|} \sum_{a'} A(s, a')

    The value says how good the state is and the advantage says how much better one action is than the others. Subtracting the mean advantage makes the split unique. Otherwise a constant could move freely between VV and AA.

  4. Categorical policy and its gradient

    π(a∣s)=eza∑bezb,∂∂zk(−log⁡π(a∣s))=π(k∣s)−1[k=a]\pi(a \mid s) = \frac{e^{z_a}}{\sum_{b} e^{z_b}}, \qquad \frac{\partial}{\partial z_k}\big(-\log \pi(a \mid s)\big) = \pi(k \mid s) - \mathbb{1}[k = a]

    A softmax over the logits gives action probabilities. The gradient of the negative log-likelihood is the probabilities minus a one-hot vector of the action taken. nll_loss scales it by the sample's weight, such as an advantage.

  5. Gaussian policy log-density

    log⁡π(a∣s)=∑d[−(ad−μd(s))22σd2−log⁡σd−12log⁡2π]\log \pi(a \mid s) = \sum_{d} \left[ -\frac{(a_d - \mu_d(s))^{2}}{2 \sigma_d^{2}} - \log \sigma_d - \tfrac{1}{2} \log 2\pi \right]

    Each action dimension is an independent normal around the network's mean. Raising this for actions that turned out well moves the mean toward them and adjusts the spread.

  6. Adam update

    mt=β1mt−1+(1−β1)gt,vt=β2vt−1+(1−β2)gt2,θt=θt−1−η mt/(1−β1t)vt/(1−β2t)+ϵm_t = \beta_1 m_{t-1} + (1 - \beta_1) g_t, \quad v_t = \beta_2 v_{t-1} + (1 - \beta_2) g_t^{2}, \quad \theta_t = \theta_{t-1} - \eta \, \frac{m_t / (1 - \beta_1^{t})}{\sqrt{v_t / (1 - \beta_2^{t})} + \epsilon}

    Adam keeps a running mean of the gradient and of its square. The step is the mean divided by the root of the mean square, so every weight moves at a similar rate whatever the raw size of its gradient. The divisions by 1−βt1 - \beta^{t} correct the averages for starting at zero.

Symbols

hlh_l
output of layer l for a batch (h_0 is the input)
Wl,  blW_l,\; b_l
weights and bias of layer l
φ\varphi
hidden activation, tanh or ReLU
δl\delta_l
gradient of the loss at layer l before the activation
LL
the loss being minimized
V(s)V(s)
state value from the dueling head
A(s,a)A(s, a)
advantage of action a from the dueling head
zkz_k
logit of discrete action k
π(a∣s)\pi(a \mid s)
probability or density the policy gives action a in state s
μd(s),  σd\mu_d(s),\; \sigma_d
mean and standard deviation of action dimension d
gtg_t
gradient of the loss for one parameter at update t
mt,  vtm_t,\; v_t
running averages of the gradient and of its square
η\eta
learning rate
β1,  β2,  ϵ\beta_1,\; \beta_2,\; \epsilon
Adam averaging rates (0.9 and 0.999) and a small constant

Worked by hand

Two small calculations. First, a dueling head outputs V=2V = 2 and advantages (1,3)(1, 3) for two actions. Second, a categorical policy has logits (0,ln⁡3)(0, \ln 3) and action 1 was taken.

Aˉ=(1+3)/2=2\bar{A} = (1 + 3) / 2 = 2
Q=(2+1−2,  2+3−2)=(1,  3)Q = \big(2 + 1 - 2,\; 2 + 3 - 2\big) = (1,\; 3)
π=(11+3,  31+3)=(0.25,  0.75)\pi = \left(\frac{1}{1 + 3},\; \frac{3}{1 + 3}\right) = (0.25,\; 0.75)
−log⁡π(1)=−ln⁡0.75=0.2877-\log \pi(1) = -\ln 0.75 = 0.2877
∇z=(0.25−0,  0.75−1)=(0.25,  −0.25)\nabla_z = (0.25 - 0,\; 0.75 - 1) = (0.25,\; -0.25)

The Q values average to VV, as the dueling formula guarantees. A gradient step lowers the logit of action 0 and raises that of action 1, making the action that was taken more likely.

Visual example

Loading the example.

Try this

  • Click each box to read what that stage outputs for the current observation.
  • Choose took a2 and press Ten steps: π(a2) grows, and the Q values move too because the encoder is shared.
  • Drag the observation sliders and check that the mean of Q always equals V.

Code sample

import numpy as np
from impl import Adam, QNetwork
from config import NetworksConfig

cfg = NetworksConfig(obs_dim=3, action_dim=2, hidden_sizes=(16,), dueling=True)
net = QNetwork(cfg)
opt = Adam(net, cfg.learning_rate)                # updates the network's arrays in place
obs, target = np.ones((5, 3)), np.zeros((5, 2))
for _ in range(100):
    q = net.forward(obs)                       # (5, 2)
    net.backward((q - target) / len(obs))      # gradient of 0.5 * mean squared error
    opt.step()
Read the implementation (239 lines)
"""Shared RL networks in NumPy: MLP encoder, Q head (plain or dueling), categorical and Gaussian policy heads.

Backpropagation is written by hand. Each network keeps the activations of its last `forward` call, so call
`backward` right after the `forward` it belongs to. `parameters()` and `gradients()` return matching lists of
arrays, which is all `Adam` needs.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import NetworksConfig
except ImportError:  # run from the template's own folder
    from config import NetworksConfig


class MLP:
    """Fully connected network. Hidden layers use the activation; the output layer does too if asked."""

    def __init__(self, sizes, activation: str = "tanh", activate_output: bool = False, rng=None) -> None:
        """sizes: layer widths from input to output, e.g. (4, 32, 2). rng: generator for the initial weights."""
        rng = rng or np.random.default_rng(0)
        self.activation = activation
        self.activate_output = activate_output
        self.weights, self.biases = [], []
        for n_in, n_out in zip(sizes[:-1], sizes[1:]):
            scale = math.sqrt(2.0 / n_in) if activation == "relu" else math.sqrt(1.0 / n_in)
            self.weights.append(rng.normal(0.0, scale, size=(n_in, n_out)))
            self.biases.append(np.zeros(n_out))
        self.grad_weights = [np.zeros_like(w) for w in self.weights]
        self.grad_biases = [np.zeros_like(b) for b in self.biases]
        self._inputs: list[np.ndarray] = []
        self._outputs: list[np.ndarray] = []

    def _is_activated(self, layer: int) -> bool:
        return layer < len(self.weights) - 1 or self.activate_output

    def forward(self, x: np.ndarray) -> np.ndarray:
        """x: shape (batch, sizes[0]) -> shape (batch, sizes[-1])."""
        self._inputs, self._outputs = [], []
        h = np.asarray(x, dtype=float)
        for i, (w, b) in enumerate(zip(self.weights, self.biases)):
            self._inputs.append(h)
            h = h @ w + b
            if self._is_activated(i):
                h = np.tanh(h) if self.activation == "tanh" else np.maximum(h, 0.0)
            self._outputs.append(h)
        return h

    def backward(self, grad_output: np.ndarray) -> np.ndarray:
        """Backpropagate dLoss/dOutput (batch, sizes[-1]); stores weight gradients, returns dLoss/dInput."""
        g = np.asarray(grad_output, dtype=float)
        for i in reversed(range(len(self.weights))):
            if self._is_activated(i):
                out = self._outputs[i]
                g = g * (1.0 - out**2) if self.activation == "tanh" else g * (out > 0.0)
            self.grad_weights[i] = self._inputs[i].T @ g
            self.grad_biases[i] = g.sum(axis=0)
            g = g @ self.weights[i].T
        return g

    def parameters(self) -> list[np.ndarray]:
        return self.weights + self.biases

    def gradients(self) -> list[np.ndarray]:
        return self.grad_weights + self.grad_biases


class Adam:
    """Adam optimizer over anything with `parameters()` and `gradients()`; updates the arrays in place."""

    def __init__(self, module, learning_rate: float = 1e-3, beta1: float = 0.9, beta2: float = 0.999, eps: float = 1e-8) -> None:
        self.module = module
        self.lr, self.beta1, self.beta2, self.eps = learning_rate, beta1, beta2, eps
        self.m = [np.zeros_like(p) for p in module.parameters()]
        self.v = [np.zeros_like(p) for p in module.parameters()]
        self.t = 0

    def step(self) -> None:
        """Apply one update using the gradients stored by the module's last `backward`."""
        self.t += 1
        for p, g, m, v in zip(self.module.parameters(), self.module.gradients(), self.m, self.v):
            m *= self.beta1
            m += (1.0 - self.beta1) * g
            v *= self.beta2
            v += (1.0 - self.beta2) * g * g
            m_hat = m / (1.0 - self.beta1**self.t)
            v_hat = v / (1.0 - self.beta2**self.t)
            p -= self.lr * m_hat / (np.sqrt(v_hat) + self.eps)


def _encoder(config: NetworksConfig, rng) -> MLP:
    return MLP((config.obs_dim, *config.hidden_sizes), config.activation, activate_output=True, rng=rng)


class QNetwork:
    """Encoder plus a Q head: observations (batch, obs_dim) -> action values (batch, action_dim)."""

    def __init__(self, config: NetworksConfig | None = None) -> None:
        self.config = config or NetworksConfig()
        rng = np.random.default_rng(self.config.seed)
        feat = self.config.hidden_sizes[-1]
        self.encoder = _encoder(self.config, rng)
        self.advantage = MLP((feat, self.config.action_dim), rng=rng)  # the whole Q head when not dueling
        self.value = MLP((feat, 1), rng=rng) if self.config.dueling else None

    def forward(self, obs: np.ndarray) -> np.ndarray:
        feat = self.encoder.forward(obs)
        adv = self.advantage.forward(feat)
        if self.value is None:
            return adv
        self.state_value = self.value.forward(feat)  # (batch, 1), kept for inspection
        return self.state_value + adv - adv.mean(axis=1, keepdims=True)

    def backward(self, grad_q: np.ndarray) -> np.ndarray:
        """grad_q: dLoss/dQ, shape (batch, action_dim). Returns dLoss/dObs."""
        grad_q = np.asarray(grad_q, dtype=float)
        if self.value is None:
            return self.encoder.backward(self.advantage.backward(grad_q))
        grad_adv = grad_q - grad_q.mean(axis=1, keepdims=True)
        grad_feat = self.advantage.backward(grad_adv) + self.value.backward(grad_q.sum(axis=1, keepdims=True))
        return self.encoder.backward(grad_feat)

    def greedy_action(self, obs: np.ndarray) -> np.ndarray:
        """Best action per row, shape (batch,)."""
        return self.forward(obs).argmax(axis=1)

    def parameters(self) -> list[np.ndarray]:
        extra = self.value.parameters() if self.value is not None else []
        return self.encoder.parameters() + self.advantage.parameters() + extra

    def gradients(self) -> list[np.ndarray]:
        extra = self.value.gradients() if self.value is not None else []
        return self.encoder.gradients() + self.advantage.gradients() + extra


class CategoricalPolicy:
    """Encoder plus logits over discrete actions."""

    def __init__(self, config: NetworksConfig | None = None) -> None:
        self.config = config or NetworksConfig()
        rng = np.random.default_rng(self.config.seed)
        self.encoder = _encoder(self.config, rng)
        self.head = MLP((self.config.hidden_sizes[-1], self.config.action_dim), rng=rng)
        self.rng = np.random.default_rng(self.config.seed + 1)

    def forward(self, obs: np.ndarray) -> np.ndarray:
        """Logits, shape (batch, action_dim)."""
        return self.head.forward(self.encoder.forward(obs))

    def backward(self, grad_logits: np.ndarray) -> np.ndarray:
        return self.encoder.backward(self.head.backward(grad_logits))

    def log_probs(self, obs: np.ndarray) -> np.ndarray:
        """Log probability of every action, shape (batch, action_dim)."""
        z = self.forward(obs)
        z = z - z.max(axis=1, keepdims=True)
        return z - np.log(np.exp(z).sum(axis=1, keepdims=True))

    def probs(self, obs: np.ndarray) -> np.ndarray:
        return np.exp(self.log_probs(obs))

    def log_prob(self, obs: np.ndarray, actions: np.ndarray) -> np.ndarray:
        """Log probability of the given actions (batch,) under the policy, shape (batch,)."""
        actions = np.asarray(actions, dtype=int)
        return self.log_probs(obs)[np.arange(len(actions)), actions]

    def sample(self, obs: np.ndarray) -> np.ndarray:
        """Draw one action per row, shape (batch,)."""
        p = self.probs(obs)
        u = self.rng.random((len(p), 1))
        return np.minimum((p.cumsum(axis=1) < u).sum(axis=1), p.shape[1] - 1)

    def nll_loss(self, obs: np.ndarray, actions: np.ndarray, weights: np.ndarray | None = None):
        """Weighted negative log-likelihood and its gradient with respect to the logits.

        loss = -mean_b weights_b * log pi(actions_b | obs_b). With weights = advantages this is the policy-gradient
        loss; with weights = 1 it is behaviour cloning. Returns (loss, grad_logits); pass grad_logits to `backward`.
        """
        actions = np.asarray(actions, dtype=int)
        w = np.ones(len(actions)) if weights is None else np.asarray(weights, dtype=float)
        log_p = self.log_probs(obs)
        rows = np.arange(len(actions))
        grad = np.exp(log_p)
        grad[rows, actions] -= 1.0
        return float(-(w * log_p[rows, actions]).mean()), grad * w[:, None] / len(actions)

    def parameters(self) -> list[np.ndarray]:
        return self.encoder.parameters() + self.head.parameters()

    def gradients(self) -> list[np.ndarray]:
        return self.encoder.gradients() + self.head.gradients()


class GaussianPolicy:
    """Encoder plus an action mean; the log standard deviation is one learned vector shared by all states."""

    def __init__(self, config: NetworksConfig | None = None) -> None:
        self.config = config or NetworksConfig()
        rng = np.random.default_rng(self.config.seed)
        self.encoder = _encoder(self.config, rng)
        self.head = MLP((self.config.hidden_sizes[-1], self.config.action_dim), rng=rng)
        self.log_std = np.full(self.config.action_dim, self.config.init_log_std, dtype=float)
        self.grad_log_std = np.zeros_like(self.log_std)
        self.rng = np.random.default_rng(self.config.seed + 1)

    def forward(self, obs: np.ndarray) -> np.ndarray:
        """Action mean, shape (batch, action_dim)."""
        return self.head.forward(self.encoder.forward(obs))

    def sample(self, obs: np.ndarray) -> np.ndarray:
        """mean + std * N(0, 1), shape (batch, action_dim)."""
        mean = self.forward(obs)
        return mean + np.exp(self.log_std) * self.rng.standard_normal(mean.shape)

    def log_prob(self, obs: np.ndarray, actions: np.ndarray) -> np.ndarray:
        """Log density of `actions` (batch, action_dim), summed over action dimensions, shape (batch,)."""
        z = (np.asarray(actions, dtype=float) - self.forward(obs)) / np.exp(self.log_std)
        return (-0.5 * z**2 - self.log_std - 0.5 * math.log(2.0 * math.pi)).sum(axis=1)

    def nll_loss(self, obs: np.ndarray, actions: np.ndarray, weights: np.ndarray | None = None) -> float:
        """loss = -mean_b weights_b * log pi(actions_b | obs_b); also backpropagates it, filling every gradient."""
        actions = np.asarray(actions, dtype=float)
        w = np.ones(len(actions)) if weights is None else np.asarray(weights, dtype=float)
        std = np.exp(self.log_std)
        z = (actions - self.forward(obs)) / std
        log_p = (-0.5 * z**2 - self.log_std - 0.5 * math.log(2.0 * math.pi)).sum(axis=1)
        scale = w[:, None] / len(actions)
        self.grad_log_std = (scale * (1.0 - z**2)).sum(axis=0)
        self.encoder.backward(self.head.backward(-scale * z / std))
        return float(-(w * log_p).mean())

    def parameters(self) -> list[np.ndarray]:
        return self.encoder.parameters() + self.head.parameters() + [self.log_std]

    def gradients(self) -> list[np.ndarray]:
        return self.encoder.gradients() + self.head.gradients() + [self.grad_log_std]
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
10, run with python3 -m unittest -v

Practice

Build QNetwork(NetworksConfig(obs_dim=3, action_dim=2, hidden_sizes=(16,), dueling=True)) with an Adam optimizer and fit it to a zero target on five observations, as in the template's usage example, printing the loss as it falls. Then check backward numerically: nudge one entry of net.parameters()[0] by a small amount, recompute the loss, and compare the change with the matching entry of net.gradients()[0].

Check on learning

  1. In a dueling head, what would happen during training if the mean advantage were not subtracted?
    A way to think about it

    Add a constant to VV and subtract it from every AA. The output QQ does not change, so ask what the loss can tell the two heads about that constant.

  2. The gradient of the categorical loss is probabilities minus a one-hot vector. If the policy already gives the chosen action probability 0.99, how large is the gradient, and what does that imply late in training?
    A way to think about it

    Write out the gradient for that case and compare it with the case where the chosen action has probability 0.1.

  3. GaussianPolicy learns the log of the standard deviation, not the standard deviation itself. What problems does that avoid?
    A way to think about it

    Consider what an unconstrained gradient step could do to a parameter that must stay positive, and how step sizes compare when σ\sigma is 0.01 versus 10.

  4. The hidden layers start with weights of spread 1/nin\sqrt{1/n_{\text{in}}} for tanh and 2/nin\sqrt{2/n_{\text{in}}} for ReLU. Why should the spread depend on the layer's width and on the activation?
    A way to think about it

    Estimate the variance of a sum of ninn_{\text{in}} random terms, then recall that ReLU sets about half of its inputs to zero.

  5. On the first Adam step, how large is the change to a weight, whatever the size of its gradient? What does this say about choosing the learning rate?
    A way to think about it

    Set t=1t = 1 in the update and simplify m1m_1 and v1v_1 after bias correction.