Module contents
Stage 2 of 9Advanced 100 min

Behavior cloning and rollout evaluation

Train state-based behavior cloning as a baseline and establish the evaluation protocol: success rate over many episodes with new initial states, confidence intervals, and multiple training seeds. Measure drift between visited states and demonstrations and relate it to failures.

After this lesson you can

  • Train an MLP behavior-cloning policy with normalization.
  • Implement the rollout-evaluation harness with intervals and multiple seeds.
  • Show the lack of correlation between validation loss and success rate.
  • Measure state drift and locate where failures begin.

Before you start

A small error can change the next questions

A policy imitating the expert is not tested just once. Its first action changes the world, and therefore also the next observation it receives. If it deviates slightly from a demonstration, the next decision may have to be made in a state that never appeared in the dataset. In a task involving contact, that difference can affect which part of the object the pusher touches and the entire subsequent trajectory.

The previous lesson’s demonstration collection separated episodes, saved the applied action, and provided a scripted expert. We will now build a baseline on the same T-pushing simulator. The policy receives the pusher position and the T’s eight exact vertices, privileged information from the simulator: it is not a visual policy. The goal is fixed. The action is an absolute target in millimeters; the adapter clips it to the table before applying it. Later we will replace the vertices with images.

InteractiveA deviation changes the next input
  • Biased policy
  • Expert cloud boundary
0.08
0.05
Deviation at step 1001.59
First step outside cloud20
The explicit model is yt+1=(1−k)yt+by_{t+1}=(1-k)y_t+b, with y0=0y_0=0. The expert remains at zero and the demonstration region ends at y=1y=1. Change bias bb and correction kk: when does the policy leave the region?

The figure does not claim to measure the robot. It is a deterministic model that makes feedback visible. If 0<k<10<k<1, then yt=b[1−(1−k)t]/ky_t=b[1-(1-k)^t]/k and the deviation approaches b/kb/k. Sufficient correction can keep it within the region, but persistent bias can make it leave even if the bias is small at each decision. This does not imply that every unstable policy grows quadratically: the bound we will see is a worst-case guarantee under specific assumptions.

Learn actions and preserve their units

We use an MLP with two hidden layers of 256 ReLU units. Inputs have 18 components, two for the pusher and 16 for the vertices, and the output has two. The vertices are in the same fixed frame as the action. Normalization prevents a coordinate from dominating solely because of scale, but does not itself provide geometric invariance or remove the need to test new positions. Dropout is not used: the goal is a deterministic, transparent baseline, not a guarantee that regularization is unnecessary. The training protocol includes independent seeds, a separate validation set, and an explicit budget.

Dropout is a possible ablation if the model memorizes, but should be disabled during ordinary evaluation and compared under the same budget and rollout seeds. Lower MSE with dropout also does not guarantee improved success. The recipe avoids deciding this by intuition: it fixes the set and criteria before examining the test.

The split must use complete episodes. Two adjacent steps in the same trajectory are very similar, and splitting them between training and validation would produce a misleading estimate. Do not compute means or standard deviations on the evaluation set either. The preceding dataset contains 80 training episodes and 20 for validation; rollout selection and test initial states use other seeds. Training seeds change initialization and minibatch order, not the initial conditions used to compare policies.

From loss to a control decision

For a fixed probability and independent episodes from the same distribution, the Wilson interval with z=1.96z=1.96 is

p^+z2/(2n)1+z2/n  ±  z1+z2/np^(1−p^)n+z24n2.\frac{\hat p+z^2/(2n)}{1+z^2/n}\;\pm\;\frac{z}{1+z^2/n}\sqrt{\frac{\hat p(1-\hat p)}{n}+\frac{z^2}{4n^2}}.

The interval quantifies episode uncertainty for one fixed policy and that initial-state distribution. It does not cover variation across training runs. Report each training seed too, and avoid combining their 300 episodes as if they were 300 independent models. To compare two policies, evaluate them with the same initial states: the paired difference may be more informative than two separate intervals, although overlapping intervals are not a formal test of equality.

Validation loss answers a different question: how well actions are predicted in states recorded by the expert. Success rate answers what happens when the policy induces its own states. Two checkpoints can reverse order under these metrics. We reserve 20 states to choose a checkpoint by success rate and another 100 to measure it, separate from the demonstrations. That selection is noisy and may overfit the 20 episodes; it is reported alongside the alternative loss-based selection, and the final set is not used for selection. Selection does not guarantee improvement: the experiment must show what actually happened.

The cost of leaving the distribution

