Skip to content

minimal_mjx.utils

Configs, logging, plotting, and setup helpers.

minimal_mjx.utils.config

Classes:

Name Description
FlowSeqDumper
Config

Reads a run's YAML config and hands its values to library functions.

Functions:

Name Description
read_yaml
read_config

Reads the YAML config file at path into a ConfigDict.

create_config_dict

Converts a dictionary to a ConfigDict.

save_config

Saves a ConfigDict (or dict) to a YAML file.

get_commit_hash
deepcopy_config

FlowSeqDumper

Bases: Dumper

Methods:

Name Description
represent_sequence
Source code in src/minimal_mjx/utils/config.py
class FlowSeqDumper(yaml.Dumper):
    def represent_sequence(self, tag, sequence, flow_style=None):
        # Force all sequences (lists) to use flow style
        return super().represent_sequence(tag, sequence, flow_style=True)

represent_sequence

represent_sequence(tag, sequence, flow_style=None)
Source code in src/minimal_mjx/utils/config.py
def represent_sequence(self, tag, sequence, flow_style=None):
    # Force all sequences (lists) to use flow style
    return super().represent_sequence(tag, sequence, flow_style=True)

Config

Reads a run's YAML config and hands its values to library functions.

This is the only place that knows the YAML layout. Library functions take plain arguments (run_dir, ppo_params, ...), so a different config layout only needs a subclass that overrides these properties.

Methods:

Name Description
load
save

Write the config to path (default run_dir / 'config.yaml').

Attributes:

Name Type Description
cfg
algorithm str

Learning algorithm, e.g. 'ppo' (the default when unset).

env_name str

Environment class name, e.g. 'Cheetah'.

backend str

Backend for evaluation environments, 'np' or 'jnp'.

env_params ConfigDict

The env_config section, given to env classes as env_params.

ppo_params dict

Brax PPO settings, passed to the trainer as keyword arguments.

network_params dict

Network settings for the configured algorithm.

normalize_observations bool

Whether training keeps a running observation normalizer.

name str

Run name.

total_timesteps str
is_test bool

Runs named test may be overwritten and do not record a git hash.

save_dir Path

Parent directory of all runs for this config.

run_dir Path

Run directory: save_dir / name.

Source code in src/minimal_mjx/utils/config.py
class Config:
    """Reads a run's YAML config and hands its values to library functions.

    This is the only place that knows the YAML layout. Library functions take plain
    arguments (``run_dir``, ``ppo_params``, ...), so a different config layout only
    needs a subclass that overrides these properties.
    """

    def __init__(self, config: Path):
        self.cfg = read_config(config)

    def load(self, config):
        self.cfg = read_config(config)
        return self.cfg

    def save(self, path: Path = None, make_dir=True, rewrite_test=True, warn_github_changes=True):
        """Write the config to ``path`` (default ``run_dir / 'config.yaml'``).

        Runs not named ``test`` record the current git commit as ``git_hash``.
        """
        if path is None:
            path = self.run_dir / 'config.yaml'
        if make_dir:
            os.makedirs(self.run_dir, exist_ok=self.is_test)

        if not self.is_test and rewrite_test:
            self.cfg.git_hash = get_commit_hash(warn=warn_github_changes)

        save_config(self.cfg, path)

    @property
    def algorithm(self) -> str:
        """Learning algorithm, e.g. ``'ppo'`` (the default when unset)."""
        return self.cfg.get('algorithm', 'ppo')

    @property
    def env_name(self) -> str:
        """Environment class name, e.g. ``'Cheetah'``."""
        return self.cfg.env

    @property
    def backend(self) -> str:
        """Backend for evaluation environments, ``'np'`` or ``'jnp'``."""
        return self.cfg.backend

    @property
    def env_params(self) -> config_dict.ConfigDict:
        """The ``env_config`` section, given to env classes as ``env_params``."""
        return create_config_dict(self.cfg.env_config.to_dict())

    @property
    def ppo_params(self) -> dict:
        """Brax PPO settings, passed to the trainer as keyword arguments."""
        return self.cfg.learning_params.ppo_params.to_dict()

    @property
    def network_params(self) -> dict:
        """Network settings for the configured algorithm."""
        return self.cfg.learning_params.network_params.to_dict()

    @property
    def normalize_observations(self) -> bool:
        """Whether training keeps a running observation normalizer."""
        return self.cfg.learning_params.ppo_params.normalize_observations

    @property
    def name(self) -> str:
        """Run name."""
        return self.cfg.name

    @property
    def total_timesteps(self) -> str:
        return self.cfg.learning_params.ppo_params.num_timesteps

    @name.setter
    def name(self, value: str):
        self.cfg.name = str(value)

    @property
    def is_test(self) -> bool:
        """Runs named ``test`` may be overwritten and do not record a git hash."""
        return self.name == 'test'

    @property
    def save_dir(self) -> Path:
        """Parent directory of all runs for this config."""
        return Path(self.cfg.save_dir)

    @save_dir.setter
    def save_dir(self, value):
        self.cfg.save_dir = str(value)

    @property
    def run_dir(self) -> Path:
        """Run directory: ``save_dir / name``."""
        return self.save_dir / self.name

cfg instance-attribute

cfg = read_config(config)

algorithm property

algorithm: str

Learning algorithm, e.g. 'ppo' (the default when unset).

env_name property

env_name: str

Environment class name, e.g. 'Cheetah'.

backend property

backend: str

Backend for evaluation environments, 'np' or 'jnp'.

env_params property

env_params: ConfigDict

The env_config section, given to env classes as env_params.

ppo_params property

ppo_params: dict

Brax PPO settings, passed to the trainer as keyword arguments.

network_params property

network_params: dict

Network settings for the configured algorithm.

normalize_observations property

normalize_observations: bool

Whether training keeps a running observation normalizer.

name property writable

name: str

Run name.

total_timesteps property

total_timesteps: str

is_test property

is_test: bool

Runs named test may be overwritten and do not record a git hash.

save_dir property writable

save_dir: Path

Parent directory of all runs for this config.

run_dir property

run_dir: Path

Run directory: save_dir / name.

load

load(config)
Source code in src/minimal_mjx/utils/config.py
def load(self, config):
    self.cfg = read_config(config)
    return self.cfg

save

save(
    path: Path = None,
    make_dir=True,
    rewrite_test=True,
    warn_github_changes=True,
)

Write the config to path (default run_dir / 'config.yaml').

Runs not named test record the current git commit as git_hash.

Source code in src/minimal_mjx/utils/config.py
def save(self, path: Path = None, make_dir=True, rewrite_test=True, warn_github_changes=True):
    """Write the config to ``path`` (default ``run_dir / 'config.yaml'``).

    Runs not named ``test`` record the current git commit as ``git_hash``.
    """
    if path is None:
        path = self.run_dir / 'config.yaml'
    if make_dir:
        os.makedirs(self.run_dir, exist_ok=self.is_test)

    if not self.is_test and rewrite_test:
        self.cfg.git_hash = get_commit_hash(warn=warn_github_changes)

    save_config(self.cfg, path)

read_yaml

read_yaml(yaml_file)
Source code in src/minimal_mjx/utils/config.py
def read_yaml(yaml_file):
    try:
        with open(yaml_file, 'r') as file:
            data = yaml.safe_load(file)
    except Exception as e:
        raise Exception(f"Error reading {yaml_file}: {e}") from e
    return data

