Module contents
Stage 1 of 8Advanced 90 min

MuJoCo environments and evaluation protocol

Install MuJoCo and Gymnasium, study Hopper, HalfCheetah, Walker2d and Ant, and build the project evaluation protocol with separate deterministic episodes, multiple seeds, IQM and stratified bootstrap intervals; measure random and zero-policy baselines.

After this lesson you can

  • Describe observations, actions, rewards and ending conditions for each environment.
  • Handle termination and truncation correctly in the interaction loop.
  • Implement the evaluation harness with IQM and stratified bootstrap intervals.
  • Measure and record random and zero-policy baselines for each environment.

Before you start

Before training, decide what improvement means

Two agents walk in a simulation. One gets a higher return in a run; the other falls in the same test. Have you found the best algorithm? Not yet: perhaps the first had a favorable initial state, its exploratory actions were lucky, or the second received fewer training steps. In reinforcement learning, one run combines algorithm decisions with seed and episode variation. The project’s first tool is therefore a measurement rule, not an optimizer.

A Markov decision process separates state, action, transition and reward. MuJoCo implements physical dynamics; Gymnasium provides a common interaction interface. Before PPO or SAC we need to know what enters and leaves that interface and when a transition permits estimating subsequent value. Then we fix statistical units: one training seed produces one policy; several evaluation episodes estimate its performance. Ten episodes from one policy are not ten independent training runs.

The deliverable is a harness that records returns, end causes and configuration, calculates a summary and its uncertainty, and permits repeatable measurement of trivial policies. Random and zero baselines do not prove a method learns: they expose wiring, unit and scale errors before spending time training.

The simulator as a measuring instrument

The model describes bodies, joints, masses, contacts and actuators. The policy receives positions and velocities, not necessarily absolute horizontal position. That omission may be deliberate: if task and dynamics are horizontally translation-invariant, velocity and relative positions suffice for an origin-independent decision. Do not infer that every observation is a Markov state: omitted contact forces, noisy sensors or hidden physical parameters can make it partial. Consult the MuJoCo physics model and relationship between step size and integration before changing the model.

We use v5 versions and default parameters. The following sizes and formulas are documented by Gymnasium for Hopper, HalfCheetah, Walker2d and Ant. Options such as contact observations or health limits can change; if changed, the table no longer describes the default environment.

EnvironmentActionObservationDecision intervalReward and end
Hopper-v53110.008 sForward plus health minus control cost; may terminate for an unhealthy state.
HalfCheetah-v56170.05 sForward minus control cost; no health termination by default.
Walker2d-v56170.008 sForward plus health minus control cost; may terminate for an unhealthy state.
Ant-v581050.05 sForward plus health minus control and contact costs; may terminate for an unhealthy state.

Actions are bounded control vectors, not desired-position commands interpreted identically across models. Forward reward uses horizontal displacement divided by decision interval. Control cost penalizes large actions; the health term can reward staying within defined conditions. Ant adds contact cost. High return can therefore result from a combination of speed, duration and costs: inspecting only the sum hides the mechanism. The default external limit is 1000 decisions in all four environments; HalfCheetah can reach it even in an unnatural posture.

With the linked pages’ defaults, forward weight is 1 in all four environments. The squared-action norm coefficient is 0.001 for Hopper and Walker2d, 0.1 for HalfCheetah and 0.5 for Ant. Hopper and Walker2d add health reward 1 when healthy; Ant also has health weight 1 and penalizes the squared norm of clipped contact forces with coefficient 0.0005. Signed components appear in info, so they can be summed and checked against total reward.

Default conditions also differ. Hopper terminates if its state leaves the documented healthy range, height drops below 0.7 or torso angle leaves [-0.2, 0.2]. Walker2d terminates if state becomes nonfinite, height leaves [0.8, 2.0] or angle leaves [-1, 1]. Ant terminates if state becomes nonfinite or height leaves [0.2, 1.0]. These describe the cited implementation, not a universal definition of falling. HalfCheetah has no such default termination. Check interval endpoints and options in the installed version’s code before making a boundary test.

Ant-v5 includes contact forces in its default observation; do not carry over dimensions or costs from Ant-v4 without checking. Nor is the decision interval a universal MuJoCo constant: it depends on the model file and frame_skip. The lab queries the installed environment, records versions and can reveal changed behavior before comparing with an earlier run.