To diagnose it we measure, at each rollout step, the normalized Euclidean distance to the nearest state among all training steps. This is a distance in 18-feature space using the same training statistics; it is neither a physical distance in millimeters nor a calibrated density. The eight vertices are correlated, so this metric gives object geometry more weight than a single coordinate. Inspect the trajectory and do not infer causality from a high value. Failure can have other causes and an observation close to the data can require a different action because of hidden history.

InteractiveThree rollouts against recorded states
  • Sampled expert states
  • T origin under BC
  • Target origin
20000
100
Initial seed20000
Coverage after step0.0 %
Episode successNo
The cloud contains one in every 30 states from the 80 expert training episodes, projected onto the T's origin position in millimeters. The line shows three real rollouts of the checkpoint selected by success for training seed 0, from initial seeds 20000, 20001, and 20002. Step through the episode and observe coverage after each action; all three ended unsuccessfully. The projection omits orientation and pusher position and does not replace the 18-dimensional distance.

The classical bound explains the risk, not a specific rate. Assume horizon TT, the same cost ct(s,a)∈[0,1]c_t(s,a)\in[0,1] for both policies, equal coupled transitions when the same action is chosen, and probability of disagreement with the expert at most ϵ\epsilon under the expert’s state distribution at each time. Couple the trajectories until their first disagreement. By the union bound, the probability of having disagreed before step tt is at most (t−1)ϵ(t-1)\epsilon. If no disagreement occurs through step tt itself, state and action coincide and so does that step’s cost; on the complementary event the extra cost is at most 1. Thus,

J(π)−J(π∗)≤∑t=1Ttϵ=T(T+1)2ϵ.J(\pi)-J(\pi^*)\leq\sum_{t=1}^{T}t\epsilon=\frac{T(T+1)}{2}\epsilon.

Including disagreement at the step itself gives the sum through tt; the cost difference can be negative and the bound remains valid. It is also trivially bounded by TT. The argument needs a notion of disagreement that controls cost: with continuous actions, two nearly identical actions are not literally equal and a small MSE does not directly imply that assumption. Ross, Gordon and Bagnell (2011) present the problem and the interactive method we will study next. The bound does not imply every task has quadratic error or that moving away causes every failure.

Lab: train and deploy

First run the complete mode of collection. The empuje_t_programadas dataset must contain its metadata, tables, and splits. The following three files contain exactly the simulator and reader extracted from that lesson and this lab’s harness: download p13_pusht.py, p13_aloha.py, and p13_bc.py into the same kernel working directory. ALOHA is supplied for the following lessons and is not used in this training. You need NumPy, SciPy, PyArrow, Pillow, MuJoCo, and PyTorch. In the repository, the cell also finds the files in public/data/p13/l02.

The training loop uses Adam with learning rate 3⋅10−43\cdot10^{-4}, 60 epochs, batches of 512, and seeds 0, 1, and 2. Every 20 epochs it computes MSE on the 20 held-out episodes and rolls out on 20 selection seeds, 10000 through 10019. For each training seed it saves the best checkpoint by MSE and the best by success, breaking ties in favor of the earlier epoch; both are evaluated with the same 100 seeds 20000 through 20099. If both criteria select the same checkpoint, their results coincide. The results file retains success, duration, and per-step distance, and each checkpoint stores normalization statistics. Episodes are simulated independently and inference is batched: this reduces network calls without changing the physics or making episodes a single sample.

[ ]Cloning and evaluation of 100 episodes per seedLocal GPU
import os, sys
from pathlib import Path
modulos = Path(os.environ.get('P13_BC_CODE_DIR', 'public/data/p13/l02'))
if modulos.exists():
    sys.path.insert(0, str(modulos.resolve()))
from p13_bc import experimento

base = Path(os.environ.get('ATLAS_LAB_DIR', Path.home() / 'atlas-lab'))
dataset = base / 'p13-l01' / 'completo' / 'empuje_t_programadas'
assert (dataset / 'meta' / 'info.json').exists(), 'Ejecuta primero p13-l01 en modo completo.'
salida = Path(os.environ.get('P13_BC_OUTPUT_DIR', base / 'p13-l02'))
resultado = experimento(dataset, salida, n_epochs=60, seeds=(0, 1, 2))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The result belongs to this run and the installed MuJoCo version. It is not directly compared with official Push-T, which uses different physics. The action test set comes from successful demonstrations; rollout seeds are drawn from initial conditions without filtering by success. The expert plans with privileged access and the MLP observes only the current state, so we also do not assume it can reproduce every expert decision.

