Lesson 6.3 — Imitation Learning
Previous lesson · 6.2 Vision-Language Models · Course overview · Next lesson · 6.4 Diffusion Policy
Robot Learning as Feedback Control
A policy maps observations or an observation history to actions. The system dynamics use those actions to evolve the state. The observation model determines what is available to the policy. In a partially observed system, an observation may leave dynamics-relevant information hidden.
The teaching system is a fully observed two-dimensional point mass with target at the origin. Position is measured in metres, velocity in metres per second, and action in metres per second squared. Each action component is bounded by two. With sampling period 0.1 s, update the velocity first, then advance the position using that new velocity.
The expert is saturated PD feedback. The simulated disturbance adds a velocity impulse immediately before the action at step 10. The imitation objective fits expert labels. Closed-loop evaluation measures how the resulting actions interact with disturbances and dynamics.
State–Observation–Action Simulator
Episodes and Time-aligned Demonstrations
Store episode identity, timestamp, observation, action, validity, coordinate frame, and sampling rate. The label paired with is the action applied to obtain the next observation. Fit normalization statistics on training episodes and use the same transformation during evaluation.
Split whole episodes because adjacent samples are correlated. There are 12 nominal training episodes, eight nominal validation episodes, and 32 perturbed episodes for out-of-distribution development evaluation. The latter use independent seeds and were examined during development.
A training window stays inside its episode. When an offline recording ends early, mask padded future labels and normalize by the number of valid scalar targets. The teaching chunk policy uses a stronger supervision setup. From each queried state, the known expert and simulator generate four future actions, including actions beyond the rollout evaluation horizon.
Episode & Trajectory Inspector
| Step | State (q, v) | Expert action | Valid mask |
|---|---|---|---|
| 0 | (-0.1839, 0.0355, 0.1121, 0.0837) | (0.1854, -0.1726) | 1 |
| 1 | (-0.1714, 0.0417, 0.125, 0.0622) | (0.146, -0.156) | 1 |
| 2 | (-0.1581, 0.046, 0.1334, 0.0435) | (0.1112, -0.1395) | 1 |
| 3 | (-0.1443, 0.0488, 0.1378, 0.0274) | (0.0806, -0.1234) | 1 |
Behavior Cloning
Treat expert actions as supervised targets. Continuous deterministic regression can use squared error, while a probabilistic policy can use negative log-likelihood. With squared error the population minimizer is the conditional mean. Here the expert is deterministic, so the experiments focus on changes in the state distribution.
The one-step network has widths 4, 12, and 2, with 86 trainable parameters. The scaled tanh bounds its outputs in . The history version takes the current and previous states and has widths 8, 12, and 2, with 134 parameters. At the first step it duplicates the current observation. Because the full state is already observed, the previous state need not help. The rollout lab feeds back the policy's own trajectory.
Supervised Policy Training
Covariate Shift and Compounding Error

