Module contents
Stage 6 of 9Advanced 120 min

ACT: action chunking with transformers

Implement ACT: a transformer predicts a chunk of future actions from images and proprioception, with a CVAE encoder capturing the style of each demonstration and temporal ensembling during execution. Train in simulated bimanual tasks and T pushing and measure the effect of chunk size.

After this lesson you can

  • Implement the CVAE encoder, policy transformer, and loss with a KL term.
  • Implement temporal ensembling of overlapping chunks.
  • Train on simulated bimanual tasks and compare with published rates.
  • Measure the effect of chunk size and ensembling on success.

Before you start

A decision that lasts several steps

A gripper handing a cube to another needs more than choosing where to go now. It must coordinate approach, closure, and release across a sequence of contacts. One-step behavior cloning learns each action separately. If it sees an ambiguous observation during a pause, it can alternate between advancing and waiting. Predicting a sequence can express a coherent decision over time, although it does not guarantee the robot succeeds.

An action chunk of length kk predicts kk consecutive actions from one observation. If you execute the entire chunk, an episode of TT steps needs ⌈T/k⌉\lceil T/k\rceil queries, provided the last prediction is truncated at the end. That reduction counts policy queries: it does not show physical error falls in the same proportion. A perturbation halfway through the chunk is not observed until the next query.

InteractiveWhat happens when a setpoint changes?
  • Setpoint
  • Ensembled action
  • Active chunks
8
0.15
29
Available predictions8
Ensembled action0.570
Current setpoint1
The teaching model has a setpoint that jumps at step 25 and predictions with an explicit sinusoidal error. Change length and weight: chunks issued before the jump continue to vote afterward. These are not robot rollouts.

In the figure, the chunk issued at ss predicts for u≥su \ge s the setpoint observed at ss plus 0.2sin⁡(0.8s+0.3(u−s))0.2\sin(0.8s+0.3(u-s)). The blue curve averages predictions available for each instant, not actions from different instants. Increasing kk leaves more predictions from before the jump active. If mm is positive, ACT’s scheme gives more weight to older predictions, potentially delaying incorporation of the new observation. The figure illustrates that tradeoff with a controlled model; it does not estimate success or smoothness for a real robot.

A CVAE that sees the future only during training

Multimodality arises when an observation permits several valid continuations. A coherent chunk might go around the obstacle to the left or to the right. A single regression can average both and produce a trajectory through the obstacle.

In the ACT policy with a CVAE, the posterior encoder receives proprioception qtq_t and demonstrated actions at:t+k−1a_{t:t+k-1}. It returns μ\vb{\mu} and log⁡σ2\log\vb{\sigma}^2 of a diagonal Gaussian. The policy receives the image, proprioception, and a style sample z\vb{z}, and returns the full chunk. The posterior encoder is used only during training: true future actions are unavailable during deployment. ACT uses z=0\vb{z}=\vb{0}, the standard-normal prior mean, not the mean of a posterior it can no longer access.

The encoder-decoder transformer integrates image, proprioception, and style tokens; positional queries in the decoder produce one output per future step. The posterior uses the action sequence and proprioception. Its distribution is brought close to N(0,I)\Normal(\vb{0},\mat{I}) with a KL penalty. For dzd_z independent components:

DKL(q∥p)=12∑j=1dz(μj2+σj2−1−log⁡σj2).D_{\mathrm{KL}}(q\Vert p)=\frac12\sum_{j=1}^{d_z}\left(\mu_j^2+\sigma_j^2-1-\log\sigma_j^2\right).

For a window crossing the end of an episode, a mask excludes padding actions from reconstruction. The loss combines absolute error on valid actions and βDKL\beta D_{\mathrm{KL}}. ACT’s public code uses L1, although the algorithm printed in the paper presents MSE: this choice must be declared to reproduce the implementation. L1 mean and KL sum must have explicit scales, since changing their reduction changes the numerical meaning of β\beta.

The sample is constructed with reparameterization z=μ+σ⊙ϵ\vb{z}=\vb{\mu}+\vb{\sigma}\odot\vb{\epsilon}, ϵ∼N(0,I)\vb{\epsilon}\sim\Normal(\vb{0},\mat{I}): noise does not depend on the parameters and the gradient passes through μ\vb{\mu} and σ\vb{\sigma}. The preceding KL is the sum of the KLs between each univariate Gaussian and N(0,1)\Normal(0,1). It is zero precisely when all means are zero and all variances one. That does not prove style is useful: it is also compatible with a posterior that has collapsed to the prior.

