Module contents
Lesson 11 of 33Core 110 min

Action chunking and ACT

Predict action chunks, derive the conditional VAE behind ACT, and study temporal ensembling and leader-follower teleoperation.

After this lesson you can

  • Explain how chunking reduces the number of decisions and helps with pauses and non-Markovian demonstrations.
  • Derive ACT's conditional VAE loss and explain the test-time style variable.
  • Implement ACT with learned action queries and image and proprioception encoders.
  • Implement exponential temporal ensembling and measure smoothness and success.
  • Design an ablation of chunk size against disturbance responsiveness.

Before you start

Deciding an action sequence

When a gripper approaches a part at 50 Hz, a small error in each prediction can change the images and states it receives next. Predicting a sequence of related actions can maintain coherence during movement; executing the whole sequence without looking can also leave the robot unable to react to a disturbance. Chunk size and observation frequency are separate choices.

InteractiveStability and responsiveness
  • position
  • goal
8
8
Queries8
Final error0.054
Total action change0.605
A scalar policy fitted to synthetic demonstrations queries position to generate chunks; add a push and compare query frequencies. This is not a real robot policy.
InteractiveOverlapping predictions
Age 0
action 0.86
weight 0.13
Age 1
action 0.54
weight 0.14
Age 2
action 0.31
weight 0.16
Age 3
action 0.69
weight 0.17
Age 4
action 0.82
weight 0.19
Age 5
action 0.41
weight 0.21
  • chunked
  • ensembled
12
0.10
Ensembled action0.598
Chunk action0.862
Compare the mean of predictions for the same instant with executing six-step chunks. Weights follow ACT's convention: the oldest prediction has index zero.
InteractiveA latent slice
  • x
  • y
0
x after chunk0.120
y after chunk0.442
Chunks calculated by two reduced ACT models trained on the lab's synthetic insertion task, with and without KL. A single chunk is integrated from the same observation; it does not represent real operators or full-policy success.

From teleoperation to a dataset

In leader-follower teleoperation, a person moves a leader arm and a controller makes a follower arm track its positions. ALOHA uses two arm pairs and cameras to collect bimanual demonstrations. In Zhao and colleagues, leader positions are target actions and observations include images and follower positions. They are not interchangeable: the difference between target and actual position determines part of the effort produced by the low-level controller.

Synchronize actions, images and states using timestamps. A chunk of 100 actions represents two seconds at 50 Hz and ten seconds at 10 Hz; mixing frequencies without resampling changes the task. The gripper may have different units, limits and dynamics from joints, so normalize it with its own statistics. An image delayed relative to the action makes supervision a causally incorrect relationship even when each file appears valid.

Action chunking learns πθ(at:t+k−1∣ot)\pi_\theta(a_{t:t+k-1}\mid o_t) instead of one action. If an entire chunk executes open-loop and the episode has TT steps, there are approximately ⌈T/k⌉\lceil T/k\rceil queries instead of TT. This reduces high-level decisions but does not show accumulated error is divided by kk: each chunk may contain correlated errors and a disturbance can invalidate it. Replanning before exhausting the chunk combines a long prediction horizon with frequent observations.

A human pause shows the limitation of a Markov policy: the same image and configuration may appear before and after a pause with different future actions. A chunk can represent a coherent sequence, but an ambiguous observation does not reveal which of several intentions applies. A latent, temporal context or additional information can help; they do not automatically make hidden intent observed.

Consider two demonstrations reaching the same position: one person waits four steps before grasping, another continues immediately. Single-action regression on that observation may fit an average matching neither sequence. If training includes a complete chunk and a latent encoding the demonstration pattern, the decoder can learn a coherent pause. At deployment, however, the future chunk is unavailable for inferring that pattern; fixing or choosing the latent changes the resulting behaviour.

The first figure does not claim to demonstrate a statistical improvement from chunking. It fits twenty linear predictors by least squares to trajectories from a synthetic scalar expert and adds a small deterministic bias at each query. If a push occurs during chunk execution, an earlier query incorporates the new state sooner. The replanning control is clipped to chunk size because an unpredicted action cannot be executed. Total action change measures variation, not force or wear.

A conditional VAE for chunks

ACT uses a conditional VAE policy. During training, posterior qϕ(z∣otpropio,at:t+k−1)q_\phi(z\mid o_t^{\rm propio},a_{t:t+k-1}) observes proprioception and the demonstrated chunk; decoder pθ(at:t+k−1∣ot,z)p_\theta(a_{t:t+k-1}\mid o_t,z) also receives images. The usual prior is p(z)=N(0,I)p(z)=\mathcal N(0,I). The variational inequality gives