read_config

read_config(path)

Reads the YAML config file at path into a ConfigDict.

Source code in src/minimal_mjx/utils/config.py
def read_config(path):
    """Reads the YAML config file at ``path`` into a ConfigDict."""
    data = read_yaml(path)
    return config_dict.ConfigDict(data)

create_config_dict

create_config_dict(config: dict) -> ConfigDict

Converts a dictionary to a ConfigDict.

Source code in src/minimal_mjx/utils/config.py
def create_config_dict(config: dict) -> config_dict.ConfigDict:
    """Converts a dictionary to a ConfigDict."""
    config_dict_obj = config_dict.ConfigDict()
    for key, value in config.items():
        if isinstance(value, dict):
            config_dict_obj[key] = create_config_dict(value)
        else:
            config_dict_obj[key] = value
    return config_dict_obj

save_config

save_config(config, path)

Saves a ConfigDict (or dict) to a YAML file.

Source code in src/minimal_mjx/utils/config.py
def save_config(config, path):
    """Saves a ConfigDict (or dict) to a YAML file."""
    if isinstance(config, config_dict.ConfigDict):
        config = config.to_dict()
    with open(path, 'w') as file:
        yaml.dump(config, file, Dumper=FlowSeqDumper, default_flow_style=False)

get_commit_hash

get_commit_hash(warn=True)
Source code in src/minimal_mjx/utils/config.py
def get_commit_hash(warn=True):
    import subprocess

    try:
        commit_hash = subprocess.check_output(
            ['git', 'rev-parse', 'HEAD']
        ).decode('utf-8').strip()

        # Check for unadded / uncommitted changes
        status_output = subprocess.check_output(
            ['git', 'status', '--porcelain']
        ).decode('utf-8').strip()

        if status_output and warn:
            input("⚠️ Warning: There are unadded or uncommitted changes in the repository. Press ENTER to continue...")

        return commit_hash

    except subprocess.CalledProcessError as e:
        print(f"Error getting commit hash: {e}")
        return None

deepcopy_config

deepcopy_config(config: ConfigDict)
Source code in src/minimal_mjx/utils/config.py
def deepcopy_config(config: config_dict.ConfigDict):
    return copy.deepcopy(config)

minimal_mjx.utils.logging

Functions:

Name Description
flatten_config

Flatten a nested (dict-like) config so every leaf is keyed by its path, joined by sep.

unflatten_config

Inverse of flatten_config: rebuild a nested config from its a/b/c keys.

initialize_wandb

Initialize and return a new W&B run.

save_model

Save a Brax checkpoint and optionally log it as a W&B artifact.

save_training_state

Overwrite the run's learner state, so a continued run picks up mid-stream.

load_training_state

(step, state) restored into like's pytree, or None if the run saved none.

save_run_id

Record which W&B run wrote output_dir, for a later job to continue it.

load_run_id

The W&B run id a previous job left in output_dir, or None.

get_latest_artifact

Return the last-logged artifact of run whose name contains prefix, or raise ValueError.

get_earliest_artifact

Return the first artifact of run matching prefix written at or past

download_model

Download a W&B run's config and a policy checkpoint into run_dir.

Attributes:

Name Type Description
TRAIN_STATE_DIRNAME
RUN_ID_FNAME

TRAIN_STATE_DIRNAME module-attribute

TRAIN_STATE_DIRNAME = 'training_state'

RUN_ID_FNAME module-attribute

RUN_ID_FNAME = 'wandb_run_id.txt'

flatten_config

flatten_config(config, parent_key='', sep='/')

Flatten a nested (dict-like) config so every leaf is keyed by its path, joined by sep.

Source code in src/minimal_mjx/utils/logging.py
def flatten_config(config, parent_key='', sep='/'):
    """Flatten a nested (dict-like) config so every leaf is keyed by its path, joined by `sep`.
    """
    items = {}
    for key, value in config.items():
        key = str(key)
        if sep in key:
            raise ValueError(
                f"Config key '{key}'{f' (under {parent_key})' if parent_key else ''} contains "
                f"'{sep}', which is reserved as the delimiter between nesting levels. Rename "
                f"the key (e.g. '{key.replace(sep, '_')}') or flatten with a different `sep`."
            )
        new_key = f'{parent_key}{sep}{key}' if parent_key else key
        if hasattr(value, 'items'):
            items.update(flatten_config(value, new_key, sep=sep))
        else:
            items[new_key] = value
    return items

unflatten_config

unflatten_config(flat_config, sep='/')

Inverse of flatten_config: rebuild a nested config from its a/b/c keys.

Source code in src/minimal_mjx/utils/logging.py
def unflatten_config(flat_config, sep='/'):
    """Inverse of `flatten_config`: rebuild a nested config from its `a/b/c` keys.
    """
    config = {}
    for key, value in flat_config.items():
        if key.startswith('_'):
            continue
        *parents, leaf = key.split(sep)
        node = config
        for depth, parent in enumerate(parents):
            node = node.setdefault(parent, {})
            if not isinstance(node, dict):
                raise ValueError(
                    f"Cannot unflatten '{key}': '{sep.join(parents[:depth + 1])}' is a "
                    f"value ({node!r}), not a section."
                )
        node[leaf] = value
    return config

initialize_wandb

initialize_wandb(
    entity="njanwani-gatech",
    project="prefMORL",
    name="test",
    config={},
    **kwargs,
)

Initialize and return a new W&B run.

Source code in src/minimal_mjx/utils/logging.py
def initialize_wandb(entity='njanwani-gatech', project='prefMORL', name='test', config={}, **kwargs):
    """Initialize and return a new W&B run."""
    return wandb.init(
        entity    = entity,
        project   = project,
        name      = name,
        config    = config,
        **kwargs
    )

save_model

save_model(
    current_step,
    make_policy,
    params,
    network_config,
    output_dir: Path,
    run: Run = None,
)

Save a Brax checkpoint and optionally log it as a W&B artifact.

Source code in src/minimal_mjx/utils/logging.py
def save_model(current_step, make_policy, params, network_config, output_dir: Path, run: wandb.Run = None):
    """Save a Brax checkpoint and optionally log it as a W&B artifact."""
    checkpoint.save(
        path=output_dir.resolve(),
        step=current_step,
        params=params,
        config=network_config,
        config_fname=_CONFIG_FNAME,
    )
    if run:
        artifact = wandb.Artifact(name=f'{run.id}_hypernetworks', type='model')
        artifact.add_dir((output_dir / f'{current_step:012d}').resolve())
        artifact.metadata['iteration'] = current_step
        run.log_artifact(artifact)

save_training_state

save_training_state(
    output_dir: Path, step: int, state: Any
) -> None

Overwrite the run's learner state, so a continued run picks up mid-stream.

TODO: clean up this docstring

A brax checkpoint holds what inference needs -- the policy's params and the observation normalizer. Training also depends on the optimizer's moments and on networks the policy never runs, such as a value function, so those are written here instead. Only the newest state is kept, since a run continues where it stopped.

