Skip to content

moplayground.eval

Evaluating trained runs over many tradeoffs at once. Each function returns the per-objective episode returns for every checkpoint, from which Pareto fronts and their statistics (utils.pareto) are computed.

moplayground.eval.pareto

Functions:

Name Description
get_pareto_rollout

Build a jit/vmapped rollout fn that sweeps a batch of (key, tradeoff, params).

compute_fronts

Run rollouts for every checkpoint in every run over a fixed batch of

get_morlax_fronts

Compute Pareto fronts for one or more MORLAX (hypernetwork) runs.

get_amor_fronts

Compute Pareto fronts for one or more AMOR (tradeoff-conditioned) runs.

get_pareto_rollout

get_pareto_rollout(env, N_STEPS, make_policy)

Build a jit/vmapped rollout fn that sweeps a batch of (key, tradeoff, params).

The same scaffold works for any algorithm — algorithm-specific details live inside make_policy.

Parameters:

Name Type Description Default
env the brax/mjx environment to roll out in.
required
N_STEPS int, number of env steps per rollout.
required
make_policy callable with signature

(params, deterministic, tradeoff) -> policy(obs, key) -> (action, extras).

required

Returns:

Name Type Description
run_rollouts jit-compiled fn ``(keys, tradeoffs, params) -> ((final_state, returns), None)``

vmapped over the leading axis of keys and tradeoffs. returns is the per-objective episodic return, shape (NUM_ENVS, num_objs).

Source code in src/moplayground/eval/pareto.py
def get_pareto_rollout(env, N_STEPS, make_policy):
    """Build a jit/vmapped rollout fn that sweeps a batch of (key, tradeoff, params).

    The same scaffold works for any algorithm — algorithm-specific details live
    inside ``make_policy``.

    Parameters
    ----------
    env : the brax/mjx environment to roll out in.
    N_STEPS : int, number of env steps per rollout.
    make_policy : callable with signature
        ``(params, deterministic, tradeoff) -> policy(obs, key) -> (action, extras)``.

    Returns
    -------
    run_rollouts : jit-compiled fn ``(keys, tradeoffs, params) -> ((final_state, returns), None)``
        vmapped over the leading axis of ``keys`` and ``tradeoffs``. ``returns`` is
        the per-objective episodic return, shape ``(NUM_ENVS, num_objs)``.
    """
    policy_rng = jax.random.PRNGKey(0)

    def step_fn(carry, _, policy):
        state, old_reward = carry
        action, _ = policy(state.obs, policy_rng)
        new_state = env.step(state, action)
        # accumulate per-objective reward, masking out steps after termination
        return (new_state, old_reward + new_state.reward * (1 - new_state.done)), None

    def rollout(key, tradeoff, params):
        policy = make_policy(
            params        = params,
            deterministic = True,
            tradeoff     = tradeoff,
        )
        scan_step_fn = functools.partial(step_fn, policy=policy)
        state = env.reset(key)
        carry = (state, state.reward)
        return jax.lax.scan(scan_step_fn, carry, (), N_STEPS)

    return jax.jit(jax.vmap(rollout, in_axes=(0, 0, None)))

compute_fronts

compute_fronts(run_dirs, num_objectives, rng, env, N_STEPS, NUM_ENVS, make_policy, load_params_fn, model_files_per_run, save_results)

Run rollouts for every checkpoint in every run over a fixed batch of randomly sampled tradeoffs, and return the resulting Pareto fronts.

Algorithm-agnostic: callers supply make_policy and load_params_fn to plug in MORLAX, AMOR, or anything else with the right shapes. The rollout JIT is built once and reused across every run in run_dirs — so multiple runs that share an environment and network architecture amortize the compile cost.

Parameters:

Name Type Description Default
run_dirs list of run directories, all sharing the same environment.

save_results writes into each file's owning run directory.

required
num_objectives int, number of objectives.
required
rng PRNGKey used both to sample the (fixed) batch of tradeoffs and to

seed the per-rollout env reset keys.

