Skip to content

moplayground.learning

Connecting the multi-objective trainers to mm.train, and loading trained policies back. See Training a policy and Rolling out a policy.

moplayground.learning.training

Functions:

Name Description
setup_morlax
setup_amor
mo_wrapper

Multi-Objective Wrapper

setup_morlax

setup_morlax(train_fn_params, network_factory_params, resumed)
Source code in src/moplayground/learning/training.py
def setup_morlax(train_fn_params, network_factory_params, resumed):

    network_factory = functools.partial(
        factory.make_morlax_networks,
        **network_factory_params
    )

    train_fn = functools.partial(
        morlax.train, **dict(train_fn_params),
        network_factory=network_factory,
        wrap_env_fn=mo_wrapper
    )

    return train_fn, network_factory

setup_amor

setup_amor(train_fn_params, network_factory_params, resumed)
Source code in src/moplayground/learning/training.py
def setup_amor(train_fn_params, network_factory_params, resumed):

    network_factory = functools.partial(
        factory.make_amor_networks,
        **network_factory_params
    )

    train_fn = functools.partial(
        amor.train, **dict(train_fn_params),
        network_factory=network_factory,
        wrap_env_fn=mo_wrapper
    )

    return train_fn, network_factory

mo_wrapper

mo_wrapper(env: MjxEnv, episode_length: int = 1000, action_repeat: int = 1, randomization_fn=None) -> Wrapper

Multi-Objective Wrapper

Source code in src/moplayground/learning/training.py
def mo_wrapper(
    env: mjx_env.MjxEnv,
    episode_length: int = 1000,
    action_repeat: int = 1,
    randomization_fn = None,
) -> wrapper.Wrapper:
    """Multi-Objective Wrapper"""

    env = VmapWrapper(env)
    env = MultiObjectiveEpisodeWrapper(env, episode_length, action_repeat)
    env = wrapper.BraxAutoResetWrapper(env)
    return env

moplayground.learning.inference

Functions:

Name Description
get_all_models

Checkpoint directories in run_dir, sorted by training step.

get_last_model

Most recent checkpoint directory in run_dir.

load_mo_policy

Load the latest multi-objective policy in run_dir.

load_hypernetworks

Load MORLAX networks and hypernetwork params from a checkpoint.

load_hypernetwork_inference_fn

Loads policy inference function from PPO checkpoint.

load_amor_networks

Load AMOR networks + saved (normalizer, policy, value) params.

load_make_amor_inference_fn

Load the (call-time-tradeoff) AMOR inference function from a checkpoint.

get_all_models

get_all_models(run_dir) -> list[Path]

Checkpoint directories in run_dir, sorted by training step.

A checkpoint directory is a subdirectory whose name is an integer (the training step), e.g. 000050032640.

Source code in src/moplayground/learning/inference.py
def get_all_models(run_dir) -> list[Path]:
    """Checkpoint directories in ``run_dir``, sorted by training step.

    A checkpoint directory is a subdirectory whose name is an integer (the
    training step), e.g. ``000050032640``.
    """
    run_dir = Path(run_dir)
    if not run_dir.exists():
        raise FileNotFoundError(f"Model directory does not exist: {run_dir}")
    model_files = [p for p in run_dir.iterdir() if p.is_dir() and p.name.isdigit()]
    model_files.sort(key=lambda p: int(p.name))
    return model_files

get_last_model

get_last_model(run_dir) -> Path

Most recent checkpoint directory in run_dir.

Source code in src/moplayground/learning/inference.py
def get_last_model(run_dir) -> Path:
    """Most recent checkpoint directory in ``run_dir``."""
    return get_all_models(run_dir)[-1]

load_mo_policy

load_mo_policy(algorithm: str, network_params: dict, num_objectives: int, run_dir, tradeoff: ndarray, network_factory=None, deterministic: bool = True)

Load the latest multi-objective policy in run_dir.

Dispatches on algorithm ('morlax' or 'amor'). Returns a 2-arg callable policy(obs, key) -> (action, extras) with tradeoff baked in, so it is compatible with mm.eval.rollout_policy and other consumers.

For AMOR specifically, the underlying inference function natively accepts a tradeoff at call time (so the tradeoff can change per step). To get that 3-arg form, call :func:load_amor_inference_fn directly instead of this function.