Read the solid traces first. The plot isolates one lateral coordinate of the lesson’s point mass. It starts at rest on the centerline. The expert keeps it there. An illustrative policy with a persistent sideways acceleration leaves it. At the marked instant both its position and its velocity differ from those in the expert demonstration.
The expert action on the original recording at that timestamp is zero. At the visited state, the same expert commands acceleration back toward the centerline. The dashed curve shows what would happen if the expert took over there. It briefly continues outward because the mass already has outward velocity. A corrective action changes velocity before it changes position. The biased policy in this illustration is prescribed to expose the mechanism.
Training error averages over the states visited by the expert. A learned policy can cause the system to visit different states, including states with few demonstrations. Linearize around an expert trajectory. Let denote the learned action's deviation from the expert's action at the same state. Let and be local dynamics derivatives and the expert's local feedback derivative.
The closed-loop term determines local accumulation, and stable feedback can attenuate perturbations. The linearization can become inaccurate far from the nominal trajectory or near switches and action saturation. A scalar example with constant feedback multiplier and action error gives the geometric sum below.
Use the lab to compare multipliers inside and outside the unit circle. Worst-case horizon bounds from imitation-learning theory require assumptions about costs and visited states. The simulated physical state error depends on the closed-loop dynamics.
Compute how a persistent action bias propagates through a linearized system
Compounding Error Simulator
DAgger and Dataset Aggregation
Collect trajectories under a learned policy or an expert–learner mixture. At the states actually visited, query the action the expert would take. Append those counterfactual expert labels to the training data and resume fitting.
At the marked state in the preceding figure, a DAgger collector can record the expert’s corrective acceleration and still let the learner take the next action. That single state–action pair is a valid new training example. Drawing the dashed recovery illustrates what the label means. Executing that recovery is optional during collection.
The mixture in the collection rule denotes a choice between policies, which can be sampled at each step. The experiment sets the expert action probability to zero during collection. At updates 80, 160, and 240, run six perturbed learner episodes and query 35 expert labels per episode. The dataset grows from 420 to 1050 labels. Behavior cloning uses the same 320 optimizer updates but keeps the initial 420 labels. The difference in supervision includes both extra expert queries and perturbed collection conditions.
Dataset Aggregation Player
Joint and Cartesian Actions
Specify whether the output means an absolute joint position, an increment, a velocity, an end-effector motion, or a force or torque. Its meaning depends on the coordinate frame, units, and sampling interval. Rotation updates require a representation compatible with composition on .
For a planar arm with two one-metre links, differentiate the end-effector position to obtain its Jacobian. The straight configuration makes the Jacobian singular. Damped least squares solves a regularized tracking problem. For positive damping it remains well-defined at this configuration and trades Cartesian tracking accuracy for smaller joint velocities.
Joint / Cartesian Action Inspector
Prediction Horizons and Temporal Ensembling
A chunk policy predicts consecutive actions at once. In the teaching model the eight outputs are reshaped to four two-dimensional commands. The controller can execute actions before reading a new observation. Larger reduces policy calls and lengthens the time between corrections.
ACT uses a Transformer and conditional variational training to predict action chunks. A training encoder can see the demonstrated chunk; the reference inference uses the zero latent. Temporal ensembling combines predictions for the same execution step made from different earlier observations. Only chunks that cover the current step enter the average. The reference implementation weights earlier predictions more heavily.
The lab computes such a weighted average using predictions along a recorded rollout of the deterministic chunk MLP. It keeps the rollout state fixed when comparing the average and the individual predictions. The training experiment uses the deterministic MLP and varies how many outputs are executed before replanning.
Prediction Horizon & Temporal Ensembling
| Prediction origin | Predicted action | Normalized weight |
|---|---|---|
| 0 | (1.3896, -1.3352) | 1 |
Engineering Experiment · BC, DAgger, and Chunked BC
Compare 86-parameter single-step BC and DAgger, 134-parameter history BC, and 164-parameter chunked BC. The default uses seed 3, batch size 32, learning rate 0.01, and 320 Adam updates. The nominal initial position and velocity ranges are m and m/s per axis. Perturbed evaluation widens the position range to m and applies a step-10 velocity impulse of up to 1.8 m/s per axis. Each evaluation episode lasts 35 steps.
Success checks position and velocity at the final step. The tracking metric averages squared displacement over time and coordinates. The action-increment metric measures successive acceleration-command differences, without dividing by sampling time. Final position error averages the terminal Euclidean norm.
Live BC vs. DAgger Training
PyTorch benchmark · Seed 3
| Policy | Nominal action MSE | OOD tracking MSE | Final error (m) | Success | Δaction MSE |
|---|---|---|---|---|---|
| Expert | — | 0.106530 | 0.072230 | 65.62% | 0.059429 |
| BC | 6.28876e-06 | 0.129314 | 0.103786 | 43.75% | 0.033282 |
| History BC | 2.97229e-05 | 0.149399 | 0.133895 | 43.75% | 0.017098 |
| DAgger | 0.000505234 | 0.110448 | 0.066094 | 71.88% | 0.049479 |
| Chunk E=4 | — | 0.186441 | 0.205072 | 37.50% | 0.047292 |
| Chunk E=1 | — | 0.134190 | 0.116026 | 43.75% | 0.032270 |
Behavior cloning has very low nominal action error and succeeds in 14 of the 32 perturbed episodes. DAgger succeeds in 23 and has higher nominal action error. Both chunk rows use the same learned model. Executing four actions per plan gives 12 successful rollouts, while replanning after each action gives 14. The expert succeeds in 21 of these finite-horizon rollouts. These measurements reflect different query budgets and one synthetic development split.
Reproducible PyTorch implementation
The CPU float64 script trains the four policies and reports supervision and rollout metrics as JSON. Inspect nominal action errors and perturbed trajectory outcomes separately.
import math,json,sys,torch
from torch import nn
torch.set_num_threads(1);torch.set_default_dtype(torch.float64)
H=4; T=35; DT=.1; LIMIT=2.
class RNG:
def __init__(self,s): self.s=s
def __call__(self): self.s=(1664525*self.s+1013904223)%2**32;return self.s/2**32
def u(self,a):return a*(2*self()-1)
def expert(s):return [max(-2,min(2,-1.8*s[i]-1.3*s[i+2])) for i in range(2)]
def step(s,a):
v=[.95*s[i+2]+DT*a[i] for i in range(2)]
return [s[i]+DT*v[i] for i in range(2)]+v
def label(s,h):
y=[]
for _ in range(h):
a=expert(s);y+=a;s=step(s,a)
return y
def obs(s,prev,mode):return s+prev if mode=='history' else s
def cases(seed,n,shift):
r=RNG(seed);return [([r.u(1.0 if shift else .35),r.u(1.0 if shift else .35),r.u(.15),r.u(.15)],[r.u(1.8),r.u(1.8)] if shift else [0.,0.]) for _ in range(n)]
class Policy(nn.Module):
def __init__(self,seed,mode):
super().__init__();self.mode=mode;d=8 if mode=='history' else 4;m=8 if mode=='chunk' else 2
self.l1=nn.Linear(d,12);self.l2=nn.Linear(12,m);r=RNG(seed+100)
with torch.no_grad():
for p in self.parameters(): p.copy_(torch.tensor([r.u(.4) for _ in range(p.numel())]).reshape(p.shape))
def forward(self,x):return 2*torch.tanh(self.l2(torch.tanh(self.l1(x))))
def predict(self,x):
with torch.no_grad():return self(torch.tensor(x)).tolist()
def rollout(case,mode,p=None,execute=1):
s,imp=case; s=s.copy();prev=s.copy();states=[s];acts=[];data=[];queue=[]
for k in range(T):
if k==10:s=s[:2]+[s[2]+imp[0],s[3]+imp[1]];states[-1]=s
x=obs(s,prev,mode); data.append((x,label(s,H if mode=='chunk' else 1)))
if p is None:a=expert(s)
else:
if not queue:queue=p.predict(x)[:2*execute]
a=queue[:2];queue=queue[2:]
acts.append(a);prev=s;s=step(s,a);states.append(s)
return states,acts,data
def dataset(cs,mode,p=None):return [row for c in cs for row in rollout(c,mode,p)[2]]
def metrics(p,mode,cs,execute=1):
rr=[rollout(c,mode,p,execute) for c in cs];n=len(rr)
mse=sum(sum(sum(q*q for q in s[:2]) for s in states[1:]) for states,_,_ in rr)/(n*T*2)
err=sum(math.hypot(*states[-1][:2]) for states,_,_ in rr)/n
ok=sum(math.hypot(*states[-1][:2])<.12 and math.hypot(*states[-1][2:])<.2 for states,_,_ in rr)/n
jerk=sum(sum(sum((a[i]-b[i])**2 for i in range(2)) for a,b in zip(acts[1:],acts[:-1])) for _,acts,_ in rr)/(n*(T-1)*2)
return dict(tracking=mse,final=err,success=ok,delta=jerk)
def train(mode='bc',seed=3,updates=320,lr=.01):
p=Policy(seed,mode);opt=torch.optim.Adam(p.parameters(),lr=lr);r=RNG(seed+200)
ds=dataset(cases(seed,12,False),mode);vs=dataset(cases(seed+1000,8,False),mode);test=cases(seed+2000,32,True);hist=[]
for t in range(updates+1):
if t% (updates//4)==0 or t==updates:
with torch.no_grad():
x,y=map(torch.tensor,zip(*vs));mse=((p(x)-y)**2).mean().item()
hist.append(dict(t=t,size=len(ds),mse=mse,**metrics(p,mode,test,H if mode=='chunk' else 1)))
if mode=='dagger' and t>0 and t<updates:ds+=dataset(cases(seed+300+t,6,True),mode,p)
if t==updates:break
batch=[ds[int(r()*len(ds))] for _ in range(32)];x,y=map(torch.tensor,zip(*batch));loss=((p(x)-y)**2).mean();opt.zero_grad();loss.backward();opt.step()
return dict(hist=hist,p={k:v.detach().tolist() for k,v in p.named_parameters()},replan=metrics(p,mode,test,1),openloop=metrics(p,mode,test,H if mode=='chunk' else 1))
if __name__=='__main__':
out={m:train(m) for m in ['bc','history','dagger','chunk']};out['expert']=metrics(None,'bc',cases(2003,32,True));print(json.dumps(out))
References and Next Lesson
- Ross, Gordon, and Bagnell introduce dataset aggregation. DAgger · Learning from Demonstrations
- Zhao et al. use chunked generation and temporal ensembling. ACT · ACT implementation
- The course covers imitation learning and distribution shift. Berkeley Deep RL
- The next lesson uses a conditional diffusion model for action chunks. Diffusion Policy
Previous lesson · 6.2 Vision-Language Models · Course overview · Next lesson · 6.4 Diffusion Policy