Skip to content

minimal_mjx.learning

Training policies and loading them back. See Training a policy for how these fit together.

minimal_mjx.learning.training

Classes:

Name Description
Resume

What a continued run inherits from the checkpoints already in its directory.

Functions:

Name Description
setup_ppo

Default handler: brax PPO. Returns (train_fn, network_factory).

find_checkpoints

The run's checkpoint directories, named by step and ordered by it.

find_resume

Where training left off in output_dir, or None if it never checkpointed.

apply_resume

A copy of ppo_params asking the algorithm for only the steps the run still owes.

create_training_directory

Create the run output directory, refusing to clobber an earlier run.

train

Train a policy on the given environment.

Resume dataclass

What a continued run inherits from the checkpoints already in its directory.

Attributes:

Name Type Description
path Path
step int
epoch int
Source code in src/minimal_mjx/learning/training.py
@dataclasses.dataclass
class Resume:
    """What a continued run inherits from the checkpoints already in its directory."""

    path  : Path  # newest checkpoint, i.e. the params to restart from
    step  : int   # env steps already trained
    epoch : int   # epochs already run, one checkpoint each after the one at step 0

path instance-attribute

path: Path

step instance-attribute

step: int

epoch instance-attribute

epoch: int

setup_ppo

setup_ppo(
    ppo_params: dict,
    network_params: dict,
    resumed: Resume | None = None,
)

Default handler: brax PPO. Returns (train_fn, network_factory).

train_fn is a :func:functools.partial of the brax PPO trainer with all algorithm params pre-bound; network_factory builds the PPO networks.

Source code in src/minimal_mjx/learning/training.py
def setup_ppo(ppo_params: dict, network_params: dict, resumed: Resume | None = None):
    """Default handler: brax PPO. Returns ``(train_fn, network_factory)``.

    ``train_fn`` is a :func:`functools.partial` of the brax PPO trainer with all
    algorithm params pre-bound; ``network_factory`` builds the PPO networks.
    """
    network_factory = functools.partial(
        ppo_networks.make_ppo_networks,
        mean_kernel_init_fn=jax.nn.initializers.lecun_uniform,
        **network_params
    )
    train_fn = functools.partial(
        train_ppo, **ppo_params,
        network_factory=network_factory,
        # brax restores the checkpointed params and normalizer, not its optimizer.
        restore_checkpoint_path=None if resumed is None else str(resumed.path),
        wrap_env_fn=wrapper.wrap_for_brax_training,
    )
    return train_fn, network_factory

find_checkpoints

find_checkpoints(output_dir) -> list[Path]

The run's checkpoint directories, named by step and ordered by it.

Source code in src/minimal_mjx/learning/training.py
def find_checkpoints(output_dir) -> list[Path]:
    """The run's checkpoint directories, named by step and ordered by it."""
    output_dir = Path(output_dir)
    if not output_dir.exists():
        return []
    return sorted(
        (p for p in output_dir.iterdir() if p.is_dir() and p.name.isdigit()),
        key=lambda p: int(p.name),
    )

find_resume

find_resume(output_dir) -> Resume | None

Where training left off in output_dir, or None if it never checkpointed.

The epoch count is the number of checkpoints past the one written at step 0, which is what a run writes per epoch; taking it from the directory keeps it right across several continuations, and across a schedule whose epochs changed size.

Source code in src/minimal_mjx/learning/training.py
def find_resume(output_dir) -> Resume | None:
    """Where training left off in ``output_dir``, or None if it never checkpointed.

    The epoch count is the number of checkpoints past the one written at step 0, which is
    what a run writes per epoch; taking it from the directory keeps it right across
    several continuations, and across a schedule whose epochs changed size.
    """
    checkpoints = find_checkpoints(output_dir)
    if not checkpoints:
        return None
    return Resume(checkpoints[-1], int(checkpoints[-1].name), len(checkpoints) - 1)

apply_resume

apply_resume(ppo_params: dict, resumed: Resume) -> dict

A copy of ppo_params asking the algorithm for only the steps the run still owes.