For a batch of shape (B,k,da)(B,k,d_a), the lab computes the sum of absolute errors at valid positions and divides by the number of valid components. It sums KL over latent dimensions and averages over the batch. Thus a window with much padding does not artificially reduce L1 scale. The consulted LeRobot implementation averages the masked tensor over all positions, including padding as zeros: with much padding, reconstruction weighs less relative to KL. These are different recipes even with the same numerical value of β\beta.

With β\beta too large, the posterior may approach the prior and the decoder ignore z\vb{z}; with β\beta too small, it may encode demonstration details unavailable during deployment. No value is universal: inspect reconstruction, KL, and success on held-out episodes. Using z=0z=0 is ACT’s deterministic choice, not a guarantee of selecting a distribution mode.

Ensemble predictions for the same instant

Temporal ensembling queries the policy at every step and retains active chunks. For time tt, order their predictions by issue time from oldest to newest. If at(i)a_t^{(i)} is prediction ii and wi=exp⁡(−mi)w_i=\exp(-mi), apply

a^t=∑iwiat(i)∑iwi.\hat a_t=\frac{\sum_i w_i a_t^{(i)}}{\sum_i w_i}.

With m=0m=0 the average is uniform. With m>0m>0 the oldest prediction is favored, as in Zhao et al., section IV-A. A convention ordering newest to oldest reverses the effect. The average is componentwise and assumes actions are represented in a space where averaging makes sense: do not interpolate periodic angles across their discontinuity without handling it, or average discrete gripper decisions as though they were continuous positions.

In the first steps there are fewer than kk chunks, and after each chunk ends it no longer has a valid prediction for later instants. The buffer must store issue time and actual length; a predicted action equal to zero is a valid value, not a missing-entry marker. If a prediction comes from a chunk issued at ss, its index for tt is t−st-s, provided 0≤t−s<k0\le t-s<k. The exercise also tests this order and exclusion of expired chunks.

[ ]Average for one instantBrowser
import numpy as np

def ensemble(buffer, t, m):
    candidatos = sorted(((s, np.asarray(a[t-s], dtype=float)) for s, a in buffer
                         if s <= t < s + len(a)), key=lambda p: p[0])
    if not candidatos or m < 0:
        raise ValueError("Sin predicciones o peso negativo")
    w = np.exp(-m * np.arange(len(candidatos)))
    return np.average(np.stack([a for _, a in candidatos]), axis=0, weights=w)

buffer = [(0, [[0.0], [0.0], [0.0]]), (1, [[1.0], [1.0], [1.0]])]
print("uniforme:", ensemble(buffer, 1, 0), "| favorece el antiguo:", ensemble(buffer, 1, 1))

Ensembling requires one inference per step as well as maintaining chunks. At 50 Hz control, the budget per step is 20 ms to observe, infer, ensemble, and send the command. Measure end-to-end latency and its distribution on your hardware: the architecture does not promise the frequency will be met.

Lab: implement and run the policy

The lab uses episodes from demonstration collection. Download act_model.py, act_experiment.py, window_data.py, training_resume.py, p13_pusht.py, and p13_aloha.py to the same directory. The last two recover the simulator interface from lesson 1 and need its dependencies and assets. The dataset is generated beforehand using that lesson. Image columns are not mixed with privileged simulator state: the policy receives only image and proprioception. Images remain compressed in memory and are decoded when each window is sampled.

The model in the file is a compact variant, not a numerically identical copy of published ACT. A CNN produces a grid of 16 tokens to which learned positions are added. The posterior encoder processes a classification token, proprioception, and kk actions; the first token produces μ\mu and log⁡σ2\log\sigma^2. The policy encoder mixes image, proprioception, and style, and kk distinct queries pass through a decoder with cross-attention. Output has shape (lote, k, dimensiones_de_acción). Masks prevent the posterior from attending to padding; L1 loss excludes it too.

The program samples windows within training episodes, computes state and action means and standard deviations on that set only, trains with AdamW, and saves weights, statistics, and configuration. At deployment it denormalizes before calling the environment. --ensemble queries every step; without it, each entire chunk is executed. The training seed must not be confused with the evaluation reset seed. For example, after preparing the transfer dataset:

python act_experiment.py train --task transferencia --data RUTA_AL_CONJUNTO --out act-k100.pt --chunk 100 --steps 10000 --seed 0
python act_experiment.py eval --task transferencia --out act-k100.pt --episodes 100 --eval-seed 20000
python act_experiment.py eval --task transferencia --out act-k100.pt --episodes 100 --eval-seed 20000 --ensemble

