Module contents
Lesson 12 of 33Core 120 min

Diffusion Policy and flow matching policies

Model multimodal action chunks with observation-conditioned diffusion or flow matching, then compare sampling quality, receding-horizon execution and inference latency.

After this lesson you can

  • Formulate a conditional diffusion policy over action chunks and derive its DDPM loss.
  • Implement a FiLM-conditioned temporal 1D U-Net with receding-horizon execution.
  • Explain multimodal diffusion and contrast its training with implicit behavior cloning.
  • Replace the diffusion objective with flow matching and compare quality against sampling steps.
  • Budget inference latency against control frequency and choose sampler and horizon accordingly.

Before you start

Generate actions, observe again

Pushing a piece around an obstacle may admit two valid trajectories. A policy averaging both actions may drive into the obstacle’s centre. Instead of emitting one mean, a generative policy learns an observation-conditioned distribution of action chunks and draws a coherent sample. Diversity alone does not guarantee safety, success or a solution outside the data.

InteractiveFrom noise to a chunk
0
19
Reverse step20
Middle lateral action−0.508
Two measured traces from the lab's NumPy network were chosen for final lateral actions near −0.5 and +0.5. They are synthetic trajectories, not Push-T episodes; clean-chunk estimates are shown.
InteractiveThree horizons

Bars show ideal queries and execution for 32 steps. Blue: query; green: change. The model predicts 16 positions from the first observation, leaving up to 15 actions from the current observation. Tp limits retained positions.

CPU trial: one seed and 80 steps, changing the object at step 40; another run with To=2 changes it at step 41. Wait indicates when the next observation arrives, not whether the policy reacts correctly. The To window supplies the oldest and current image; To=1 duplicates it. The change slider affects only the diagram.

2
16
4
13
Applied Ta4
Next query16
Wait in steps3
Checkpoint: success0/1
Checkpoint: maximum reward0.413
Checkpoint: action variation857.59
Change at step 41: wait to observe3 steps
A query and execution diagram accompanies independent measurements of the public checkpoint with several effective windows. Changing the diagram does not change the measurement.
InteractiveMeasured quality and latency

Observed success (0 to 1)

  • DDPM
  • DDIM
  • flow

Mean latency per inference

  • DDPM
  • DDIM
  • flow
  • one-step deadline
10
Deadline per step100.0 ms
Episodes per point3
Actual results of a short lab run with three episodes per point; the time line is the ideal deadline for one control step. Machine load affects latencies.

Observation-conditioned diffusion

Diffusion Policy applies diffusion to a chunk a0∈RTp×daa_0\in\mathbb R^{T_p\times d_a}. During training, choose an observation oo, expert chunk and step kk, and add Gaussian noise:

ak=αˉk a0+1−αˉk ϵ,ϵ∼N(0,I).a_k=\sqrt{\bar\alpha_k}\,a_0+\sqrt{1-\bar\alpha_k}\,\epsilon,\qquad\epsilon\sim\mathcal N(0,I).

The network ϵθ(ak,k,o)\epsilon_\theta(a_k,k,o) minimizes Eo,a0,k,ϵ∥ϵ−ϵθ(ak,k,o)∥2\mathbb E_{o,a_0,k,\epsilon}\|\epsilon-\epsilon_\theta(a_k,k,o)\|^2. With sufficient capacity and data, the optimal estimator is the conditional expectation of noise. The perturbed-distribution score satisfies ∇aklog⁡pk(ak∣o)=−E[ϵ∣ak,o]/1−αˉk\nabla_{a_k}\log p_k(a_k\mid o)=-\mathbb E[\epsilon\mid a_k,o]/\sqrt{1-\bar\alpha_k}. This identity concerns the noisy distribution and optimal estimator; a finite network does not necessarily recover the exact score.

At inference, start from noise and iterate a reverse process. DDPM adds noise at intermediate steps; DDIM allows a shorter sequence and, with zero stochastic parameter, is deterministic given the initial sample. Fewer steps usually reduce cost but can hurt quality: measure the trade-off on the task. Chi and colleagues propose modelling visual actions this way and evaluating in simulation and robots.

The first figure retains two actual traces from an MLP trained on the lab’s synthetic distribution, chosen among one hundred samples by final lateral component. The control traverses clean-chunk estimates from noisy states; these are not independent samples or Push-T results. Clipping and summing actions draws an illustrative trajectory. Other seeds can produce intermediate or out-of-mode values; diffusion does not mathematically exclude the mean.

