Module contents
Lesson 8 of 33Core 120 min

Behavior cloning: imitation as supervised learning

Learn policies from expert demonstrations, analyze compounding error, multimodality and causal confusion, and compare Gaussian-mixture and discretized action heads.

After this lesson you can

  • Formalize imitation learning using policies, induced state distributions and surrogate losses.
  • Prove the O(T²ε) behavior-cloning cost bound and construct a matching example.
  • Show how squared-error regression can average modes into invalid actions.
  • Implement Gaussian-mixture and k-means-plus-offset policy heads and compare them with MSE regression.
  • Diagnose causal confusion when observations reveal a previous action.

Before you start

Learning by watching

In ALVINN, a network learned to drive from examples. The idea transfers to an arm: record what the expert sees and the action taken, then fit a policy to reproduce that relationship. We need not design a reward for every detail, but must understand what demonstrations cover and what happens when the policy controls the next state.

InteractiveThe cloner that leaves the corridor
  • One trajectory: e²
  • Expectation E[e²]
25
0.02
50
Lateral error0.438
Inside nowNo
A lateral trajectory with bias and noise is compared with its analytical expectation. This is a simplified model without lateral correction, not a robot measurement.
InteractiveThe mean of two good decisions can collide
100
Head
Selected mode
Learned action0.000
Geometric resultCollides
Mixture means−0.27 / 0.27
A mean, Gaussian mixture and two discrete centres are fitted to synthetic data; choose a head and mode to see its curve.
InteractiveRoad or brake light?
First 45 steps of the closed-loop episode
Obstacle
Brake

Coloured cell: obstacle present or brake applied.

0.30
1000
Validation accuracy93.6 %
Closed-loop accuracy46.1 %
Previous brake weight0.85
A linear predictor is fitted to synthetic data with an imperfect visual signal; compare validation with the expert's previous action and execution with its own previous action.

Imitating a distribution

The imitation problem starts from expert trajectories τ=(o1,a1,…,oT,aT)\tau=(o_1,a_1,\ldots,o_T,a_T). Policy πθ(a∣o)\pi_\theta(a\mid o) receives potentially partial observations oo and generates actions. System state evolves under those actions, so state distribution dπtd_\pi^t depends on the policy. Two very similar demonstrations are not equivalent to two independent episodes: split training and validation by trajectory and hold out episodes and seeds for evaluation.

Behavior cloning minimizes supervised loss over expert observations, for example −∑log⁡πθ(at∣ot)-\sum\log\pi_\theta(a_t\mid o_t) or squared error for a deterministic output. With a fixed-variance Gaussian, maximum likelihood is equivalent to minimizing squared error up to constants and scale. Validation loss measures prediction under the demonstration distribution; it does not directly measure success after the policy’s actions change the world.

If dπEtd_{\pi_E}^t is the expert state distribution at step tt, its average occupancy distribution is dˉπE=T−1∑tdπEt\bar d_{\pi_E}=T^{-1}\sum_t d_{\pi_E}^t. Empirical loss approximates an expectation under that distribution and the mechanism producing expert observations and actions. The control objective, however, is evaluated under dˉπθ\bar d_{\pi_\theta}. This distinction locates the problem: even with an excellent fit on dˉπE\bar d_{\pi_E}, the supervised set may not contain recoveries from the cloner’s deviations.

Before fitting a network, plot some observation-action pairs and check latency, units and temporal alignment. If the image at tt is mistakenly paired with an action at t+1t+1, low loss can conceal information leakage or systematic delay. Normalizing with statistics calculated across the whole collection also leaks evaluation information. Data from one demonstration are temporal and correlated; random frame splitting distributes near duplicates between training and validation, making an episode split more informative.

Fix the interface: a torque action at 1 kHz and Cartesian velocity at 10 Hz imply different executors. Normalize with training statistics and apply the same transformation at evaluation; handle periodic orientations carefully. History can resolve ambiguity from partial observation but can also introduce spurious signals. In lesson six the pushing expert observes privileged position; a visual policy must infer it from the image or receive an estimate available at deployment.

When an error changes later data