In a run with MuJoCo 4.0.1 and the code’s three seeds, validation MSE fell between epochs 20 and 60: from 0.04695 to 0.04457, from 0.04722 to 0.04519, and from 0.04714 to 0.04374, respectively. However, all nine checkpoints had 0 successes in the 20 selection episodes. Loss chose epoch 60 and success rate chose 20 due to the tie-break; all six models obtained 0/100 on test, with Wilson [0,0.037][0, 0.037] for each. This is a negative result: reducing loss did not produce measurable success in this experiment. Because the observed rates are constant, it makes no sense here to calculate Pearson correlation or claim a general absence of correlation has been demonstrated.

Mean normalized distance for failures also grew between the first 50 steps and the last 50. For the first seed’s loss-selected checkpoint it went from 2.149 to 3.329; for the rollout-selected checkpoint, from 2.462 to 4.127. These are training-neighbor distances under the metric defined above, not probabilities or millimeters. The trajectories show drift, but this comparison does not prove drift is the sole cause of failure. Expert decisions can depend on its internal plan even when the current observation is similar, a possibility worth investigating that this measurement alone does not resolve.

[ ]Compare criteria and driftLocal GPU
import numpy as np
for r in resultado:
    print('entrenamiento', r['seed'])
    for criterion in ('val', 'roll'):
        z = r[criterion]
        fail = [e for e in z['episodes'] if not e['success']]
        ok = [e for e in z['episodes'] if e['success']]
        def tramo(grupo, inicio, fin):
            vals = [v for e in grupo for v in e['drift'][inicio:fin]]
            return round(float(np.mean(vals)), 3) if vals else None
        print(criterion, 'época', z['epoch'], 'éxitos', z['successes'], '/', z['n'],
              'Wilson', np.round(z['wilson'], 3), 'pasos medios',
              round(np.mean([e['steps'] for e in z['episodes']]), 1),
              'distancia media pasos 0:50 éxito/fallo', tramo(ok, 0, 50), tramo(fail, 0, 50),
              'fallos pasos 250:300', tramo(fail, 250, 300))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

To locate when failures appear, also plot distance by time. Successful episode lengths vary because they end on reaching the goal, while failed episodes reach the horizon: a late mean for successes does not describe all initially included episodes. In particular, do not interpret a late difference as a causal effect of drift without examining trajectories.

[ ]Distance curves by stepLocal GPU
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(7, 3))
for r in resultado:
    for name, style in [('roll', '-'), ('val', '--')]:
        episodes = r[name]['episodes']
        for success, suffix in [(False, 'fallo'), (True, 'éxito')]:
            rows = [e['drift'] for e in episodes if e['success'] == success]
            if not rows:
                continue
            means = [np.mean([x[t] for x in rows if len(x) > t]) if any(len(x) > t for x in rows) else np.nan for t in range(300)]
            ax.plot(means, style, alpha=0.6, label=f"semilla {r['seed']} {name} {suffix}")
ax.set(xlabel='Paso', ylabel='Distancia normalizada al vecino experto')
ax.legend(fontsize=7, ncol=2)
fig.tight_layout()
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericUncertainty of a rate
Calculate the lower bound of the 95% Wilson interval for 37 successes in 50 episodes, using z = 1.96.
ProofCouple two trajectories
Prove: Under the assumptions of the preceding bound, the expected cost difference is at most εT(T+1)/2.
0
The trajectories coincide until the policy and the expert take different actions.

Step 1 of 3. How do you bound the probability of a first disagreement before or at step t?

QuizChoose a checkpoint
An MLP has lower MSE on held-out demonstrations than another, but fails more often when deployed from new initial states. What best explains the discrepancy?
CodeIndependent episodes
Implement evaluate_policy(policy, env_fn, n_episodes, seeds). env_fn(seed) creates an independent environment whose reset returns an observation and step(action) returns (observation, success, done). Run episodes in parallel with ThreadPoolExecutor until termination or 300 steps. Return successes, interval, and mean_steps. seeds contains exactly n_episodes seeds and n_episodes is positive. policy is safe for concurrent calls.
def evaluate_policy(policy, env_fn, n_episodes, seeds):
  pass
Shift+Enter to run

The enduring idea

Key idea

BC learns actions on the demonstration distribution, but its rollout visits a distribution dependent on its own decisions. Separate episodes and statistics, preserve action units, measure success on new initial states with intervals and multiple seeds, and use drift as a diagnostic rather than an automatic explanation. The next lesson asks what changes if the expert can label exactly the states the policy visits.