Receding horizon and architecture

Receding-horizon control stores ToT_o observations, predicts TpT_p actions and executes Ta≤TpT_a\leq T_p before observing again and generating a chunk. If the object moves just after a query, long execution can retain stale actions; querying each step can cause variations between regenerated chunks. The second diagram shows when a change can be seen under one timing convention and accompanies a checkpoint measurement with effective windows, not a set of retrained models.

The observation condition can integrate camera images, proprioception and the noise index. A 1D U-Net uses temporal convolutions and FiLM modulation, scaling and shifting activations according to the condition; skip connections recover temporal resolution. A transformer can use noisy actions as tokens and cross-attention to observations. The paper recommends starting with the convolutional variant and considering a transformer for rapid changes or complex tasks, with greater hyperparameter sensitivity. Its visual encoder uses ResNet-18 and replaces BatchNorm with GroupNorm, useful with exponential moving averaging of weights.

Normalize each action dimension with known training-set statistics and retain the inverse transformation. In the lab’s Push-T, target positions in [0,512][0,512] map approximately to [−1,1][-1,1]. If a saturated dimension has another scale or a gripper has a different range, the same noise has different meaning. Exponential moving average (EMA) accumulates smoothed weights and must also be updated consistently across model components; it does not itself guarantee a better policy.

Implicit behavior cloning learns low energy for expert actions and compares negative candidates. Choosing an action requires optimizing or searching candidates at inference; negative selection and optimization can be difficult. Diffusion supervises noise generated from a known distribution, avoiding that particular negative-sampling problem while introducing a sampling loop and retaining fitting and cost challenges. Florence and colleagues introduce IBC.

From noise to velocity

A flow-matching policy learns a velocity field transporting noise x0x_0 toward actions x1x_1. On straight interpolation xt=(1−t)x0+tx1x_t=(1-t)x_0+tx_1, the conditional target is v=x1−x0v=x_1-x_0. Train vθ(xt,t,o)v_\theta(x_t,t,o) with squared error and sample by integrating x˙=vθ(x,t,o)\dot x=v_\theta(x,t,o), for example with Euler. A straight training path does not imply the learned solution is exact in one step; discretization, model and data errors matter.

Diffusion and flow can be compared with the same encoder, data, seeds and budget. Denoising loss alone does not measure whether the piece reaches the goal. Evaluate complete episodes, shared conditions and latency with uncertainty; three episodes only demonstrate the procedure. The local comparison uses small models trained from scratch, so it does not automatically reproduce a public checkpoint’s results.

The third figure records one lab run with ten demonstrations, 400 updates and three episodes per point. All shown configurations achieved 0/3 successes: this observation does not establish equivalence or measure attainable capability with more training. Latency includes encoding and GPU synchronization on a shared machine. Change frequency to compare with an ideal deadline, remembering that mean latency is not a worst-case guarantee and sensors and actuators also take time.

Inference latency includes image encoding, every sampler step, transfers and synchronization. If the network takes 8 ms per step, 100 evaluations cost 800 ms before other overhead. At 10 Hz, eight actions occupy 800 ms: that budget works only if computation overlaps execution and observation age is acceptable. Strictly synchronous inference with a fresh observation that must finish before the next step has 100 ms, at most 12 ideal 8 ms evaluations. The original work reports a measurement for specific hardware and configuration; it should not be transferred to another machine without measurement.

Lab: a small denoiser

Chunks with two lateral modes are generated and a NumPy MLP is trained to predict noise conditioned on a scalar state. DDPM uses twenty steps and DDIM six. The GMM and discrete centroids fit known generator mode labels, an artificial advantage over the denoiser; they are teaching references, not trained implementations from lesson 8. Sign proportions and separation are shown, not robotic success.

The short schedule leaves a small signal at the end of the forward process even though sampling begins from pure normal noise: this deliberate approximation keeps the example manageable. Large separation does not guarantee a sample follows either mode; inspect the full histogram and repeat with other seeds. The loss denominator averages all chunk components, so its scale depends on that convention.

