Looking for the lab runner…

Hands-on lab 10 of 10 · Flow matching

Flow matching for multimodal action chunks (pi0-style action head)

A VLA such as pi0 outputs a CHUNK of H future actions at once, and it generates the chunk with flow matching: start from Gaussian noise and follow a learned velocity field for ~10 Euler steps. You implement the interpolation path, the velocity target, the loss, the training loop, the Euler sampler, and the two chunk utilities (cutting demonstrations into chunks, and executing chunks with re-planning). Then you train a tiny velocity MLP on demonstrations with TWO valid behaviours (pass an obstacle on the left or on the right) and check that samples land on one of the two modes, not on their average (which would drive into the obstacle).

Time: 45-60 minCheck: python labs/check.py 10The training step takes about 5-20 s on a CPU.

The maths, step by step (this guide's convention)

a: an action chunk [H, d_a] from the data (H actions of d_a numbers); eps ~ N(0, I) of the same shape; t in [0, 1]: t = 0 is pure noise, t = 1 is data.

  1. 1
    Path (straight line between noise and data):
    x_t = (1 - t) * eps + t * a
  2. 2
    Velocity along the path (constant in t):
    v = d x_t / dt = a - eps
  3. 3
    Loss: t ~ Uniform(0, 1) per sample (pi0 uses a Beta distribution that

    favours noisy t; uniform is fine here):

    L = || v_theta(x_t, t) - (a - eps) ||^2

    The network sees only x_t and t, so it learns the AVERAGE of a - eps over all (eps, a) pairs that pass through x_t: a velocity field whose flow carries the noise distribution onto the data distribution.

  4. 4
    Sampling with Euler, K steps (n_steps in the code), dt = 1 / K:
    x = eps;  for i = 0 .. K-1:  t_i = i / K;  x = x + v_theta(x, t_i) * dt
    After the last step x is a sample at t = 1.
  5. 5

    Chunks: a demonstration of T_demo steps gives T_demo - H + 1 training chunks (sliding windows). At run time the policy predicts a chunk, the robot executes the first n_exec actions, then the policy is called again.

(openpi's code writes the same ODE backwards: x_t = t eps + (1 - t) a,
t from 1 to 0. Same model, same samples, mirrored time.)

Read alongside

How to work on this page

  1. Write each function in its cell, in order. The hints open one at a time: try Hint 1 first.
  2. ▶ Run (Ctrl/⌘+Enter) defines the cell in this lab's Python process; variables persist between cells, as in a notebook. Try your functions in the scratch cell at the bottom.
  3. ✓ Run checks saves the file and runs python labs/check.py 10: each step turns from TODO to PASS. A FAIL shows what was expected.
  4. Save (Ctrl/⌘+S) writes all cells to labs/lab10_flow_matching.py (the previous version is kept in labs/.backup/), so you can also continue in any editor. After ↺ Reset kernel, press ▶ Run all.

Editor keys: Tab / Shift+Tab indent and dedent by 4 spaces, Enter keeps the indentation, Shift+Enter runs the cell and moves to the next one.

Cells on this page:

0 Imports

Imports

run first

The lab file's imports. Run this cell first (or press Run all).

1 path, target and loss

interpolate(noise, actions, t)

to write

x_t = (1 - t) * noise + t * actions.

noise, actions: [B, H, d_a]; t: [B] floats in [0, 1] (one time per sample).

Hint 1
reshape t to [B, 1, 1] so it broadcasts over the chunk.
Hint 2
t = t.view(-1, *([1] * (actions.dim() - 1)))

velocity_target(noise, actions)

to write

v = d x_t / dt = actions - noise.

Hint 1
differentiate x_t = (1 - t) * noise + t * actions with respect to t.

flow_matching_loss(model, actions, noise, t)

to write

Scalar MSE between model(x_t, t) and the velocity target.

Hint 1
x_t = interpolate(noise, actions, t); return F.mse_loss(model(x_t, t), velocity_target(...))

G Given: the velocity network and the demonstration data

time_embedding(t, dim=32, max_period=1000.0)

given

Sinusoidal embedding of continuous t in [0, 1]: [B] → [B, dim].

Show the given code (it is already written: just run it)

class VelocityMLP(nn.Module)

given

v_theta(x_t, t) for a whole chunk: flatten [H, d_a], concatenate a time embedding, MLP.

Show the given code (it is already written: just run it)

mode_chunks(horizon=8)

given

The two clean behaviours, [2, H, 2]: velocity (vx, vy) per step. vx = 1 (drive forward); vy = +/- a smooth bump (swerve left or right around an obstacle).

Show the given code (it is already written: just run it)

make_demo_chunks(n, generator=None, horizon=8, std=0.05)

given

n demonstration chunks [n, H, 2]: half swerve left, half right, plus small noise.

Show the given code (it is already written: just run it)

2 training loop

train_flow_matching(model, chunks, steps=2000, batch_size=256, lr=0.001, seed=0)

to write

Train with flow_matching_loss on random minibatches of chunks [N, H, d_a].

Each step: batch_size random chunks, noise ~ N(0, I) of the same shape, t ~ Uniform(0, 1) [batch_size], Adam update. Use a torch.Generator seeded with seed for the random draws. Returns the per-step losses (floats).

Hint 1
the same loop as lab 06's train_denoiser, with continuous t: t = torch.rand(batch_size, generator=g)
Hint 2
a = chunks[torch.randint(0, len(chunks), (batch_size,), generator=g)] noise = torch.randn(a.shape, generator=g)

3 Euler sampling

euler_sample(model, noise, n_steps=10)

to write

Integrate dx/dt = model(x, t) from t = 0 (noise [B, H, d_a]) to t = 1.

Step i (i = 0 .. n_steps - 1) evaluates the model at t_i = i / n_steps, passed as a float tensor [B], and moves x by velocity * (1 / n_steps).

Hint 1
x = noise; dt = 1.0 / n_steps; loop i over range(n_steps).
Hint 2
t = torch.full((x.shape[0],), i * dt); x = x + model(x, t) * dt (never evaluate at t = 1: some exact velocity fields divide by 1 - t.)

4 action chunks

chunk_trajectory(traj, horizon, stride=1)

to write

Sliding windows of a demonstration: traj [T_demo, d_a] → [num_chunks, horizon, d_a].

Window c starts at step c * stride; num_chunks = (T_demo - horizon) // stride + 1.

Hint 1
a loop with torch.stack works; Tensor.unfold does it in one call.
Hint 2
traj.unfold(0, horizon, stride) is [num_chunks, d_a, horizon]; transpose the last two.

rollout_chunks(policy, n_actions, n_exec)

to write

Receding-horizon execution.

policy(step) returns a chunk [H, d_a] planned at time step (the number of actions executed so far). Execute its first n_exec actions (fewer at the very end), then call the policy again, until n_actions actions are executed. Returns (actions [n_actions, d_a], call_steps: list of the step values passed to the policy).

Hint 1
step = 0; while step < n_actions: chunk = policy(step); take chunk[:min(n_exec, n_actions - step)]; step += that many.
Hint 2
collect the pieces in a list and torch.cat them at the end.

✎ Scratch cell

Experiment here: print shapes, call your functions on small inputs. This cell runs in the same Python process as the cells above, is not part of Run all and is not saved to the lab file (your browser keeps it).