Compounding error arises because the policy visits states different from those seen during training. Assume horizon TT, per-step cost in [0,1][0,1], and probability of disagreement with the expert at most ϵ\epsilon under each expert-time distribution. Until the first disagreement the trajectories are coupled. By the union bound, the probability of having disagreed by step tt is at most tϵt\epsilon. Even if everything goes wrong after the first error,

J(π)−J(πE)≤∑t=1Tmin⁡(1,tϵ)≤T2ϵ.J(\pi)-J(\pi_E)\leq \sum_{t=1}^T\min(1,t\epsilon)\leq T^2\epsilon.

This is an upper bound under these assumptions, not an exact prediction or a general result from arbitrary MSE. Total cost also cannot exceed TT. If only the time-averaged error ϵ\epsilon is known, first summing per-step probabilities still gives a bound of order T2ϵT^2\epsilon. Ross and Bagnell (2010) study this distribution shift.

The scaling can be attained: in a good state, the policy errs with probability ϵ\epsilon and enters an absorbing bad state with cost 1. The probability of being bad at tt is 1−(1−ϵ)t1-(1-\epsilon)^t, and expected cost is their sum. For small TϵT\epsilon, that sum is approximately ϵT(T+1)/2\epsilon T(T+1)/2; for longer horizons it saturates at order TT. With T=200T=200 and ϵ=0.01\epsilon=0.01, T2ϵ=400T^2\epsilon=400 but the trivial cost bound is 200: the quadratic bound does not say actual cost can exceed 200.

The first figure illustrates a different calculation: lateral displacement satisfies et+1=et+b+ηte_{t+1}=e_t+b+\eta_t, with b=0.04/Nb=0.04/\sqrt N, independent zero-mean ηt\eta_t with standard deviation σ\sigma, and e0=0e_0=0. Thus E[et2]=(bt)2+tσ2\mathbb E[e_t^2]=(bt)^2+t\sigma^2. The quadratic curve is squared lateral error in this model, not the cost bound above; NN changes a hypothetical bias and does not train a network. The blue line uses a fixed pseudorandom sequence. A policy with corrective feedback can have different dynamics.

An unbiased random error in that walk contributes tσ2t\sigma^2 to expected squared error; a constant bias contributes (bt)2(bt)^2. The imitation bound concerns disagreement probability and cumulative cost under potentially adverse transitions. Neither formula claims all robots have error quadratic in time. To diagnose a real policy, record when it leaves demonstration coverage, how the observation changes, and whether the following action corrects or amplifies the deviation.

Two correct answers

Multimodality occurs when the same observation permits several valid behaviours. If the action is −a-a or +a+a with equal probability, the minimizer of E[(a−a^)2∣o]\mathbb E[(a-\hat a)^2\mid o] is E[a∣o]=0\mathbb E[a\mid o]=0: the average may go straight into the obstacle. Not every human distribution is multimodal in the chosen representation, and a mean is not always invalid; check the context.

A Gaussian-mixture policy predicts weights wkw_k, means μk\mu_k and standard deviations σk>0\sigma_k>0 conditioned on oo:

log⁡π(a∣o)=logsumexp⁡k ⁣(log⁡wk+log⁡N(a;μk,Σk)).\log\pi(a\mid o)=\operatorname{logsumexp}_k\!\left(\log w_k+\log\mathcal N(a;\mu_k,\Sigma_k)\right).

Subtracting the maximum before exponentiating prevents overflow and numerical loss when summing very small densities. The second figure actually fits an MSE mean, a two-Gaussian mixture with EM and two k-means centres to synthetic actions. Selecting a mode uses its mean or centre; the geometric curve is y=0.5+asin⁡(πx)y=0.5+a\sin(\pi x) against a circle of radius 0.15. The mode choice exposes ambiguity; it is not a trained robot policy.

For logarithmic values uu and vv, calculate m=max⁡(u,v)m=\max(u,v) and then m+log⁡(eu−m+ev−m)m+\log(e^{u-m}+e^{v-m}). A very unlikely component no longer requires directly calculating eu+eve^u+e^v at an extreme scale. In a learned mixture also watch for standard deviations that are too small: unconstrained, a density can concentrate on a few samples and give misleading loss values. Limiting or regularizing deviation and evaluating generated actions helps, but the specific choice affects the model.