num_timesteps is the run's whole budget, so continuing a run is a matter of raising it: the algorithm is handed the difference.

Source code in src/minimal_mjx/learning/training.py
def apply_resume(ppo_params: dict, resumed: Resume) -> dict:
    """A copy of ``ppo_params`` asking the algorithm for only the steps the run still owes.

    ``num_timesteps`` is the run's whole budget, so continuing a run is a matter of
    raising it: the algorithm is handed the difference.
    """
    total = ppo_params['num_timesteps']
    if resumed.step >= total:
        raise ValueError(
            f"{resumed.path.parent} has already trained {resumed.step} of the "
            f"{total} steps in num_timesteps; raise num_timesteps to continue it"
        )
    print(
        f'Resuming {resumed.path.parent} from {resumed.step} steps (epoch '
        f'{resumed.epoch}); {total - resumed.step} steps left of {total}'
    )
    return {**ppo_params, 'num_timesteps': total - resumed.step}

create_training_directory

create_training_directory(
    run_dir, overwrite=False, resume=False
) -> Path

Create the run output directory, refusing to clobber an earlier run.

If the directory already exists but holds nothing a run produced -- only a stale config, or the run id of a job that died before its first epoch -- it is reused. overwrite reuses it whatever it holds (e.g. for scratch runs), and so does resume, for a run that continues the checkpoints already there.

Source code in src/minimal_mjx/learning/training.py
def create_training_directory(run_dir, overwrite=False, resume=False) -> Path:
    """Create the run output directory, refusing to clobber an earlier run.

    If the directory already exists but holds nothing a run produced -- only a stale
    config, or the run id of a job that died before its first epoch -- it is reused.
    ``overwrite`` reuses it whatever it holds (e.g. for scratch runs), and so does
    ``resume``, for a run that continues the checkpoints already there.
    """
    # Written before training starts, so their presence alone is not training output.
    stale = {'config.yaml', mm.utils.logging.RUN_ID_FNAME}
    run_dir = Path(run_dir)
    if run_dir.exists():
        if not (resume or overwrite) and not all(
            path.is_file() and path.name in stale for path in run_dir.iterdir()
        ):
            raise FileExistsError(f"Training directory already exists: {run_dir}")
    else:
        run_dir.mkdir(parents=True, exist_ok=True)
    return run_dir

train

train(
    env,
    eval_env,
    run_dir,
    train_fn_params,
    network_factory_params,
    handle_params,
    run=None,
    progress_cls=None,
    resume=False,
    overwrite=False,
)

Train a policy on the given environment.

Creates run_dir, resolves the training algorithm via handle_params then wraps the resulting train_fn with progress/checkpoint callbacks and runs it. Saving the run's config is up to the caller (see :meth:minimal_mjx.utils.config.Config.save).

Parameters:

Name Type Description Default
env

Training environment.

required
eval_env

Evaluation environment used for periodic rollouts.

required
run_dir

Directory for checkpoints and progress output.

required
train_fn_params

Algorithmic parameters for your specific training algo.

required
network_factory_params

Keyword arguments for the network factory.

required
run

(optional) Experiment-tracking handle (e.g. a wandb run).

None
handle_params

Callable (ppo_params, network_params, resumed) -> (train_fn, network_factory), where resumed is a :class:Resume or None.

required
progress_cls

(optional) Progress callback class, built as progress_cls(save_dir, total_timesteps, run) and handed to the algorithm through its plot_progress method. Defaults to :class:minimal_mjx.utils.plotting.Progress.

None
resume

(optional) If True, continue the checkpoints already in run_dir instead of refusing to overwrite it. num_timesteps is then the run's total budget and the algorithm trains what is left of it, checkpointing and plotting on the step axis the earlier job stopped on. An algorithm opts in by reading resumed; without that it retrains its whole share from scratch into the same directory.

False
overwrite

(optional) If True, train into run_dir even if it holds an earlier run's output.

False

Returns:

Type Description

Tuple (make_inference_fn, trained_params, metrics).