required
env environment to roll out in.
required
N_STEPS int, env steps per rollout.
required
NUM_ENVS int, number of tradeoffs sampled (== number of parallel rollouts

per checkpoint).

required
make_policy callable with signature

(params, deterministic, tradeoff) -> policy(obs, key) -> (action, extras), passed through to :func:get_pareto_rollout.

required
load_params_fn callable ``file -> params`` mapping a checkpoint path to the

params pytree expected by make_policy.

required
model_files_per_run list of lists of checkpoint paths, aligned with

run_dirs. model_files_per_run[i] are the checkpoints for run_dirs[i].

required
save_results if True, dump per-checkpoint returns to

{run_dir}/obj{j}.txt (where run_dir is the file's owning run directory and j is its index within that run's checkpoints).

required

Returns:

Name Type Description
rewards_over_iters ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,

per-objective episodic return. Files are concatenated in run order.

tradeoffs_over_iters ndarray, same shape, the tradeoff used for each

rollout. Fixed across checkpoints (broadcast along axis 0).

Source code in src/moplayground/eval/pareto.py
def compute_fronts(
    run_dirs,
    num_objectives,
    rng,
    env,
    N_STEPS,
    NUM_ENVS,
    make_policy,
    load_params_fn,
    model_files_per_run,
    save_results,
):
    """Run rollouts for every checkpoint in every run over a fixed batch of
    randomly sampled tradeoffs, and return the resulting Pareto fronts.

    Algorithm-agnostic: callers supply ``make_policy`` and ``load_params_fn`` to
    plug in MORLAX, AMOR, or anything else with the right shapes. The rollout
    JIT is built once and reused across every run in ``run_dirs`` — so multiple
    runs that share an environment and network architecture amortize the
    compile cost.

    Parameters
    ----------
    run_dirs : list of run directories, all sharing the same environment.
        ``save_results`` writes into each file's owning run directory.
    num_objectives : int, number of objectives.
    rng : PRNGKey used both to sample the (fixed) batch of tradeoffs and to
        seed the per-rollout env reset keys.
    env : environment to roll out in.
    N_STEPS : int, env steps per rollout.
    NUM_ENVS : int, number of tradeoffs sampled (== number of parallel rollouts
        per checkpoint).
    make_policy : callable with signature
        ``(params, deterministic, tradeoff) -> policy(obs, key) -> (action, extras)``,
        passed through to :func:`get_pareto_rollout`.
    load_params_fn : callable ``file -> params`` mapping a checkpoint path to the
        params pytree expected by ``make_policy``.
    model_files_per_run : list of lists of checkpoint paths, aligned with
        ``run_dirs``. ``model_files_per_run[i]`` are the checkpoints for
        ``run_dirs[i]``.
    save_results : if True, dump per-checkpoint returns to
        ``{run_dir}/obj{j}.txt`` (where ``run_dir`` is the file's owning run
        directory and ``j`` is its index within that run's checkpoints).

    Returns
    -------
    rewards_over_iters : ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,
        per-objective episodic return. Files are concatenated in run order.
    tradeoffs_over_iters : ndarray, same shape, the tradeoff used for each
        rollout. Fixed across checkpoints (broadcast along axis 0).
    """
    # one env-reset key per tradeoff; same batch reused across checkpoints
    keys = jax.random.split(rng, NUM_ENVS)
    tradeoffs = jax.random.dirichlet(rng, alpha=np.ones(num_objectives), shape=(NUM_ENVS,))

    run_rollouts = get_pareto_rollout(env, N_STEPS, make_policy)

    flat = []
    for run_dir, files in zip(run_dirs, model_files_per_run):
        for j, file in enumerate(files):
            flat.append((run_dir, j, file))

    rewards_over_iters = []
    for run_dir, j, file in tqdm(flat):
        params = load_params_fn(file)
        (_, rewards), _ = run_rollouts(keys, tradeoffs, params)
        rewards_over_iters.append(rewards)
        if save_results:
            pd.DataFrame.from_dict(
                {f'obj{k}': objs for k, objs in enumerate(rewards.T)}
            ).to_csv(Path(run_dir) / f'obj{j}.txt')

    rewards_over_iters = np.array(rewards_over_iters)
    tradeoffs_over_iters = np.repeat(
        tradeoffs[np.newaxis, :, :], rewards_over_iters.shape[0], axis=0,
    )
    return rewards_over_iters, tradeoffs_over_iters