[ ]Chunk and mode denoisingBrowser
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.default_rng(12)
K=8;D=2*K;S=20
beta=np.linspace(.01,.2,S);alpha=1-beta;abar=np.cumprod(alpha)
N=1000;state=rng.uniform(-.5,.5,(N,1));mode=rng.choice([-1.,1.],(N,1))
phase=np.linspace(0,np.pi,K)[None,:]
chunks=np.stack([mode*.55*np.sin(phase)-state*.2,np.ones((N,K))*.25],axis=-1).reshape(N,D)
chunks+=rng.normal(0,.025,chunks.shape)
W1=rng.normal(0,.12,(D+2,64));b1=np.zeros(64);W2=rng.normal(0,.08,(64,D));b2=np.zeros(D)
def network(noisy,obs,t):
    inp=np.concatenate([noisy,obs,t[:,None]/(S-1)],axis=1);hidden=np.tanh(inp@W1+b1)
    return hidden@W2+b2,inp,hidden
for _ in range(700):
    idx=rng.integers(N,size=64);t=rng.integers(S,size=64);eps=rng.normal(size=(64,D));a=abar[t,None];noisy=np.sqrt(a)*chunks[idx]+np.sqrt(1-a)*eps
    pred,inp,h=network(noisy,state[idx],t);delta=2*(pred-eps)/pred.size;g2=h.T@delta;gb2=delta.sum(0);dh=([email protected])*(1-h*h);g1=inp.T@dh;gb1=dh.sum(0)
    W1-=.04*g1;b1-=.04*gb1;W2-=.04*g2;b2-=.04*gb2
def sample(method,n,steps=20):
    x=rng.normal(size=(n,D));obs=np.zeros((n,1));indices=np.unique(np.linspace(0,S-1,steps,dtype=int))[::-1]
    for j,t in enumerate(indices):
        eps,_,_=network(x,obs,np.full(n,t));a=abar[t];x0=(x-np.sqrt(1-a)*eps)/np.sqrt(a)
        if method=='DDPM':
            assert steps==S
            mean=(x-beta[t]*eps/np.sqrt(1-a))/np.sqrt(alpha[t]);var=beta[t]*(1-(abar[t-1] if t else 1))/(1-a);x=mean+np.sqrt(max(0,var))*rng.normal(size=x.shape)
        else:
            ap=abar[indices[j+1]] if j+1<len(indices) else 1.;x=np.sqrt(ap)*x0+np.sqrt(1-ap)*eps
    return x.reshape(n,K,2)
