Lesson 6.4 — Diffusion Policy
Previous lesson · 6.3 Imitation Learning · Course overview · Next lesson · 6.5 Vision-Language-Action Models
From Behavior Cloning to Diffusion Policy
Diffusion Policy generates a distribution over actions conditioned on observations. It denoises in the space of complete action chunks, then executes a prefix and replans. The denoising clock advances inside one policy call. The control clock advances when an action is executed.
A deterministic behavior-cloning policy fitted with squared error estimates the conditional mean. Diffusion Policy also learns from demonstrations, using a conditional distribution to represent multiple possible chunks.
The simulated point mass moves from to past a circular obstacle at the origin of radius 0.5 m. The simulation runs at 10 Hz for 50 steps. The expert tracks upper and lower reference paths. Let , , and choose the route.
The simulator obtains reference derivatives by finite differences of the reference positions. The mode is hidden from the learner, so the same first observation can have different actions. Later states can reveal which route is in progress. The averaged demonstration in the lab uses time-aligned expert actions without replanning, revealing what averaging the two modes can do.
Deterministic vs. Multimodal Policy
Observation, Prediction, and Execution Windows
Think of the proposed chunk as a row of command slots. During one policy call, the denoiser can revise every slot many times. The first slot still belongs to the current physical control step throughout those revisions. Physical time advances only as the controller applies commands.
When does the next observation enter?
Read the two rows against the same physical timeline. Where they overlap, two planning calls proposed commands for the same future instant. The second proposal uses the newer observation. The solid part of the first row has already happened. Increasing the execution horizon moves the next observation later while leaving the prediction horizon fixed.
Each condition combines the current and previous four-coordinate states, episode phase, and the two endpoint heights. Repeat the first state when there is no prior observation. The model predicts a chunk starting at the current action index. Actions are divided by two for training and multiplied by two before applying the physical command limit.
There are 24 training endpoint pairs with two routes per pair and 50 training windows per route. Eight disjoint pairs give 16 held-out demonstrations. The expert can supply seven steps of continuation beyond the 50-step evaluation horizon, so each training label has a full future chunk. With a finite offline log, windows must respect episode boundaries and missing future targets need a validity mask.
Inspect the observation and action entries in an actual expert window
Horizon & Dataset Window Inspector
| Slice | Values |
|---|---|
| Current state | (-1.5, -0.1209, 0, 0) |
| Previous state | (-1.5, -0.1209, 0, 0) |
| Progress, start y, goal y | (0, -0.1209, 0.0233) |
Conditional Forward Diffusion on Action Chunks
Distinguish physical step , chunk index , and diffusion time . The forward process perturbs all 16 normalized action scalars, while the condition remains clean. The teaching schedule uses 20 variances linearly spaced from 0.015 to 0.5.
The closed-form draw has the correct distribution at a chosen time. Holding one noise vector fixed across frames shows how the coefficients change but couples the displayed states differently from a forward chain with fresh increments. The retention at the terminal time is positive, so the Gaussian prior is an approximation. At high noise, errors in the predicted noise are amplified in the clean-action estimate.
Action Chunk Forward Noising
Conditional Temporal U-Net and Transformer
A temporal U-Net transposes the action tensor from batch, horizon, and action channels into batch, channels, and time for one-dimensional convolution. It uses downsampling for longer-range temporal interactions and upsampling with skip connections to return to the input horizon. FiLM broadcasts its feature-channel scales and offsets across time. A Transformer can use action tokens and links to observation tokens while keeping the same output shape.
The dataflow lab applies actual small convolution, modulation, resampling, and skip operations. The training lab uses a separate MLP. In the reference implementation, track where the policy encodes observations, calls the noise scheduler, and slices the action prefix. The slice, normalization, and conditioning details belong to the chosen configuration.
Conditional 1D U-Net Dataflow
Noise Prediction on a Conditioned Window
Flatten the noisy action tensor and concatenate the 11 observation features and three time features. The 30–32–16 MLP uses tanh and has 1520 parameters. Every training update draws a random recorded window, diffusion index, and noise. Validation reuses 256 corruptions.
The prediction has the shape of the added noise. The MSE averages over action coordinates, horizon entries, and training examples. Its population minimizer is the conditional mean noise given the noisy action chunk, time, and observation. Closed-loop tracking and noise regression measure different quantities.
Check the network input and noise-target shapes
Noise Prediction Tensor Dataflow
DDPM and DDIM on Action Chunks
Start from a 16-dimensional Gaussian and keep the observation condition fixed while going from the final diffusion time to zero. Use each noise prediction to estimate the clean chunk and construct the next state.
At the update is deterministic given the initial noise and condition. At with adjacent indices it gives the fixed-posterior-variance DDPM update. Skipping steps changes the update sequence. The default uses ten DDIM evaluations per generated chunk. Intermediate clean estimates are unrestricted. Clip and rescale only the final normalized actions before execution.
DDPM / DDIM Action Denoising
Receding-horizon Execution
Generate actions and execute the first , or fewer at the end of an episode. Then observe again. At 10 Hz with , replanning happens every 0.4 s, giving 13 plans over 50 control steps. Ten network evaluations per plan give 130 per episode. More generally, the in the count below denotes network evaluations per plan.
The perturbed rollout applies a velocity change of up to 0.24 m/s per axis before the action at step 20. Repeated sampling can change the planned route, while longer execution intervals delay corrections. Network evaluation counts track computational work. Wall-clock delay also depends on the deployed system.
Closed-loop Replanning Simulator
Engineering Experiment · Closed-loop Diffusion Policy
Train Single BC (11–32–2, 450 parameters), Chunk BC (11–32–16, 912), and the diffusion MLP (30–32–16, 1520). The default uses seed 3, 1200 Adam updates, a batch size of 32, and learning rate 0.003. There are 256 fixed validation windows and 32 separately seeded perturbed closed-loop episodes. The policies use their own observations during rollout. The default diffusion sampler uses ten DDIM steps; the comparison also uses twenty adjacent DDPM steps.
The collision test samples simulated states and counts a collision if a point falls inside the disc. Success also requires goal distance below 0.25 m and final speed below 0.35 m/s. The sampled collision check does not inspect the entire continuous path between control points. The reported action-increment MSE compares successive acceleration commands. The upper route label reads the sign of at the state nearest .
Live Diffusion Policy Training
PyTorch benchmark · Seed 3
Validation objective MSE changes from 0.061921 to 0.000931 for Single BC, from 0.095808 to 0.003773 for Chunk BC, and from 1.047568 to 0.110256 for diffusion noise regression.
| Policy | Collision | Success | Goal error | Final speed | Δaction MSE | NFE / episode |
|---|---|---|---|---|---|---|
| Expert | 0.00% | 100.00% | 0.02329 | 0.02915 | 0.01028 | 0 |
| Single BC E=1 | 56.25% | 6.25% | 0.35935 | 0.18740 | 0.01504 | 50 |
| Chunk BC E=1 | 96.88% | 3.12% | 0.24351 | 0.08360 | 0.00944 | 50 |
| Chunk BC E=4 | 100.00% | 0.00% | 0.23493 | 0.15281 | 0.01231 | 13 |
| Chunk BC E=8 | 100.00% | 0.00% | 0.17453 | 0.15758 | 0.00330 | 7 |
| Diffusion policy E=1 | 59.38% | 0.00% | 0.97472 | 0.77074 | 1.66817 | 500 |
| Diffusion policy E=4 | 71.88% | 0.00% | 0.83858 | 0.60654 | 1.68128 | 130 |
| Diffusion policy E=8 | 75.00% | 0.00% | 0.83318 | 0.63323 | 1.70779 | 70 |
| DP DDPM E=4 | 87.50% | 0.00% | 0.56956 | 0.46864 | 0.60605 | 260 |
Potential contributors include limited temporal structure in the MLP, amplification at high noise, changes in route across replans, and the shift from nominal training trajectories to perturbed rollouts. The comparison does not isolate those effects. Inspect individual failures along with aggregate metrics when changing any one of these factors.
Reproducible PyTorch implementation
The CPU float64 script trains the three networks, rolls them out, and writes the measured results to result0604.json.
import math,json,torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
H=8;T=50;N=20;D=11;R=.5
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 z(self):return math.sqrt(-2*math.log(max(self(),1e-15)))*math.cos(2*math.pi*self())
def clip(x):return max(-2,min(2,x))
def step(s,a):
v=[.95*s[i+2]+.1*a[i] for i in range(2)];return [s[i]+.1*v[i] for i in range(2)]+v
def cases(seed,n,shift=False):
r=RNG(seed);return [[r.u(.23),r.u(.23),r.u(.24) if shift else 0,r.u(.24) if shift else 0] for _ in range(n)]
def ref(k,c,m):
t=min(1,k/T);b=t*t*(3-2*t);return [-1.5+3*b,c[0]+(c[1]-c[0])*b+m*.95*math.sin(math.pi*t)**2]
def expert(s,k,c,m):
q=ref(k,c,m);qn=ref(k+1,c,m);qp=ref(max(0,k-1),c,m);v=[(qn[i]-qp[i])/.2 for i in range(2)];acc=[(qn[i]-2*q[i]+qp[i])/.01 for i in range(2)]
return [clip(acc[i]+.5*v[i]+5*(q[i]-s[i])+3*(v[i]-s[i+2])) for i in range(2)]
def cond(s,prev,k,c):return s+prev+[k/T,c[0],c[1]]
def demo(c,m):
s=[-1.5,c[0],0,0];prev=s;xs=[];aa=[];ss=[s]
for k in range(T+H-1):
xs.append(cond(s,prev,k,c));a=expert(s,k,c,m);aa+=a;prev=s;s=step(s,a);ss.append(s)
return [(xs[k],[a/2 for a in aa[2*k:2*(k+H)]]) for k in range(T)],ss[:T+1]
def dataset(cs):return [x for c in cs for m in [-1,1] for x in demo(c,m)[0]]
AB=[1.]
for k in range(N):AB.append(AB[-1]*(1-(.015+.485*k/(N-1))))
class Net(nn.Module):
def __init__(self,mode,seed):
super().__init__();d=D+2*H+3 if mode=='dp' else D;o=2 if mode=='single' else H*2;self.l1=nn.Linear(d,32);self.l2=nn.Linear(32,o);r=RNG(seed+100)
with torch.no_grad():
for p in self.parameters():p.copy_(torch.tensor([r.u(.2) for _ in range(p.numel())]).reshape(p.shape))
def forward(self,x):return self.l2(torch.tanh(self.l1(x)))
def noisy(x,y,r):
t=1+int(r()*N);e=[r.z() for _ in y];a=math.sqrt(AB[t]);b=math.sqrt(1-AB[t]);return x+[a*v+b*w for v,w in zip(y,e)]+[t/N,a,b],e
def sample(p,c,r,n=N,eta=0):
x=torch.tensor([r.z() for _ in range(2*H)]);path=[x.tolist()];ts=[round(N-i*N/n) for i in range(n+1)]
with torch.no_grad():
for t,s in zip(ts,ts[1:]):
a,b=math.sqrt(AB[t]),math.sqrt(1-AB[t]);e=p(torch.tensor(c+x.tolist()+[t/N,a,b]));x0=(x-b*e)/a;sig=eta*math.sqrt((1-AB[s])/(1-AB[t])*(1-AB[t]/AB[s]));x=math.sqrt(AB[s])*x0+math.sqrt(max(0,1-AB[s]-sig*sig))*e+sig*torch.tensor([r.z() for _ in range(2*H)]);path.append(x.tolist())
return path
def rollout(p,c,mode,E=1,n=10,eta=0,seed=4,m=1):
r=RNG(seed);s=[-1.5,c[0],0,0];prev=s;ss=[s];aa=[];queue=[];calls=0
with torch.no_grad():
for k in range(T):
if k==20:s=s[:2]+[s[2]+c[2],s[3]+c[3]];ss[-1]=s
if mode=='expert':a=expert(s,k,c,m)
else:
if not queue:
o=cond(s,prev,k,c);y=sample(p,o,r,n,eta)[-1] if mode=='dp' else p(torch.tensor(o)).tolist();queue=[clip(2*z) for z in y[:2*E]];calls+=1
a=queue[:2];queue=queue[2:]
aa.append(a);prev=s;s=step(s,a);ss.append(s)
return ss,aa,calls
def metrics(p,cs,mode,E=1,n=10,eta=0):
rr=[rollout(p,c,mode,E,n,eta,900+i,m=(-1)**i) for i,c in enumerate(cs)];out=[]
for c,(ss,aa,calls) in zip(cs,rr):
clear=min(math.hypot(*s[:2]) for s in ss);err=math.hypot(ss[-1][0]-1.5,ss[-1][1]-c[1]);vel=math.hypot(*ss[-1][2:]);out.append([float(clear<R),float(clear>=R and err<.25 and vel<.35),err,vel,sum(sum((a[i]-b[i])**2 for i in range(2)) for a,b in zip(aa[1:],aa[:-1]))/(2*(T-1)),calls*(n if mode=='dp' else 1),float(ss[min(range(len(ss)),key=lambda i:abs(ss[i][0]))][1]>0)])
return dict(zip(['collision','success','goal','speed','delta','nfe','upper'],[sum(x)/len(out) for x in zip(*out)]))
def train(mode,seed=3,updates=1200,lr=.003):
p=Net(mode,seed);op=torch.optim.Adam(p.parameters(),lr=lr);r=RNG(seed+200);ds=dataset(cases(seed,24));vs=dataset(cases(seed+1000,8));vr=RNG(seed+300);vb=[vs[int(vr()*len(vs))] for _ in range(256)];vb=[noisy(x,y,vr) if mode=='dp' else (x,y[:2] if mode=='single' else y) for x,y in vb];vx,vy=map(torch.tensor,zip(*vb));hist=[]
for i in range(updates+1):
if i%(updates//4)==0:
with torch.no_grad():hist.append([i,((p(vx)-vy)**2).mean().item()])
if i==updates:break
b=[ds[int(r()*len(ds))] for _ in range(32)];b=[noisy(x,y,r) if mode=='dp' else (x,y[:2] if mode=='single' else y) for x,y in b];x,y=map(torch.tensor,zip(*b));op.zero_grad();((p(x)-y)**2).mean().backward();op.step()
return p,hist
if __name__=='__main__':
cs=cases(2003,32,True);out={'expert':metrics(None,cs,'expert')}
for mode in ['single','chunk','dp']:
p,h=train(mode);d={'hist':h,'p':{k:v.detach().tolist() for k,v in p.named_parameters()}};out[mode]=d
for E in ([1] if mode=='single' else [1,4,8]):d[str(E)]=metrics(p,cs,mode,E)
if mode=='dp':d['ddpm']=metrics(p,cs,mode,4,20,1)
print(mode,h,{k:v for k,v in d.items() if k not in ['p','hist']},flush=True)
open('result0604.json','w').write(json.dumps(out))
References and Policy Source
- Chi et al. study action diffusion and receding-horizon control. Diffusion Policy · Project page
- Reference denoiser and action execution code. Conditional 1D U-Net · Hybrid image policy
- Diffusion objectives, sampling, and conditional modulation. DDPM · DDIM · FiLM
- Additional robotics implementations. Official Diffusion Policy repository · LeRobot
The next lesson conditions action generation on images and instructions and adds a flow-matching action expert.
Previous lesson · 6.3 Imitation Learning · Course overview · Next lesson · 6.5 Vision-Language-Action Models