get_morlax_fronts

get_morlax_fronts(run_dirs, network_params, num_objectives, rng, env, N_STEPS, NUM_ENVS, save_results=False, only_final=False)

Compute Pareto fronts for one or more MORLAX (hypernetwork) runs.

Parameters:

Name Type Description Default
run_dirs run directory, or list of run directories. Every run must deploy

the same environment and network architecture; the rollout JIT is built once and reused across all of them. Check this before calling (see moplayground.utils.config.check_same_env).

required
network_params dict, network-factory keyword arguments shared by all runs.
required
num_objectives int, number of objectives.
required
rng PRNGKey used both to sample the (fixed) batch of tradeoffs and to

seed the per-rollout env reset keys.

required
env environment to roll out in.
required
N_STEPS int, env steps per rollout.
required
NUM_ENVS int, number of tradeoffs sampled (== number of parallel rollouts

per checkpoint).

required
save_results if True, dump per-checkpoint returns to

{run_dir}/obj{j}.txt for each owning run.

False
only_final if True, evaluate only the final checkpoint of each run.
False

Returns:

Name Type Description
rewards_over_iters ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,

per-objective episodic return. Files are concatenated in run order.

tradeoffs_over_iters ndarray, same shape, the tradeoff used for each

rollout. Fixed across checkpoints (broadcast along axis 0).

Source code in src/moplayground/eval/pareto.py
def get_morlax_fronts(run_dirs, network_params, num_objectives, rng, env, N_STEPS,
                      NUM_ENVS, save_results=False, only_final=False):
    """Compute Pareto fronts for one or more MORLAX (hypernetwork) runs.

    Parameters
    ----------
    run_dirs : run directory, or list of run directories. Every run must deploy
        the same environment and network architecture; the rollout JIT is
        built once and reused across all of them. Check this before calling
        (see ``moplayground.utils.config.check_same_env``).
    network_params : dict, network-factory keyword arguments shared by all runs.
    num_objectives : int, number of objectives.
    rng : PRNGKey used both to sample the (fixed) batch of tradeoffs and to
        seed the per-rollout env reset keys.
    env : environment to roll out in.
    N_STEPS : int, env steps per rollout.
    NUM_ENVS : int, number of tradeoffs sampled (== number of parallel rollouts
        per checkpoint).
    save_results : if True, dump per-checkpoint returns to
        ``{run_dir}/obj{j}.txt`` for each owning run.
    only_final : if True, evaluate only the final checkpoint of each run.

    Returns
    -------
    rewards_over_iters : ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,
        per-objective episodic return. Files are concatenated in run order.
    tradeoffs_over_iters : ndarray, same shape, the tradeoff used for each
        rollout. Fixed across checkpoints (broadcast along axis 0).
    """
    run_dirs = _as_list(run_dirs)

    model_files_per_run = []
    for run_dir in run_dirs:
        files = mop.learning.inference.get_all_models(run_dir)
        if only_final:
            files = [files[-1]]
        model_files_per_run.append(files)

    # MORLAX: params == hypernet params; make_policy directly takes (params, deterministic, tradeoff)
    first_file = model_files_per_run[0][0]
    make_policy, _ = mop.learning.inference.load_hypernetwork_inference_fn(
        network_params, num_objectives, path=first_file,
    )

    def load_params_fn(file):
        _, hyperparams = mop.learning.inference.load_hypernetworks(
            network_params, num_objectives, path=file,
        )
        return hyperparams

    return compute_fronts(
        run_dirs, num_objectives, rng, env, N_STEPS, NUM_ENVS,
        make_policy, load_params_fn, model_files_per_run, save_results,
    )

