Skip to content

UDRL

Upside-Down RL turns reinforcement learning into supervised learning. The policy takes a command next to the observation: a return to obtain and a number of steps to obtain it in. It learns, from its own past experience, which action led to which outcome, then is asked for slightly better outcomes than the best it has seen.

Papers: Schmidhuber, Reinforcement Learning Upside Down: Don't Predict Rewards -- Just Map Them to Actions, 2019 (arXiv:1912.02875), whose training procedure Ajax follows. The companion paper by Srivastava, Shyam, Mutz, Jaśkowski and Schmidhuber, Training Agents using Upside-Down Reinforcement Learning, 2019 (arXiv:1912.02877), reports the first experiments; its code is not public.

When to use it

UDRL has no critic, no value estimate and, by default, no discount: it learns only by supervised steps on its own replayed experience. Its commands are a return and a horizon, so it suits episodic tasks, and research on command-conditioned policies.

Feature UDRL
Discrete actions yes
Continuous actions yes, a tanh-squashed Gaussian, mapped onto the environment's bounds
Memory (memory=) no
Environments gymnax, Brax, MuJoCo Playground
Image observations yes, a CNN encoder (cnn_image_shape)
Several seeds in one call yes, train(seed=[...])
Extension phases pretrain, post_update, eval_metrics, observe, actor_loss, action, transform_action, actuate, choose_replay_action (which extensions run)
Resume and checkpoints yes; a run split by a checkpoint equals the run left whole

Example

from ajax import UDRL
from ajax.logging import LoggingConfig

agent = UDRL("CartPole-v1", n_envs=4)
logging = LoggingConfig(log_frequency=10_240, backends=())
state, evaluations = agent.train(seed=[1, 2], n_timesteps=51_200, logging_config=logging)
print(evaluations["Eval/episodic mean reward"])   # the policy, commanded as below
print(evaluations["Train/episodic mean reward"])  # returns of the episodes collected
print(state.command_target_return)                # the return the agent now asks for

With a logging_config, UDRL evaluates its policy every log_frequency steps on num_episode_test episodes. train returns the evaluation (Eval/episodic mean reward, Eval/episodic entropy, Eval/mean episodic length, and Eval/commanded return and Eval/commanded horizon, the command each episode starts from) and the training metrics of those iterations (Train/episodic mean reward, Train/actor_loss, Train/mean_rtg, Train/mean_horizon, Train/n_completed_episodes).

Key hyperparameters

Argument Default What it does
n_envs 1 environments stepped in parallel
n_steps 64 length of the segment collected per iteration
buffer_capacity 64 segments kept in the replay
n_updates_per_iter 64 gradient steps per iteration
batch_size 64 samples per gradient step
actor_learning_rate 3e-4 Adam step size
actor_architecture ("128", "relu", "128", "relu") hidden layers
max_grad_norm None gradient clipping by global norm
gamma 1.0 discount of the returns-to-go logged as Train/mean_rtg, a diagnostic only: commands, the top-K statistics and the training targets sum rewards undiscounted, as in the paper
command_return_init, command_horizon_init 1.0, 100.0 the first command
command_topk 32 best episodes the next command is built from
command_return_boost 1.0 multiplies the top episodes' mean return
command_target_tau 1.0 smoothing of the command (1: replaced every iteration)
command_scale_r, command_scale_h 0.02, 0.01 scaling of the command before the network
normalize_observations, normalize_rewards, reward_normalization_gamma False, False, None running normalisation; the rewards' divisor is the spread of the return discounted by reward_normalization_gamma, gamma if None
cnn_image_shape, cnn_extra_obs_dim, cnn_spec None, 0, None convolutional encoder for flat image observations, the features after the image, and the encoder's layers; the command joins the encoder's output
episode_length, action_repeat None, 1 simulator steps per episode and per agent step, on Brax and Playground; None is 1,000 steps, or a mujoco: task's own time limit (Environments)
expert_policy None an expert the rollout runs alongside: a residual policy (ResidualPolicy) or gain mode (ExpertGains) acts through it and the observation features read it
eval_expert_policy None an expert whose return each evaluation logs, which takes no other part in the run
extensions () research features (see Extensions)

How it works

Each iteration:

  1. collects n_steps steps per environment with the current policy and commands, decreasing each command as reward is received and steps pass;
  2. stores that segment in a first-in first-out replay of buffer_capacity segments;
  3. sets the next command from the command_topk best episodes in the replay: a return between their mean and their mean plus one standard deviation, and their mean length as the horizon;
  4. takes n_updates_per_iter supervised steps, each maximising the log-likelihood of the action taken. Each sample is a state, the action taken there, and as command what actually followed: the reward summed up to a random later step of the same episode, and that number of steps.