Now consider what each body must control. Hopper is a planar single-legged system: its three actuators operate leg joints, but the body also has translation and orientation coordinates evolving through dynamics. The agent does not directly control torso height. Staying upright requires coordinating action, contact and movement. A fall is not a visual category interpreted by the camera: it results from the programmed health condition. Changing that condition changes the problem even if the video looks identical.

Walker2d is also planar but has two legs. Six action components act on both legs’ joints, and observation includes positions and velocities that distinguish gait phases. A zero policy does not mean a frozen state: gravity, contacts and initial conditions still act. Even without control, the simulator integrates a trajectory. Check end cause alongside return: a short episode accumulating health reward differs from one reaching the limit.

HalfCheetah has six controls in a planar body with front and rear segments. The default task does not terminate on a health test: simulation can continue until the external limit. Since reward subtracts control cost and lacks Hopper’s health term, an immobile policy’s return has a different interpretation. A random policy can generate substantial cost without compensating progress. These are formula mechanisms, not a prediction that every seed yields negative return.

Ant is three-dimensional with four articulated legs. Physical orientation cannot be reduced to a planar angle, and some internal coordinates encode orientation as a quaternion. Therefore do not treat the entire qpos vector as a uniform list of angles. The explorer selects only hinge joints and reads each coordinate’s direction from the model. Contact forces and their cost are especially relevant here. Similar positions may have different velocities or contacts, so the same action can have different future effects. An observation’s value depends on its contents, not its appearance in one frame.

InteractiveExplore a physical trajectory
MuJoCo frame from step 1. The plots show step 1. Playback uses sampled frames.
rooty angle (rad)
−0.22−0.100.01step 1end: 141
Step reward and recorded components
−0.330.391.10step 1end: 141
  • total
  • forward
  • control
  • healthy
Policy
1
Environment seed0
Step reward0.999
forward−0.001
control0.000
healthy1.000
rooty angle−0.005 rad
Episode endtermination, step 141
Select environment and policy and explore the lab’s recorded trajectory. Curves and readouts show physical evolution and reward breakdown; the ending indicates termination or truncation. One trajectory alone does not characterize the results distribution.

Two ending causes, two different decisions

Let rtr_t be observed reward and V(s)V(s) an estimate of future discounted return. The one-step target is

yt=rt+γ(1−1[terminated])V(st+1).y_t=r_t+\gamma(1-\mathbf{1}[\mathrm{terminated}])V(s_{t+1}).

On genuine termination the task’s future ends and no value is added. If only an external cutoff was reached, the subsequent physical state still has a future in the original problem: use V(st+1)V(s_{t+1}). For example, if an approximation returns V(st+1)=10V(s_{t+1})=10, reward is 11 and γ=0.9\gamma=0.9, the target is 11 on termination and 1010 on pure truncation. The next cell checks the calculation and states the assumption: subsequent value corresponds to the final observation, not the next episode’s initial observation.

[ ]Two different masksBrowser
reward, gamma, next_value = 1.0, 0.9, 10.0
for terminated, truncated in [(True, False), (False, True), (False, False)]:
    target = reward + gamma * (not terminated) * next_value
    reset = terminated or truncated
    print(f"terminated={terminated}, truncated={truncated}: objetivo={target:.1f}, reset={reset}")

If both flags are true, task termination prevails for value: the mask is zero. A vectorized implementation with automatic reset must recover the final observation supplied by the wrapper, not evaluate the newly reset state. Check the installed API, since the name and behavior of that data can change.

There is a subtlety: if the finite horizon is part of the task, reaching it is genuine termination. To keep the process Markov, observation must distinguish time remaining when it changes optimal decisions. An external limit cutting a continuing task is different. The label does not replace understanding the objective: when designing a custom environment, assign flags according to intended semantics.

What independent evaluation means

The aim is to compare outcome distributions of complete procedures, not pick the best curve point after seeing it. Fix interaction steps and evaluation schedule for all. Hold out evaluation seeds separate from training and hyperparameter selection. A Gaussian policy can be evaluated at its mean, with the same action rescaling and clipping as deployment; declare this because deterministic and stochastic policies are different objects. If the task requires a stochastic policy, evaluate it as such and record that choice. Disable normalizer updates during evaluation and use statistics saved with the model.

