Module contents
Stage 7 of 9Research 120 min

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

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.

InteractiveTwo modes under noise
  • Noisy sequence
  • Exact posterior mean
0.24
2
Posterior probability of upper mode0.411
Generated modeupper
Change the seed and signal fraction. With strong noise the posterior mean can fall between modes; with enough signal it approaches one of them. This is an analytic model, not a trajectory generated by the robot.

In the figure’s model, a0=Sf\vb{a}_0=S\vb{f}, where SS takes values −1-1 and +1+1 with equal probability and fi=sin⁡(πi/15)f_i=\sin(\pi i/15). We observe an=αˉa0+1−αˉϵ\vb{a}_n=\sqrt{\bar\alpha}\vb{a}_0+\sqrt{1-\bar\alpha}\vb{\epsilon}, with ϵ∼N(0,I)\vb{\epsilon}\sim\Normal(\vb{0},\mat{I}). Gaussian likelihoods give

E[S∣an]=tanh⁡ ⁣(αˉ ⟨an,f⟩1−αˉ).\E[S\mid\vb{a}_n]=\tanh\!\left(\frac{\sqrt{\bar\alpha}\,\inner{\vb{a}_n}{\vb{f}}}{1-\bar\alpha}\right).

The blue curve is that expectation multiplied by f\vb{f}. 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 1−αˉ1-\bar\alpha. When their logarithms are subtracted, terms ∥an∥2\norm{\vb{a}_n}^2 and αˉ∥f∥2\bar\alpha\norm{\vb{f}}^2 cancel, and the log posterior odds are 2αˉ⟨an,f⟩/(1−αˉ)2\sqrt{\bar\alpha}\inner{\vb{a}_n}{\vb{f}}/(1-\bar\alpha). 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 A0∈RH×da\mat{A}_0\in\R^{H\times d_a} be a window of normalized actions and oo the observation. The forward diffusion process produces

An=αˉnA0+1−αˉnϵ,ϵ∼N(0,I).\mat{A}_n=\sqrt{\bar\alpha_n}\mat{A}_0+\sqrt{1-\bar\alpha_n}\mat{\epsilon}, \qquad \mat{\epsilon}\sim\Normal(\mat{0},\mat{I}).

Sample an index nn and fresh noise per example, and minimize squared error between that noise and ϵθ(An,n,o)\epsilon_\theta(\mat{A}_n,n,o). Here squared error applies to noise conditioned on a noisy sequence, not all valid actions given only oo. 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 0<αˉn<10<\bar\alpha_n<1, the optimal noise predictor under squared loss is E[ϵ∣An,o]\E[\mat{\epsilon}\mid\mat{A}_n,o]. Moreover, if differentiation is allowed under the integral mixing the forward-process Gaussians,

∇Anlog⁡pn(An∣o)=−E[ϵ∣An,o]1−αˉn.\nabla_{\mat{A}_n}\log p_n(\mat{A}_n\mid o) =-\frac{\E[\mat{\epsilon}\mid\mat{A}_n,o]}{\sqrt{1-\bar\alpha_n}}.

The identity follows by differentiating the Gaussian density of An\mat{A}_n given A0\mat{A}_0: its logarithmic gradient is −(An−αˉnA0)/(1−αˉn)-(\mat{A}_n-\sqrt{\bar\alpha_n}\mat{A}_0)/(1-\bar\alpha_n). Averaging over the posterior of A0\mat{A}_0 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 ϵ\epsilon and the sampler interprets the same output as ϵ\epsilon. The αˉ\bar\alpha 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 η=0\eta=0, first estimate

A^0=An−1−αˉn ϵθ(An,n,o)αˉn.\widehat{\mat{A}}_0=\frac{\mat{A}_n-\sqrt{1-\bar\alpha_n}\,\epsilon_\theta(\mat{A}_n,n,o)}{\sqrt{\bar\alpha_n}}.

For the next lower index jj, compute Aj=αˉjA^0+1−αˉjϵθ\mat{A}_j=\sqrt{\bar\alpha_j}\widehat{\mat{A}}_0+\sqrt{1-\bar\alpha_j}\epsilon_\theta. On the last step use αˉ=1\bar\alpha=1. 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.

[ ]Ten DDIM steps with known noiseBrowser
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-9

The 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.

InteractiveReal proposals during DDIM
  • Target
  • Object
  • Proposed actions
  • Pusher
0
StageInitial noise
Action targets16
Clipped components25.0 %
Initial scene 20000 and a diffusion checkpoint trained with seed 0; proposals after each of ten DDIM steps are shown, projected to the action range. These are network proposals, not positions actually traversed by the robot.

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 [−1,1][-1,1]. 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 2.43×10−72.43\times10^{-7}: 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 BB sequences, input has shape (B,H,da)(B,H,d_a). 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 dad_a 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 (B,H,da)(B,H,d_a). The network does not see the exact object in privileged state: it receives only the camera and pusher position.

The cosine schedule constructs decreasing αˉn\bar\alpha_n, with bounded increments to avoid division by zero at the final level. EMA maintains another copy of the weights and updates it as θEMA←λθEMA+(1−λ)θ\theta_{\mathrm{EMA}}\leftarrow\lambda\theta_{\mathrm{EMA}}+(1-\lambda)\theta. 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 hh as (1+γ(o,n))h+β(o,n)(1+\gamma(o,n))h+\beta(o,n): scale and bias depend on the condition. The 1+1+ 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 (Ho,Hp,Ha)=(1,16,8)(H_o,H_p,H_a)=(1,16,8); it is not equivalent to using eight previous images.

Horizon and reaction time

Receding-horizon control generates HpH_p actions, executes only Ha≤HpH_a\le H_p, and observes again. HoH_o is the number of observations available for each prediction. A small HaH_a 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 1/0.035≈28.571/0.035\approx28.57 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 Ha=8H_a=8 to Ha=2H_a=2 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 [−1,1][-1,1] 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 [−1,1][-1,1] 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.

InteractiveCompare policies on T pushing
  • Target
  • Object
  • Pusher
0
Coverage17.5 %
Episode outcomeFailure
Recorded rollouts of the four training-seed-0 policies on the first five of 100 held-out scenes. A frame corresponds to state after the action is applied; change policy and seed to compare the same reset.

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.

SeedSuccesses (95% Wilson)Mean coverage (95% bootstrap)DDIM, median
00/100 (0 to 3.70%)3.25% (1.66 to 5.06%)29.37 ms
10/100 (0 to 3.70%)5.54% (3.67 to 7.61%)20.61 ms
20/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

Numeric
Each generation with 10 DDIM steps takes 35 ms. What is the ideal maximum replanning frequency in Hz?
Quiz
Why does squared noise-prediction loss not force actions from every mode to be averaged during generation?
Quiz
For rapidly changing contacts, which decision offers more frequent observations?
Code
Implement FiLMResidualBlock1D. It receives a kernel of shape (output_channels, input_channels, 3), a convolution bias, and a condition-projection matrix of shape (2 × channels, condition_dimensions). When called with x (batch, channels, time) and cond (batch, condition_dimensions), apply temporal convolution with zero padding and preserved length, project cond and split scale and bias, compute ReLU((1 + scale) × convolution + bias), and add x. Use correlation without reversing the kernel.
import numpy as np
class FiLMResidualBlock1D:
  def __init__(self, kernel, bias, cond_projection):
      pass
  def __call__(self, x, cond):
      pass
Shift+Enter to run
Key idea

Diffusion 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.