Source code in src/moplayground/learning/inference.py
def load_mo_policy(
    algorithm: str,
    network_params: dict,
    num_objectives: int,
    run_dir,
    tradeoff: np.ndarray,
    network_factory = None,
    deterministic: bool = True,
):
    """Load the latest multi-objective policy in ``run_dir``.

    Dispatches on ``algorithm`` (``'morlax'`` or ``'amor'``). Returns a 2-arg callable
    ``policy(obs, key) -> (action, extras)`` with ``tradeoff`` baked in, so it
    is compatible with ``mm.eval.rollout_policy`` and other consumers.

    For AMOR specifically, the underlying inference function natively accepts
    a tradeoff at call time (so the tradeoff can change per step). To get
    that 3-arg form, call :func:`load_amor_inference_fn` directly instead of
    this function.
    """
    if algorithm == 'morlax':
        if network_factory is None:
            network_factory = make_morlax_networks
        hypernetwork_inference_fn, params = load_hypernetwork_inference_fn(
            network_params,
            num_objectives,
            run_dir         = run_dir,
            network_factory = network_factory,
        )
        return hypernetwork_inference_fn(
            params        = params,
            deterministic = deterministic,
            tradeoff     = tradeoff,
            single_policy = True,
        )
    elif algorithm == 'amor':
        if network_factory is None:
            network_factory = make_amor_networks
        make_amor_inference_fn, params = load_make_amor_inference_fn(
            network_params,
            num_objectives,
            run_dir         = run_dir,
            network_factory = network_factory,
        )
        # checkpoint stores (normalizer, policy, value); inference uses (normalizer, policy).
        normalizer_params, policy_params = params[0], params[1]
        amor_inference_fn = make_amor_inference_fn(
            params        = (normalizer_params, policy_params),
            deterministic = deterministic,
        )
        tradeoff_jnp = jax.numpy.asarray(tradeoff)
        def policy(obs, key):
            return amor_inference_fn(obs, tradeoff_jnp, key)
        return policy
    else:
        raise ValueError(f"Unknown algorithm '{algorithm}'.")

load_hypernetworks

load_hypernetworks(network_params: dict, num_objectives: int, run_dir=None, path=None, network_factory=make_morlax_networks, quiet=True) -> tuple[MORLAXNetworks, dict]

Load MORLAX networks and hypernetwork params from a checkpoint.

Parameters:

Name Type Description Default
network_params dict

MORLAX network-factory keyword arguments.

required
num_objectives int

Number of objectives.

required
run_dir

Run directory; the latest checkpoint in it is used when path is not given.

None
path

Explicit checkpoint directory. Overrides run_dir.

None
Source code in src/moplayground/learning/inference.py
def load_hypernetworks(
    network_params: dict,
    num_objectives: int,
    run_dir = None,
    path = None,
    network_factory = make_morlax_networks,
    quiet = True
) -> tuple[mop.moppo.factory.MORLAXNetworks, dict]:
    """Load MORLAX networks and hypernetwork params from a checkpoint.

    Args:
        network_params: MORLAX network-factory keyword arguments.
        num_objectives: Number of objectives.
        run_dir: Run directory; the latest checkpoint in it is used when
            ``path`` is not given.
        path: Explicit checkpoint directory. Overrides ``run_dir``.
    """
    if path is None:
        path = get_last_model(run_dir)
    path = Path(path)
    if not quiet: print(f'Loading model at {path.as_posix()}')
    fullpath = epath.Path(path.resolve())
    params_config = checkpoint.load_config(fullpath)
    hyperparams = checkpoint.load(fullpath)
    network_factory = functools.partial(
        network_factory,
        key            = jax.random.PRNGKey(0),
        num_objectives = num_objectives,
        **network_params
    )
    hypernetworks = get_network(params_config, network_factory)
    return hypernetworks, hyperparams

load_hypernetwork_inference_fn

load_hypernetwork_inference_fn(network_params: dict, num_objectives: int, run_dir=None, path=None, network_factory=make_morlax_networks)

Loads policy inference function from PPO checkpoint.

Source code in src/moplayground/learning/inference.py
def load_hypernetwork_inference_fn(
    network_params: dict,
    num_objectives: int,
    run_dir = None,
    path = None,
    network_factory = make_morlax_networks,
):
    """Loads policy inference function from PPO checkpoint."""
    hypernetworks, hyperparams = load_hypernetworks(
        network_params, num_objectives, run_dir=run_dir, path=path,
        network_factory=network_factory,
    )
    make_inference_fn = make_hypernetwork_inference_fn(hypernetworks)
    return make_inference_fn, hyperparams