Source code in src/minimal_mjx/utils/logging.py
def save_training_state(output_dir: Path, step: int, state: Any) -> None:
    """Overwrite the run's learner state, so a continued run picks up mid-stream.
    # TODO: clean up this docstring
    A brax checkpoint holds what inference needs -- the policy's params and the
    observation normalizer. Training also depends on the optimizer's moments and on
    networks the policy never runs, such as a value function, so those are written here
    instead. Only the newest state is kept, since a run continues where it stopped.
    """
    ocp.PyTreeCheckpointer().save(
        (Path(output_dir) / TRAIN_STATE_DIRNAME).resolve(), (step, state), force=True
    )

load_training_state

load_training_state(
    output_dir: Path, like: Any
) -> tuple[int, Any] | None

(step, state) restored into like's pytree, or None if the run saved none.

like is a freshly built state: orbax fills its arrays, so the restored state has the same tree structure, shapes and dtypes by construction.

Source code in src/minimal_mjx/utils/logging.py
def load_training_state(output_dir: Path, like: Any) -> tuple[int, Any] | None:
    """`(step, state)` restored into `like`'s pytree, or None if the run saved none.

    `like` is a freshly built state: orbax fills its arrays, so the restored state has
    the same tree structure, shapes and dtypes by construction.
    """
    path = (Path(output_dir) / TRAIN_STATE_DIRNAME).resolve()
    if not path.exists():
        return None
    return ocp.PyTreeCheckpointer().restore(path, item=(0, like))

save_run_id

save_run_id(output_dir: Path, run: Run | None) -> None

Record which W&B run wrote output_dir, for a later job to continue it.

Source code in src/minimal_mjx/utils/logging.py
def save_run_id(output_dir: Path, run: wandb.Run | None) -> None:
    """Record which W&B run wrote `output_dir`, for a later job to continue it."""
    if run is not None:
        (Path(output_dir) / RUN_ID_FNAME).write_text(str(run.id))

load_run_id

load_run_id(output_dir: Path) -> str | None

The W&B run id a previous job left in output_dir, or None.

Source code in src/minimal_mjx/utils/logging.py
def load_run_id(output_dir: Path) -> str | None:
    """The W&B run id a previous job left in `output_dir`, or None."""
    path = Path(output_dir) / RUN_ID_FNAME
    return path.read_text().strip() if path.exists() else None

get_latest_artifact

get_latest_artifact(run: Run, prefix: str) -> Artifact

Return the last-logged artifact of run whose name contains prefix, or raise ValueError.

Source code in src/minimal_mjx/utils/logging.py
def get_latest_artifact(run: wandb.apis.public.Run, prefix: str) -> wandb.Artifact:
    """Return the last-logged artifact of `run` whose name contains `prefix`, or raise ValueError."""
    matches = [artifact for artifact in run.logged_artifacts() if prefix in artifact.name]
    if not matches:
        raise ValueError(
            f"No '{prefix}' artifact found for run {run.id}. "
            f"Logged artifacts: {[a.name for a in run.logged_artifacts()] or 'none'}"
        )
    return matches[-1]

get_earliest_artifact

get_earliest_artifact(
    run: Run, prefix: str, iterations: float
) -> Artifact

Return the first artifact of run matching prefix written at or past iterations training steps, or raise ValueError.

A checkpoint artifact records the step it was written at in metadata['iteration'], so the choice is made from the run's artifact listing without downloading any of them.

Source code in src/minimal_mjx/utils/logging.py
def get_earliest_artifact(
    run: wandb.apis.public.Run, prefix: str, iterations: float
) -> wandb.Artifact:
    """Return the first artifact of `run` matching `prefix` written at or past
    `iterations` training steps, or raise ValueError.

    A checkpoint artifact records the step it was written at in `metadata['iteration']`,
    so the choice is made from the run's artifact listing without downloading any of them.
    """
    matches = [
        artifact for artifact in run.logged_artifacts()
        if prefix in artifact.name and 'iteration' in artifact.metadata
    ]
    past = [a for a in matches if a.metadata['iteration'] >= iterations]
    if not past:
        raise ValueError(
            f"No '{prefix}' artifact at or past {iterations:.0f} iterations for run "
            f"{run.id}. Logged iterations: "
            f"{sorted(a.metadata['iteration'] for a in matches) or 'none'}"
        )
    return min(past, key=lambda a: a.metadata['iteration'])

download_model

download_model(
    run_id: str,
    run_dir: Path | str,
    entity: str,
    project: str,
    prefix: str,
    iterations: float | None = None,
) -> str

Download a W&B run's config and a policy checkpoint into run_dir.