Repeat with other sizes and seeds, and with insercion and empuje_t. The program saves success by seed, the interval, and median network latency. That latency excludes rendering, preprocessing, and actuation, so it does not demonstrate that the full system meets 20 ms. Selecting the last checkpoint, as this program does, is a different protocol from the original; to select by validation, incorporate a separate validation set and keep test untouched. This compact model’s KL weight is not directly comparable to the original either, because loss reduction changes its scale.

The bimanual evaluation below grouped four independent environments in each network call. To reproduce that protocol, also download act_batched_eval.py and run it with --task transferencia --checkpoint act-k100.pt --out evaluacion.json --episodes 100 --batch 4; add --ensemble for the second variant. Recorded latency is per batch of four and is not directly equivalent to that of an individual controller. Grouping inference can slightly alter rounding, so save batch size alongside trajectories.

To contrast with LeRobot 0.3.3’s ACT implementation, lerobot_act_experiment.py adapts the same bimanual-task states, images, and actions to its interface. It also needs window_data.py, training_resume.py, p13_pusht.py, and p13_aloha.py. A ResNet is built without pretrained visual weights and training-set statistics are used. The implementation and visual architecture are not identical to this lesson’s compact model, so the contrast does not isolate a single difference.

A CPU integration check trained one update with two demonstrations and executed one action in each mode on the same scene; both actions were finite and identical at that first instant. This is an interface test, not a performance comparison: the latter requires complete training and paired rollouts. The program saves the contract, checkpoint hash, and one trace per episode; its --max-steps option is for diagnostics and the default preserves the full horizon.

On Windows, leaving CUDA_VISIBLE_DEVICES empty did not hide the GPU from this installation. The first LeRobot replica computed with model and tensors on CPU, but the process also created a CUDA context; the system did not permit measurement of that context’s memory per process. In a separate control with one CPU update, batch 8, chunk 100, and two demonstrations, leaving CUDA visible or hiding it with CUDA_VISIBLE_DEVICES=-1 produced identical weights, statistics, optimizer, and NumPy and PyTorch generators. That control does not prove equality across a complete campaign: record the configuration used for each replica.

For long evaluations, lerobot_act_eval_incremental.py and episode_store.py save one atomic part per scene and then assemble the same JSON results format. Each part retains actions and the full MuJoCo integration state; in the checked transfer task the latter has 262 components. The manifest fixes the checkpoint, backend, and code hashes, and each part has its own hash. If a partial file from the previous evaluator exists, the incremental path rejects and preserves it: resume it with the program that created it.

python lerobot_act_eval_incremental.py eval --task transferencia --out act-lerobot.pt \
  --device cpu --episodes 100 --eval-seed 20000

Add --ensemble for the second mode. An act-lerobot.pt.pause file requests a stop after the episode ends; repeat the same command to continue from complete parts. Our test with two CPU scenes outside reserved seeds interrupted and resumed the incremental path: the previous evaluator produced exactly the same actions, states, rewards, and results for one open-loop step and four steps with ensembling. That check validates the short workflow, not success or speed of a complete campaign.

To interrupt without losing training state, create the empty file act-k100.pt.pause. After finishing the current update, the program saves act-k100.pt.resume.pt with optimizer, random generators, step, and data-file hashes, and exits. To continue, repeat the training command with the same arguments and add --resume. The program rejects a different contract or data. The resumable checkpoint is not the final evaluation model.

A protocol that enables comparison

In the original ACT repository, the simulated tasks are cube transfer and bimanual insertion. The example uses 50 scripted episodes, k=100k=100, KL weight 10, hidden dimension 512, and 2000 epochs; the README reports approximately 90% and 50% success for transfer and insertion respectively. These are references for that implementation and protocol, not results obtained here. Lesson 1 defines our own tasks and recording; retain frequency, camera, actions, seeds, success definition, and episode count when reporting a comparison. A difference in any of them prevents interpreting the difference as an isolated policy effect.

To measure the effect of kk, train one policy per size on the same episodes with recorded training seeds. Evaluate each checkpoint with and without ensembling on the same held-out initial seeds. Report successes and total, Wilson intervals per condition, and variation among training seeds. Do not confuse evaluation episodes with independent training replicas. The test set plays no part in normalization or checkpoint selection.