For each independent training run ii and task jj, average several test episode returns to obtain XijX_{ij}. Here return is the undiscounted sum of episode rewards to communicate performance; critic discount serves a different objective and must be stated separately. Episode count controls evaluation noise but does not replace new training seeds. The same evaluation seed list facilitates paired comparison when conditions are comparable, without making states visited by different policies identical.

Aggregating across tasks requires comparable scales. Hopper and Ant returns have units and ranges from different rewards. Before aggregating define a fixed per-task normalization with justified references, and report per-task results too. If reference difference is zero, normalization is undefined. Do not choose reference points after seeing results to make an algorithm look better. For this lesson’s baselines we report each task separately in raw return.

Interquartile mean and profiles

The mean can change substantially with one exceptional run. Interquartile mean, IQM, sorts scores, removes a quarter from each tail and averages the middle. When sample count is not divisible by four, rliable uses scipy.stats.trim_mean: it removes floor(n/4) observations from each tail. For ten it removes two per side and retains six; it does not interpolate quartiles. State the convention because other trimmed means can weight endpoints partially.

InteractiveHow much does an extreme result matter?
Eight illustrative scores, sorted from lowest to highest.
  • Middle four
  • Two from each tail
  • Mean
  • IQM
0501001502001102203304405506607708160
The IQM drops positions 1, 2, 7, and 8 and averages positions 3 through 6.
160
Mean of all eight55.00
IQM: mean of the central four45.00
The set is an explicit teaching example, not a MuJoCo measurement. Change the extreme and compare mean with IQM. Discarded points still exist: trimming defines another statistic, not proof they are errors.

IQM does not remove the need to inspect the distribution. It can hide extreme failures important for safety or deployment, and with few runs trimming leaves even less information. A performance profile shows, for each threshold τ\tau, the fraction of scores above it. Its curve does not itself identify failure causes, but shows whether improved aggregate performance comes with a tail of poor runs. Agarwal and colleagues propose intervals, IQM and profiles to avoid conclusions based only on a point aggregate.

Stratified bootstrap

The nonparametric bootstrap approximates statistic variation by resampling observations with replacement. If each column is a task, resample within each column the same number of runs as that task has. Each replicate retains each task’s fixed weight and avoids an accidentally dominant task. Calculate IQM for each replicate and take percentiles for the chosen level. The 95% percentile interval uses the 2.5 and 97.5 percentiles.

The procedure assumes resampled units are exchangeable within each task. If several episodes belong to one training run, resampling episodes as independent training runs underestimates training uncertainty. For a paired difference preserve pairs during resampling; for independent algorithms resample each according to its design. A confidence interval does not guarantee a 95% probability that the fixed parameter lies in the observed interval. Frequentist interpretation concerns procedure coverage under assumptions, and with few seeds bootstrap can be unstable and miss events absent from the sample.

Operation order matters. If each training run has several episodes, first summarize those episodes by a fixed rule and then resample training runs within each task. Resampling all buffer transitions does not answer this question either: they are temporally dependent observations, while the desired statistic describes trained policies, not individual steps. To quantify evaluation variability within each run too, a hierarchical bootstrap can resample runs and then episodes within each selected run. Preserve the structure that generated the data.

An algorithm difference deserves its own interval. Overlap of two individual intervals is not an equivalent test to an interval for their difference: dependence between estimators and interval construction matter. With paired design form corresponding differences and resample pairs; with independent runs do not invent pairs from matching table positions. Identical numeric training seeds can yield useful correlations but do not alone guarantee effective pairing if algorithms consume randomness differently. Describe how conditions were shared and check the design.

A narrow interval answers the stated question under the chosen procedure. It does not correct selection bias: choosing the best configuration after testing many and evaluating on the same seeds can make the summary optimistic. Separate search and test, fix the training point to report and record failed trials. Nor does it correct unequal budgets. If a method performs more interactions or uses extra observations, the observed difference belongs to that particular comparison, not necessarily the isolated update rule.

Choose a seeding strategy in advance, save integers and configuration state, and repeat with multiple training runs. Fixing a seed makes one run reproducible under compatible conditions; it does not show that a conclusion holds for new seeds. Versions, platform, precision and parallelism also vary: record the environment and retain raw data.

Two levels of uncertainty