The config is saved, unchanged, as run_dir / 'config.yaml' (rebuilt from the run's logged config if it has no config artifact). Its paths still point at where the run trained, so update them before reusing it, e.g. with :class:minimal_mjx.utils.config.Config.

The checkpoint is the last artifact whose name contains prefix, or, with iterations, the first one written at or past that many training steps. Returns the checkpoint's directory.

Source code in src/minimal_mjx/utils/logging.py
def download_model(run_id: str, run_dir: Path | str,
                   entity: str, project: str, prefix: str,
                   iterations: float | None = None) -> str:
    """Download a W&B run's config and a policy checkpoint into ``run_dir``.

    The config is saved, unchanged, as ``run_dir / 'config.yaml'`` (rebuilt from the
    run's logged config if it has no config artifact). Its paths still point at where
    the run trained, so update them before reusing it, e.g. with
    :class:`minimal_mjx.utils.config.Config`.

    The checkpoint is the last artifact whose name contains ``prefix``, or, with
    ``iterations``, the first one written at or past that many training steps.
    Returns the checkpoint's directory.
    """
    run_dir = Path(run_dir)
    api = wandb.Api()
    run = api.run(f'{entity}/{project}/{run_id}')

    run_dir.mkdir(parents=True, exist_ok=True)
    try:
        config_artifact = get_latest_artifact(run, 'config')
    except ValueError:
        save_config(unflatten_config(run.config), run_dir / 'config.yaml')
    else:
        config_artifact.download(root=run_dir)

    policy_artifact = (
        get_latest_artifact(run, prefix) if iterations is None
        else get_earliest_artifact(run, prefix, iterations)
    )
    artifact_dir = policy_artifact.download(
        root=str(run_dir / str(policy_artifact.metadata['iteration']))
    )
    return artifact_dir

minimal_mjx.utils.plotting

Plotting utilities for MuJoCo simulation data, reward metrics, and video export.

Classes:

Name Description
InfoPlotter

Collects arbitrary info-dict fields over time and exports to HDF5.

MujocoPlotter

Collects MuJoCo mjData fields over time and exports to HDF5.

RewardPlotter

Accumulates per-step reward components and produces a summary figure.

Progress

Brax PPO progress callback that accumulates the eval reward curve.

Functions:

Name Description
set_mpl_params

Configure matplotlib for publication-quality LaTeX-style figures.

get_subplot_grid

Return (nrows, ncols) for a roughly square grid that fits n subplots.

get_mj_scene_option

Create an MjvOption with common visualization flags toggled.

add_text_to_frame

Overlay text on a frame (in-place) and return it.

infer_frame_dim
load_progress

Refill a :class:Progress's curves from the progress.csv a previous job wrote.

check_directory_exists
save_metrics

Plot metrics from a RewardPlotter and save the figure to path.

save_video

Write a list of frames to an MP4 video at the environment control rate.

load_dict_from_hdf5

Load all datasets from an HDF5 file into a {key: ndarray} dict.

InfoPlotter

Collects arbitrary info-dict fields over time and exports to HDF5.

Methods:

Name Description
add_row

Append one timestep of data from an info dict.

to_numpy

Convert all stored lists to numpy arrays in-place.

save_to_h5

Write all data to an HDF5 file.

Attributes:

Name Type Description
DEFAULT_PLOTKEY list[str]
plotkey list[str]
data dict[str, list[Any]]
Source code in src/minimal_mjx/utils/plotting.py
class InfoPlotter:
    """Collects arbitrary info-dict fields over time and exports to HDF5."""

    DEFAULT_PLOTKEY: list[str] = []

    def __init__(self, plotkey: list[str] | None = None) -> None:
        self.plotkey: list[str] = plotkey if plotkey is not None else self.DEFAULT_PLOTKEY
        self.data: dict[str, list[Any]] = {key: [] for key in self.plotkey}
        self.data['time'] = []

    def add_row(self, time: float, info: dict[str, Any]) -> None:
        """Append one timestep of data from an info dict."""
        for key in self.plotkey:
            self.data[key].append(info[key].copy())
        self.data['time'].append(time)

    def to_numpy(self) -> None:
        """Convert all stored lists to numpy arrays in-place."""
        for key in self.data:
            self.data[key] = np.array(self.data[key])

    def save_to_h5(self, filename: str | Path) -> None:
        """Write all data to an HDF5 file."""
        with h5py.File(filename, 'w') as f:
            for key in self.data:
                f.create_dataset(key, data=np.array(self.data[key]))

DEFAULT_PLOTKEY class-attribute instance-attribute

DEFAULT_PLOTKEY: list[str] = []

plotkey instance-attribute

plotkey: list[str] = (
    plotkey if plotkey is not None else self.DEFAULT_PLOTKEY
)

data instance-attribute

data: dict[str, list[Any]] = {
    key: [] for key in self.plotkey
}

add_row

add_row(time: float, info: dict[str, Any]) -> None

Append one timestep of data from an info dict.

Source code in src/minimal_mjx/utils/plotting.py
def add_row(self, time: float, info: dict[str, Any]) -> None:
    """Append one timestep of data from an info dict."""
    for key in self.plotkey:
        self.data[key].append(info[key].copy())
    self.data['time'].append(time)

to_numpy

to_numpy() -> None

Convert all stored lists to numpy arrays in-place.

Source code in src/minimal_mjx/utils/plotting.py
def to_numpy(self) -> None:
    """Convert all stored lists to numpy arrays in-place."""
    for key in self.data:
        self.data[key] = np.array(self.data[key])

save_to_h5

save_to_h5(filename: str | Path) -> None

Write all data to an HDF5 file.

Source code in src/minimal_mjx/utils/plotting.py
def save_to_h5(self, filename: str | Path) -> None:
    """Write all data to an HDF5 file."""
    with h5py.File(filename, 'w') as f:
        for key in self.data:
            f.create_dataset(key, data=np.array(self.data[key]))

MujocoPlotter

Collects MuJoCo mjData fields over time and exports to HDF5.

Methods:

Name Description
add_row

Append one timestep of data from an mjData-like object.

to_numpy

Convert all stored lists to numpy arrays in-place.

save_to_h5

Write all data to an HDF5 file.

time_idx

Return the index of the last entry at or before time.

Attributes:

Name Type Description
DEFAULT_PLOTKEY list[str]
plotkey list[str]
record_time bool
data dict[str, list[Any]]
Source code in src/minimal_mjx/utils/plotting.py
class MujocoPlotter:
    """Collects MuJoCo mjData fields over time and exports to HDF5."""

    DEFAULT_PLOTKEY: list[str] = ['qpos', 'qvel', 'ctrl', 'sensordata', 'qfrc_actuator']

    def __init__(self, plotkey: list[str] | None = None, record_time: bool = True) -> None:
        self.plotkey: list[str] = plotkey if plotkey is not None else self.DEFAULT_PLOTKEY
        self.record_time: bool = record_time
        self.data: dict[str, list[Any]] = {key: [] for key in self.plotkey}
        if record_time:
            self.data['time'] = []

    def add_row(self, data: mujoco.MjData) -> None:
        """Append one timestep of data from an mjData-like object."""
        if self.record_time:
            self.data['time'].append(getattr(data, 'time'))
        for key in self.plotkey:
            self.data[key].append(getattr(data, key).copy())

    def to_numpy(self) -> None:
        """Convert all stored lists to numpy arrays in-place."""
        for key in self.plotkey:
            self.data[key] = np.array(self.data[key])

    def save_to_h5(self, filename: str | Path) -> None:
        """Write all data to an HDF5 file."""
        with h5py.File(filename, 'w') as f:
            for key in self.data:
                f.create_dataset(key, data=np.array(self.data[key]))

    @classmethod
    def time_idx(cls, time: float, data: dict[str, list[Any]]) -> int:
        """Return the index of the last entry at or before *time*."""
        if 'time' not in data:
            raise ValueError("Time data is required for indexing.")
        time_array = np.array(data['time'])
        idx = np.searchsorted(time_array, time)
        if idx == 0 or idx == len(time_array):
            raise ValueError("Time index out of bounds.")
        return idx - 1

DEFAULT_PLOTKEY class-attribute instance-attribute

DEFAULT_PLOTKEY: list[str] = [
    "qpos",
    "qvel",
    "ctrl",
    "sensordata",
    "qfrc_actuator",
]

plotkey instance-attribute

plotkey: list[str] = (
    plotkey if plotkey is not None else self.DEFAULT_PLOTKEY
)

record_time instance-attribute

record_time: bool = record_time

data instance-attribute

data: dict[str, list[Any]] = {
    key: [] for key in self.plotkey
}

add_row

add_row(data: MjData) -> None

Append one timestep of data from an mjData-like object.

Source code in src/minimal_mjx/utils/plotting.py
def add_row(self, data: mujoco.MjData) -> None:
    """Append one timestep of data from an mjData-like object."""
    if self.record_time:
        self.data['time'].append(getattr(data, 'time'))
    for key in self.plotkey:
        self.data[key].append(getattr(data, key).copy())

to_numpy

to_numpy() -> None

Convert all stored lists to numpy arrays in-place.

Source code in src/minimal_mjx/utils/plotting.py
def to_numpy(self) -> None:
    """Convert all stored lists to numpy arrays in-place."""
    for key in self.plotkey:
        self.data[key] = np.array(self.data[key])

save_to_h5

save_to_h5(filename: str | Path) -> None

Write all data to an HDF5 file.

Source code in src/minimal_mjx/utils/plotting.py
def save_to_h5(self, filename: str | Path) -> None:
    """Write all data to an HDF5 file."""
    with h5py.File(filename, 'w') as f:
        for key in self.data:
            f.create_dataset(key, data=np.array(self.data[key]))

time_idx classmethod

time_idx(time: float, data: dict[str, list[Any]]) -> int

Return the index of the last entry at or before time.

Source code in src/minimal_mjx/utils/plotting.py
@classmethod
def time_idx(cls, time: float, data: dict[str, list[Any]]) -> int:
    """Return the index of the last entry at or before *time*."""
    if 'time' not in data:
        raise ValueError("Time data is required for indexing.")
    time_array = np.array(data['time'])
    idx = np.searchsorted(time_array, time)
    if idx == 0 or idx == len(time_array):
        raise ValueError("Time index out of bounds.")
    return idx - 1

RewardPlotter

Accumulates per-step reward components and produces a summary figure.

Methods:

Name Description
add_row

Record one timestep of metric values and total reward.

plot

Create a multi-subplot figure of all metrics plus total reward.

Attributes:

Name Type Description
axkey dict[str, int]
axdata dict[str, list[float]]
rewards list[float]
Source code in src/minimal_mjx/utils/plotting.py
class RewardPlotter:
    """Accumulates per-step reward components and produces a summary figure."""

    def __init__(self, metrics: Sequence[str]) -> None:
        self.axkey: dict[str, int] = {}
        self.axdata: dict[str, list[float]] = {}
        self.rewards: list[float] = []
        for i, metric in enumerate(metrics):
            self.axkey[metric] = i
            self.axdata[metric] = []

    def add_row(self, metrics: dict[str, float], reward: float) -> None:
        """Record one timestep of metric values and total reward."""
        self.rewards.append(reward)
        for metric in metrics:
            self.axdata[metric].append(metrics[metric])

    def plot(self, figsize: tuple[int, int] = (10, 10),
             title: str = 'Metrics') -> tuple[mfig.Figure, np.ndarray]:
        """Create a multi-subplot figure of all metrics plus total reward."""
        nrows, ncols = get_subplot_grid(len(self.axdata) + 1)
        fig, axs = plt.subplots(nrows, ncols, figsize=figsize)
        axs = axs.flatten()
        fig.suptitle(title)

        for metric in self.axdata:
            axs[self.axkey[metric]].set_title(metric)
            axs[self.axkey[metric]].plot(self.axdata[metric])

        axs[len(self.axdata)].set_title('Total Reward')
        axs[len(self.axdata)].plot(self.rewards)
        return fig, axs

axkey instance-attribute

axkey: dict[str, int] = {}

axdata instance-attribute

axdata: dict[str, list[float]] = {}

rewards instance-attribute

rewards: list[float] = []

add_row

add_row(metrics: dict[str, float], reward: float) -> None

Record one timestep of metric values and total reward.

Source code in src/minimal_mjx/utils/plotting.py
def add_row(self, metrics: dict[str, float], reward: float) -> None:
    """Record one timestep of metric values and total reward."""
    self.rewards.append(reward)
    for metric in metrics:
        self.axdata[metric].append(metrics[metric])

plot

plot(
    figsize: tuple[int, int] = (10, 10),
    title: str = "Metrics",
) -> tuple[Figure, ndarray]

Create a multi-subplot figure of all metrics plus total reward.

Source code in src/minimal_mjx/utils/plotting.py
def plot(self, figsize: tuple[int, int] = (10, 10),
         title: str = 'Metrics') -> tuple[mfig.Figure, np.ndarray]:
    """Create a multi-subplot figure of all metrics plus total reward."""
    nrows, ncols = get_subplot_grid(len(self.axdata) + 1)
    fig, axs = plt.subplots(nrows, ncols, figsize=figsize)
    axs = axs.flatten()
    fig.suptitle(title)

    for metric in self.axdata:
        axs[self.axkey[metric]].set_title(metric)
        axs[self.axkey[metric]].plot(self.axdata[metric])

    axs[len(self.axdata)].set_title('Total Reward')
    axs[len(self.axdata)].plot(self.rewards)
    return fig, axs

Progress

Brax PPO progress callback that accumulates the eval reward curve.

Pass :meth:plot_progress as brax's progress_fn. The curve is rewritten to save_dir/progress.csv on every eval, and every scalar metric is logged to run (e.g. a wandb run) when one is given.

Methods:

Name Description
load

Refill the curves from an earlier job's progress.csv (see :func:load_progress).

plot_progress

Brax PPO progress callback: accumulate eval reward, log native W&B lines.

Attributes:

Name Type Description
run
times
x_data
y_data
y_dataerr
save_dir
total_timesteps
Source code in src/minimal_mjx/utils/plotting.py
class Progress:
    """Brax PPO progress callback that accumulates the eval reward curve.

    Pass :meth:`plot_progress` as brax's ``progress_fn``. The curve is rewritten to
    ``save_dir/progress.csv`` on every eval, and every scalar metric is logged to
    ``run`` (e.g. a wandb run) when one is given.
    """

    def __init__(self, save_dir, total_timesteps=None, run=None) -> None:
        self.run                = run
        self.times              = []
        self.x_data             = []
        self.y_data             = []
        self.y_dataerr          = []
        self.save_dir           = Path(save_dir)
        self.total_timesteps    = total_timesteps

    def load(self, before=None) -> None:
        """Refill the curves from an earlier job's ``progress.csv`` (see :func:`load_progress`)."""
        load_progress(
            self.save_dir, self.times, self.x_data, self.y_data, self.y_dataerr,
            before=before,
        )

    def plot_progress(self, num_steps, metrics) -> None:
        """Brax PPO progress callback: accumulate eval reward, log native W&B lines.

        Logs every scalar brax metric via ``run.log`` so each renders as a native,
        interactive W&B line chart, and writes the raw curve to ``progress.csv``.
        """
        print('=== TRAINING EPOCH ===')
        print('time', datetime.now(ZoneInfo("America/New_York")).strftime("%Y-%m-%d %H:%M:%S %Z"))
        print('num_steps', num_steps)
        if self.total_timesteps is not None:
            print('total steps', self.total_timesteps)

        self.times.append(datetime.now())
        self.x_data.append(int(num_steps))
        self.y_data.append(float(metrics["eval/episode_reward"]))
        self.y_dataerr.append(float(metrics["eval/episode_reward_std"]))
        pd.DataFrame(
            {
                'times': self.times,
                'x': self.x_data,
                'y': self.y_data,
                'yerr': self.y_dataerr
            }
        ).to_csv(
            self.save_dir / 'progress.csv',
            index=False
        )

        if np.isnan(self.y_data[-1]) or np.isnan(self.y_dataerr[-1]):
            raise Exception(f'NaN found... \n\n{self.y_data}\n\n{self.y_dataerr}')

        if self.run:
            # Log every scalar brax metric so each gets a native line chart.
            scalars = {}
            for k, v in metrics.items():
                try:
                    scalars[k] = float(v)
                except (TypeError, ValueError):
                    continue
            self.run.log(scalars, step=num_steps)

run instance-attribute

run = run

times instance-attribute

times = []

x_data instance-attribute

x_data = []

y_data instance-attribute

y_data = []

y_dataerr instance-attribute

y_dataerr = []

save_dir instance-attribute

save_dir = Path(save_dir)

total_timesteps instance-attribute

total_timesteps = total_timesteps

load

load(before=None) -> None

Refill the curves from an earlier job's progress.csv (see :func:load_progress).

Source code in src/minimal_mjx/utils/plotting.py
def load(self, before=None) -> None:
    """Refill the curves from an earlier job's ``progress.csv`` (see :func:`load_progress`)."""
    load_progress(
        self.save_dir, self.times, self.x_data, self.y_data, self.y_dataerr,
        before=before,
    )

plot_progress

plot_progress(num_steps, metrics) -> None

Brax PPO progress callback: accumulate eval reward, log native W&B lines.

Logs every scalar brax metric via run.log so each renders as a native, interactive W&B line chart, and writes the raw curve to progress.csv.

Source code in src/minimal_mjx/utils/plotting.py
def plot_progress(self, num_steps, metrics) -> None:
    """Brax PPO progress callback: accumulate eval reward, log native W&B lines.

    Logs every scalar brax metric via ``run.log`` so each renders as a native,
    interactive W&B line chart, and writes the raw curve to ``progress.csv``.
    """
    print('=== TRAINING EPOCH ===')
    print('time', datetime.now(ZoneInfo("America/New_York")).strftime("%Y-%m-%d %H:%M:%S %Z"))
    print('num_steps', num_steps)
    if self.total_timesteps is not None:
        print('total steps', self.total_timesteps)

    self.times.append(datetime.now())
    self.x_data.append(int(num_steps))
    self.y_data.append(float(metrics["eval/episode_reward"]))
    self.y_dataerr.append(float(metrics["eval/episode_reward_std"]))
    pd.DataFrame(
        {
            'times': self.times,
            'x': self.x_data,
            'y': self.y_data,
            'yerr': self.y_dataerr
        }
    ).to_csv(
        self.save_dir / 'progress.csv',
        index=False
    )

    if np.isnan(self.y_data[-1]) or np.isnan(self.y_dataerr[-1]):
        raise Exception(f'NaN found... \n\n{self.y_data}\n\n{self.y_dataerr}')

    if self.run:
        # Log every scalar brax metric so each gets a native line chart.
        scalars = {}
        for k, v in metrics.items():
            try:
                scalars[k] = float(v)
            except (TypeError, ValueError):
                continue
        self.run.log(scalars, step=num_steps)

set_mpl_params

set_mpl_params(
    label_size: int = 16,
    title_size: int = 18,
    tick_size: int = 14,
    legend_size: int = 14,
) -> None

Configure matplotlib for publication-quality LaTeX-style figures.

Source code in src/minimal_mjx/utils/plotting.py
def set_mpl_params(label_size: int = 16, title_size: int = 18,
                   tick_size: int = 14, legend_size: int = 14) -> None:
    """Configure matplotlib for publication-quality LaTeX-style figures."""
    mpl.rcParams.update({
        "text.usetex": True,
        "font.family": "serif",
        "font.serif": ["Times New Roman", "Times", "DejaVu Serif"],
        "mathtext.fontset": "cm",
        "axes.labelsize": label_size,
        "axes.titlesize": title_size,
        "xtick.labelsize": tick_size,
        "ytick.labelsize": tick_size,
        "legend.fontsize": legend_size,
        "figure.titlesize": title_size,
    })

get_subplot_grid

get_subplot_grid(n: int) -> tuple[int, int]

Return (nrows, ncols) for a roughly square grid that fits n subplots.

Source code in src/minimal_mjx/utils/plotting.py
def get_subplot_grid(n: int) -> tuple[int, int]:
    """Return (nrows, ncols) for a roughly square grid that fits *n* subplots."""
    ncols = int(np.ceil(np.sqrt(n)))
    nrows = int(np.ceil(n / ncols))
    return nrows, ncols

get_mj_scene_option

get_mj_scene_option(
    contacts: bool = False,
    perts: bool = False,
    com: bool = False,
    geomgroup2: bool = True,
    geomgroup3: bool = False,
) -> MjvOption

Create an MjvOption with common visualization flags toggled.

Source code in src/minimal_mjx/utils/plotting.py
def get_mj_scene_option(contacts: bool = False, perts: bool = False, com: bool = False,
                        geomgroup2: bool = True, geomgroup3: bool = False) -> mujoco.MjvOption:
    """Create an MjvOption with common visualization flags toggled."""
    scene_option = mujoco.MjvOption()
    scene_option.geomgroup[2] = geomgroup2
    scene_option.geomgroup[3] = geomgroup3
    scene_option.flags[mujoco.mjtVisFlag.mjVIS_CONTACTPOINT] = contacts
    scene_option.flags[mujoco.mjtVisFlag.mjVIS_PERTFORCE] = perts
    scene_option.flags[mujoco.mjtVisFlag.mjVIS_COM] = com
    return scene_option

add_text_to_frame

add_text_to_frame(
    pixels: ndarray,
    text: str,
    org: tuple[int, int],
    size: float = 1,
    thickness: int = 2,
    color: tuple[int, int, int] = (255, 255, 255),
    outline_color: tuple[int, int, int] | None = (0, 0, 0),
    outline_thickness: int = 2,
) -> ndarray

Overlay text on a frame (in-place) and return it.

Source code in src/minimal_mjx/utils/plotting.py
def add_text_to_frame(pixels: np.ndarray, text: str, org: tuple[int, int],
                      size: float = 1, thickness: int = 2,
                      color: tuple[int, int, int] = (255, 255, 255),
                      outline_color: tuple[int, int, int] | None = (0, 0, 0),
                      outline_thickness: int = 2) -> np.ndarray:
    """Overlay text on a frame (in-place) and return it.
    """
    if outline_color is not None and outline_thickness > 0:
        cv2.putText(
            pixels, text, org, cv2.FONT_HERSHEY_SIMPLEX,
            size, outline_color, thickness + 2 * outline_thickness, cv2.LINE_AA,
        )
    cv2.putText(
        pixels, text, org, cv2.FONT_HERSHEY_SIMPLEX,
        size, color, thickness, cv2.LINE_AA,
    )
    return pixels

infer_frame_dim

infer_frame_dim(mj_model, width, height)
Source code in src/minimal_mjx/utils/plotting.py
def infer_frame_dim(
        mj_model, width, height
    ):
    if width is None:
        width = mj_model.vis.global_.offwidth
    if height is None:
        height = mj_model.vis.global_.offheight

    return width, height

load_progress

load_progress(
    save_dir, times, x_data, y_data, y_dataerr, before=None
) -> None

Refill a :class:Progress's curves from the progress.csv a previous job wrote.

The callback rewrites the file from these lists on every eval, so a continued run that started them empty would drop the epochs it inherited. before is the step it restarts from: rows at or past it are left out, the run evaluating that state again as its own first row.

Source code in src/minimal_mjx/utils/plotting.py
def load_progress(save_dir, times, x_data, y_data, y_dataerr, before=None) -> None:
    """Refill a :class:`Progress`'s curves from the `progress.csv` a previous job wrote.

    The callback rewrites the file from these lists on every eval, so a continued run
    that started them empty would drop the epochs it inherited. `before` is the step it
    restarts from: rows at or past it are left out, the run evaluating that state again
    as its own first row.
    """
    path = Path(save_dir) / 'progress.csv'
    if not path.exists():
        return
    frame = pd.read_csv(path)
    if before is not None:
        frame = frame[frame['x'] < before]
    times.extend(pd.to_datetime(frame['times']).tolist())
    x_data.extend(frame['x'].tolist())
    y_data.extend(frame['y'].tolist())
    y_dataerr.extend(frame['yerr'].tolist())

check_directory_exists

check_directory_exists(path)
Source code in src/minimal_mjx/utils/plotting.py
def check_directory_exists(path):
    path = Path(path)
    if path.suffix:
        raise Exception('path is a file, not a directory', path.resolve())

    if path.exists() and path.is_dir():
        return True
    else:
        response = input(f"Directory '{path}' does not exist. Create it? [y/N]: ").strip().lower()
        if response == 'y':
            path.mkdir(parents=True, exist_ok=True)
            return True
        else:
            return False

save_metrics

save_metrics(
    plotter: RewardPlotter,
    path: Path = Path("visualization/metrics.pdf"),
) -> None

Plot metrics from a RewardPlotter and save the figure to path.

Source code in src/minimal_mjx/utils/plotting.py
def save_metrics(plotter: RewardPlotter, path: Path = Path('visualization/metrics.pdf')) -> None:
    """Plot metrics from a RewardPlotter and save the figure to *path*."""
    print(f'Saving metrics to {path}')
    path = Path(path)
    if not check_directory_exists(path.parent):
        return
    fig, _ = plotter.plot()
    fig.tight_layout()
    fig.savefig(path)
    plt.close(fig)

save_video

save_video(
    frames: list[ndarray],
    dt: float,
    path: Path = Path("visualization/policy_rollout.mp4"),
) -> None

Write a list of frames to an MP4 video at the environment control rate.

Source code in src/minimal_mjx/utils/plotting.py
def save_video(frames: list[np.ndarray], dt: float,
               path: Path = Path('visualization/policy_rollout.mp4')) -> None:
    """Write a list of frames to an MP4 video at the environment control rate."""
    print(f'Saving video to {path}')
    path = Path(path)
    if not check_directory_exists(path.parent):
        return
    media.write_video(path, frames, fps=round(1 / dt))

load_dict_from_hdf5

load_dict_from_hdf5(
    filename: str | Path,
) -> dict[str, ndarray]

Load all datasets from an HDF5 file into a {key: ndarray} dict.

Source code in src/minimal_mjx/utils/plotting.py
def load_dict_from_hdf5(filename: str | Path) -> dict[str, np.ndarray]:
    """Load all datasets from an HDF5 file into a {key: ndarray} dict."""
    out: dict[str, np.ndarray] = {}
    with h5py.File(filename, 'r') as f:
        for key in f.keys():
            out[key] = np.array(f[key][:])
    return out

minimal_mjx.utils.state

Classes:

Name Description
EnvState

Functions:

Name Description
get_batch_shape

Gets the batch size of an observation Pytree.

EnvState dataclass

Methods:

Name Description
replace

Replace fields in the MujocoState.

Attributes:

Name Type Description
data MjData
obs ndarray
reward float
done bool
metrics dict
info dict
Source code in src/minimal_mjx/utils/state.py
@dataclass
class EnvState:
    data: mujoco.MjData
    obs: np.ndarray
    reward: float
    done: bool
    metrics: dict
    info: dict

    def replace(self, **kwargs):
        """Replace fields in the MujocoState."""
        return EnvState(
            data=kwargs.get('data', self.data),
            obs=kwargs.get('obs', self.obs),
            reward=kwargs.get('reward', self.reward),
            done=kwargs.get('done', self.done),
            metrics=kwargs.get('metrics', self.metrics),
            info=kwargs.get('info', self.info)
        )

data instance-attribute

data: MjData

obs instance-attribute

obs: ndarray

reward instance-attribute

reward: float

done instance-attribute

done: bool

metrics instance-attribute

metrics: dict

info instance-attribute

info: dict

replace

replace(**kwargs)

Replace fields in the MujocoState.

Source code in src/minimal_mjx/utils/state.py
def replace(self, **kwargs):
    """Replace fields in the MujocoState."""
    return EnvState(
        data=kwargs.get('data', self.data),
        obs=kwargs.get('obs', self.obs),
        reward=kwargs.get('reward', self.reward),
        done=kwargs.get('done', self.done),
        metrics=kwargs.get('metrics', self.metrics),
        info=kwargs.get('info', self.info)
    )

get_batch_shape

get_batch_shape(obs) -> tuple

Gets the batch size of an observation Pytree.

Returns () if obs came from a single env, and (num_envs,) if obs came from a batched rollout.

Source code in src/minimal_mjx/utils/state.py
def get_batch_shape(obs) -> tuple:
    """Gets the batch size of an observation Pytree. 

    Returns () if obs came from a single env, and (num_envs,) if obs came from a 
    batched rollout.
    """
    return jax.tree_util.tree_leaves(obs)[0].shape[:-1]

minimal_mjx.utils.setupGPU

Functions:

Name Description
setup_gpu
add_ICD_config

Attempt to write an NVIDIA ICD config for libglvnd (Linux only).

mujoco_EGL_rendering
setup_XLA_Triton

Optionally set XLA flags to enable Triton GEMM. Harmless if XLA not used,

setup_intel_gpu
check_gpu_connection

Lightweight GPU presence check: return True if NVIDIA tools are available and responding.

run_setup

Attributes:

Name Type Description
logger
INTEL_GPU

logger module-attribute

logger = logging.getLogger(__name__)

INTEL_GPU module-attribute

INTEL_GPU = True

setup_gpu

setup_gpu()
Source code in src/minimal_mjx/utils/setupGPU.py
def setup_gpu():
    system = platform.system()
    logger.debug(f"Detected OS: {system}")

    if system == "Darwin":
        logger.debug("macOS detected — using Core OpenGL (CGL).")
        os.environ["MUJOCO_GL"] = "cgl"
        return

    if system == "Linux":
        nvidia_smi_path = shutil.which("nvidia-smi")
        if nvidia_smi_path:
            try:
                subprocess.run([nvidia_smi_path, "-L"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                logger.debug("NVIDIA GPU detected — using EGL.")
                os.environ["MUJOCO_GL"] = "egl"
                return
            except subprocess.CalledProcessError:
                pass
        logger.debug("No NVIDIA GPU — using OSMesa (software).")
        os.environ["MUJOCO_GL"] = "osmesa"
        return

    logger.debug("Unknown OS — using OSMesa.")
    os.environ["MUJOCO_GL"] = "osmesa"

add_ICD_config

add_ICD_config()

Attempt to write an NVIDIA ICD config for libglvnd (Linux only). This file typically requires root privileges. We try to create it only on Linux and catch permission errors — if we can't write it, just warn.

Source code in src/minimal_mjx/utils/setupGPU.py
def add_ICD_config():
    """
    Attempt to write an NVIDIA ICD config for libglvnd (Linux only).
    This file typically requires root privileges. We try to create it only on Linux
    and catch permission errors — if we can't write it, just warn.
    """
    if platform.system() != "Linux":
        return

    NVIDIA_ICD_CONFIG_PATH = "/usr/share/glvnd/egl_vendor.d/10_nvidia.json"
    if os.path.exists(NVIDIA_ICD_CONFIG_PATH):
        logger.debug(f"ICD config already exists at {NVIDIA_ICD_CONFIG_PATH}.")
        return

    icd_json = """{
  "file_format_version" : "1.0.0",
  "ICD" : {
    "library_path" : "libEGL_nvidia.so.0"
  }
}
"""
    try:
        # Attempt to create directories if missing
        os.makedirs(os.path.dirname(NVIDIA_ICD_CONFIG_PATH), exist_ok=True)
        with open(NVIDIA_ICD_CONFIG_PATH, "w") as f:
            f.write(icd_json)
        logger.debug(f"Wrote NVIDIA ICD config to {NVIDIA_ICD_CONFIG_PATH}.")
    except PermissionError:
        logger.debug(f"Permission denied: cannot write {NVIDIA_ICD_CONFIG_PATH}. Run as root to install ICD, or skip this step.")
    except Exception as e:
        logger.debug(f"Unexpected error writing ICD config: {e}")

mujoco_EGL_rendering

mujoco_EGL_rendering()
Source code in src/minimal_mjx/utils/setupGPU.py
def mujoco_EGL_rendering():
    if platform.system() != "Linux":
        logger.debug("EGL rendering not supported on this OS. Skipping.")
        return
    try:
        subprocess.run(["nvidia-smi"], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        os.environ["MUJOCO_GL"] = "egl"
        logger.debug("Set MUJOCO_GL='egl' for GPU-backed rendering.")
    except Exception:
        logger.debug("NVIDIA GPU not available, skipping EGL rendering.")

setup_XLA_Triton

setup_XLA_Triton()

Optionally set XLA flags to enable Triton GEMM. Harmless if XLA not used, but only useful for GPU-backed XLA computations.

Source code in src/minimal_mjx/utils/setupGPU.py
def setup_XLA_Triton():
    """
    Optionally set XLA flags to enable Triton GEMM. Harmless if XLA not used,
    but only useful for GPU-backed XLA computations.
    """
    xla_flags = os.environ.get("XLA_FLAGS", "")
    flag_to_add = "--xla_gpu_triton_gemm_any=True"
    if flag_to_add not in xla_flags:
        if xla_flags and not xla_flags.endswith(" "):
            xla_flags += " "
        xla_flags += flag_to_add
        os.environ["XLA_FLAGS"] = xla_flags
        logger.debug("Appended XLA flag for Triton GEMM (XLA_FLAGS updated).")
    else:
        logger.debug("XLA Triton flag already present.")

setup_intel_gpu

setup_intel_gpu()
Source code in src/minimal_mjx/utils/setupGPU.py
def setup_intel_gpu():
    # Set up environment for Intel integrated GPU (e.g., UHD Graphics 620)
    logger.debug('Setting up Intel GPU (UHD Graphics 620)...')
    os.environ['MUJOCO_GL'] = 'osmesa'  # Use OSMesa for software rendering
    logger.debug('Set MUJOCO_GL=osmesa for Intel GPU.')

check_gpu_connection

check_gpu_connection()

Lightweight GPU presence check: return True if NVIDIA tools are available and responding. Don't call this on macOS (no nvidia-smi there).

Source code in src/minimal_mjx/utils/setupGPU.py
def check_gpu_connection():
    """
    Lightweight GPU presence check: return True if NVIDIA tools are available and responding.
    Don't call this on macOS (no nvidia-smi there).
    """
    if platform.system() != "Linux":
        logger.debug("Skipping NVIDIA connectivity check (non-Linux system).")
        return False

    nvidia_smi_path = shutil.which("nvidia-smi")
    if not nvidia_smi_path:
        logger.debug("nvidia-smi not found on PATH.")
        return False

    try:
        subprocess.run([nvidia_smi_path], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        logger.debug("NVIDIA GPU appears available.")
        return True
    except subprocess.CalledProcessError:
        logger.debug("nvidia-smi returned non-zero exit code — GPU may be unreachable or driver issue.")
        return False
    except Exception as e:
        logger.debug(f"Error checking nvidia-smi: {e}")
        return False

run_setup

run_setup()
Source code in src/minimal_mjx/utils/setupGPU.py
def run_setup():
    logger.debug("Starting GPU / rendering environment setup...")
    if False and INTEL_GPU:
        setup_intel_gpu()
        return
    check_gpu_connection()
    setup_gpu()
    add_ICD_config()

    if platform.system() == "Linux":
        mujoco_EGL_rendering()

    setup_XLA_Triton()
    logger.debug(f"Finished setup. MUJOCO_GL={os.environ.get('MUJOCO_GL')}")
    logger.debug("MUJOCO_GL is now: %s", os.environ.get("MUJOCO_GL"))

minimal_mjx.utils.delete_failed_runs

Functions:

Name Description
delete_failed_runs

Finds and deletes all failed/crashed runs in a specified W&B project,

main

delete_failed_runs

delete_failed_runs(
    entity: str, project: str, assume_yes: bool = False
) -> None

Finds and deletes all failed/crashed runs in a specified W&B project,

printing the number of associated logged artifacts for each run. Each deletion is confirmed interactively unless assume_yes is set.

Source code in src/minimal_mjx/utils/delete_failed_runs.py
def delete_failed_runs(entity: str, project: str, assume_yes: bool = False) -> None:
    """Finds and deletes all failed/crashed runs in a specified W&B project,

    printing the number of associated logged artifacts for each run. Each
    deletion is confirmed interactively unless ``assume_yes`` is set.
    """
    # Initialize the public API
    api = wandb.Api()

    path = f"{entity}/{project}"
    print(f"Fetching runs from: {path}...")

    try:
        # Retrieve all runs for the project path
        runs = api.runs(path)
    except Exception as e:
        print(f"Error connecting to project path '{path}': {e}", file=sys.stderr)
        return

    deleted_count = 0
    skipped_count = 0

    for run in runs:
        # Filter for failed or crashed states
        if run.state in ["failed", "crashed"]:
            try:
                # Retrieve and count the logged artifacts for this run
                logged_artifacts = list(run.logged_artifacts())
                artifact_count = len(logged_artifacts)
            except Exception:
                artifact_count = 0

            print(f"Run: {run.name} ({run.id})")
            print(f"  - State: {run.state}")
            print(f"  - Logged Artifacts: {artifact_count}")

            if not assume_yes and not _confirm(
                f"Delete this run and its {artifact_count} artifact(s)?"
            ):
                print("  - Skipped.")
                print("-" * 40)
                skipped_count += 1
                continue

            print("  - Deleting...")
            print("-" * 40)

            # Deletes the run and all of its associated artifacts
            run.delete(delete_artifacts=True)
            deleted_count += 1

    print(
        f"\nExecution finished. Successfully deleted {deleted_count} runs "
        f"({skipped_count} skipped)."
    )

main

main() -> None
Source code in src/minimal_mjx/utils/delete_failed_runs.py
def main() -> None:
    # Set up the command-line interface argument parser
    parser = argparse.ArgumentParser(
        description="Delete failed and crashed W&B runs along with their logged artifacts."
    )

    # Positional arguments require inputs; change to flags if you want defaults
    parser.add_argument(
        "-e",
        "--entity",
        type=str,
        required=True,
        help="Your W&B team name or personal username.",
    )
    parser.add_argument(
        "-p",
        "--project",
        type=str,
        required=True,
        help="The specific W&B project name.",
    )
    parser.add_argument(
        "-y",
        "--yes",
        action="store_true",
        help="Delete without asking for confirmation on each run.",
    )

    # Parse inputs from the console
    args = parser.parse_args()

    # Run the main task
    delete_failed_runs(
        entity=args.entity, project=args.project, assume_yes=args.yes
    )