In our own run of the compact model on this project’s MuJoCo Push-T, it was trained with 200 demonstrations, 10 000 updates, training seed 0, and chunks of 20 actions. The same 100 held-out initial states were evaluated in both modes: open loop and temporal ensembling, where every active chunk contributes its vote.

ModeSuccesses (95% Wilson)Mean coverage (95% bootstrap)
Open loop0/100 (0% to 3.70%)4.24% (2.60% to 6.09%)
With voting0/100 (0% to 3.70%)5.25% (3.33% to 7.37%)

The bootstrap resamples the 100 scenes with 10 000 replicates; it does not measure variation across training runs. The downloadable summary includes seeds and result hashes. An independent review reproduced the first steps of one scene and checked statistics and masks, but the result is still one network: it does not establish that ACT, other chunk sizes, or ensembling fail in general. Nor does it establish the small coverage difference is a replicable improvement. Supervised loss on demonstration states and success in a full rollout measure different things.

Two other networks with the same data and budget, seeds 1 and 2, were trained on CPU and also achieved 0/100 in each mode when evaluated on CPU on those scenes. Mean final coverage for seed 1 was 3.96% open loop and 3.82% with ensembling; for seed 2 it was 2.42% and 4.45%. The first network was trained on CUDA, so observed variation between it and the others mixes seed and training backend. The per-replica summary retains that distinction and per-model intervals.

In the bimanual experiment the action has 14 components, six positions and one gripper per arm. The overhead camera measures 120×160120\times160 pixels and each episode lasts 400 steps at 50 Hz. Success is recorded if reward reaches level 4 at any time, even if the episode continues. The lesson 1 expert uses a mocap copy and adapts two contact details; its demonstrations and our camera are therefore not necessarily identical to those in the paper’s table. A useful comparison places both protocols side by side and declares differences without attributing them to the algorithm.

As the first measured point of that curve, the compact variant trained on transfer with 50 demonstrations, k=20k=20, one seed, and 12 500 updates achieved 6/100 successes open loop and 2/100 with temporal ensembling. The 95% Wilson intervals are 2.78% to 12.48% and 0.55% to 7.00%, respectively. Both evaluations used the same initial seeds and inference grouped in batches of four independent environments. Five scenes succeeded only in open mode, one only with ensembling, and another succeeded in both; the summary with hashes retains the counts. This is one checkpoint: the observed difference does not determine the general effect of ensembling or replace the curve over sizes and seeds. It is not compared numerically as an identical replica of the published 90%, since architecture and parts of the protocol differ.

A second independent training run with the same configuration achieved 3/100 open loop and 2/100 with ensembling, evaluated on CPU in batches of four on the same scenes; one scene succeeded in both modes, two only open, one only with ensembling, and 96 in neither. The first seed, repeated on that same backend, retained counts of 6/100 and 2/100. The two-seed summary includes intervals and hashes. These are two different networks evaluated on the same 100 scenes, not 200 independent scenes or sufficient evidence for a general conclusion about ensembling.

For k=50k=50, under the same CPU protocol the two seeds achieved 7/100 and 6/100 open loop, versus 5/100 and 7/100 with ensembling. In the second network no scene succeeded in both modes: six succeeded only open loop and seven only with ensembling. These overlaps matter for interpreting the paired comparison and cannot be inferred from marginal rates alone. For k=100k=100, rates were 9/100 and 6/100 open loop, versus 4/100 and 6/100 with ensembling.

For insertion, the checkpoint with k=20k=20 and seed 0 achieved 3/100 open loop and 1/100 with ensembling. None of those scenes succeeded in both modes: three only open loop, one only with ensembling, and 96 in neither. The second seed achieved 0/100 in both modes; for each rate the 95% Wilson interval reaches approximately 3.70%. Two networks do not allow a general difference to be attributed to the task.

With k=50k=50, the two insertion networks achieved 1/100 and 4/100 open loop, and 0/100 and 1/100 with ensembling. With k=100k=100 they achieved 2/100 and 0/100 open loop, and 1/100 and 1/100 with ensembling. Each rate is based on 100 episodes, but variation across networks is supported by only two training initializations. Per-network intervals are available in the figure.

InteractiveChunk size and bimanual success
  • Training 0
  • Training 1
Actions per chunk
20
Seed 0 (Wilson 95 %)6/100: 6.0 % [2.8 %, 12.5 %]
Seed 1 (Wilson 95 %)3/100: 3.0 % [1.0 %, 8.5 %]
Compact model: 50 demonstrations, 12 500 updates, and 100 paired scenes per network and mode. Select task, length, and mode. Lines connect observed points and do not prove a trend between them.