log⁡pθ(a∣o)≥Eqϕ[log⁡pθ(a∣o,z)]−DKL(qϕ(z∣o,a)∥p(z)).\log p_\theta(a\mid o)\geq\mathbb E_{q_\phi}\left[\log p_\theta(a\mid o,z)\right]-D_{\rm KL}\left(q_\phi(z\mid o,a)\|p(z)\right).

With a fixed-scale Laplace decoder, negative log-likelihood is proportional to the sum of absolute errors plus a constant. ACT optimizes L1 reconstruction plus KL weighted by β\beta; for β≠1\beta\ne1 this is a weighted objective, not exactly the standard ELBO. Padded actions at episode ends are masked. Excessive KL can cause the posterior to ignore demonstrations and the decoder to ignore zz; without regularization the posterior may move away from the prior and make z=0z=0 unrepresentative.

At inference the style encoder disappears because the true sequence does not yet exist; the original work fixes z=0z=0, the prior mean. Sampling a new style at every query could introduce jumps between overlapping chunks. Keeping one sample fixed during a phase is another experimental decision, not a safety guarantee. The latent distribution need not cleanly separate operators or be interpretable axis by axis.

The third figure retains measured outputs from the local lab, not hand-drawn trajectories. Both models trained on the same synthetic examples and a fixed observation; the control moves all eight latent coordinates simultaneously among five values and the toggle shows another training run without KL. Chunks are clipped to action limits and integrated against the same simplified wall. This arbitrary slice illustrates latent sensitivity; it does not establish that a value corresponds to an operator or that a difference between two runs is due only to KL.

For a diagonal Gaussian with mean μ\mu and log variance ℓ\ell, KL against the standard prior is 12∑j(μj2+eℓj−1−ℓj)\tfrac12\sum_j(\mu_j^2+e^{\ell_j}-1-\ell_j). Sampling uses z=μ+eℓ/2⊙ϵz=\mu+e^{\ell/2}\odot\epsilon, with standard normal ϵ\epsilon, allowing gradients to propagate. Evaluation should separate reconstruction loss, KL and success rate; low demonstration loss does not ensure good behaviour when the policy visits different states.

Architecture and execution

The ACT architecture uses a ResNet visual encoder, a transformer fusing visual tokens, proprioception and style, and a decoder with kk learned queries. Each query produces one position in the chunk through cross-attention to observation tokens. The posterior encoder processes proprioception and future actions during training. The original model retains spatial tokens and multiple cameras; the lab reduces size and resolution to expose the components and compares against LeRobot’s implementation.

Decoder queries identify positions in the chunk; they are not true actions shifted by one position. The model therefore predicts kk actions in parallel from observation and latent, unlike an autoregressive generator receiving the previous action as input. The posterior encoder does receive demonstrated actions during training, but that path is not used when deploying the policy. Confusing the paths would introduce future information into evaluation.

For model comparison, split complete episodes between training and validation. Splitting neighbouring windows from the same episode leaks nearly identical images and actions. Repeat training with several seeds and use the same evaluation initial conditions; report demonstrations, interaction steps, model queries and inference time. This page’s lab uses one training seed and a minimal simulation, so it explores the mechanism and detects faults rather than reproducing ALOHA’s published rates.

Temporal ensembling queries the policy each step and stores predictions from multiple chunks corresponding to the same instant tt. Ordered oldest to newest, it uses wi=e−miw_i=e^{-mi} and at=∑iwia^t(i)/∑iwia_t=\sum_iw_i\hat a_t^{(i)}/\sum_iw_i. With m>0m>0 this convention favours older predictions; m=0m=0 gives a uniform mean. Opposite age weighting favours newer observations and is another convention, so always state the ordering. It does not average actions from different instants. It can smooth noise but introduce inertia during a real change.

The second figure calculates an exact average for synthetic signals and compares it with executing the same chunk until its boundary every six steps. Change mm and compare contributions for the same instant, not just curves. In the original paper ablations use four simulated setups: mean rate varied from 1% at k=1k=1 to 44% at k=100k=100 without temporal ensembling; these are results for those tasks and settings, not a law for every robot. The same work notes that very slow feedback can harm fine manipulation. Predicting several language tokens shares the idea of emitting multiple outputs, although a control sequence affects the environment and must respect latency and safety.