get_amor_fronts

get_amor_fronts(run_dirs, network_params, num_objectives, rng, env, N_STEPS, NUM_ENVS, save_results=False, only_final=False)

Compute Pareto fronts for one or more AMOR (tradeoff-conditioned) runs.

Parameters:

Name Type Description Default
run_dirs run directory, or list of run directories. Every run must deploy

the same environment and network architecture; the rollout JIT is built once and reused across all of them. Check this before calling (see moplayground.utils.config.check_same_env).

required
network_params dict, network-factory keyword arguments shared by all runs.
required
num_objectives int, number of objectives.
required
rng PRNGKey used both to sample the (fixed) batch of tradeoffs and to

seed the per-rollout env reset keys.

required
env environment to roll out in.
required
N_STEPS int, env steps per rollout.
required
NUM_ENVS int, number of tradeoffs sampled (== number of parallel rollouts

per checkpoint).

required
save_results if True, dump per-checkpoint returns to

{run_dir}/obj{j}.txt for each owning run.

False
only_final if True, evaluate only the final checkpoint of each run.
False

Returns:

Name Type Description
rewards_over_iters ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,

per-objective episodic return. Files are concatenated in run order.

tradeoffs_over_iters ndarray, same shape, the tradeoff used for each

rollout. Fixed across checkpoints (broadcast along axis 0).

Source code in src/moplayground/eval/pareto.py
def get_amor_fronts(run_dirs, network_params, num_objectives, rng, env, N_STEPS,
                    NUM_ENVS, save_results=False, only_final=False):
    """Compute Pareto fronts for one or more AMOR (tradeoff-conditioned) runs.

    Parameters
    ----------
    run_dirs : run directory, or list of run directories. Every run must deploy
        the same environment and network architecture; the rollout JIT is
        built once and reused across all of them. Check this before calling
        (see ``moplayground.utils.config.check_same_env``).
    network_params : dict, network-factory keyword arguments shared by all runs.
    num_objectives : int, number of objectives.
    rng : PRNGKey used both to sample the (fixed) batch of tradeoffs and to
        seed the per-rollout env reset keys.
    env : environment to roll out in.
    N_STEPS : int, env steps per rollout.
    NUM_ENVS : int, number of tradeoffs sampled (== number of parallel rollouts
        per checkpoint).
    save_results : if True, dump per-checkpoint returns to
        ``{run_dir}/obj{j}.txt`` for each owning run.
    only_final : if True, evaluate only the final checkpoint of each run.

    Returns
    -------
    rewards_over_iters : ndarray, shape ``(total_checkpoints, NUM_ENVS, num_objs)``,
        per-objective episodic return. Files are concatenated in run order.
    tradeoffs_over_iters : ndarray, same shape, the tradeoff used for each
        rollout. Fixed across checkpoints (broadcast along axis 0).
    """
    run_dirs = _as_list(run_dirs)

    model_files_per_run = []
    for run_dir in run_dirs:
        files = mop.learning.inference.get_all_models(run_dir)
        if only_final:
            files = [files[-1]]
        model_files_per_run.append(files)

    # AMOR's native inference fn takes the tradeoff at call time: policy(obs, tradeoff, key).
    # Wrap it to match the (params, deterministic, tradeoff) -> policy(obs, key) shape used by
    # get_pareto_rollout.
    first_file = model_files_per_run[0][0]
    make_amor_inference_fn, _ = mop.learning.inference.load_make_amor_inference_fn(
        network_params, num_objectives, path=first_file,
    )

    def make_policy(params, deterministic, tradeoff):
        # checkpoint stores (normalizer, policy, value); inference only needs (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

    def load_params_fn(file):
        _, params = mop.learning.inference.load_make_amor_inference_fn(
            network_params, num_objectives, path=file,
        )
        return params

    return compute_fronts(
        run_dirs, num_objectives, rng, env, N_STEPS, NUM_ENVS,
        make_policy, load_params_fn, model_files_per_run, save_results,
    )