Discretization with offsets groups actions into centres ckc_k, predicts a distribution over indices and an offset δk(o)\delta_k(o); the action is ck+δkc_k+\delta_k. Behavior Transformers combines discretization and correction with a history transformer. The lab’s simple head shares the idea of centres and offsets but does not reproduce the full model or its results. VQ-BeT explores vector quantization for multimodal actions and behaviours.

Correlation and control

Causal confusion can appear when a feature predicts the expert’s action in the dataset but the policy changes that feature when acting. In the example of de Haan, Jayaraman and Levine (2019), a brake light can result from a previous action and become a misleading signal. Validation with expert history can favour that correlation; during execution, history comes from the policy.

The third figure constructs a synthetic process where the obstacle persists with probability 0.95 per step and the visual signal fails with adjustable probability. It fits least squares with or without previous braking. In validation, previous braking comes from the expert; during execution, from the policy’s own prediction, with initial brake zero. Compare accuracy in both sets and disable the signal. The result illustrates a mechanism; it does not show that all history is bad or replace interventions and environment evaluation.

A useful comparison changes one cause at a time: run the policy with and without the suspect signal, or test states where previous braking and obstacle presence disagree. If supervised fit falls but closed-loop behaviour improves, the earlier signal probably enabled a prediction that did not hold during control. Memory may still be needed to infer velocity or hidden objects; design and evaluate it under use conditions rather than eliminating it on principle.

Lab: three heads in NumPy

We generate 80 demonstrations by repeating two deterministic trajectories around a circle; these are not 80 unique trajectories. We train a tanh hidden layer from scratch with Adam implemented in NumPy. Outputs are MSE, a Gaussian mixture with log-sum-exp, and k-means centres with offsets. At each step the cloner observes current progress and position, predicts an action and changes its position; we count collisions and squared distance to the nearest expert mode at each instant. The 100 seeds change stochastic mixture and discretization choices; deterministic MSE repeats the same trajectory. They are not 100 independent scenarios.

[ ]Three policies in a bimodal environmentBrowser
import numpy as np
rng=np.random.default_rng(2024);T=30;A_SCALE=.05
def expert_path(sign):
    x=np.arange(T+1)/T;return .5+sign*.27*np.sin(np.pi*x)
obs=[];actions=[]
for ep in range(80):
    sign=-1 if ep%2==0 else 1;y=expert_path(sign)
    for t in range(T):obs.append([t/T,(y[t]-.5)/.3]);actions.append((y[t+1]-y[t])/A_SCALE)
X=np.array(obs);Y=np.array(actions)[:,None]
def softmax(z):
    z=z-z.max(axis=1,keepdims=True);e=np.exp(z);return e/e.sum(axis=1,keepdims=True)
def logsumexp(z):
    m=z.max(axis=1,keepdims=True);return m+np.log(np.exp(z-m).sum(axis=1,keepdims=True))
def kmeans(a,k=2):
    centers=np.array([np.quantile(a,.2),np.quantile(a,.8)])
    for _ in range(25):
        labels=np.argmin((a-centers[None,:])**2,axis=1)
        centers=np.array([a[labels==j].mean() if np.any(labels==j) else centers[j] for j in range(k)])
    return centers