The figure data identify the seed, mode, and hashes of the checkpoint and result used for each point.

The paired analysis retains the four categories for each network and resamples the 100 scenes together 10 000 times. For example, in insertion with k=20k=20 and seed 0, the difference ensembling minus open loop was −2 percentage points and its per-scene bootstrap interval was −6 to 2 points. For seed 1, both modes always failed and the empirical bootstrap gives [0,0][0,0]; that degenerate interval does not prove the true probabilities are equal. Wilson intervals per mode and repeated training runs address different uncertainties.

Contrast with LeRobot ACT

Four LeRobot networks were trained, one per task and seed, with 50 demonstrations, k=100k=100, and 12 500 updates. Each was evaluated on the same 100 seeds open loop and with ensembling. The table also shows this lesson’s compact-variant result for those seeds and that size; each figure is successes out of 100. Bracketed intervals are 95% Wilson for LeRobot.

Task and seedCompact A / ELeRobot A / E
Transfer, 09 / 491 / 90
Transfer, 16 / 690 / 89
Insertion, 02 / 114 / 14
Insertion, 10 / 117 / 14

A indicates open-loop execution and E ensembling. For LeRobot, 95% Wilson intervals in transfer are, respectively for A and E, [83.77%, 95.19%] and [82.56%, 94.48%] for seed 0; [82.56%, 94.48%] and [81.37%, 93.75%] for seed 1. In insertion they are [8.53%, 22.14%] in both modes for seed 0; [10.89%, 25.55%] and [8.53%, 22.14%] for seed 1.

Equal rates do not imply the same scenes. In insertion with seed 0, LeRobot succeeded in both modes on 11 scenes, only open loop on three, and only with ensembling on another three; 83 failed in both. Paired bootstrap by scene gives an ensembling-minus-open difference of zero points and interval −5 to +5 points. In transfer with seed 1, the respective counts were 86, 4, 3, and 7, with a −1 point difference and interval −6 to +4 points. The intervals describe these scenes for each network, not variation across training runs.

The difference between implementations can also be paired by scene. In transfer, seed 0 and open loop, the compact network succeeded on 9 and LeRobot on 91: nine scenes succeeded with both, 82 only with LeRobot, and nine with neither. The observed difference is 82 points, with per-scene bootstrap of 74 to 89 points. All four compact k=100k=100 networks were trained on CUDA and all four LeRobot networks on CPU; all these evaluations used CPU. Visual and transformer architectures, loss reduction, and inference batch size also differ: the compact model was evaluated in groups of four and LeRobot scene by scene. The contrast shows what happened with these two recipes; it does not identify which difference caused it or reproduce the paper’s results unchanged.

The LeRobot summary includes eight conditions, four contrasts between modes and eight against the compact model, together with hashes and bootstrap seeds. It is generated with export_lerobot_results.py, after checking each checkpoint and evaluation with audit_lerobot_checkpoint.py and audit_lerobot_eval.py. The traces retain 14 actions and the full state: 262 components for transfer and 293 for insertion. The two training seeds must not be counted as 200 independent scenes.

Exercises

Numeric
An episode lasts 400 steps. How many queries are needed if complete chunks of 100 steps are executed?
Quiz
What information does ACT's latent have during deployment?
Quiz
A rapid perturbation can move the object between decisions. Which option allows it to be observed sooner?
Proof
Prove: For vector predictions ai\vb{a}_i of the same instant and weights wi>0w_i>0, the weighted average minimizes F(a)=∑iwi∥a−ai∥2F(\vb{a})=\sum_i w_i\norm{\vb{a}-\vb{a}_i}^2.
0
Assume at least one prediction and positive weights.

Step 1 of 3. What is the gradient of F?

Code
Implement temporal_ensemble(buffer, t, m). buffer contains pairs (issue time, sequence of vectors) in arbitrary order. Average only predictions covering t, with weights exp(-m*i) from oldest to newest. Reject negative m or missing predictions with ValueError.
import numpy as np
def temporal_ensemble(buffer, t, m):
  pass
Shift+Enter to run
Key idea

A chunk makes an action sequence explicit; the CVAE provides a style variable during training and ensembling combines overlapping predictions for the same step. Size, reactivity, and inference cost are experimental decisions, not properties guaranteed by the architecture.