For example, a future action has three predictions 0.20.2, 0.40.4 and 0.80.8, oldest to newest. With m=0m=0 the average is 1.4/31.4/3; with positive mm the first receives greater weight under the original convention. If an obstacle suddenly appears, that inertia can retain an earlier prediction that is no longer appropriate. Measure success, reaction time, action changes and inference cost together, and retain predictions by instant to diagnose the result.

Lab: chunks in a 2D task

Synthetic planar demonstrations are generated with and without a hidden pause. State is a two-coordinate position, action is a bounded 2D displacement and the goal is (1, 1); a two-dimensional disturbance is added halfway through the episode. A NumPy MLP predicts one, four or eight steps; chunk execution is compared with ensembling queried every step. Success requires ending within 0.12 Euclidean units of the goal; the smoothness metric sums Euclidean norms of action changes. Forty evaluation seeds show the effect in this system without estimating real-robot performance.

[ ]Compare chunks and ensembleBrowser
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.default_rng(4)
T=30
def expert(x,t,pause):
    return np.zeros(2) if 8<=t<8+pause else np.clip(.25*(np.ones(2)-x),-.12,.12)
def demonstrations(n):
    episodes=[]
    for _ in range(n):
        x=rng.uniform(-.2,.2,2);pause=int(rng.choice([0,4]));states=[];actions=[]
        for t in range(T):
            a=expert(x,t,pause);states.append(x.copy());actions.append(a.copy());x=x+a
        episodes.append((states,actions))
    return episodes
data=demonstrations(60)
def train(k):
    X=[];Y=[]
    for states,acts in data:
        for t in range(T-k+1):X.append([*states[t],1]);Y.append(np.asarray(acts[t:t+k]).reshape(-1))
    X=np.asarray(X);Y=np.asarray(Y);h=24
    W1=rng.normal(0,.3,(3,h));W2=rng.normal(0,.1,(h,2*k))
    for _ in range(200):
        idx=rng.integers(len(X),size=64);x=X[idx];y=Y[idx];hidden=np.tanh(x@W1);pred=hidden@W2;delta=2*(pred-y)/len(idx)/(2*k)
        g2=hidden.T@delta;g1=x.T@(([email protected])*(1-hidden**2));W1-=.08*g1;W2-=.08*g2
    return lambda x:(np.tanh(np.array([*x,1])@W1)@W2).reshape(k,2)
def rollout(model,k,ensemble,seed):
    r=np.random.default_rng(seed);x=r.uniform(-.2,.2,2);buffer=[];last=np.zeros(2);smooth=0
    for t in range(T):
        if t==15:x+=np.array([-.12,.08])
        if ensemble or t%k==0:buffer.append((t,model(x)))
        buffer=[(start,p) for start,p in buffer if t-start<k]
        if ensemble:
            weights=np.exp(-.2*np.arange(len(buffer)));a=sum(w*p[t-start] for w,(start,p) in zip(weights,buffer))/sum(weights)
        else:start,p=buffer[-1];a=p[t-start]
        a=np.clip(a,-.12,.12);smooth+=np.linalg.norm(a-last);last=a.copy();x=x+a
    return np.linalg.norm(x-np.ones(2))<.12,smooth
rows=[]
for k in [1,4,8]:
    model=train(k)
    for ensemble in [False,True]:
        results=[rollout(model,k,ensemble,1000+s) for s in range(40)];success=np.mean([v[0] for v in results]);smooth=np.mean([v[1] for v in results]);rows.append((k,ensemble,success,smooth));print('k',k,'ensamble',ensemble,'éxito',round(success,3),'cambio total medio',round(smooth,3))
fig,axes=plt.subplots(1,2,figsize=(8,3))
for mode in [False,True]:
    points=[r for r in rows if r[1]==mode];label='ensamble' if mode else 'bloques'
    axes[0].plot([r[0] for r in points],[r[2] for r in points],marker='o',label=label);axes[1].plot([r[0] for r in points],[r[3] for r in points],marker='o',label=label)
axes[0].set(xlabel='tamaño k',ylabel='éxito en 40 semillas',ylim=(-.05,1.05));axes[1].set(xlabel='tamaño k',ylabel='cambio total de acción');axes[0].legend();plt.tight_layout();plt.show()

Local lab: ACT and insertion comparison

This lab constructs a 2D insertion task with simplified contact, synthetic images and known state; it is not a physical arm simulation. It generates 80 episodes with two pause patterns, trains a reduced ACT with ResNet-18 and transformer, and compares with LeRobot ACT and Gaussian-mixture BC. Each model receives the same samples and 200 updates; evaluation uses 20 common initial conditions. Create an isolated environment and install pip install lerobot==0.3.3 torchvision; no visual weights are downloaded. The experiment is small and printed values depend on seed and budget, so they are not a conclusive implementation comparison.