To see why training seeds and episodes are not interchangeable, consider a fixed task. Let Θi\Theta_i be the policy produced by independent training run ii and GijG_{ij} the return of its evaluation episode jj. Define μ(Θi)=E[Gij∣Θi]\mu(\Theta_i)=\E[G_{ij}\mid\Theta_i] and σ2(Θi)=Var⁡(Gij∣Θi)\sigma^2(\Theta_i)=\Var(G_{ij}\mid\Theta_i). If episodes are conditionally independent and identically distributed for each policy, their mean Gˉi\bar G_i satisfies

Var⁡(Gˉi)=Var⁡(μ(Θi))+1mE[σ2(Θi)].\Var(\bar G_i)=\Var(\mu(\Theta_i)) + \frac{1}{m}\E[\sigma^2(\Theta_i)].

The equality follows from the law of total variance: conditional mean of the average is μ(Θi)\mu(\Theta_i) and its conditional variance is σ2(Θi)/m\sigma^2(\Theta_i)/m. Increasing mm reduces the second term, each policy’s evaluation noise, but not the first, variation in quality across training runs. Evaluating one policy over many episodes teaches us about that policy, not the distribution of policies produced by training. If shared conditions or seeds make episodes conditionally dependent, the formula also needs covariance terms.

Now average nn independent training runs, each evaluated with mm independent episodes under the same conditions. Global mean variance is the preceding expression divided by nn. This decomposition does not say the mean is always the best summary or directly give IQM variance; it explains why a design must allocate budget between training and evaluation instead of confusing units. It also shows why a single-seed learning curve cannot reveal frequent method failures.

There is a practical tradeoff. If episode noise is very large, increasing episode count makes each policy estimate more stable. If trained policies vary greatly, adding training seeds reveals that variation even with few episodes each. Allocation should follow the question and pilots separate from final evaluation. Do not choose it afterward to obtain the most favorable interval. Retain individual returns so aggregation can be changed in exploratory analysis without reconstructing published table data.

What a profile does and does not show

A profile can use one task or normalized scores from several. At a fixed threshold its height is an empirical proportion; it never increases as the threshold rises. When one curve is above another over a threshold region, a larger fraction of that sample’s scores exceed those thresholds. If curves cross, one method may produce more moderate runs and the other more extremes: a single average does not tell the full story. A bootstrap band can represent curve uncertainty at each threshold, but a pointwise band is not automatically simultaneous across the whole curve.

Scale choice affects threshold meaning. In raw return, a common Hopper and Ant threshold mixes differently defined rewards. On a normalized scale, zero and one can represent two per-task references, but only if references and scale direction are consistently fixed. If the upper reference is below the lower, ordering reverses; if equal, division fails. Do not extrapolate conclusions about new tasks from a small selected set: resampling seeds within each task quantifies run uncertainty within included tasks, not necessarily uncertainty from choosing tasks from a broader population.

Lab: installation and evaluation

On Windows, from the project root, activate a virtual environment and install gymnasium[mujoco], numpy, scipy and rliable in the same interpreter. Gymnasium documents installation and MuJoCo its Python binding. In PowerShell run python -m pip install "gymnasium[mujoco]" numpy scipy "pandas<3" rliable. An isolated environment with pandas 2.2.3 and rliable 1.2.0 was used for interval comparison; some arch and pandas 3 combinations fail when importing the library. Save pip freeze output with results. Rendering with render_mode="human" opens a local window; for captures use rgb_array and close the environment afterward. A remote session without graphics support may need extra backend configuration: calculating returns without rendering does not depend on that window.

The first cell builds the harness from scratch. policy receives an observation and action space; a learned agent can ignore the space or use it to check bounds. A separate seed is passed to action space in addition to the reset seed. The function returns the last observation before reset, both flags and components published by info. The example neither uses a GPU nor trains a policy.

[ ]Episode harnessLocal GPU
import platform
import gymnasium as gym
import mujoco
import numpy as np
import scipy

print("Python", platform.python_version(), "Gymnasium", gym.__version__,
      "MuJoCo", mujoco.__version__, "NumPy", np.__version__, "SciPy", scipy.__version__)