load_amor_networks

load_amor_networks(network_params: dict, num_objectives: int, run_dir=None, path=None, network_factory=make_amor_networks, quiet=True) -> tuple

Load AMOR networks + saved (normalizer, policy, value) params.

Parameters:

Name Type Description Default
network_params dict

AMOR network-factory keyword arguments.

required
num_objectives int

Number of objectives.

required
run_dir

Run directory; the latest checkpoint in it is used when path is not given.

None
path

Explicit checkpoint directory. Overrides run_dir.

None
Source code in src/moplayground/learning/inference.py
def load_amor_networks(
    network_params: dict,
    num_objectives: int,
    run_dir = None,
    path = None,
    network_factory = make_amor_networks,
    quiet = True
) -> tuple:
    """Load AMOR networks + saved (normalizer, policy, value) params.

    Args:
        network_params: AMOR network-factory keyword arguments.
        num_objectives: Number of objectives.
        run_dir: Run directory; the latest checkpoint in it is used when
            ``path`` is not given.
        path: Explicit checkpoint directory. Overrides ``run_dir``.
    """
    if path is None:
        path = get_last_model(run_dir)
    path = Path(path)
    if not quiet: print(f'Loading model at {path.as_posix()}')
    fullpath = epath.Path(path.resolve())
    params_config = checkpoint.load_config(fullpath)
    saved_params = checkpoint.load(fullpath)
    network_factory = functools.partial(
        network_factory,
        key            = jax.random.PRNGKey(0),
        num_objectives = num_objectives,
        **network_params,
    )
    amor_networks = get_network(params_config, network_factory)
    return amor_networks, saved_params

load_make_amor_inference_fn

load_make_amor_inference_fn(network_params: dict, num_objectives: int, run_dir=None, path=None, network_factory=make_amor_networks)

Load the (call-time-tradeoff) AMOR inference function from a checkpoint.

Returns (amor_inference_fn, saved_params) where amor_inference_fn has signature (params, deterministic) -> policy(obs, tradeoff, key) and saved_params is the (normalizer, policy, value) 3-tuple from the checkpoint.

Source code in src/moplayground/learning/inference.py
def load_make_amor_inference_fn(
    network_params: dict,
    num_objectives: int,
    run_dir = None,
    path = None,
    network_factory = make_amor_networks,
):
    """Load the (call-time-tradeoff) AMOR inference function from a checkpoint.

    Returns ``(amor_inference_fn, saved_params)`` where ``amor_inference_fn`` has
    signature ``(params, deterministic) -> policy(obs, tradeoff, key)`` and
    ``saved_params`` is the ``(normalizer, policy, value)`` 3-tuple from the
    checkpoint.
    """
    amor_networks, saved_params = load_amor_networks(
        network_params, num_objectives, run_dir=run_dir, path=path,
        network_factory=network_factory,
    )
    make_inference_fn = make_amor_inference_fn(amor_networks)
    return make_inference_fn, saved_params

moplayground.learning.wrappers

Classes:

Name Description
MultiObjectiveEpisodeWrapper

Maintains episode step count and sets done at episode end.

MultiObjectiveEvalWrapper

Brax env with eval metrics.

MultiObjectiveEpisodeWrapper

Bases: Wrapper

Maintains episode step count and sets done at episode end.

Methods:

Name Description
reset
step

Attributes:

Name Type Description
episode_length
action_repeat
Source code in src/moplayground/learning/wrappers.py
class MultiObjectiveEpisodeWrapper(Wrapper):
    """Maintains episode step count and sets done at episode end."""

    def __init__(self, env: Env, episode_length: int, action_repeat: int):
        super().__init__(env)
        self.episode_length = episode_length
        self.action_repeat = action_repeat

    def reset(self, rng: jax.Array) -> State:
        state = self.env.reset(rng)
        state.info['steps'] = jnp.zeros(rng.shape[:-1])
        state.info['truncation'] = jnp.zeros(rng.shape[:-1])
        # Keep separate record of episode done as state.info['done'] can be erased
        # by AutoResetWrapper
        state.info['episode_done'] = jnp.zeros(rng.shape[:-1])
        episode_metrics = dict()
        episode_metrics['sum_reward'] = jnp.zeros_like(state.reward)
        episode_metrics['length'] = jnp.zeros(rng.shape[:-1])
        for metric_name in state.metrics.keys():
            episode_metrics[metric_name] = jnp.zeros(rng.shape[:-1])
        state.info['episode_metrics'] = episode_metrics
        return state

    def step(self, state: State, action: jax.Array) -> State:
        def f(state, _):
            nstate = self.env.step(state, action)
            return nstate, nstate.reward

        state, rewards = jax.lax.scan(f, state, (), self.action_repeat)
        state = state.replace(reward=jnp.sum(rewards, axis=0))
        steps = state.info['steps'] + self.action_repeat
        one = jnp.ones_like(state.done)
        zero = jnp.zeros_like(state.done)
        episode_length = jnp.array(self.episode_length, dtype=jnp.int32)
        done = jnp.where(steps >= episode_length, one, state.done)
        state.info['truncation'] = jnp.where(
            steps >= episode_length, 1 - state.done, zero
        )
        state.info['steps'] = steps

        # Aggregate state metrics into episode metrics
        prev_done = state.info['episode_done']
        state.info['episode_metrics']['sum_reward'] += jnp.sum(rewards, axis=0)
        state.info['episode_metrics']['sum_reward'] *= (1 - prev_done[:, jnp.newaxis])
        state.info['episode_metrics']['length'] += self.action_repeat
        state.info['episode_metrics']['length'] *= (1 - prev_done)
        for metric_name in state.metrics.keys():
            if metric_name != 'reward':
                state.info['episode_metrics'][metric_name] += state.metrics[metric_name]
                state.info['episode_metrics'][metric_name] *= (1 - prev_done)
        state.info['episode_done'] = done
        return state.replace(done=done)

episode_length instance-attribute

episode_length = episode_length

action_repeat instance-attribute

action_repeat = action_repeat

reset

reset(rng: Array) -> State
Source code in src/moplayground/learning/wrappers.py
def reset(self, rng: jax.Array) -> State:
    state = self.env.reset(rng)
    state.info['steps'] = jnp.zeros(rng.shape[:-1])
    state.info['truncation'] = jnp.zeros(rng.shape[:-1])
    # Keep separate record of episode done as state.info['done'] can be erased
    # by AutoResetWrapper
    state.info['episode_done'] = jnp.zeros(rng.shape[:-1])
    episode_metrics = dict()
    episode_metrics['sum_reward'] = jnp.zeros_like(state.reward)
    episode_metrics['length'] = jnp.zeros(rng.shape[:-1])
    for metric_name in state.metrics.keys():
        episode_metrics[metric_name] = jnp.zeros(rng.shape[:-1])
    state.info['episode_metrics'] = episode_metrics
    return state

step

step(state: State, action: Array) -> State
Source code in src/moplayground/learning/wrappers.py
def step(self, state: State, action: jax.Array) -> State:
    def f(state, _):
        nstate = self.env.step(state, action)
        return nstate, nstate.reward

    state, rewards = jax.lax.scan(f, state, (), self.action_repeat)
    state = state.replace(reward=jnp.sum(rewards, axis=0))
    steps = state.info['steps'] + self.action_repeat
    one = jnp.ones_like(state.done)
    zero = jnp.zeros_like(state.done)
    episode_length = jnp.array(self.episode_length, dtype=jnp.int32)
    done = jnp.where(steps >= episode_length, one, state.done)
    state.info['truncation'] = jnp.where(
        steps >= episode_length, 1 - state.done, zero
    )
    state.info['steps'] = steps

    # Aggregate state metrics into episode metrics
    prev_done = state.info['episode_done']
    state.info['episode_metrics']['sum_reward'] += jnp.sum(rewards, axis=0)
    state.info['episode_metrics']['sum_reward'] *= (1 - prev_done[:, jnp.newaxis])
    state.info['episode_metrics']['length'] += self.action_repeat
    state.info['episode_metrics']['length'] *= (1 - prev_done)
    for metric_name in state.metrics.keys():
        if metric_name != 'reward':
            state.info['episode_metrics'][metric_name] += state.metrics[metric_name]
            state.info['episode_metrics'][metric_name] *= (1 - prev_done)
    state.info['episode_done'] = done
    return state.replace(done=done)

MultiObjectiveEvalWrapper

Bases: Wrapper

Brax env with eval metrics.

Methods:

Name Description
reset
step
Source code in src/moplayground/learning/wrappers.py
class MultiObjectiveEvalWrapper(Wrapper):
    """Brax env with eval metrics."""

    def reset(self, rng: jax.Array) -> State:
        reset_state = self.env.reset(rng)
        reset_state.metrics['reward'] = reset_state.reward
        eval_metrics = EvalMetrics(
            episode_metrics=jax.tree_util.tree_map(
                jnp.zeros_like, reset_state.metrics
            ),
            active_episodes=jnp.ones(reset_state.reward.shape[0]),
            episode_steps=jnp.zeros(reset_state.reward.shape[0]),
        )
        reset_state.info['eval_metrics'] = eval_metrics
        return reset_state

    def step(self, state: State, action: jax.Array) -> State:
        state_metrics = state.info['eval_metrics']
        if not isinstance(state_metrics, EvalMetrics):
            raise ValueError(
                f'Incorrect type for state_metrics: {type(state_metrics)}'
            )
        del state.info['eval_metrics']
        nstate = self.env.step(state, action)
        episode_steps = jnp.where(
            state_metrics.active_episodes,
            nstate.info['steps'],
            state_metrics.episode_steps,
        )
        # The vector reward is accumulated separately (it has an objective axis).
        # Use this step's nstate.reward: envs carry metrics forward, so
        # nstate.metrics['reward'] would still hold the previous step's reward.
        old_reward = state_metrics.episode_metrics.pop('reward')
        nstate.metrics.pop('reward', None)
        episode_metrics = jax.tree_util.tree_map(
            lambda a, b: a + b * state_metrics.active_episodes,
            state_metrics.episode_metrics,
            nstate.metrics,
        )
        nstate.metrics['reward'] = nstate.reward
        episode_metrics['reward'] = old_reward + nstate.reward * state_metrics.active_episodes[:, jnp.newaxis]
        active_episodes = state_metrics.active_episodes * (1 - nstate.done)

        eval_metrics = EvalMetrics(
            episode_metrics=episode_metrics,
            active_episodes=active_episodes,
            episode_steps=episode_steps,
        )
        nstate.info['eval_metrics'] = eval_metrics
        return nstate

reset

reset(rng: Array) -> State
Source code in src/moplayground/learning/wrappers.py
def reset(self, rng: jax.Array) -> State:
    reset_state = self.env.reset(rng)
    reset_state.metrics['reward'] = reset_state.reward
    eval_metrics = EvalMetrics(
        episode_metrics=jax.tree_util.tree_map(
            jnp.zeros_like, reset_state.metrics
        ),
        active_episodes=jnp.ones(reset_state.reward.shape[0]),
        episode_steps=jnp.zeros(reset_state.reward.shape[0]),
    )
    reset_state.info['eval_metrics'] = eval_metrics
    return reset_state

step

step(state: State, action: Array) -> State
Source code in src/moplayground/learning/wrappers.py
def step(self, state: State, action: jax.Array) -> State:
    state_metrics = state.info['eval_metrics']
    if not isinstance(state_metrics, EvalMetrics):
        raise ValueError(
            f'Incorrect type for state_metrics: {type(state_metrics)}'
        )
    del state.info['eval_metrics']
    nstate = self.env.step(state, action)
    episode_steps = jnp.where(
        state_metrics.active_episodes,
        nstate.info['steps'],
        state_metrics.episode_steps,
    )
    # The vector reward is accumulated separately (it has an objective axis).
    # Use this step's nstate.reward: envs carry metrics forward, so
    # nstate.metrics['reward'] would still hold the previous step's reward.
    old_reward = state_metrics.episode_metrics.pop('reward')
    nstate.metrics.pop('reward', None)
    episode_metrics = jax.tree_util.tree_map(
        lambda a, b: a + b * state_metrics.active_episodes,
        state_metrics.episode_metrics,
        nstate.metrics,
    )
    nstate.metrics['reward'] = nstate.reward
    episode_metrics['reward'] = old_reward + nstate.reward * state_metrics.active_episodes[:, jnp.newaxis]
    active_episodes = state_metrics.active_episodes * (1 - nstate.done)

    eval_metrics = EvalMetrics(
        episode_metrics=episode_metrics,
        active_episodes=active_episodes,
        episode_steps=episode_steps,
    )
    nstate.info['eval_metrics'] = eval_metrics
    return nstate