Source code in src/minimal_mjx/learning/training.py
def train(
    env,
    eval_env,
    run_dir,
    train_fn_params,
    network_factory_params,
    handle_params,
    run=None,
    progress_cls=None,
    resume=False,
    overwrite=False,
):
    """Train a policy on the given environment.

    Creates ``run_dir``, resolves the training algorithm via ``handle_params``
    then wraps the resulting ``train_fn`` with progress/checkpoint callbacks and runs
    it. Saving the run's config is up to the caller (see
    :meth:`minimal_mjx.utils.config.Config.save`).

    Args:
        env: Training environment.
        eval_env: Evaluation environment used for periodic rollouts.
        run_dir: Directory for checkpoints and progress output.
        train_fn_params: Algorithmic parameters for your specific training algo.
        network_factory_params: Keyword arguments for the network factory.
        run: (optional) Experiment-tracking handle (e.g. a wandb run).
        handle_params: Callable
            ``(ppo_params, network_params, resumed) -> (train_fn, network_factory)``,
            where ``resumed`` is a :class:`Resume` or None.
        progress_cls: (optional) Progress callback class, built as
            ``progress_cls(save_dir, total_timesteps, run)`` and handed to the
            algorithm through its ``plot_progress`` method. Defaults to
            :class:`minimal_mjx.utils.plotting.Progress`.
        resume: (optional) If True, continue the checkpoints already in ``run_dir``
            instead of refusing to overwrite it. ``num_timesteps`` is then the run's
            total budget and the algorithm trains what is left of it, checkpointing
            and plotting on the step axis the earlier job stopped on. An algorithm opts
            in by reading ``resumed``; without that it retrains its whole share from
            scratch into the same directory.
        overwrite: (optional) If True, train into ``run_dir`` even if it holds an
            earlier run's output.

    Returns:
        Tuple ``(make_inference_fn, trained_params, metrics)``.
    """
    if progress_cls is None:
        progress_cls = mm.utils.plotting.Progress
    output_dir = create_training_directory(run_dir, overwrite=overwrite, resume=resume)
    mm.utils.logging.save_run_id(output_dir, run)

    train_fn_params = dict(train_fn_params)
    total_timesteps = train_fn_params['num_timesteps']
    resumed = find_resume(output_dir) if resume else None
    if resume and resumed is None:
        print(f'Nothing to resume in {output_dir}; training from scratch.')
    if resumed is not None:
        train_fn_params = apply_resume(train_fn_params, resumed)
    # Steps the algorithm reports are its own; the run's axis carries on from here.
    step_offset = 0 if resumed is None else resumed.step

    # Resolve the training algorithm.
    train_fn, network_factory = handle_params(train_fn_params, network_factory_params, resumed)

    # PPO params are still read here for the network config and progress plot. The algo
    # was handed the steps still owed, but the plot reports against the whole budget.
    train_fn_params = {**train_fn_params, 'num_timesteps': total_timesteps}
    network_config = checkpoint.network_config(
        observation_size=eval_env.observation_size,
        action_size=eval_env.action_size,
        normalize_observations=train_fn_params['normalize_observations'],
        network_factory=network_factory,
    )

    def save_model_fn(current_step, make_policy, params, training_state=None):
        """Checkpoint the policy, and the learner state a continued run would need."""
        step = step_offset + current_step
        mm.utils.logging.save_model(
            step, make_policy, params,
            network_config = network_config,
            output_dir     = output_dir,
            run            = run,
        )
        if training_state is not None:
            mm.utils.logging.save_training_state(output_dir, step, training_state)

    progress = progress_cls(output_dir, total_timesteps, run)
    if resumed is not None:
        progress.load(before=resumed.step)
    times = progress.times
    first = len(times)  # this job's own rows, for the timings printed below
    train_fn = functools.partial(
        train_fn,
        progress_fn=lambda num_steps, metrics: progress.plot_progress(
            step_offset + num_steps, metrics
        ),
        policy_params_fn=save_model_fn,
    )

    print(
        'Started training at',
        datetime.now(ZoneInfo("America/New_York")).strftime("%Y-%m-%d %H:%M:%S %Z")
    )
    make_inference_fn, trained_params, metrics = train_fn(
        environment=env,
        eval_env=eval_env,
    )
    print(f"time to jit: {times[first + 1] - times[first]}")
    print(f"time to train: {times[-1] - times[first + 1]}")

    return make_inference_fn, trained_params, metrics