def run_episode(env, policy, seed):
    obs, _ = env.reset(seed=seed)
    env.action_space.seed(10000 + seed)
    total = 0.0
    steps = 0
    trace = []
    while True:
        action = policy(obs, env.action_space)
        next_obs, reward, terminated, truncated, info = env.step(action)
        total += float(reward)
        steps += 1
        obs = next_obs
        if seed == 0:
            trace.append({"step": steps, "reward": float(reward),
                          "qpos": env.unwrapped.data.qpos.copy(),
                          "reward_parts": {k: float(v) for k, v in info.items()
                                           if k.startswith("reward_") and np.isscalar(v)}})
        if terminated or truncated:
            return {"seed": seed, "return": total, "steps": steps,
                    "terminated": bool(terminated), "truncated": bool(truncated),
                    "final_observation": next_obs, "info": info, "trace": trace}

def zero_policy(obs, space):
    return np.zeros(space.shape, dtype=space.dtype)

def random_policy(obs, space):
    return space.sample()

print("Objetivos de prueba:", 1.0 + 0.9 * 0 * 10, 1.0 + 0.9 * 1 * 10)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The final observation permits calculating the target with the mask described above; it is not used after reset. The preceding code evaluates a policy; it does not update a critic. For a trained agent, load its state and normalizers before calling the harness, set inference mode and provide a function returning valid actions. If recurrent, its hidden state must also reset at episode start and persist between steps.

Now construct IQM and its interval without rliable. Rows represent independent runs and columns tasks; for baselines each column contains ten independent episodes of untrained policies. For a trained algorithm, each row must correspond to one independent training run summarized over its evaluation episodes. Resampling preserves row count within each task.

[ ]IQM and stratified bootstrap from scratchLocal GPU
def iqm(scores):
    values = np.sort(np.asarray(scores, dtype=float), axis=None)
    if not len(values) or not np.isfinite(values).all():
        raise ValueError("Se requieren puntuaciones finitas")
    k = len(values) // 4
    return float(values[k:len(values)-k].mean() if k else values.mean())

def iqm_with_ci(scores, n_boot=10000, seed=20261028):
    scores = np.asarray(scores, dtype=float)
    if scores.ndim != 2 or not scores.size or not np.isfinite(scores).all() or n_boot < 1:
        raise ValueError("Se espera una matriz finita y réplicas positivas")
    rng = np.random.default_rng(seed)
    n, tasks = scores.shape
    replicates = np.empty(n_boot)
    for b in range(n_boot):
        indices = rng.integers(0, n, size=(n, tasks))
        replicates[b] = iqm(scores[indices, np.arange(tasks)])
    return iqm(scores), np.percentile(replicates, [2.5, 97.5])

print("Ejemplo de ocho:", iqm([1, 2, 3, 4, 5, 6, 7, 20]))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Compare the point calculation with the library and test a matrix with constant columns: stratified replicates must preserve them. Another implementation’s interval can differ numerically due to random sequence, interval method and replicate count; a matching point estimate does not prove the bootstrap correct. Library code is the reference for the trimming convention.

[ ]Compare with rliableLocal GPU
from rliable import metrics

example = np.arange(1.0, 9.0).reshape(4, 2)
print("IQM propio y rliable:", iqm(example), metrics.aggregate_iqm(example))
assert np.isclose(iqm(example), metrics.aggregate_iqm(example))
constant_columns = np.tile([0.0, 10.0], (4, 1))
point, interval = iqm_with_ci(constant_columns, n_boot=1000, seed=7)
print("Columnas constantes:", point, interval)
assert np.allclose(interval, [5, 5])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Finally run both policies for ten seeds per environment. Do not mix raw returns from different tasks in the aggregate. Each row’s interval quantifies variation among differently seeded episodes of that fixed policy, not uncertainty between nonexistent training runs. Returns print in reset seed order 0 to 9; action seed is 10000 plus reset seed, as fixed by the harness.

[ ]Real baselines in four environmentsLocal GPU
env_ids = ["Hopper-v5", "HalfCheetah-v5", "Walker2d-v5", "Ant-v5"]
baseline_results = {}
for env_id in env_ids:
    baseline_results[env_id] = {}
    for name, policy in [("cero", zero_policy), ("aleatoria", random_policy)]:
        env = gym.make(env_id)
        try:
            episodes = [run_episode(env, policy, seed) for seed in range(10)]
        finally:
            env.close()
        scores = np.array([episode["return"] for episode in episodes])[:, None]
        point, interval = iqm_with_ci(scores)
        baseline_results[env_id][name] = episodes
        print(env_id, name, "IQM", round(point, 3), "IC95", np.round(interval, 3).tolist())
        print("  retornos (semillas 0 a 9):", np.round(scores[:, 0], 3).tolist())
        print("  pasos:", [e["steps"] for e in episodes],
              "terminados/truncados:", sum(e["terminated"] for e in episodes),
              sum(e["truncated"] for e in episodes))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