centers=kmeans(Y)
class MLP:
    def __init__(self,head,seed):
        self.head=head;r=np.random.default_rng(seed);out={'mse':1,'gmm':6,'bins':4}[head]
        self.p=[r.normal(0,.2,(2,24)),np.zeros(24),r.normal(0,.1,(24,out)),np.zeros(out)]
        if head=='gmm':self.p[3][2:4]=[-.5,.5];self.p[3][4:6]=-1.
        self.m=[np.zeros_like(p) for p in self.p];self.v=[np.zeros_like(p) for p in self.p];self.it=0
    def forward(self,x):
        h=np.tanh(x@self.p[0]+self.p[1]);return h,h@self.p[2]+self.p[3]
    def train(self,x,y,lr=.01):
        h,z=self.forward(x);n=len(x)
        if self.head=='mse':
            err=z-y;loss=np.mean(err**2);dz=2*err/n
        elif self.head=='gmm':
            logits,mu,raw=z[:,:2],z[:,2:4],z[:,4:6];ls=np.clip(raw,-3.,1.);w=softmax(logits)
            lp=logits-logsumexp(logits)-.5*((y-mu)/np.exp(ls))**2-ls-.5*np.log(2*np.pi)
            norm=logsumexp(lp);r=np.exp(lp-norm);loss=-norm.mean()
            dz=np.concatenate((w-r,r*(mu-y)*np.exp(-2*ls),r*(1-((y-mu)/np.exp(ls))**2)*((raw>=-3)&(raw<=1))),axis=1)/n
        else:
            logits,off=z[:,:2],z[:,2:4];labels=np.argmin((y-centers[None,:])**2,axis=1);one=np.eye(2)[labels];w=softmax(logits);error=centers[None,:]+off-y
            loss=np.mean(-np.sum(one*(logits-logsumexp(logits)),axis=1)+np.sum(one*error**2,axis=1))
            dz=np.concatenate((w-one,2*one*error),axis=1)/n
        dh=(dz@self.p[2].T)*(1-h*h);grads=[x.T@dh,dh.sum(axis=0),h.T@dz,dz.sum(axis=0)]
        self.it+=1
        for i,g in enumerate(grads):
            self.m[i]=.9*self.m[i]+.1*g;self.v[i]=.999*self.v[i]+.001*g*g
            self.p[i]-=lr*(self.m[i]/(1-.9**self.it))/(np.sqrt(self.v[i]/(1-.999**self.it))+1e-8)
        return loss
    def act(self,x,r):
        _,z=self.forward(np.asarray(x)[None,:])
        if self.head=='mse':return float(z[0,0])*A_SCALE
        probs=softmax(z[:,:2])[0];j=int(r.random()>probs[0])
        return float(z[0,2+j] if self.head=='gmm' else centers[j]+z[0,2+j])*A_SCALE
def rollout(model,seed):
    r=np.random.default_rng(seed);y=.5;ys=[y];collision=False
    for t in range(T):
        a=model.act([t/T,(y-.5)/.3],r);y+=np.clip(a,-.06,.06);x=(t+1)/T;ys.append(y)
        collision|=np.hypot(x-.5,y-.5)<=.12
    expert=np.stack([expert_path(-1),expert_path(1)]);divergence=np.mean(np.min((np.array(ys)[None,:]-expert)**2,axis=0))
    return not collision,divergence
models={}
for idx,head in enumerate(['mse','gmm','bins']):
    model=MLP(head,seed=30+idx);loss=0.
    for it in range(300):
        inds=rng.integers(0,len(X),256);loss=model.train(X[inds],Y[inds])
    results=[rollout(model,seed) for seed in range(100)]
    print(head,'pérdida final minibatch',round(loss,4),'éxitos',sum(r[0] for r in results),'/100','divergencia media',round(np.mean([r[1] for r in results]),5))
    models[head]=model

Final minibatch loss and success measure different things. The episode has 30 steps and collision is checked at sampled states, without a guarantee between them. Divergence here is geometric distance to two reference trajectories, not KL divergence or a generally estimated distance between distributions. The policy chooses a discrete component at each step; a real controller may need memory or temporal consistency to avoid switching modes.

Local lab: clone pushing from images

Install PyTorch, MuJoCo, Gymnasium 1.1 or later, NumPy and Matplotlib. The code reproduces lesson six’s pushing environment: an expert uses privileged block position and a policy receives image and proprioception. It collects 1,000 episodes, trains a small residual network with three heads and uses the first 10, 100 or 1,000 episodes as nested sets. During collection, an image and action are recorded every five steps, although the expert controls every step; unrecorded steps are not rendered. Every observation is rendered at evaluation. Recorded images are reduced to 32×32; the goal is fixed and is not a separate input. Evaluation uses 20 new seeds per model; the Wilson interval reflects binomial uncertainty under this test’s conditions, not variation across training runs. Collection and rendered evaluation may take several minutes and memory for images. CUDA is selected when available.