minimal_mjx.learning.inference

Inference utilities for loading and interacting with trained RL models.

Functions:

Name Description
get_step_reset

Return (step, reset) functions, jitted if using JAX backend.

get_all_models

Return all checkpoint directories in run_dir, sorted by step if requested.

get_last_model

Return the most recent checkpoint directory in run_dir.

load_policy

Load and return a policy from checkpoint_path, or the last checkpoint in

get_params

Load and return model parameters from path, or the last checkpoint in

get_step_reset

get_step_reset(env: Any) -> tuple[Callable, Callable]

Return (step, reset) functions, jitted if using JAX backend.

Source code in src/minimal_mjx/learning/inference.py
def get_step_reset(env: Any) -> tuple[Callable, Callable]:
    """Return (step, reset) functions, jitted if using JAX backend."""
    if env._np == jax.numpy:
        print('jitting')
        reset = jax.jit(env.reset)
        step = jax.jit(env.step)
    else:
        reset = env.reset
        step = env.step
    return step, reset

get_all_models

get_all_models(
    run_dir: Path | str, sort: bool = True
) -> List[Path]

Return all checkpoint directories in run_dir, sorted by step if requested.

Source code in src/minimal_mjx/learning/inference.py
def get_all_models(run_dir: Path | str, sort: bool = True) -> List[Path]:
    """Return all checkpoint directories in ``run_dir``, sorted by step if requested."""
    run_dir = Path(run_dir)
    if not run_dir.exists():
        raise FileNotFoundError(f"Model directory does not exist: {run_dir}")
    model_files = [
        path for path in map(Path, glob(str(run_dir / '*')))
        if path.is_dir() and path.name.isdigit()
    ]
    if sort:
        model_files.sort(key=lambda x: int(x.name))
    return model_files

get_last_model

get_last_model(run_dir: Path | str) -> Path

Return the most recent checkpoint directory in run_dir.

Source code in src/minimal_mjx/learning/inference.py
def get_last_model(run_dir: Path | str) -> Path:
    """Return the most recent checkpoint directory in ``run_dir``."""
    model_files = get_all_models(run_dir, sort=True)
    if not model_files:
        raise FileNotFoundError(f"No checkpoints in {run_dir}")
    return model_files[-1]

load_policy

load_policy(
    run_dir: Path | str,
    deterministic: bool = True,
    checkpoint_path: Optional[Path] = None,
) -> Callable

Load and return a policy from checkpoint_path, or the last checkpoint in run_dir.

Source code in src/minimal_mjx/learning/inference.py
def load_policy(
    run_dir: Path | str,
    deterministic: bool = True,
    checkpoint_path: Optional[Path] = None
) -> Callable:
    """Load and return a policy from ``checkpoint_path``, or the last checkpoint in
    ``run_dir``."""
    if checkpoint_path is None:
        path = get_last_model(run_dir)
    else:
        path = Path(checkpoint_path)
    print(f'Loading model at {path.as_posix()}')
    policy = checkpoint.load_policy(
        path.resolve(),
        deterministic=deterministic
    )
    return policy

get_params

get_params(
    run_dir: Path | str,
    path: Optional[Path] = None,
    silent: bool = False,
) -> Any

Load and return model parameters from path, or the last checkpoint in run_dir.

Source code in src/minimal_mjx/learning/inference.py
def get_params(
    run_dir: Path | str,
    path: Optional[Path] = None,
    silent: bool = False
) -> Any:
    """Load and return model parameters from ``path``, or the last checkpoint in
    ``run_dir``."""
    if path is None:
        path = get_last_model(run_dir)
    path = Path(path)
    if not silent:
        print(f'Loading model at {path.as_posix()}')
    params = checkpoint.load(epath.Path(path.resolve()))
    return params