A reference run with Gymnasium 1.4.0 and MuJoCo 3.17.0 produced the values below, rounded to three decimals. The percentile interval uses 10000 replicates and seed 20261028. These are results from this installation, not universal benchmarks: rerun the cell and save all scores and versions if platform or configuration changes.

EnvironmentPolicyIQM95% bootstrap CI
Hopper-v5zero140.815[123.803, 170.618]
Hopper-v5random15.205[9.475, 23.125]
HalfCheetah-v5zero-0.011[-0.747, 0.496]
HalfCheetah-v5random-276.823[-327.661, -209.854]
Walker2d-v5zero90.438[85.650, 101.309]
Walker2d-v5random2.069[-1.910, 7.678]
Ant-v5zero994.365[991.841, 997.000]
Ant-v5random-22.383[-56.244, -4.088]

Ant’s high return under zero action illustrates why reward must be broken down: health reward accumulated over many steps can contribute greatly without useful walking. This does not imply all seeds or versions behave identically. Comparing zero and random is a reward and dynamics diagnostic under this protocol; it does not measure learning ability.

The explorer uses the seed-zero trace for each combination. The harness retains that seed’s actual qpos coordinates and components in memory: they are not numbers chosen to make a figure. Explorer image sheets are generated by restoring each recorded position to the model and calling mj_forward before rendering. Frames are a discrete trajectory sample, not continuous video. Hopper and Walker2d body segments are colored to distinguish them without changing geometry or dynamics. The optional snippet below generates a sheet for one combination; it requires Pillow and a compatible graphics context and does not run automatically during statistical evaluation.

from PIL import Image