def summary(name,a):
    middle=a[:,K//2,0];print(name,'fracción modo derecho',round(float(np.mean(middle>0)),3),'separación mediana |x|',round(float(np.median(abs(middle))),3))
ddpm=sample('DDPM',200);ddim=sample('DDIM',200,6)
# Dos componentes gaussianas estimadas con las etiquetas de modo del conjunto sintético.
means=np.stack([chunks[mode[:,0]==s].mean(axis=0) for s in [-1,1]])
stds=np.stack([chunks[mode[:,0]==s].std(axis=0) for s in [-1,1]])
chosen=rng.integers(0,2,200);gmm=(means[chosen]+stds[chosen]*rng.normal(size=(200,D))).reshape(200,K,2)
bins=means[chosen].reshape(200,K,2)
for name,a in [('DDPM 20 pasos',ddpm),('DDIM 6 pasos',ddim),('GMM de referencia',gmm),('centroides discretos',bins)]:summary(name,a)
fig,ax=plt.subplots(figsize=(7,3))
for name,a in [('DDPM',ddpm),('DDIM',ddim),('GMM',gmm),('discreto',bins)]:ax.hist(a[:,K//2,0],bins=28,alpha=.4,label=name,density=True)
ax.set(xlabel='acción lateral en el paso central',ylabel='densidad');ax.legend();plt.tight_layout();plt.show()

Local lab: real Push-T and comparison

Create an isolated environment and install pip install lerobot==0.3.3 gym-pusht==0.1.8 diffusers==0.35.2 opencv-python pandas pyarrow. The program downloads the public lerobot/pusht dataset, reads the first ten episodes and images, and trains from scratch a FiLM 1D U-Net with GroupNorm ResNet-18 for diffusion and another for flow matching; it retains EMA. A third policy is the LeRobot implementation, also trained from scratch. All receive 400 updates; configurations use three evaluation seeds and at most 100 steps, a short trial that may yield zero successes.

Each generation’s latency is measured with CUDA synchronization when applicable. The custom visual encoding is calculated once per query, not at every sampling step. The comparison varies iteration count and Ta, reporting maximum reward, action variation and success; it does not establish policy convergence or measure physical-robot latency. Images arrive at 10 Hz in the dataset and execution uses four actions per query except in explicit ablations.

[ ]Train and evaluate in Push-TLocal GPU
import copy, time
from pathlib import Path
import numpy as np
import pandas as pd
import cv2
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet18
import gymnasium as gym
import gym_pusht
from huggingface_hub import snapshot_download
from lerobot.configs.types import FeatureType, PolicyFeature, NormalizationMode
from lerobot.policies.diffusion.configuration_diffusion import DiffusionConfig
from lerobot.policies.diffusion.modeling_diffusion import DiffusionPolicy

torch.set_num_threads(2);torch.manual_seed(12);rng=np.random.default_rng(12)
device='cuda' if torch.cuda.is_available() else 'cpu';K=8;TRAIN_STEPS=20;UPDATES=400;EVAL_SEEDS=(100,101,102);EVAL_HORIZON=100
root=Path(snapshot_download('lerobot/pusht',repo_type='dataset',local_dir='pusht-data'))
table=pd.read_parquet(root/'data/chunk-000/file-000.parquet');table=table[table.episode_index<10].copy().reset_index(drop=True)
cap=cv2.VideoCapture(str(root/'videos/observation.image/chunk-000/file-000.mp4'));frames=[]
for _ in range(len(table)):
    ok,frame=cap.read()
    if not ok:raise RuntimeError('Vídeo incompleto o decodificador AV1 no disponible')
    frames.append(cv2.resize(cv2.cvtColor(frame,cv2.COLOR_BGR2RGB),(64,64)))
cap.release();images=np.stack(frames);states=np.stack(table['observation.state'].values).astype(np.float32)/256-1;actions=np.stack(table.action.values).astype(np.float32)/256-1
valid=np.array([i for i in range(len(table)-K+1) if table.episode_index[i]==table.episode_index[i+K-1]])
print('Dataset lerobot/pusht: 10 episodios, fotogramas',len(table),'ventanas completas',len(valid),flush=True)
def batch(n):
    ids=rng.choice(valid,size=n);imgs=torch.from_numpy(images[ids]).permute(0,3,1,2).float().to(device)/255
    states_t=torch.from_numpy(states[ids]).to(device);acts=torch.from_numpy(np.stack([actions[i:i+K] for i in ids])).to(device)
    return imgs,states_t,acts

class Block(nn.Module):
    def __init__(self,cin,cout,cond):
        super().__init__();self.conv=nn.Conv1d(cin,cout,3,padding=1);self.norm=nn.GroupNorm(8,cout);self.film=nn.Linear(cond,2*cout);self.skip=nn.Conv1d(cin,cout,1)
    def forward(self,x,c):
        scale,bias=self.film(c).chunk(2,dim=1);h=self.norm(self.conv(x));return F.silu(h*(1+scale[:,:,None])+bias[:,:,None])+self.skip(x)
class Policy(nn.Module):
    def __init__(self):
        super().__init__();gn=lambda c:nn.GroupNorm(min(32,c),c);self.vision=resnet18(weights=None,norm_layer=gn);self.vision.fc=nn.Linear(512,32)
        self.cond=nn.Sequential(nn.Linear(35,64),nn.SiLU(),nn.Linear(64,64));self.b1=Block(2,32,64);self.down=nn.Conv1d(32,64,4,stride=2,padding=1);self.b2=Block(64,64,64);self.up=nn.ConvTranspose1d(64,32,4,stride=2,padding=1);self.b3=Block(64,32,64);self.out=nn.Conv1d(32,2,1)
    def encode(self,img,state):return torch.cat([self.vision(img),state],1)
    def denoise(self,x,t,embedding):
        c=self.cond(torch.cat([embedding,t[:,None]],1));h=self.b1(x.transpose(1,2),c);d=self.b2(self.down(h),c);u=self.up(d);return self.out(self.b3(torch.cat([h,u],1),c)).transpose(1,2)
    def forward(self,x,t,img,state):return self.denoise(x,t,self.encode(img,state))
beta=torch.linspace(.01,.2,TRAIN_STEPS,device=device);alpha=1-beta;abar=alpha.cumprod(0)
def train(model,mode):
    model.to(device).train();ema=copy.deepcopy(model).eval();opt=torch.optim.Adam(model.parameters(),lr=3e-4)
    for update in range(UPDATES):
        img,s,a=batch(16);noise=torch.randn_like(a)
        if mode=='diffusion':
            ti=torch.randint(TRAIN_STEPS,(len(a),),device=device);ab=abar[ti,None,None];x=ab.sqrt()*a+(1-ab).sqrt()*noise;target=noise;t=ti.float()/(TRAIN_STEPS-1)
        else:
            t=torch.rand(len(a),device=device);x=(1-t[:,None,None])*noise+t[:,None,None]*a;target=a-noise
        loss=F.mse_loss(model(x,t,img,s),target);opt.zero_grad();loss.backward();opt.step()
        with torch.no_grad():
            for p,e in zip(model.parameters(),ema.parameters()):e.lerp_(p,.01)
    print(mode,UPDATES,'actualizaciones, pérdida final',round(float(loss.detach().cpu()),4),flush=True)
    return ema
def sample(model,img,state,method,steps):
    x=torch.randn((1,K,2),device=device)
    with torch.no_grad():
        embedding=model.encode(img,state)
        if method=='flow':
            for i in range(steps):x=x+model.denoise(x,torch.tensor([i/steps],dtype=torch.float32,device=device),embedding)/steps
        else:
            ids=np.unique(np.linspace(0,TRAIN_STEPS-1,steps,dtype=int))[::-1]
            for j,i in enumerate(ids):
                eps=model.denoise(x,torch.tensor([i/(TRAIN_STEPS-1)],dtype=torch.float32,device=device),embedding);a=abar[i];x0=(x-(1-a).sqrt()*eps)/a.sqrt()
                if method=='DDPM':
                    assert steps==TRAIN_STEPS;prev=abar[i-1] if i else torch.ones((),device=device);variance=beta[i]*(1-prev)/(1-a)
                    x=(x-beta[i]*eps/(1-a).sqrt())/alpha[i].sqrt()+variance.sqrt()*torch.randn_like(x)
                else:
                    prev=abar[ids[j+1]] if j+1<len(ids) else torch.ones((),device=device);x=prev.sqrt()*x0+(1-prev).sqrt()*eps
    return x.clamp(-1,1)
def evaluate(model,method,steps,exec_horizon=4):
    successes=0;times=[];rewards=[];variations=[]
    for seed in EVAL_SEEDS:
        env=gym.make('gym_pusht/PushT-v0',obs_type='pixels',render_mode='rgb_array',max_episode_steps=EVAL_HORIZON);obs,info=env.reset(seed=seed);best=0.;success=False;last=None;variation=0.
        for t in range(EVAL_HORIZON):
            if t%exec_horizon==0:
                img=torch.from_numpy(cv2.resize(obs,(64,64))).permute(2,0,1)[None].float().to(device)/255;s=torch.tensor(info['pos_agent'],device=device,dtype=torch.float32)[None]/256-1
                if device=='cuda':torch.cuda.synchronize()
                start=time.perf_counter()
                if method=='LeRobot':
                    model.reset()
                    with torch.no_grad():chunk=torch.stack([model.select_action({'observation.image':img,'observation.state':s}) for _ in range(4)],dim=1)
                else:chunk=sample(model,img,s,method,steps)
                if device=='cuda':torch.cuda.synchronize()
                times.append((time.perf_counter()-start)*1000);block=chunk[0].detach().cpu().numpy()
            action=np.clip((block[t%exec_horizon]+1)*256,0,512).astype(np.float32);variation+=0. if last is None else float(np.linalg.norm(action-last));last=action.copy();obs,r,term,trunc,info=env.step(action);best=max(best,float(r));success|=bool(info['is_success'])
            if term or trunc:break
        successes+=int(success);rewards.append(best);variations.append(variation);env.close()
    print(method,steps,'pasos; Ta',exec_horizon,'éxito',successes,'/',len(EVAL_SEEDS),'recompensa máxima media',round(float(np.mean(rewards)),3),'variación media',round(float(np.mean(variations)),2),'ms por inferencia media',round(float(np.mean(times)),2),flush=True)
    return successes,float(np.mean(times))

diff=train(Policy(),'diffusion');flow=train(Policy(),'flow')
for method,steps in [('DDPM',20),('DDIM',3),('DDIM',6),('DDIM',12)]:evaluate(diff,method,steps)
for horizon in (1,8):evaluate(diff,'DDIM',6,exec_horizon=horizon)
for steps in (3,6,12):evaluate(flow,'flow',steps)
config=DiffusionConfig(device=device,input_features={'observation.image':PolicyFeature(type=FeatureType.VISUAL,shape=(3,64,64)),'observation.state':PolicyFeature(type=FeatureType.STATE,shape=(2,))},output_features={'action':PolicyFeature(type=FeatureType.ACTION,shape=(2,))},normalization_mapping={'VISUAL':NormalizationMode.IDENTITY,'STATE':NormalizationMode.IDENTITY,'ACTION':NormalizationMode.IDENTITY},n_obs_steps=1,horizon=K,n_action_steps=4,crop_shape=None,pretrained_backbone_weights=None,down_dims=(32,64),n_groups=8,num_train_timesteps=TRAIN_STEPS,num_inference_steps=6,noise_scheduler_type='DDIM')
reference=DiffusionPolicy(config).to(device);optimizer=torch.optim.Adam(reference.parameters(),lr=3e-4);reference.train()
for update in range(UPDATES):
    img,s,a=batch(16);loss,_=reference({'observation.image':img[:,None],'observation.state':s[:,None],'action':a,'action_is_pad':torch.zeros(len(s),K,dtype=torch.bool,device=device)});optimizer.zero_grad();loss.backward();optimizer.step()
print('LeRobot',UPDATES,'actualizaciones, pérdida final',round(float(loss.detach().cpu()),4),flush=True);reference.eval();evaluate(reference,'LeRobot',6)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Check a public checkpoint

The horizon diagram includes an independent measurement using the public LeRobot checkpoint, revision 84a7c23178445c6bbf7e1a884ff497017910f653. The model accepts two observations and predicts a sequence of 16 temporal positions. To study an effective window of 1, 2 or 4 observations, the test takes the oldest and current; with one it duplicates image and state. Chunks of 1, 4 or 8 actions execute with ten-step DDIM. Each combination uses seed 100, up to 80 steps and a disturbance shifting the piece 40 units at step 40. All nine runs achieved 0/1 successes: they are individual disturbed trajectories, not a reliable success estimate or conclusive responsiveness comparison.

The checkpoint card reports 65.4% success in 500 episodes under its evaluation, a different protocol from this disturbed trial. The prediction control can limit output to 8 or up to 16 positions: the internal horizon begins at the previous observation, so with two observations at most 15 actions remain from the current instant. For measured chunks of up to 8 actions, limiting to 8 or keeping all available yields the same executed actions. This neither retrains with another internal horizon nor changes network cost. Untested combinations are marked accordingly.

A second trial places the change at step 41 with two effective observations. First subsequent queries occur at steps 41, 44 and 48 for chunks of 1, 4 and 8 actions: waits of 0, 3 and 7 steps. This measures when new information can enter, not whether the model action corrects the disturbance. Here too all three trajectories gave 0/1 successes. The following code downloads weights, checks their SHA-256 and reproduces the local test; by default the change is at 40. To repeat the second test, set HORIZON_EVENT=41 and HORIZON_OBS=2 before execution. More seeds address a stronger question.

[ ]Checkpoint and effective windows in Push-TLocal GPU
import time, json, os, hashlib
from huggingface_hub import snapshot_download
from collections import deque
from pathlib import Path
import numpy as np, torch, gymnasium as gym, gym_pusht
from diffusers import DDIMScheduler
from lerobot.policies.diffusion.modeling_diffusion import DiffusionPolicy
from lerobot.policies.diffusion.configuration_diffusion import DiffusionConfig
from lerobot.configs.types import FeatureType, PolicyFeature

torch.set_num_threads(2);device='cuda' if torch.cuda.is_available() else 'cpu'
cfg=DiffusionConfig(device=device,input_features={'observation.image':PolicyFeature(type=FeatureType.VISUAL,shape=(3,96,96)),'observation.state':PolicyFeature(type=FeatureType.STATE,shape=(2,))},output_features={'action':PolicyFeature(type=FeatureType.ACTION,shape=(2,))})
checkpoint=Path(snapshot_download('lerobot/diffusion_pusht',revision='84a7c23178445c6bbf7e1a884ff497017910f653',allow_patterns=['config.json','model.safetensors']))
with (checkpoint/'model.safetensors').open('rb') as weights:
 assert hashlib.file_digest(weights,'sha256').hexdigest()=='995d14d35db57d95c35ad9704c3d79c8612b7bc45f3877e5c46c2cdc516856a8'
model=DiffusionPolicy.from_pretrained(str(checkpoint),config=cfg,strict=True).to(device).eval()
model.diffusion.noise_scheduler=DDIMScheduler.from_config(model.diffusion.noise_scheduler.config);model.diffusion.num_inference_steps=10
results=[];pilot=os.environ.get('HORIZON_PILOT')=='1';event_step=int(os.environ.get('HORIZON_EVENT','40'))
to_values=(2,) if pilot else tuple(int(v) for v in os.environ.get('HORIZON_OBS','1,2,4').split(','))
for to in to_values:
 for ta in ((4,) if pilot else (1,4,8)):
  torch.manual_seed(123);model.config.n_action_steps=ta;model.reset();history=deque(maxlen=to)
  limit=2 if pilot else 80
  env=gym.make('gym_pusht/PushT-v0',obs_type='pixels',render_mode='rgb_array',max_episode_steps=limit)
  obs,info=env.reset(seed=100);last=None;variation=0.;best=0.;success=False;changed=False;first_query=None;block=[]
  for t in range(limit):
   if t==event_step:
    obj=env.unwrapped.block;obj.position=(max(50,min(462,obj.position.x+40)),obj.position.y);obj.velocity=(0,0);env.unwrapped.space.reindex_shapes_for_body(obj);obs=env.unwrapped.get_obs();changed=True
   im=torch.from_numpy(obs.copy()).permute(2,0,1)[None].float().to(device)/255
   state=torch.tensor(info['pos_agent'],dtype=torch.float32,device=device)[None]
   history.append((im,state))
   if t%ta==0:
    if changed and first_query is None:first_query=t
    first=history[0];current=history[-1]
    normalized=[]
    for image,state_tensor in (first,current):
     b=model.normalize_inputs({'observation.image':image,'observation.state':state_tensor})
     b['observation.images']=torch.stack([b['observation.image']],dim=-4)
     normalized.append(b)
    for key in ('observation.images','observation.state'):
     model._queues[key]=deque([b[key] for b in normalized],maxlen=2)
    with torch.no_grad():
     chunk=model.predict_action_chunk(normalized[-1])[0].cpu().numpy()
    block=chunk
   action=np.clip(block[t%ta],0,512).astype(np.float32)
   variation+=0. if last is None else float(np.linalg.norm(action-last));last=action.copy()
   obs,reward,term,trunc,info=env.step(action);best=max(best,float(reward));success|=bool(info['is_success'])
   if term or trunc:break
  env.close();record={'effective_observations':to,'prediction_window':16,'execution':ta,'steps':t+1,'perturbation_applied':changed,'event_step':event_step,'first_query_after_event':first_query,'success':int(success),'max_reward':best,'action_variation':variation};results.append(record);print(record,flush=True)
  out=os.environ.get('HORIZON_OUTPUT','effective_horizons_pilot.json' if pilot else f'effective_horizons_event{event_step}.json')
  Path(out).write_text(json.dumps(results,indent=2),encoding='utf8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Practice

Proof
Prove: Relate noise prediction to the conditional score.
0
For each k, a_k=√ᾱ_k a_0+√(1−ᾱ_k) ε; ε is standard normal and independent of the clean chunk given observation.

Step 1 of 3. Which function minimizes expected squared error when predicting ε?

Numeric
At 10 Hz, 8 actions execute over 0.8 s. If each network evaluation takes 8 ms and can overlap execution, how many complete steps ideally fit?
Quiz
Why does an energy policy such as IBC need candidates and a search at inference?
Quiz
With multiple cameras and few demonstrations, what starting point do the Diffusion Policy authors recommend?
Code
Implement receding_horizon_rollout(env,policy,T_o,T_p,T_a). reset returns (obs,info), step returns five Gymnasium values. Retain the last T_o observations, initially padding with the first; policy(history,T_p) returns a chunk of T_p actions. Execute T_a actions or until termination and return the executed-action list. Require 1≤T_a≤T_p.
def receding_horizon_rollout(env,policy,T_o,T_p,T_a):
  pass
Shift+Enter to run
Key idea
A generative policy produces conditioned chunks; sampling steps and horizons should be chosen with success, variation and latency measured together.