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
MLP.forwardpasses 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.MLP.backwardtakes 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.QNetworkputs a linear head on the encoder that gives one value per action. Withdueling=Trueit has two heads, a state value and per-action advantages, and combines them.CategoricalPolicyoutputs logits.probs,sampleandlog_probread them through a softmax, andnll_lossreturns the loss with its gradient on the logits.GaussianPolicyoutputs the mean of a continuous action. Its log standard deviation is one learned vector shared by all states.Adamreadsparameters()andgradients()from any of these and updates the arrays in place when you callstep.
Watch out for
- Each network keeps only the activations of its last
forward. Callingbackwardafter a differentforwarduses the wrong activations and gives wrong gradients without any error. CategoricalPolicy.nll_lossreturns a gradient that you must pass tobackward, whileGaussianPolicy.nll_lossbackpropagates 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
| If | Use instead |
|---|---|
| Observations are images | A convolutional encoder, or a VAE as in the World Models vision lesson |
| The agent needs memory of earlier steps | A recurrent model, as in the World Models memory lesson |
| The state space is tiny | A table, as in Tabular Q-learning or SARSA |
Math foundations
One layer, forward
Each layer is a linear map followed by a nonlinearity. Rows of are batch items. Without a stack of layers would collapse into a single linear map.
One layer, backward
The chain rule for one layer. is the gradient arriving at the layer's output times the slope of the activation there: for tanh, and 1 or 0 for ReLU. The second expression is what gets handed to the layer below.
Dueling Q head
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 and .
Categorical policy and its gradient
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_lossscales it by the sample's weight, such as an advantage.Gaussian policy log-density
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.
Adam update
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 correct the averages for starting at zero.
Symbols
- output of layer l for a batch (h_0 is the input)
- weights and bias of layer l
- hidden activation, tanh or ReLU
- gradient of the loss at layer l before the activation
- the loss being minimized
- state value from the dueling head
- advantage of action a from the dueling head
- logit of discrete action k
- probability or density the policy gives action a in state s
- mean and standard deviation of action dimension d
- gradient of the loss for one parameter at update t
- running averages of the gradient and of its square
- learning rate
- Adam averaging rates (0.9 and 0.999) and a small constant
Worked by hand
Two small calculations. First, a dueling head outputs and advantages for two actions. Second, a categorical policy has logits and action 1 was taken.
The Q values average to , 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
- 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 and subtract it from every . The output does not change, so ask what the loss can tell the two heads about that constant.
- 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.
GaussianPolicylearns 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 is 0.01 versus 10.
- The hidden layers start with weights of spread for tanh and 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 random terms, then recall that ReLU sets about half of its inputs to zero.
- 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 in the update and simplify and after bias correction.