env_id, policy_name = "Hopper-v5", "cero"
frames = baseline_results[env_id][policy_name][0]["trace"]
indices = np.linspace(0, len(frames) - 1, 30).round().astype(int)
env = gym.make(env_id, render_mode="rgb_array", width=200, height=150)
try:
    env.reset(seed=0)
    env.unwrapped.mujoco_renderer.default_cam_config["distance"] = 2.4
    env.unwrapped.mujoco_renderer.default_cam_config["azimuth"] = 90.0
    colors = {"torso": [0.92, 0.42, 0.14, 1], "thigh": [0.14, 0.58, 0.78, 1],
              "leg": [0.92, 0.68, 0.20, 1], "foot": [0.17, 0.42, 0.74, 1]}
    model = env.unwrapped.model
    for j in range(model.ngeom):
        body = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, int(model.geom_bodyid[j]))
        if body in colors:
            model.geom_matid[j] = -1
            model.geom_rgba[j] = colors[body]
    sheet = Image.new("RGB", (1200, 750))
    for i, index in enumerate(indices):
        env.unwrapped.data.qpos[:] = frames[index]["qpos"]
        mujoco.mj_forward(env.unwrapped.model, env.unwrapped.data)
        sheet.paste(Image.fromarray(env.render()), ((i % 6) * 200, (i // 6) * 150))
    sheet.save("hopper-cero.jpg", quality=85)
    print("Pasos representados:", [frames[i]["step"] for i in indices])
finally:
    env.close()

For another environment or policy change both keys and use the camera configuration appropriate to that model. Steps selected by linspace include endpoints and may repeat if the trajectory is shorter than the number of images. The hinge angle in the plot is extracted using the model’s jnt_qposadr address and expressed in radians; it is not necessarily the same coordinate for all four bodies. The vertical line follows the exact selected step, while the image uses the nearest saved frame. Each label shows the difference.

The table also teaches reading an interval with its unit. For Hopper, zero policy has IQM 140.815 and random 15.205 in this run, but each policy was evaluated once per initial seed. The interval describes episode dispersion under the chosen procedure; it says nothing about dispersion of PPO training. Random actions come from action_space with a separate seed from reset. Repeating this experiment with another action distribution measures another policy. Printed step counts and indicators reveal whether return differences coincide with longer episodes, although that coincidence alone does not identify a physical cause.

The next comparison uses the full library to calculate an interval on the same Hopper scores. The point estimate should match. We do not require identical endpoints because index generators differ; both should resample by task and use the percentile method. If import fails, the cell reports the problem and leaves the comparison pending compatible dependencies instead of substituting invented data.

[ ]Compare the interval with rliableLocal GPU
for env_id, policies in baseline_results.items():
    for name, episodes in policies.items():
        scores = np.array([e["return"] for e in episodes])[:, None]
        own_point = iqm(scores)
        reference = metrics.aggregate_iqm(scores)
        print(env_id, name, "IQM propio/rliable:", round(own_point, 3), round(reference, 3))
        assert np.isclose(own_point, reference)
try:
    from rliable import library as rly
except Exception as exc:
    rly = None
    print("Contraste de intervalo no disponible:", type(exc).__name__, str(exc))
if rly is not None:
    hopper = np.array([e["return"] for e in baseline_results["Hopper-v5"]["cero"]])[:, None]
    own, own_ci = iqm_with_ci(hopper, n_boot=10000)
    estimates, intervals = rly.get_interval_estimates(
        {"cero": hopper}, metrics.aggregate_iqm, reps=10000,
        random_state=np.random.RandomState(20261028))
    print("Propio:", own, own_ci)
    print("rliable:", estimates["cero"], intervals["cero"])
    assert np.isclose(own, estimates["cero"])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Independent checking of all eight rows in a compatible environment produced the same eight IQMs with both implementations and nearby intervals. That proximity is an empirical check, not a coverage proof. Exact interval comparison would also require the same indices and quantile convention; running different seeds only permits studying Monte Carlo variation.

When integrating a learned actor, avoid another unit error: if a network emits normalized values, map them to actual action limits exactly as in training. Evaluating raw output without the mapping can change control. Likewise, if training wrapped observations with normalization, applying the actor to raw observations does not evaluate the trained policy. Save wrapper configuration with each model and check with a fixed observation that harness and training code produce the same deterministic action.

For a real comparison, save for every training run: code version identifier, environment and wrapper configuration, seed, actual steps, optimization settings, normalizer state and checkpoint. For each evaluation episode retain seed, raw return, length, flags and policy version. The report must include all runs, including interrupted or failed ones, with a treatment rule fixed before results are seen. A table of successes alone can be accurate for selected runs yet misleading about the complete procedure.

For a performance profile calculate the fraction of runs above each threshold and plot it against threshold. The next cell retains the current run’s ten Hopper measurements and checks that this fraction does not increase as threshold rises. In multitask studies normalize first with fixed references and also show each task separately.

[ ]Performance profileLocal GPU
scores = np.array([e["return"] for e in baseline_results["Hopper-v5"]["cero"]])
thresholds = np.linspace(scores.min(), scores.max(), 6)
profile = np.array([(scores > t).mean() for t in thresholds])
print("Umbrales:", np.round(thresholds, 3))
print("Fracciones superiores:", profile)
assert np.all(np.diff(profile) <= 0)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

QuizHopper’s final step
In a continuing task the final transition has been observed. What subsequent-value mask and reset decision correspond to a terminal fall and an external time cutoff?
NumericTrim the tails
Eight run scores are 0, 2, 4, 8, 9, 10, 15 and 21. Calculate IQM using the rliable convention.
QuizThree runs
A report compares means of three training runs per method and concludes the higher mean is generally superior. What is the most precise criticism?
CodeResample tasks of different sizes
Implement iqm_with_ci(scores, n_boot, seed=0) for a list of score vectors, one per task, possibly of different lengths. First calculate the mean of per-task IQMs, weighting tasks equally even when run counts differ. For each replicate resample with replacement within each task, retaining its size, and recalculate that mean. Return (estimación, intervalo), the estimate and its interval from the 2.5 and 97.5 percentiles. Use rliable integer trimming within each task and reject empty tasks, nonfinite values and n_boot < 1.
import numpy as np

def iqm_with_ci(scores, n_boot, seed=0):
  pass
Shift+Enter to run
Key idea

An RL comparison begins by defining what is measured and what is independent. Resetting after a fall or time limit does not always mean cutting value bootstrap. Separating training and evaluation, recording versions and seeds, retaining per-task results and showing uncertainty turns an isolated number into examinable evidence.