Diffusion Policy
Implement Diffusion Policy: a 1D temporal U-Net generates action sequences by diffusion conditioned on observations through FiLM, trained with the diffusion project recipe and sampled with DDIM in a few steps. Execute with a receding horizon and compare with behavior cloning, Gaussian mixture, and ACT on T pushing.
After this lesson you can
- Implement the temporal U-Net with FiLM conditioning on observations.
- Train with noise prediction, EMA, and the appropriate noise schedule.
- Sample with DDIM and execute with a receding horizon within the latency budget.
- Compare with previous policies on success, coverage, and latency.
Before you start
- P13Action chunkingMixture and discretized policiesVisuomotor encoder
- P07DDPM training recipeEMA and checkpoint selectionDDIM deterministic sampling
- 19Classifier-free guidanceBayesian decomposition of the conditional score
- 161D, 2D and 3D convolutions
- 24Feature-wise linear modulationReceding-horizon action execution
- 22Model predictive control
There is no single continuation
The T can be pushed from different sides. If examples contain two coherent trajectories, a regression minimizing squared action error can return their average even though that average is not either solution. Diffusion Policy learns a distribution of action sequences conditioned on observation, and generates a sample by refining noise. As with action chunks, each sample represents several steps rather than one isolated command.
Before introducing a network, consider a case where the posterior is calculated exactly. There are only two possible sequences: a positive curve and its negative. The noisy observation comes from one of them with Gaussian noise. The blue line is the posterior mean over the two possibilities; it is not a trained policy or a rollout.
In the figure’s model, , where takes values and with equal probability and . We observe , with . Gaussian likelihoods give
The blue curve is that expectation multiplied by . The control changes noise level while retaining the same seed; it does not represent consecutive steps of a reverse sampler. In a real task we do not know the two possible trajectories or their exact posterior. A network learns to predict noise from many examples.
The formula is obtained without training anything. Both likelihoods are Gaussian with the same variance . When their logarithms are subtracted, terms and cancel, and the log posterior odds are . Since the probabilities sum to one, their difference is the hyperbolic tangent of half those log odds. A posterior mean near zero can represent uncertainty between two sequences, not a third valid sequence.
From clean actions to noise and back
Let be a window of normalized actions and the observation. The forward diffusion process produces
Sample an index and fresh noise per example, and minimize squared error between that noise and . Here squared error applies to noise conditioned on a noisy sequence, not all valid actions given only . It therefore does not force generation to return the mean of the modes: initial noise selects a possible trajectory and the network corrects that sample at successive scales. Whether a particular network actually learns all modes depends on data, capacity, and training.
For a level with , the optimal noise predictor under squared loss is . Moreover, if differentiation is allowed under the integral mixing the forward-process Gaussians,
The identity follows by differentiating the Gaussian density of given : its logarithmic gradient is . Averaging over the posterior of yields expected conditional noise. The network therefore approximates the score of the noisy distribution conditioned on observation. Manually labeling each trajectory “left” or “right” is unnecessary, but examples representing those alternatives are still required.
The target label matters when connecting training and inference. Some models predict the clean action directly and others a combination called velocity; their conversion formulas are not interchangeable with those of a noise predictor. Here training explicitly compares network output with and the sampler interprets the same output as . The schedule must also match: using weights with another schedule changes both the noise level seen by the network and the reconstruction denominator.
For deterministic DDIM sampling with , first estimate
For the next lower index , compute . On the last step use . With fixed initial noise, observation, and weights, the chain is deterministic. Ten steps are a cost-quality decision; they do not automatically reproduce a long chain’s result. DDIM shares DDPM’s training objective but uses a different family of reverse processes.
Check that update with an oracle that knows the exact noise. This is an algebraic chain test, not a trained network or robot evaluation. It uses 64-bit precision to distinguish formula error from 32-bit rounding effects.
import numpy as np
rng = np.random.default_rng(1307)
t = np.arange(101) / 100
f = np.cos((t + 0.008) / 1.008 * np.pi / 2)**2
f /= f[0]
beta = np.clip(1 - f[1:] / f[:-1], 0, 0.999)
alpha = np.cumprod(1 - beta)
indices = np.rint(np.linspace(99, 0, 10)).astype(int)
clean = rng.uniform(-1, 1, (16, 2))
noise = rng.normal(size=clean.shape)
x = np.sqrt(alpha[indices[0]]) * clean + np.sqrt(1-alpha[indices[0]]) * noise
for i, n in enumerate(indices):
estimate = (x - np.sqrt(1-alpha[n]) * noise) / np.sqrt(alpha[n])
previous = alpha[indices[i+1]] if i+1 < len(indices) else 1.0
x = np.sqrt(previous) * estimate + np.sqrt(1-previous) * noise
error = float(np.max(np.abs(x-clean)))
print('índices:', indices.tolist(), '| error máximo:', error)
assert error < 1e-9The generator starts from a Gaussian tensor with the same shape as the action window. Two different noise seeds for one observation can produce different sequences, but that demonstrates output variation only. To speak of useful multimodality, check whether each sequence respects contact, reaches the goal, and covers distinct alternatives. A cloud of commands saturated at limits can be varied without being a collection of valid strategies.
For this scene and the three noise seeds chosen before sampling, 84.4%, 100%, and 96.9% of the proposal’s 32 components, respectively, ended outside . The figure clips them to convert to physical units and shows the fraction clipped at each stage. This flags these samples, not an estimate of success or a general proof of failure. The trace file retains seeds and checkpoint hash for examination.
An independent check recomputed action minima and maxima with the 200 training demonstrations and obtained exactly the statistics saved in the checkpoint. In addition, an oracle returning the true noise reproduced the complete DDIM chain on CPU with maximum error 0.00021 in float32 precision. The implementation uses a final cumulative product near : when reconstructing clean action, dividing by its square root amplifies numerical and prediction errors. The algebraic control alone does not explain observed saturation or guarantee that the learned model predicts noise well.
A conditioned temporal U-Net
For a batch of sequences, input has shape . The 1D convolution acts over time. Downsampling expands the receptive field; upsampling restores resolution and a skip connection preserves detail. The noise index is encoded with sines and cosines. A CNN converts the image into features, which are concatenated with proprioception and the index.
In the lab file, the initial convolution projects channels to 64 and the down block preserves length. A stride-two convolution halves an even horizon; the middle block processes that representation and a transposed convolution restores original length. Addition with the skip connection requires matching dimensions. The up block and final projection return . The network does not see the exact object in privileged state: it receives only the camera and pusher position.
The cosine schedule constructs decreasing , with bounded increments to avoid division by zero at the final level. EMA maintains another copy of the weights and updates it as . Evaluating that copy and the instantaneous network is an experimental decision: EMA does not guarantee greater success on every task. The code recipe saves the final EMA; it does not select the best checkpoint by success and should not be compared as if it exactly followed the paper’s selection.
FiLM transforms each activation channel as : scale and bias depend on the condition. The is a specific parameterization that begins near an identity transformation if the projection produces small values; it is not a universal FiLM requirement. Noise has the same shape as actions. At inference, state is normalized with training statistics, normalized actions are generated, and the transformation is inverted before acting. A different deployment scale changes the problem learned by the network.
During training, a window may reach the episode’s end before completing the horizon. The lab repeats the last action there: rather than teaching the network arbitrary positions for the rest, it presents a constant continuation. Because those positions enter the loss, an example near the end gives more weight to holding the last command. A mask excluding padding would answer a different question; compare this decision too when comparing implementations.
The visual condition is recomputed whenever a new chunk is generated. During the eight executed actions, no new image is incorporated into that sample. The observation window, predicted horizon, and executed horizon are therefore three different quantities. A controller predicting 16 actions, executing 8, and observing one image per query can be described as ; it is not equivalent to using eight previous images.
Horizon and reaction time
Receding-horizon control generates actions, executes only , and observes again. is the number of observations available for each prediction. A small allows a deviation to be corrected sooner, but requires replanning more often. A long prediction horizon can express a coherent maneuver, but does not make a distant prediction correct. Actual frequency depends on the complete system, not the model alone.
With ten DDIM steps and 35 ms per generation, the ideal maximum sequential replanning rate is Hz before observation and communication. If eight actions are executed at 10 Hz, there are 0.8 s between replans: even fast inference cannot react during those eight actions. For fast contact, shorten the executed horizon and measure the quality and cost of that decision.
The ideal rate of 28.57 queries per second also does not mean the robot is controlled at that frequency: the example applies commands at 10 Hz and queries only at the start of each block. Changing to approximately quadruples the number of queries in a long episode, in addition to changing opportunities to correct. If queries are synchronous, compare their duration with available time at each replanning instant; a global mean over all cycles can hide the fact that those specific cycles are slowest.
There are two different clocks. The controller applies an action every 100 ms in this project’s Push-T; planning occurs when the executed chunk is exhausted. If generation is synchronous, a delay greater than available time can leave the controller without a new command. An asynchronous implementation must also decide what to do with a sequence computed from an old observation. Measuring only the network call excludes capture, image transfer, normalization, synchronization, and action dispatch.
Lab
Download diffusion_model.py, diffusion_experiment.py, window_data.py, training_resume.py, and p13_pusht.py to the same directory and first generate episodes from the first lesson. The compact model uses one current image, not visual history; its observation horizon is one. Train a temporal U-Net with FiLM, cosine schedule, noise target, and exponential moving average of weights (EMA). Actions are scaled to using training minima and maxima; the last steps of a window crossing the end repeat the last action. This convention must be declared because it affects learned sequences.
This page’s campaign used the original dataset’s 80 training episodes and 120 additional episodes from the same scripted expert, for 200 total. Training reads only the train splits specified by the manifests, samples windows randomly, and uses batch 64. The three replicas use the same data and vary the training seed. Evaluation reserves scenes 20000 through 20099 and records whether any action reaches coverage of at least 0.95; final coverage can differ from the maximum achieved during an episode.
The three checkpoints and their manifests contain the statistics and hashes used for each training run. For this download, local contract paths were replaced with relative identifiers of the two datasets: weights and statistics are identical, but the file hash changes. Each manifest retains the original checkpoint hash and the portable copy’s hash. Published evaluations retain the original hash under which they ran; to verify them alongside portable copies, summarize_seeds.py accepts their three manifests through --portable-manifests.
python diffusion_experiment.py train --data RUTA_CONJUNTO_ORIGINAL RUTA_CONJUNTO_ADICIONAL --out diffusion.pt --steps 10000 --batch 64 --seed 0
python diffusion_experiment.py eval --out diffusion.pt --episodes 100 --eval-seed 20000 --execute 8 --ddim-steps 10
The evaluator saves each seed, success, coverage, and step count, a Wilson success interval, and a bootstrap interval for mean coverage. It measures network generation, synchronizing CUDA if a GPU is used, and computation time for each simulation cycle, including observation during replanning and actuation. It reports the 95th percentile and fraction of cycles fitting within 100 ms; it excludes communication with a physical robot and waiting to maintain the clock. This lesson’s environment is lesson 01’s MuJoCo Push-T, not the paper’s Pymunk; directly comparing published figures would confound policy and simulator.
The evaluator clips the normalized sample to before returning it to physical units. This is a lab decision: it prevents extrapolation beyond observed action minima and maxima, but may also hide that the generator requested a value outside the interval. Record the clipped fraction when investigating that type of failure; do not mistake environment saturation for an intrinsic property of diffusion.
Training saves resumable checkpoints, including EMA. If you create diffusion.pt.pause, it finishes the current update and exits after saving diffusion.pt.resume.pt. Resume with the original training command and --resume: parameters and data hashes are checked and random and optimizer states restored. The resumable file must not be confused with the final checkpoint consumed by the evaluator.
A fair comparison uses the same held-out seeds and episode counts for BC, mixture, ACT, and diffusion; normalization and selection are fitted without inspecting test. Repeat training with several seeds and retain each checkpoint: a binomial interval over episodes from one network does not describe variation across training runs. Negative results also count when the protocol is preserved.
A scene seed fixes simulator reset; a training seed fixes initialization and window sampling; a noise seed fixes a sequence of proposals from the generative policy. These are distinct sources of variation. In this evaluator the noise generator is initialized once per episode from the scene seed and advances at each query. This permits repetition on the same backend, but changing the number of replans also changes which random values the policy consumes.
Pairing scenes allows counting, for example, how many were solved only by diffusion and how many only by a baseline. That contrast retains the shared difficulty of each reset; it does not make two networks that saw different observations or demonstrations equivalent. Nor should the three replicas be multiplied by one hundred and their 300 results treated as independent scenes: the same hundred resets appear in each replica and each network shares its weights across episodes.
The previous lessons’ baselines were trained on 80 episodes and observe privileged vertices, while the previous lesson’s example ACT was trained on 200 and receives images and proprioception. Pairing scenes permits comparing observed results under those protocols, but not attributing a difference to the policy family: data, observation, and selection also change. To isolate a cause, retrain with the same subset, modalities, and budget, and retain the original comparison as a descriptive reference.
In the first replica, all four policies obtained 0 successes in the same 100 scenes; the 95% Wilson interval is 0% to 3.70% for each. Mean final coverage was 5.58% for BC, 2.52% for mixture, 4.24% for ACT, and 3.25% for diffusion. A scene bootstrap gave [3.42%, 7.96%], [1.22%, 4.10%], [2.61%, 6.11%], and [1.68%, 5.06%], respectively. The intervals describe each network and do not capture training variation. The 100-scene summary retains hashes and success pairs; the figure file contains traces for the five scenes shown, chosen by seed order rather than success.
The other two BC and mixture networks also achieved 0/100 on those resets. With training seeds 1 and 2, BC had mean coverage 3.08% [1.53%, 4.88%] and 2.49% [1.04%, 4.18%]; mixture achieved 2.87% [1.43%, 4.60%] and 1.83% [0.72%, 3.20%]. Intervals are 95% bootstrap with 10,000 scene resamples; consult the summaries for seed 1 and seed 2. For ACT only replica 0 is available here, repeated as a reference in both summaries; no unmeasured seed variation is presented.
The three diffusion replicas completed 10,000 updates and were evaluated on CPU with ten DDIM steps and execution of eight actions. Each row corresponds to a different network evaluated on the same hundred resets; the coverage interval resamples scenes 2000 times.
| Seed | Successes (95% Wilson) | Mean coverage (95% bootstrap) | DDIM, median |
|---|---|---|---|
| 0 | 0/100 (0 to 3.70%) | 3.25% (1.66 to 5.06%) | 29.37 ms |
| 1 | 0/100 (0 to 3.70%) | 5.54% (3.67 to 7.61%) | 20.61 ms |
| 2 | 0/100 (0 to 3.70%) | 5.04% (3.14 to 7.15%) | 18.81 ms |
The replica summary retains hashes and times, and the complete evaluations include each trajectory. The simulated cycle’s 95th percentile was 34.72, 24.13, and 21.89 ms, respectively. These are CPU measurements under different shared loads; they do not prove a speed difference between networks or include physical communication. Nor do they imply every replanning cycle meets 100 ms. Supervised noise loss fell during training, but no replica reached the success threshold on these scenes: that result limits this particular recipe and does not demonstrate that all diffusion policies fail on Push-T.
Exercises
import numpy as np
class FiLMResidualBlock1D:
def __init__(self, kernel, bias, cond_projection):
pass
def __call__(self, x, cond):
passDiffusion models conditioned sequences through a noise-prediction task. DDIM turns initial noise into a sample and the receding horizon trades off coherence, reactivity, and computation. The useful result is a deployed and measured policy, not just low loss.