[ ]Train ACT on simplified insertionLocal GPU
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet18
from lerobot.configs.types import FeatureType, PolicyFeature, NormalizationMode
from lerobot.policies.act.configuration_act import ACTConfig
from lerobot.policies.act.modeling_act import ACTPolicy

torch.set_num_threads(2); torch.manual_seed(17); rng=np.random.default_rng(17)
DEVICE='cuda' if torch.cuda.is_available() else 'cpu'; K=8; T=40
def image(x):
    im=np.zeros((3,64,64),dtype=np.float32); im[1,45,:]=.5; im[1,45,28:36]=0
    col=np.clip(int((x[0]+1)*31.5),0,63); row=np.clip(int(x[1]*50),0,63)
    im[0,max(0,row-1):row+2,max(0,col-1):col+2]=1
    return im
def step(x,a):
    x=x.copy();a=np.clip(a,-.08,.08);x+=a
    if x[1]>.9 and abs(x[0])>.12:x[1]=.9
    return np.clip(x,[-.9,0],[.9,1.])
def expert(x):
    return np.array([np.clip(-.8*x[0],-.08,.08),.08 if abs(x[0])<.1 else .015],dtype=np.float32)
def collect(n):
    data=[]
    for _ in range(n):
        x=np.array([rng.uniform(-.55,.55),rng.uniform(.05,.2)],dtype=np.float32);states=[];actions=[];pause=int(rng.choice([0,4]))
        for t in range(T):
            states.append(x.copy());a=np.zeros(2,dtype=np.float32) if 3<=t<3+pause else expert(x);actions.append(a);x=step(x,a)
        for t in range(T-K+1):data.append((image(states[t]),states[t],np.stack(actions[t:t+K])))
    return tuple(torch.tensor(np.stack([row[i] for row in data]),dtype=torch.float32) for i in range(3))
images,states,targets=collect(80)
print('Datos: 80 episodios, ejemplos',len(states),'pasos por episodio',T,flush=True)

class ScratchACT(nn.Module):
    def __init__(self):
        super().__init__();resnet=resnet18(weights=None);self.backbone=nn.Sequential(*list(resnet.children())[:-2]);d=32
        self.image=nn.Linear(512,d);self.state=nn.Linear(2,d);self.action=nn.Linear(2,d);self.style=nn.Linear(d,16);self.z=nn.Linear(8,d)
        self.pos=nn.Parameter(torch.randn(1,K+2,d)*.02);self.cls=nn.Parameter(torch.randn(1,1,d)*.02);self.visual_pos=nn.Parameter(torch.randn(1,4,d)*.02);self.queries=nn.Parameter(torch.randn(K,1,d)*.02)
        self.style_encoder=nn.TransformerEncoder(nn.TransformerEncoderLayer(d,4,64,batch_first=True),1)
        self.encoder=nn.TransformerEncoder(nn.TransformerEncoderLayer(d,4,64,batch_first=True),1)
        self.decoder=nn.TransformerDecoder(nn.TransformerDecoderLayer(d,4,64,batch_first=True),1);self.out=nn.Linear(d,2)
    def forward(self,img,state,actions=None,z_value=0.):
        B=len(state)
        if actions is not None:
            tokens=torch.cat([self.cls.expand(B,-1,-1),self.state(state)[:,None],self.action(actions)],dim=1)+self.pos
            mu,logvar=self.style(self.style_encoder(tokens)[:,0]).chunk(2,dim=-1);z=mu+torch.randn_like(mu)*torch.exp(.5*logvar)
        else:mu=logvar=None;z=torch.full((B,8),z_value,device=state.device)
        visual=self.backbone(img).flatten(2).transpose(1,2);visual=self.image(visual)+self.visual_pos
        obs=torch.cat([visual,self.state(state)[:,None],self.z(z)[:,None]],dim=1);memory=self.encoder(obs)
        return self.out(self.decoder(self.queries.transpose(0,1).expand(B,-1,-1),memory)),mu,logvar
class GMM(nn.Module):
    def __init__(self):
        super().__init__();self.backbone=resnet18(weights=None);self.backbone.fc=nn.Identity();self.net=nn.Sequential(nn.Linear(514,64),nn.ReLU(),nn.Linear(64,10))
    def forward(self,img,state):
        o=self.net(torch.cat([self.backbone(img),state],dim=1));return o[:,:2],o[:,2:6].reshape(-1,2,2),o[:,6:].reshape(-1,2,2).clamp(-4,1)
