Networks and the PID policy¶
An agent's networks are set by its constructor: the hidden layers as a tuple of strings, initialisers by name, optional normalisation and an image encoder. The actor can also be a PID controller whose gains the agent learns.
Hidden layers¶
An architecture is a tuple read left to right. A number adds a dense layer of that width; a name adds an activation:
from ajax import PPO
agent = PPO(
"CartPole-v1",
n_envs=8,
n_steps=128,
actor_architecture=("64", "tanh", "64", "tanh"),
critic_architecture=("256", "relu", "256", "relu"),
encoder_kernel_init="orthogonal(np.sqrt(2))", # the hidden layers' kernels
critic_bias_init="0.0", # a number gives a constant initialiser
encoder_layer_norm=True, # a LayerNorm after the hidden layers
)
state, _ = agent.train(seed=0, n_timesteps=2_048)
- Activations:
relu,tanh,leaky_relu,swish,siluandmish, or a callable. Another name is refused when training starts, with that list. "layernorm"adds a LayerNorm where it stands, so("256", "layernorm", "relu", "256", "layernorm", "relu")is RLPD's critic (Ball et al., 2023).- Widths alone, as SB3's
net_arch=[64, 64], leave the layers without an activation between them; Ajax warns and shows the tuple to write. - The output heads come after the hidden layers: the policy's mean and
standard deviation, the value, the Q-values. DQN and PQN take a single
architecturefor their Q-network.
print(agent) shows the arguments that differ from their defaults, so a
setting that did not reach the agent is missing from it.
Each agent's default follows its paper or reference implementation. The table gives the actor's (DQN's and PQN's Q-network's); the critics have the same layers, but TQC's, which have three of 512 units:
| Default | Agents |
|---|---|
("256", "relu", "256", "relu") |
SAC, ASAC, RVI-SAC, REDQ, TQC, TD3, IQL |
("256", "leaky_relu", "256", "leaky_relu") |
AVG |
("64", "tanh", "64", "tanh") |
PPO, APO, REINFORCE |
("32", "tanh", "32", "tanh") |
DAgger |
("128", "relu", "128", "relu") |
PQN, UDRL, APG (its controller) |
("120", "relu", "84", "relu") |
DQN |
CrossQ sets its widths with actor_width and critic_width, and DreamerV3
and TD-MPC2 build their own networks to their papers' specifications: see
their pages and World models.
Initialisers¶
Each agent starts its layers as its reference code does, and its page says
how: SAC's from Glorot-uniform, as haarnoja/sac; PPO's hidden layers from
orthogonal(np.sqrt(2)) and its policy's output layer from
orthogonal(0.01), a near-zero first mean, as ppo2. A layer neither the
agent nor you set starts from orthogonal(1.0), its bias from zero.
Initialisers are named by string:
"orthogonal(0.01)","lecun_uniform", or any other factory inflax.linen.initializers, with its argument in brackets (np,jnpandmathmay appear in it, as in"orthogonal(np.sqrt(2))");"zeros","trunc_normal_fan_in(1.0)"(DreamerV3's initialiser) and"symmetric_uniform(3e-3)", uniform in±3e-3;"torch_linear"for a kernel: the layer starts as torch'snn.Lineardoes, its kernel and its bias both uniform in±1/sqrt(fan_in), the fan-in being the layer's input width (so it takes no bias initialiser);- a number such as
"0.0"or"-1.0", for a constant.
PPO and APO take three of them: encoder_kernel_init for the hidden
layers' kernels, actor_bias_init for the policy head's bias and
critic_bias_init for the value head's. PPO also takes mean_kernel_init
(below).
Layer normalisation¶
The hidden layers form an encoder that the output heads read.
encoder_layer_norm=True adds a LayerNorm on its output. It is off by
default, because the SAC, TD3, PPO and DQN papers use plain MLPs. PPO takes
it as an argument. SAC, ASAC, REDQ, APO and DQN, and TD3's critics (not its
actor), read it from the network configuration, which you can set before
training:
from ajax import SAC
agent = SAC("Pendulum-v1", learning_starts=500)
agent.network_args = agent.network_args.replace(encoder_layer_norm=True)
state, _ = agent.train(seed=0, n_timesteps=1_000)
UDRL turns it on for its policy, and APG's controller always has one on its encoder. PQN puts one after every hidden layer, and AVG normalises its penultimate features instead, as their papers do, whatever the setting.
Layers per head¶
By default the output layers read the encoder's features, or the memory's,
directly. head_architecture puts hidden layers in between, written as
actor_architecture is. Each network gets its own copy, and so does each
critic of an ensemble; with a shared encoder, the actor and the critic
separate after it. head_kernel_init sets their initialiser; None uses
the encoder's. Recurrent PPO sets PureJaxRL's by default
(A shared encoder); the other actor-critic agents read
it from the network configuration:
from ajax import SAC
from ajax.networks.memory import MemoryConfig
agent = SAC("Pendulum-v1", memory=MemoryConfig("gru", 32), learning_starts=500)
agent.network_args = agent.network_args.replace(head_architecture=("64", "relu"))
DQN's, PQN's and APG's networks do not read it yet, and a PID policy, which has no hidden layers, gets no head layers.
The policy head¶
PPO exposes the policy head's options:
| Argument | Default (PPO) | Effect |
|---|---|---|
log_std_state_independent |
True |
one learned log standard deviation per action dimension; False computes it from the observation |
log_std_init |
0.0 |
the initial log standard deviation |
log_std_bounds |
None |
the (low, high) clip of the log standard deviation, whichever head (or PID policy) learns it, low < high (the agent, its network config and the actor refuse others); None leaves it unclipped |
mean_kernel_init |
None: orthogonal(0.01), a near-zero first mean |
the initialiser of the mean's output layer |
squash |
False |
tanh on the sampled action, with the matching log-probability correction (Squashing) |
PPO's defaults are its reference codes' head: a standard deviation of 1 to
start, never clipped, whatever the observation (OpenAI Baselines at
ea25b9e, ppo2's common/distributions.py:96-106 and ppo1's
ppo1/mlp_policy.py:36-39 with gaussian_fixed_var=True; CleanRL at
fe8d8a0, ppo_continuous_action.py:129; PureJaxRL at 31756b1,
ppo_continuous_action.py:41). log_std_state_independent=False with
log_std_init=-1.0 builds SAC's head instead, which
log_std_bounds=(-20.0, 2.0) clips as SAC's is.
APO sets its reference code's head (xtma/apo, built on the authors' rlpyt
fork): PPO's, around a mean passed through tanh (tanh_mean), with an
unsquashed sample and a lecun_uniform mean layer. IQL clips its log
standard deviation to (-5.0, 2.0) and DAgger leaves it unclipped, as
their reference codes do; the other agents clip theirs, a PID policy's
included, to (-20.0, 2.0).
Squashing¶
SAC, TQC, RVI-SAC, CrossQ, TD3, REDQ, ASAC, AVG and UDRL's continuous
policy, and PPO's with squash=True, act through tanh, which keeps
actions in [-1, 1]. The squashing is one wrapper, not an option of each
head: Squashed(actor) wraps any actor, and its policy is squash(pi) of
the actor's: Squash(pi) for a distribution, tanh of the action for
TD3's deterministic one. Squashed shares the actor's parameters, so they
are saved and read under the same names as the actor's alone.
Squash (in ajax.networks.distributions) takes any distrax distribution,
its latent, pi.distribution. Sampling and log-probabilities are exact.
log_prob(action) inverts tanh, which float32 cannot do once the action
rounds to ±1, so log_prob_from_raw(raw) reads the pre-tanh sample
instead, as a squashed PPO does. Two quantities have no closed form:
mean() is tanh of the latent's mean, the action the agent evaluates
with, and entropy(seed) a one-sample estimate (the latent's entropy plus
the tanh log-det-Jacobian at a sample), as brax's. The functions
latent, sample_with_raw, log_prob_from_raw and entropy read any
policy, squashed or not.
Image observations¶
PPO, DQN, PQN and UDRL can read images through a convolutional encoder.
Ajax flattens image observations, so give the image's shape
(height, width, channels) as cnn_image_shape; the encoder reshapes the
flat vector back. cnn_extra_obs_dim counts extra scalar entries after the
image, which join the image features after the convolutions. cnn_spec
sets the convolutions:
from ajax import PQN
from ajax.networks.networks import CNNSpec
# MinAtar observations are 10 x 10 images with 4 channels.
agent = PQN(
"Breakout-MinAtar",
cnn_image_shape=(10, 10, 4),
cnn_spec=CNNSpec(channels=(16, 32), kernel_sizes=(3, 3), strides=(1, 1), feature_dim=128),
)
state, _ = agent.train(seed=0, n_timesteps=2_048)
DQN and PQN default to their reference codes' networks (see their pages),
PPO and UDRL to CNNSpec():
CNNSpec field |
Default | Meaning |
|---|---|---|
channels, kernel_sizes, strides |
(16, 32), (4, 3), (2, 2) |
the ReLU convolutions |
feature_dim |
128 |
the dense layer after them |
padding |
"SAME" |
flax's padding ("VALID" for none) |
layer_norm |
False |
a LayerNorm after every layer, before its ReLU |
kernel_init |
None |
the initialiser of every layer, named as the network's other *_kernel_init settings are; None is flax's default |
The image is read in height, width, channels order. On a gymnax
environment, a cnn_image_shape other than the environment's raises an
error, and leaving it out warns that an MLP reads the flattened image.
A shared encoder¶
By default the actor and the critic each have their own encoder: the
hidden layers, or the CNN, and the memory block if there is one.
share_encoder=True gives them one. The actor and the critic then differ
only in their output layers, as in ppo2's shared network:
from ajax import PPO
agent = PPO("CartPole-v1", share_encoder=True, n_envs=2, n_steps=16, batch_size=16)
state, _ = agent.train(seed=0, n_timesteps=64)
- Who owns it. The critic, whose optimiser steps it at
critic_learning_rate. The actor keeps a copy, which the training loop refreshes after every update and every critic step. - PPO and APO train it with both losses: its gradient is the sum of the
value loss's and the policy loss's, as in one network trained down the
summed loss. One encoder needs one architecture:
actor_architectureandcritic_architecturemust be equal (a CNN replaces both). - The off-policy agents (SAC, TD3, REDQ, TQC, ASAC, RVI-SAC, AVG, IQL)
train it with the critic's loss alone; the actor reads it without a
gradient, as SAC-AE, DrQ and SB3's
share_features_extractordo. The encoder isactor_architecture: the actor's heads read its features, and the critic'scritic_architecturelayers read them with the action. A target actor (TD3's) reads the target critic's encoder, and IQL's state value keeps an encoder of its own. - Cloning pretraining (
CloningPretrain) trains the encoder too, and hands it back to the critic. - With memory, the off-policy agents share the input embeddings and the
memory block too, as Ni et al. (2022)'s shared recurrent network does.
They read the observation, the previous action and the previous reward,
which a run with memory observes (
PreviousAction(),PreviousReward(); Memory); each network keeps its own shortcut and layers after the memory, and the action the critic is asked about joins there. A target actor (TD3's) warms its memory up through the target critic's. - Not yet: CrossQ, whose batch renormalisation would have both networks' training passes move the shared encoder's running statistics.
share_encoder=None, the default, does what the agent's reference code
does:
| Agent | MLP | Image (CNN) | Memory |
|---|---|---|---|
| PPO | separate (ppo2 on MuJoCo, CleanRL, PureJaxRL) | shared (ppo2 on Atari, CleanRL) | separate, a layer per head (see below) |
| APO | separate (its rlpyt model) | - | - |
| SAC, TD3, REDQ, TQC, ASAC, RVI-SAC, AVG, IQL | separate (each reference) | - | separate (Ni et al. 2022) |
ppo2 also shares MLP networks outside MuJoCo; Ajax keeps them apart, as its MuJoCo setting does. With memory, ppo2 and PureJaxRL share the encoder and the memory block, and PureJaxRL gives each head a Dense(128) and a ReLU of its own after the memory, orthogonal with gain 2. Recurrent PPO has those layers by default (layers per head) but keeps separate memories: with one, it fails the memory probe (CartPole with the velocities hidden, as in Memory), even with normalised rewards, while separate memories pass it.
The PID policy¶
Many control tasks are run by PID controllers, which engineers can read, tune and certify. The PID policy makes the actor such a controller: its action is
where e, I and D are the tracking error, its integral and its
difference, which the PIDTermsInput
feature appends to the observation. The agent learns the gains. Pass a
PIDPolicy as the actor_architecture of SAC, TD3, REDQ, TQC, ASAC,
RVI-SAC, AVG, IQL, PPO or APO:
import jax
import jax.numpy as jnp
from flax import struct
from gymnax.environments import environment, spaces
from ajax import SAC
from ajax.extensions.observe import PIDTermsInput
from ajax.modules.pid_actor import PIDPolicy, pid_gains
@struct.dataclass
class State(environment.EnvState):
x: jax.Array # the controlled value
r: jax.Array # its set-point
@struct.dataclass
class Params(environment.EnvParams):
max_steps_in_episode: int = 10
class Setpoint(environment.Environment):
"""An integrator, x <- x + 4u, that must reach a random set-point r."""
@property
def default_params(self):
return Params()
def reset_env(self, key, params):
r = jax.random.uniform(key, minval=-1.0, maxval=1.0)
state = State(time=0, x=jnp.float32(0.0), r=r)
return self.get_obs(state), state
def step_env(self, key, state, action, params):
x = state.x + 4.0 * jnp.clip(action[0], -1.0, 1.0)
state = state.replace(x=x, time=state.time + 1)
return self.get_obs(state), state, -((state.r - x) ** 2), jnp.array(False), {}
def get_obs(self, state, params=None, key=None):
return jnp.stack([state.x, state.r])
def observation_space(self, params):
return spaces.Box(-jnp.inf, jnp.inf, (2,))
def action_space(self, params):
return spaces.Box(-1.0, 1.0, (1,))
# The observation becomes [x, r, e, I, D], with e = r - x.
terms = PIDTermsInput(current_idx=(0,), target_idx=(1,), dt=1.0)
agent = SAC(
Setpoint(),
extensions=(terms,),
env_params=Params(),
n_envs=4,
actor_architecture=PIDPolicy(n_errors=1, gains="fixed"),
critic_architecture=("64", "relu", "64", "relu"),
actor_learning_rate=3e-3,
critic_learning_rate=1e-3,
gamma=0.9,
learning_starts=500,
)
state, _ = agent.train(seed=[0, 1], n_timesteps=4_000, num_episode_test=4)
gains = pid_gains(state.actor_state.params) # {"kp", "ki", "kd"}, one value per seed
print({name: value.squeeze() for name, value in gains.items()})
The best controller here is Kp = 1/4, Ki = Kd = 0, which reaches the
set-point in one step; the repository's tests check that SAC and PPO find
it with longer training.
PIDPolicy(n_errors=1, gains="fixed", architecture=()) has two kinds of
gains:
gains |
The gains | Reading them |
|---|---|---|
"fixed" |
the actor's only parameters: a linear map with no bias and no hidden layer. The trained policy deploys as a plain PID (Lawrence et al., 2022, tune PID gains with reinforcement learning the same way) | pid_gains(params), in the agent's units (below) |
"observation" |
predicted from the observation by an MLP of architecture, as gain scheduling does |
PIDActor(policy, action_dim).apply(params, obs, method="gains"), an array of shape (..., 3, action_dim, n_errors); a squashed PID actor's parameters are the same |
- Errors.
n_errorsis the number of errors the feature tracks; with several, each action dimension gets its own gain on each error. - The start. The gains start at zero: the untrained controller commands the centre of the action box, which is no action on a symmetric box.
- Exploration. The stochastic agents explore with a learned standard
deviation that does not depend on the observation, clipped as the agent's
other heads are (
log_std_bounds: none in PPO and APO by default,[-5, 2]in IQL,[-20, 2]in the others). - No memory. A PID policy needs a continuous action space and takes no
memory: its memory is the integral and the difference in the observation.
Each agent's own output rule applies to u. SAC, TD3, REDQ, TQC, ASAC,
RVI-SAC and AVG squash it with tanh, and APO and IQL take tanh(u) as
their mean, so the deployed controller is a saturated PID; APO and IQL
sample unsquashed around tanh(u), PPO around u (unless squash=True),
and their samples are clipped to [-1, 1]. Like every action, u is then
mapped onto the environment's bounds (Actions):
the deployed controller is c + h · sat(u), with c the centre of the
action box, h its half-width and sat the agent's tanh or clip. So a
PID written in the environment's units has gains h · K (for small
signals, where tanh is close to linear) and the offset c. Observation normalisation leaves the error
terms raw, so the gains act on errors in the environment's units; the gain
network of gains="observation" reads the rest of the observation
normalised.
Two other PID features are separate from this one. APG's in-context
controller ends with a learnable PID layer on its network's output: see
APG. Gain mode (ExpertGains) lets SAC tune the
gains of an expert controller: see Expert guidance.