Lesson 5.6 — Conditional Generation & Guidance
Previous lesson · 5.5 Flow Matching · Course overview · Next lesson · 6.1 Large Language Models and Model Adaptation
Conditional Distributions and Multiple Valid Paths
A condition can describe the observation, goal, or obstacles. With a multimodal response, squared-error regression produces the conditional mean. In a path-planning example, averaging an upper detour and a lower detour can put the mean path through the obstacle.

The solid lines are the two mode centers for a symmetric scene. Take the midpoint in execution time on both routes. One position lies above the obstacle and the other lies equally far below it. Their average sits at its center. The same averaging at every execution time gives the dashed path. It minimizes average squared position error here, yet it crosses the obstacle.
A conditional generator can use a fresh noise draw to choose a coherent route for the whole path. Averaging the y-coordinates independently at each waypoint loses that route choice. The formulas below define the synthetic demonstrations, including their variations around each mode.
The teaching example uses a start at , endpoint at , and a circular obstacle at with combined radius 0.65. Two coefficients govern the shape of the continuous path.
The mode sign is equally likely to be positive or negative, with independent standard Gaussian noise in the coefficient formula. The sine functions vanish at both endpoints, so endpoint agreement is guaranteed by the parameterization. Gaussian perturbations can still produce reference paths that intersect an obstacle.
Move the obstacle and inspect both families of routes
Conditional Distribution Explorer
Concatenation, FiLM, and Cross-attention
Concatenation appends a condition vector to the features. FiLM computes condition-dependent scales and offsets for each feature channel, which can be shared across tokens. Cross-attention lets each action token read its own combination of observation tokens.
After splitting into heads and transposing, the queries have shape and keys and values have shape . Attention scores have shape . Take softmax over the observation tokens and mask any padding. Queries come from the action stream, and keys and values come from the observations. The lab uses fixed projections to show the mechanics.
Conditioning Mechanism Inspector
Time Encoding and Missing Conditions
The generation network needs the current noise or interpolation time. A sinusoidal embedding encodes that scalar with multiple frequencies. A task condition can enter through a separate projection. The generation clock and the action index describe different axes of the problem.
A zero-valued condition can be valid. An explicit presence flag lets the network distinguish it from a missing condition. The teaching model appends this flag and randomly omits the condition in roughly 15% of training examples.
Inspect time features and the explicit condition-presence flag
Time & Condition Embedding
Classifier Guidance
Take the spatial gradient of Bayes' rule at a fixed noise level. The marginal probability of the label is constant with respect to the noisy coordinate. The conditional score is the unconditional score plus the gradient of the noisy classifier's log-probability for the label.
A classifier must predict from inputs at the noise levels used by the sampler. At weight one, ideal scores and classifier gradients recover the conditional score. Increasing the weight amplifies the classifier's local influence. It can change the implied distribution across time. In the analytical example, the classifier gradient for one mixture component equals that component's score minus the mixture score.
Classifier Guidance Vector Field
Classifier-free Guidance
Train one network with a combination of present and dropped conditions. At generation time, evaluate the same point and time with the two condition flags. Interpolate or extrapolate along the difference between the two predictions.
Picture two predictions made at the same noisy state and generation time. Draw their arrows from a common origin. The displacement from the unconditional tip to the conditional tip is the effect of supplying the condition at this state. The slider moves the guided tip along that line. One copy of the displacement reaches the conditional prediction. A second copy carries it beyond. These arrows live in prediction space. The resulting route emerges only after the sampler updates its state and evaluates the network again.
This lesson sets for the unconditional prediction and for the ordinary conditional prediction. Values above one extrapolate. The original alternative convention uses with . At the same time, conversion from noise to score multiplies both predictions by the same factor. A similar combination can guide learned flow velocities, as used in the experiment. Extrapolation can favor one mode, amplify prediction errors, or make trajectories more sensitive to integration.
Classifier-free Guidance Explorer
Conditional U-Net, DiT, and Latent Diffusion
A U-Net combines multiscale processing with connections that carry spatial detail into the decoder. Conditional signals can enter residual blocks or cross-attention. A diffusion transformer embeds noisy patches or action tokens into a sequence. Its adaptive normalization can condition the scale, offset, and residual gate on time and an observation or label.
With a zero gate the initial residual block acts as the identity. Attention and feedforward branches can have their own modulation parameters. Latent diffusion applies the generative model to autoencoder latents and decodes afterward. The architecture lab traces tensor shapes and modulation, while the experiment trains small MLPs.
Conditional DiT Shape Inspector
| Stage | Shape |
|---|---|
| Action tokens | (B, H, 2) |
Conditional Flow Matching and Action Chunks
For a fixed task condition, pair a Gaussian draw with a demonstrated action chunk and interpolate. Train on the sampled velocity target. At generation, integrate from noise to data while holding the condition fixed.
An action chunk has shape . Its generation-time velocity belongs to the space of entire chunks. In the example, two generated coefficients determine a path sampled into 20 position increments. Those increments describe ideal geometric displacements. Physical execution also depends on tracking, dynamics, and the constraints of the robot.
Action Chunk Generation
Engineering Experiment · Multimodal Path Generation
All three networks are 9–24–24–2 tanh MLPs with 890 parameters. Inputs contain two noisy coefficients, one time value, two path features, three condition components, and one presence flag. Direct regression zeroes the first five features. DDPM predicts noise under a 40-step linear schedule from 0.005 to 0.25. Flow matching predicts the displacement under linear interpolation.
Each model starts from the same initialization and trains on 512 demonstrations with batches of 32. Default settings use seed 3, 1000 Adam updates, and learning rate 0.005. Validation uses 256 independent conditions. Regression, noise regression, and velocity regression target different quantities.
For each validation condition, generate one path and measure obstacle distance at 101 equally spaced path points. A path counts as colliding when its sampled minimum distance is below 0.65. The safe upper and lower fractions count the paths that pass this discrete check and have a midpoint above or below the obstacle. Between samples the distance can be smaller, so the measurement is a discrete geometric diagnostic. The interactive plot uses one additional condition with multiple initial noise draws.
DDPM uses 40 stochastic reverse updates, and flow matching uses 40 Euler steps. The browser sampler uses only the needed branch at or , giving 40 network evaluations. Extrapolation uses both branches and 80 evaluations. The PyTorch reference evaluates both branches at . Direct regression uses one evaluation.
Live Conditional Generation Training
PyTorch benchmark on the default split
| Model | w | Collision fraction | Safe upper | Safe lower | Mean minimum distance |
|---|---|---|---|---|---|
| reg | 1 | 1.0000 | 0.0000 | 0.0000 | 0.0796 |
| ddpm | 0 | 0.1289 | 0.4805 | 0.3906 | 1.0338 |
| ddpm | 1 | 0.0508 | 0.4570 | 0.4922 | 1.0382 |
| ddpm | 2 | 0.0156 | 0.3984 | 0.5859 | 1.0823 |
| ddpm | 3 | 0.0156 | 0.3555 | 0.6289 | 1.1241 |
| ddpm | 4 | 0.0156 | 0.2891 | 0.6953 | 1.1616 |
| fm | 0 | 0.1328 | 0.4062 | 0.4609 | 1.0385 |
| fm | 1 | 0.0469 | 0.3867 | 0.5664 | 1.0239 |
| fm | 2 | 0.0195 | 0.3633 | 0.6172 | 1.0425 |
| fm | 3 | 0.0195 | 0.3438 | 0.6367 | 1.0508 |
| fm | 4 | 0.0312 | 0.3086 | 0.6602 | 1.0684 |
In this synthetic run, direct regression crosses the obstacle in every evaluation path. The measured fractions are 5.08% for DDPM and 4.69% for flow matching at weight one. Weight two reduces the fractions on this split and shifts the upper/lower balance. With flow matching, weight four increases the fraction again. The experiment shows a trade-off between this particular geometric metric and mode balance within the teaching environment.
Reproducible PyTorch implementation
The script trains all three CPU float64 models, samples guided paths, and evaluates the discrete obstacle distances. Compare guidance weights with fixed conditions and noise to keep conditions and random draws from confounding the visual comparison.
import math,torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
def rng(seed):
def r():
nonlocal seed
seed=(1664525*seed+1013904223)&0xffffffff;return seed/4294967296
return r
def normal(r):return math.sqrt(-2*math.log(max(r(),1e-15)))*math.cos(2*math.pi*r())
def data(seed,n):
r=rng(seed);C=[];Y=[]
for i in range(n):
c=[.8*(r()-.5) for _ in range(3)];m=1 if r()<.5 else -1
C.append(c);Y.append([c[2]-(c[0]+c[1])/2+m*1.15+.12*normal(r),.12*normal(r)])
return torch.tensor(C),torch.tensor(Y)
T=40;beta=torch.linspace(.005,.25,T);alpha=1-beta;ab=torch.cat([torch.ones(1),alpha.cumprod(0)])
def batch(r,D,kind,n=32,drop=.15):
C,Y=D;idx=[int(r()*len(C)) for _ in range(n)];c=C[idx];y=Y[idx];t=torch.tensor([r() for _ in range(n)]);z=torch.tensor([[normal(r),normal(r)] for _ in range(n)]);mask=torch.tensor([float(r()>=drop or kind=='reg') for _ in range(n)])[:,None]
if kind=='fm':a=t;b=1-t;x=b[:,None]*z+a[:,None]*y;target=y-z
elif kind=='ddpm':k=(t*T).long()+1;t=k/T;a=ab[k].sqrt();b=(1-ab[k]).sqrt();x=a[:,None]*y+b[:,None]*z;target=z
else:t=torch.zeros_like(t);a=t;b=t;x=torch.zeros_like(y);target=y
return torch.cat([x,t[:,None],a[:,None],b[:,None],c*mask,mask],1),target
class Net(nn.Module):
def __init__(self,r):
super().__init__();self.layers=nn.ModuleList()
for ni,no in [(9,24),(24,24),(24,2)]:
l=nn.Linear(ni,no);l.weight.data.copy_(torch.tensor([.8*(r()-.5) for _ in range(ni*no)]).reshape(no,ni));l.bias.data.zero_();self.layers.append(l)
def forward(self,x):return self.layers[2](self.layers[1](self.layers[0](x).tanh()).tanh())
def flat(self):return torch.cat([p.flatten() for p in self.parameters()]).tolist()
@torch.no_grad()
def sample(m,kind,c,z,w=1,seed=900):
x=z.clone();n=len(x);r=rng(seed)
def pred(x,t,a,b):
q=torch.cat([x,torch.tensor([t,a,b]).expand(n,3),c,torch.ones(n,1)],1);p=m(q)
if w==1:return p
q[:,5:]=0;u=m(q);return u+w*(p-u)
if kind=='reg':return pred(torch.zeros_like(x),0,0,0)
for i in range(T):
if kind=='fm':t=i/T;x=x+pred(x,t,t,1-t)/T
else:
k=T-i;a=ab[k].sqrt().item();b=(1-ab[k]).sqrt().item();eps=pred(x,k/T,a,b);x=(x-beta[k-1]/b*eps)/alpha[k-1].sqrt()
if k>1:x=x+(beta[k-1]*(1-ab[k-1])/(1-ab[k])).sqrt()*torch.tensor([[normal(r),normal(r)] for _ in range(n)])
return x
def metrics(c,y):
s=torch.linspace(0,1,101);x=-2+4*s;v=c[:,0,None]*(1-s)+c[:,1,None]*s+y[:,0,None]*torch.sin(math.pi*s)+y[:,1,None]*torch.sin(2*math.pi*s);d=(x.square()+(v-c[:,2,None]).square()).sqrt().min(1).values;side=y[:,0]+(c[:,0]+c[:,1])/2-c[:,2];return dict(collision=(d<.65).double().mean().item(),upper=(side>0).double().mean().item(),safe_upper=((d>=.65)&(side>0)).double().mean().item(),safe_lower=((d>=.65)&(side<=0)).double().mean().item(),mean_clearance=d.mean().item(),goal_error=(v[:,-1]-c[:,1]).abs().mean().item())
def run(seed=3,steps=1000,lr=.005):
tr=data(seed,512);va=data(seed+1000,256);r=rng(seed+2000);z=torch.tensor([[normal(r),normal(r)] for _ in range(256)]);out={}
for kind in ['reg','ddpm','fm']:
m=Net(rng(seed+3000));opt=torch.optim.Adam(m.parameters(),lr=lr);r=rng(seed+4000);X,Y=batch(rng(seed+5000),va,kind,256,0);h=[]
for i in range(steps+1):
if i%100==0 or i==steps:
with torch.no_grad():h.append(dict(i=i,loss=(m(X)-Y).square().mean().item(),p=m.flat()))
if i==steps:break
x,y=batch(r,tr,kind);opt.zero_grad();(m(x)-y).square().mean().backward();opt.step()
out[kind]={'hist':h,'metrics':{str(w):metrics(va[0],sample(m,kind,va[0],z,w,seed+6000)) for w in ([1] if kind=='reg' else [0,1,2,3,4])}}
out['data']=metrics(*va);return out
if __name__=='__main__':
import json
a=run();print(json.dumps({k:({ 'initial':v['hist'][0]['loss'],'final':v['hist'][-1]['loss'],'metrics':v['metrics']} if k!='data' else v) for k,v in a.items()},indent=2));open('/tmp/result0506.json','w').write(json.dumps(a))
References and Chapter Synthesis
- Ho and Salimans combine conditional and unconditional predictions. Classifier-Free Diffusion Guidance
- Dhariwal and Nichol develop diffusion classifier guidance. Diffusion Models Beat GANs on Image Synthesis
- Perez et al. introduce feature-wise affine conditioning. FiLM
- Rombach et al. describe generation in compressed latent space. Latent Diffusion Models
- Peebles and Xie describe diffusion transformers and adaptive layer normalization. DiT
- Lipman et al. derive the conditional flow matching objective. Flow Matching for Generative Modeling
- The chapter's continuous-time modeling and action-generation examples build on these references. MIT 6.S184 · π₀
What each generator needs at sampling time
| Method | What training supplies | How a fresh sample is produced |
|---|---|---|
| VAE | An observation for the encoder and reconstruction term, plus a prior penalty | Draw a latent from the prior, then draw from the decoder distribution. |
| GAN | Real and generated examples for the discriminator | Send a fresh noise draw through the generator. The discriminator can be set aside. |
| Normalizing flow | Observations whose density can be evaluated through the inverse and its Jacobian | Send a base draw through the invertible map in the generation direction. |
| DDPM | A clean example and a known noise draw at a sampled time | Repeatedly predict noise and use it to form a reverse transition. |
| Score model | A noisy example and the conditional score of its known perturbation | Use the learned marginal score in a reverse SDE or probability-flow ODE. |
| Flow matching | Two endpoints, an intermediate point, and the velocity of its training path | Evaluate the learned velocity at successive positions while integrating from noise to data. |
Conditioning can enter any of these families. In the guidance experiment the scene stays fixed while one noise draw evolves into the coefficients of one path. Chapter 6 extends this distinction between observed context and generated action to learned policies.
Previous lesson · 5.5 Flow Matching · Course overview · Next lesson · 6.1 Large Language Models and Model Adaptation