[ ]Clone visual pushing and evaluateLocal GPU
import os, time
import numpy as np
import gymnasium as gym
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
import mujoco

XML='''<mujoco model="push"><option timestep="0.002"/><worldbody>
<light pos="0 0 2"/><camera name="top" pos="0 0 .5" xyaxes="1 0 0 0 1 0"/>
<geom name="table" type="plane" size="1 1 .1" friction="1 .005 .0001"/>
<body name="pusher" pos="-.15 0 .025"><joint name="px" type="slide" axis="1 0 0" damping="5"/><joint name="py" type="slide" axis="0 1 0" damping="5"/><geom type="sphere" size=".015" mass="1" rgba=".2 .4 .8 1"/><site name="tip" size=".005"/></body>
<body name="block" pos="0 0 .025"><freejoint name="blockjoint"/><geom type="box" size=".025 .025 .025" mass=".1" rgba=".8 .3 .2 1"/></body>
</worldbody><actuator><velocity joint="px" kv="100" ctrlrange="-.2 .2"/><velocity joint="py" kv="100" ctrlrange="-.2 .2"/></actuator></mujoco>'''
class PushBlockEnv(gym.Env):
    metadata={'render_modes':['rgb_array'], 'render_fps':10}
    def __init__(self,render_mode='rgb_array',max_steps=100):
        self.model=mujoco.MjModel.from_xml_string(XML);self.data=mujoco.MjData(self.model);self.render_mode=render_mode;self.max_steps=max_steps;self.renderer=None;self.capture=True
        self.action_space=spaces.Box(-1.,1.,shape=(2,),dtype=np.float32)
        self.observation_space=spaces.Dict({'rgb':spaces.Box(0,255,(64,64,3),dtype=np.uint8),'proprio':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32),'task':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32)})
        self.tip=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_SITE,'tip');self.block=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_BODY,'block')
        self.goal=np.array([.15,0.]);self.count=0
    def _obs(self):
        if self.capture:
            if self.renderer is None:self.renderer=mujoco.Renderer(self.model,64,64)
            self.renderer.update_scene(self.data,camera='top');img=self.renderer.render().copy()
        else:img=np.zeros((64,64,3),dtype=np.uint8)
        return {'rgb':img,'proprio':np.r_[self.data.qpos[:2],self.data.qvel[:2]].astype(np.float32),'task':np.r_[self.data.xpos[self.block,:2],self.goal].astype(np.float32)}
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed);mujoco.mj_resetData(self.model,self.data);self.data.qpos[3]=self.np_random.uniform(-.015,.015);self.count=0;mujoco.mj_forward(self.model,self.data)
        return self._obs(),{}
    def step(self,action):
        a=np.clip(np.asarray(action,dtype=np.float32),-1,1);mujoco.mj_forward(self.model,self.data)
        jp=np.zeros((3,self.model.nv));jr=np.zeros_like(jp);mujoco.mj_jacSite(self.model,self.data,jp,jr,self.tip)
        desired=.2*a;J=jp[:2,:2];vel=J.T@np.linalg.solve(J@J.T+1e-4*np.eye(2),desired)
        self.data.ctrl[:]=np.clip(vel,-.2,.2)
        for _ in range(50):mujoco.mj_step(self.model,self.data)
        mujoco.mj_forward(self.model,self.data)
        self.count+=1;distance=np.linalg.norm(self.data.xpos[self.block,:2]-self.goal);terminated=bool(distance<.035);truncated=bool(self.count>=self.max_steps and not terminated)
        return self._obs(),float(-distance),terminated,truncated,{'distance':float(distance),'success':terminated}
    def render(self):return self._obs()['rgb']
    def close(self):
        if self.renderer is not None:self.renderer.close();self.renderer=None