Differences from the reference

From Srivastava et al. (arXiv:1912.02877v2):

  • The replay is first-in first-out; the paper's keeps the best episodes by return (Sec. 2.2.1).
  • Training intervals end at a random later step of their episode, the paper's general form; its experiments all end them at the episode's end (Sec. 2.2.3).
  • No warm-up. The paper first fills the replay with 30 to 50 episodes of random actions (Algorithm 1, Table 4); in Ajax the first segments are the untrained policy's.

Notes

  • Segments, read as episodes. The replay stores fixed-length segments rather than whole episodes, so arrays keep a fixed shape. The sampler and the top-K statistics read episodes whole across segments, so a training command can span any part of an episode the replay holds, not only one segment.
  • Evaluation. Each evaluated episode starts from the current command (state.command_target_return and its horizon), without the random spread that collection adds, and the command decreases as in collection. The policy acts deterministically.
  • Command scaling. The command enters the network multiplied by command_scale_r and command_scale_h (two values of the paper's LunarLander search), so that it is of order one; the replay keeps it unscaled.
  • Network. The policy's encoder ends with a LayerNorm, unlike the other agents' plain MLPs. The command is carried in the last two entries of the observation, after the observation features; with cnn_image_shape the image is flattened in front of them.

Results

No learning curves are published for UDRL yet. The probes (tests/probing) train it briefly on tiny environments with known answers: that it learns from the commands that actually followed, that it scales its command alike when acting and when training, its extension phases, and a run split by a checkpoint matching the run left whole. Performance compares its speed with the other agents'.

API

ajax.agents.UDRL.UDRL.UDRL dataclass

UDRL(
    env_id,
    *,
    n_envs=1,
    env_params=None,
    weight_decay=0.0,
    episode_length=None,
    action_repeat=1,
    extensions=(),
    expert_policy=None,
    eval_expert_policy=None,
    cnn_image_shape=None,
    cnn_extra_obs_dim=0,
    cnn_spec=None,
    normalize_rewards=False,
    reward_normalization_gamma=None,
    normalize_observations=False,
    observation_clip=None,
    max_grad_norm=None,
    actor_learning_rate=0.0003,
    actor_architecture=("128", "relu", "128", "relu"),
    gamma=1.0,
    n_steps=64,
    batch_size=64,
    command_return_init=1.0,
    command_horizon_init=100.0,
    command_topk=32,
    command_return_boost=1.0,
    command_target_tau=1.0,
    command_scale_r=0.02,
    command_scale_h=0.01,
    buffer_capacity=64,
    n_updates_per_iter=64,
)

Bases: GradientClipping, ObservationNormalization, RewardNormalization, ImageObservations, ExpertGuided, OwnIterationAgent

Upside-Down RL (Schmidhuber, 2019): command-conditioned supervised policy learning on a replay of rollout segments (the module's program).

With an image (cnn_image_shape), the (d_r, d_h) command joins the CNN's embedding after the convolutions, beside cnn_extra_obs_dim features. With an expert_policy, a residual policy or gain mode acts through it, and each evaluation logs its return.

init

init(key, context)

The actor (its input the observation and the command), the collector, whose observations carry the initial command, and the empty replay of segments.

make_acting_pipeline

make_acting_pipeline(context, keeps_choice=False)

UDRL's action pipeline (interaction.ActionPipelineResult's): a sample of the actor on the observation with its command scaled, executed through the run's residual transform where it has one. With keeps_choice (an action extension in the stack), it gives the action stage the choice that executes the expert's action, in the segment's layout: the expert's own, or a residual of 0.

collect_step

collect_step(agent_state, context)

One env step: the actor reads the observation and its command (the last two columns of last_obs) scaled, the env steps, and the next observation carries the next command. With an expert, called first as every collector calls it (expert_collect_kwargs), the action is executed through the run's transform (residual RL, gain mode) and the tracked expert; the segment keeps the policy's own action, which the actor fits.

iterate

iterate(agent_state, context)

A segment, appended to the replay; the command targets from the replay's top-K episodes; n_updates_per_iter fits of the actor.

report

report(agent_state, aux)

The iteration's segment and updates.

policy_parts

policy_parts()

As its evaluation acts (evaluate): commanded by EvalCommand, each reward counting the command down in the agent's units, through the run's transform and the expert.

evaluation_metrics

evaluation_metrics(
    agent_state, key, context, num_episode_test
)

The deterministic policy's return, entropy and length on num_episode_test episodes of the shared evaluation, commanded by EvalCommand (acting through the run's transform and the expert), and the return and horizon each episode is commanded with at its start; the expert's return on the same episodes, eval_expert_policy's when given (read in agent units, as the family evaluation reads it).