def gmm_loss(out,target):
    logits,mu,logsd=out;logp=(-.5*((target[:,None,:]-mu)/logsd.exp())**2-logsd-.5*np.log(2*np.pi)).sum(-1)
    return -torch.logsumexp(F.log_softmax(logits,dim=-1)+logp,dim=-1).mean()
config=ACTConfig(device=DEVICE,input_features={'observation.images.top':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},chunk_size=K,n_action_steps=1,pretrained_backbone_weights=None,dim_model=32,n_heads=4,dim_feedforward=64,n_encoder_layers=1,n_decoder_layers=1,n_vae_encoder_layers=1,latent_dim=8,kl_weight=.01,dropout=0.)
models={'ACT propio':ScratchACT(),'ACT sin KL':ScratchACT(),'LeRobot ACT':ACTPolicy(config),'BC GMM':GMM()}
for name,model in models.items():
    model.to(DEVICE);opt=torch.optim.Adam(model.parameters(),lr=.0003);model.train()
    for update in range(200):
        idx=rng.integers(0,len(states),size=16);im=images[idx].to(DEVICE);s=states[idx].to(DEVICE);a=targets[idx].to(DEVICE)
        if name in ('ACT propio','ACT sin KL'):
            pred,mu,logvar=model(im,s,a);beta=.01 if name=='ACT propio' else 0.;loss=F.l1_loss(pred,a)+beta*(-.5*(1+logvar-mu.square()-logvar.exp()).sum(-1).mean())
        elif name=='LeRobot ACT':loss,_=model({'observation.images.top':im,'observation.state':s,'action':a,'action_is_pad':torch.zeros(len(s),K,dtype=torch.bool,device=DEVICE)})
        else:loss=gmm_loss(model(im,s),a[:,0])
        opt.zero_grad();loss.backward();opt.step()
    model.eval();success=0;changes=[]
    for seed in range(20):
        r=np.random.default_rng(10000+seed);x=np.array([r.uniform(-.55,.55),r.uniform(.05,.2)],dtype=np.float32);last=np.zeros(2);change=0
        for t in range(T):
            im=torch.tensor(image(x)[None],device=DEVICE);s=torch.tensor(x[None],dtype=torch.float32,device=DEVICE)
            with torch.no_grad():
                if name in ('ACT propio','ACT sin KL'):a=model(im,s)[0][0,0].cpu().numpy()
                elif name=='LeRobot ACT':a=model.predict_action_chunk({'observation.images.top':im,'observation.state':s})[0,0].cpu().numpy()
                else:
                    logits,means,_=model(im,s);a=means[0,logits[0].argmax()].cpu().numpy()
            a=np.clip(a,-.08,.08);change+=np.linalg.norm(a-last);last=a.copy();x=step(x,a)
        success+=int(x[1]>.95 and abs(x[0])<.12);changes.append(change)
    print(name,'actualizaciones 200; pérdida final',round(float(loss.detach().cpu()),4),'éxito',success,'/20; cambio medio',round(float(np.mean(changes)),3),flush=True)
    if name in ('ACT propio','ACT sin KL'):
        example=np.array([.3,.1],dtype=np.float32);im=torch.tensor(image(example)[None],device=DEVICE);s=torch.tensor(example[None],device=DEVICE);predictions=[]
        with torch.no_grad():
            for z in (-2.,-1.,0.,1.,2.):predictions.append(model(im,s,z_value=z)[0][0].cpu().numpy().round(4).tolist())
        print('Estilos',name,predictions,flush=True)
    model.cpu()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Practice

Proof
Prove: Derive the conditional ELBO and L1 reconstruction.
0
The prior p(z) is standard normal and the decoder uses a fixed-scale Laplace distribution.

Step 1 of 3. How is posterior q(z|o,a) introduced?

Numeric
At 50 Hz, complete chunks of 100 actions execute for 20 seconds. How many queries occur if queried at the start of each chunk?
Quiz
Why is z fixed to zero in original ACT inference?
Quiz
The same visible state occurs before and after a hidden pause. What difficulty arises?
Code
Implement temporal_ensemble(buffer,t,m). buffer is a list of (query time, action sequence), ordered oldest to newest. Keep sequences covering t and average their actions with weights exp(−m·i), where i=0 is the oldest valid sequence. Return a NumPy vector; raise ValueError if none covers t.
import numpy as np
def temporal_ensemble(buffer,t,m):
  pass
Shift+Enter to run
Key idea
A chunk reduces high-level queries while ensembling combines predictions for one instant; responsiveness depends on when it observes again and how each prediction is weighted.