def expert(obs):
    p=obs['proprio'];tip=np.array([-.15,0])+p[:2];block=obs['task'][:2];goal=obs['task'][2:];direction=goal-block;direction/=max(np.linalg.norm(direction),1e-8);behind=block-.045*direction
    target=behind if np.linalg.norm(tip-behind)>.025 and tip[0]<block[0]-.02 else goal
    return np.clip(6*(target-tip),-1,1).astype(np.float32)

import torch
from torch import nn
import torch.nn.functional as F
torch.set_num_threads(2);device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.manual_seed(41);rng=np.random.default_rng(41)
def compress(obs):return {'rgb':obs['rgb'][::2,::2].copy(),'proprio':obs['proprio'].copy()}
episodes=[];env=PushBlockEnv()
for ep in range(1000):
    env.capture=True;obs,_=env.reset(seed=ep);samples=[];t=0
    while True:
        a=expert(obs)
        if t%5==0:samples.append((compress(obs),a.copy()))
        t+=1;env.capture=(t%5==0);obs,_,done,cut,_=env.step(a)
        if done or cut:break
    episodes.append(samples)
    if (ep+1)%100==0:print('recogidas',ep+1,'demostraciones',flush=True)
env.close();print('demostraciones recogidas:',len(episodes),'transiciones:',sum(map(len,episodes)),'dispositivo:',device)
class Residual(nn.Module):
    def __init__(self,c):
        super().__init__();self.net=nn.Sequential(nn.Conv2d(c,c,3,padding=1),nn.ReLU(),nn.Conv2d(c,c,3,padding=1))
    def forward(self,x):return F.relu(x+self.net(x))
class Policy(nn.Module):
    def __init__(self,head):
        super().__init__();self.head=head
        self.vision=nn.Sequential(nn.Conv2d(3,16,5,stride=2,padding=2),nn.ReLU(),Residual(16),nn.Conv2d(16,32,3,stride=2,padding=1),nn.ReLU(),Residual(32),nn.AdaptiveAvgPool2d(1),nn.Flatten())
        out={'mse':2,'gmm':15,'bins':24}[head];self.mlp=nn.Sequential(nn.Linear(36,64),nn.ReLU(),nn.Linear(64,out))
    def forward(self,images,proprio):return self.mlp(torch.cat([self.vision(images),proprio/.2],dim=1))
def fit_centers(a,k=8):
    gen=np.random.default_rng(11);centers=a[gen.choice(len(a),k,replace=len(a)<k)].copy()
    for _ in range(20):
        labels=np.argmin(((a[:,None,:]-centers[None,:,:])**2).sum(-1),axis=1)
        for j in range(k):
            if np.any(labels==j):centers[j]=a[labels==j].mean(0)
    return centers.astype(np.float32)
def loss_for(head,out,a,centers):
    if head=='mse':return F.mse_loss(out,a)
    if head=='gmm':
        logits=out[:,:3];means=out[:,3:9].reshape(-1,3,2);logstd=out[:,9:15].reshape(-1,3,2).clamp(-4,1)
        logp=(-.5*((a[:,None,:]-means)/logstd.exp())**2-logstd-.5*np.log(2*np.pi)).sum(-1)
        return -torch.logsumexp(F.log_softmax(logits,dim=1)+logp,dim=1).mean()
    logits=out[:,:8];offsets=out[:,8:].reshape(-1,8,2)
    target=((a[:,None,:]-centers[None,:,:])**2).sum(-1).argmin(1);chosen=offsets[torch.arange(len(a),device=a.device),target]
    return F.cross_entropy(logits,target)+F.mse_loss(chosen,a-centers[target])
def predict(model,obs,centers):
    c=compress(obs);im=torch.from_numpy(c['rgb']).permute(2,0,1).float()[None].to(device)/255
    pr=torch.from_numpy(c['proprio'])[None].to(device)
    with torch.no_grad():out=model(im,pr)
    if model.head=='mse':a=out[0]
    elif model.head=='gmm':
        j=int(out[0,:3].argmax());a=out[0,3:9].reshape(3,2)[j]
    else:
        j=int(out[0,:8].argmax());a=centers[j]+out[0,8:].reshape(8,2)[j]
    return a.clamp(-1,1).cpu().numpy().astype(np.float32)
def wilson(s,n):
    z=1.96;p=s/n;den=1+z*z/n;mid=(p+z*z/(2*n))/den;half=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/den
    return mid-half,mid+half
records=[]
for num in [10,100,1000]:
    flat=[item for ep in episodes[:num] for item in ep];images=np.stack([s[0]['rgb'] for s in flat]);proprio=np.stack([s[0]['proprio'] for s in flat]);actions=np.stack([s[1] for s in flat]);centers=torch.tensor(fit_centers(actions),device=device)
    for head in ['mse','gmm','bins']:
        torch.manual_seed(41);model=Policy(head).to(device);opt=torch.optim.Adam(model.parameters(),lr=.001)
        model.train()
        for step in range(200):
            idx=rng.integers(0,len(flat),64);im=torch.from_numpy(images[idx]).permute(0,3,1,2).float().to(device)/255;pr=torch.from_numpy(proprio[idx]).to(device);a=torch.from_numpy(actions[idx]).to(device)
            loss=loss_for(head,model(im,pr),a,centers);opt.zero_grad();loss.backward();opt.step()
        model.eval();success=0;env=PushBlockEnv()
        for seed in range(20):
            obs,_=env.reset(seed=10000+seed)
            for _ in range(env.max_steps):
                obs,_,done,cut,info=env.step(predict(model,obs,centers))
                if done or cut:success+=int(done);break
        env.close();lo,hi=wilson(success,20);records.append((num,head,success,lo,hi))
        print('N',num,head,'éxitos',success,'/20','IC Wilson',round(lo,3),round(hi,3),'pérdida final',round(float(loss.detach()),4))
import matplotlib.pyplot as plt
fig,ax=plt.subplots()
for head in ['mse','gmm','bins']:
    rows=[r for r in records if r[1]==head];n=np.array([r[0] for r in rows]);p=np.array([r[2]/20 for r in rows]);lo=np.array([r[3] for r in rows]);hi=np.array([r[4] for r in rows])
    ax.errorbar(n,p,yerr=[p-lo,hi-p],marker='o',label=head)
ax.set(xscale='log',xlabel='demostraciones',ylabel='tasa de éxito',ylim=(-.05,1.05));ax.legend();plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The heads train for the same number of updates, not to guaranteed convergence. At evaluation MSE uses its output, the mixture uses the highest-weight component’s mean, and the discrete head uses the most probable centre and offset. The figures apply to this world and these seeds: for a serious comparison, repeat independent training runs, adjust budgets and consider out-of-distribution lighting, position, goals and dynamics. The interval across episodes does not cover those sources of variation.

For example, a wide Wilson interval with only 20 episodes does not justify concluding a small difference is real. All three curves use the same evaluation-seed indices, aiding paired comparison, but each point comes from one training run per head and size. A stronger study would repeat initialization and demonstration selection, declare stopping criteria and keep the final set separate. Mandlekar and colleagues study practical decisions for learning manipulation from human demonstrations; this lab is a much smaller synthetic task.

Practice

Proof
Prove: Bound the extra cost of a cloner over T steps.
0
Per-step cost is in [0,1] and disagreement probability under each expert-time distribution is at most ε.

Step 1 of 3. What is the maximum probability of having disagreed by step t?

Proof
Prove: The deterministic output minimizing squared error is the conditional mean.
0
Fix an observation o and write m=E[a|o].

Step 1 of 3. How does E[(a-c)²|o] decompose?

Numeric
For ε=0.01 and T=200, what is the ratio T²ε/(Tε)?
Quiz
Supervised loss is low, but the policy drifts into states without demonstrations and cannot recover. Which intervention addresses that symptom?
Code
Implement gmm_policy_nll(logits, means, log_stds, actions). Shapes: logits (B,K), means and log_stds (B,K,D), actions (B,D). Return NLL per example, using stable log-sum-exp and diagonal Gaussians.
import numpy as np
def gmm_policy_nll(logits, means, log_stds, actions):
  pass
Shift+Enter to run
Key idea
Cloning actions is supervised learning; evaluating the agent requires observing which states it produces and whether its actions remain valid there.