> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# CVAE, diffusion and flow-matching action heads

> Action heads trained on demonstrations with two valid choices

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/vla/generative-action-heads/index.ipynb)

In [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl.md) the operator had one right answer in every state, and MiniVLA learned it. Human demonstrations often are not like that. Two operators reach around an obstacle on different sides, and one operator picks whichever of two identical objects is closer to hand that day. The demonstrations then hold several correct actions for the same observation, and the policy has to represent them.

In this section the claw machine holds two squares of the named color, and the operator fetches one of them at random. You put six action heads on the same backbone, train them on the same demonstrations, and compare what each does when the two choices pull in opposite directions. Three of the heads are the generative models behind recent robot policies: the conditional VAE of ACT (Zhao et al., 2023), the denoising diffusion of Diffusion Policy (Chi et al., 2023), and flow matching (Lipman et al., 2022).

> [accordion] Code
>
> ```python theme={null}
> import copy
> import time
> import numpy as np
> import torch
> import torch.nn as nn
> import torch.nn.functional as F
> import matplotlib.pyplot as plt
> from cycler import cycler
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
> DEV = "cuda" if torch.cuda.is_available() else "cpu"
> torch.manual_seed(0)
> ```

```output theme={null}
<torch._C.Generator at 0x79636c9afdf0>
```

## Two right answers

The machine is the Newton simulation of the claw machine used throughout this chapter: the squares are rigid boxes under gravity, and a released box falls over a few control steps and can slide. The floor holds two squares, both of the color the instruction names, at least 0.35 apart. The instruction asks for "a" red square, and delivering either square earns reward 1. With no square of another color, the policy never has to tell colors apart to pick a correct square. Slips are switched off.

The claw starts midway between the two squares, at a random height. The operator decides at the start of each episode which square to fetch, with equal probability, and moves toward it. It aims at the square's center with an error of at most 0.015, so a few of its catches fail and the demonstrations also show the recovery: open, rise one step and try again.

> [accordion] Code
>
> ```python theme={null}
> COLOR_NAMES = ["red", "green", "blue"]
> COLOR_RGB = np.array([[0.835, 0.369, 0.0], [0.0, 0.62, 0.451], [0.0, 0.447, 0.698]], dtype=np.float32)
> TEMPLATES = ["grab a {} square", "get a {} one", "pick up a {} block"]
> VOCAB = ["<pad>"] + sorted({w for t in TEMPLATES for w in t.format("x").split() if w != "x"} | set(COLOR_NAMES))
> WORD_ID = {w: i for i, w in enumerate(VOCAB)}
> L_TEXT = 5               # instruction length in words, padded
> IMG = 64                 # image side in pixels
> MAX_STEP = 0.05          # largest claw move per step along each axis
> SIDE = 0.08              # side of a square
> CHUTE_X = 0.15           # the chute opening spans 0 <= x < CHUTE_X
> START = np.array([0.07, 0.9], dtype=np.float32)   # the claw's rest position above the chute
> T_MAX = 60               # step limit of an episode
> CATCH_WIDTH = 0.03       # catch probability exp(-(offset / CATCH_WIDTH)^2)
> SLIP_BASE, SLIP_GAIN = 0.002, 0.01   # slip probability per carried step: SLIP_BASE + SLIP_GAIN (offset / 0.02)^2
> N_SQ = 2                 # squares on the floor, both of the named color
> MIN_GAP = 0.35           # smallest distance between the two squares
>
>
> def tokenize(color_idx, template_idx):
>     """Word ids of one instruction, padded with 0 to L_TEXT words."""
>     words = TEMPLATES[template_idx].format(COLOR_NAMES[color_idx]).split()
>     return [WORD_ID[w] for w in words] + [0] * (L_TEXT - len(words))
>
>
> TEXT_TABLE = np.array([[tokenize(c, t) for t in range(len(TEMPLATES))] for c in range(3)])
> ```
>
> ```python theme={null}
> import warp as wp
> import newton
>
> wp.config.log_level = wp.LOG_WARNING
> wp.config.quiet = True
>
> CONTROL_DT = 0.1          # seconds of physics per control step
> SUBSTEPS = 16             # physics substeps per control step (even, so the double buffer ends where it started)
> HALF = SIDE / 2
>
>
> def render_torch(sq, claw, closed, device):
>     """Front-view images (n, 3, IMG, IMG) of machines, drawn on the GPU from square and claw positions.
>
>     Args:
>         sq: (n, 3, 2) bottom-centers of the squares; x < 0 means the square is gone.
>         claw: (n, 2) claw tip positions.
>         closed: (n,) bool, claw closed.
>     """
>     sq = torch.as_tensor(sq, device=device, dtype=torch.float32)
>     claw = torch.as_tensor(claw, device=device, dtype=torch.float32)
>     closed = torch.as_tensor(closed, device=device)
>     n = len(claw)
>     c = (torch.arange(IMG, device=device, dtype=torch.float32) + 0.5) / IMG
>     gx = c[None, None, :]                     # (1, 1, IMG) columns
>     gz = (1 - c)[None, :, None]               # (1, IMG, 1) rows, z up
>     img = torch.full((n, 3, IMG, IMG), 0.86, device=device)
>     img[:, :, (gz < 0.02).expand(1, IMG, IMG)[0]] = 0.55
>     chute = ((gx < CHUTE_X) & (gz < 0.12)).expand(1, IMG, IMG)[0]
>     img[:, :, chute] = 0.3
>     rgb = torch.as_tensor(COLOR_RGB, device=device)
>     for k in range(3):
>         x = sq[:, k, 0, None, None]; z = sq[:, k, 1, None, None]
>         m = (torch.abs(gx - x) < HALF) & (gz >= z) & (gz < z + SIDE)          # (n, IMG, IMG)
>         img = torch.where(m[:, None], rgb[k][None, :, None, None], img)
>     x = claw[:, 0, None, None]; z = claw[:, 1, None, None]
>     px = 1.0 / IMG
>     cable = (torch.abs(gx - x) < 0.6 * px) & (gz > z + 0.05)
>     body = (torch.abs(gx - x) < 4 * px) & (gz > z + 0.035) & (gz <= z + 0.05)
>     spread = torch.where(closed, 2.0, 4.0)[:, None, None] * px
>     prongs = (torch.abs(torch.abs(gx - x) - spread) < 0.6 * px) & (gz > z) & (gz <= z + 0.05)
>     m = cable | body | prongs
>     return torch.where(m[:, None], torch.tensor(0.12, device=device), img)
>
>
> class NewtonClawGrab:
>     """ClawGrab with Newton physics: a batch of n claw machines as parallel worlds on the GPU.
>
>     The three squares are rigid boxes (side SIDE) with gravity and contact against the floor and
>     each other. The claw is a kinematic point moved by the gantry. Grasping keeps the stochastic
>     rule of ClawGrab: a caught box is switched to a kinematic body that follows the claw, and on
>     release or slip it becomes dynamic again and falls. A box released over the chute is delivered
>     and removed from the machine. The public attributes and methods match ClawGrab, so the operator,
>     the token helpers and the training code work unchanged.
>
>     Args:
>         n: number of machines.
>         seed: seed of the layout and of the grasp rule.
>         slip: scale of the slip probability.
>         random_start: start the claw at a random position above the squares.
>         as_torch: observe() returns a CUDA tensor instead of a numpy array.
>     """
>
>     def __init__(self, n, seed=0, slip=1.0, random_start=False, as_torch=False):
>         self.n, self.rng, self.slip, self.random_start, self.as_torch = n, np.random.default_rng(seed), slip, random_start, as_torch
>         self.device = "cuda" if torch.cuda.is_available() else "cpu"
>         world = newton.ModelBuilder()
>         box = newton.ModelBuilder.ShapeConfig(density=200.0, mu=0.6)
>         for k in range(3):
>             b = world.add_body(xform=wp.transform(p=wp.vec3(0.3 + 0.2 * k, 0.0, HALF), q=wp.quat_identity()), label=f"square{k}")
>             world.add_shape_box(b, hx=HALF, hy=HALF, hz=HALF, cfg=box)
>         builder = newton.ModelBuilder()
>         builder.replicate(world, n)
>         builder.add_ground_plane(cfg=newton.ModelBuilder.ShapeConfig(mu=0.6))
>         self.model = builder.finalize(device=self.device)
>         self.solver = newton.solvers.SolverXPBD(self.model, iterations=4)
>         self.state, self.next_state = self.model.state(), self.model.state()
>         self.control = self.model.control()
>         self.collision = newton.CollisionPipeline(self.model, rigid_contact_max=48 * n)
>         self.contacts = self.collision.contacts()
>         self.flags = np.full(3 * n, int(newton.BodyFlags.DYNAMIC), np.int32)
>         self.graph = None
>         self.claw = np.zeros((n, 2), np.float32)
>         self.closed = np.zeros(n, bool)
>         self.held = np.full(n, -1)
>         self.gone = np.zeros((n, 3), bool)               # delivered squares, removed from the machine
>         self.offset = np.zeros(n, np.float32)
>         self.target = np.zeros(n, int)
>         self.template = np.zeros(n, int)
>         self.t = np.zeros(n, int)
>         self.misses = np.zeros(n, int)
>         self.slips = np.zeros(n, int)
>         self.drops = np.zeros(n, int)
>         self.wrong = np.zeros(n, bool)
>         self.sq = np.zeros((n, 3, 2), np.float32)
>         self._q = self.state.body_q.numpy().reshape(n, 3, 7)
>         self._touched = np.zeros((n, 3), bool)            # boxes moved by hand this step
>         self.reset(np.ones(n, bool))
>         self._warm = False
>
>     # -- physics plumbing -------------------------------------------------------------------------
>     def _simulate(self):
>         """Advance the physics by CONTROL_DT in SUBSTEPS substeps (captured as a CUDA graph)."""
>         dt = CONTROL_DT / SUBSTEPS
>
>         def advance():
>             for _ in range(SUBSTEPS):
>                 self.state.clear_forces()
>                 self.collision.collide(self.state, self.contacts)
>                 self.solver.step(self.state, self.next_state, self.control, self.contacts, dt)
>                 self.state, self.next_state = self.next_state, self.state
>
>         if self.device != "cuda" or not getattr(self, "_warm", True):
>             self._warm = True                               # first call compiles the kernels outside a capture
>             return advance()
>         if self.graph is None:
>             with wp.ScopedCapture() as capture:
>                 advance()
>             self.graph = capture.graph
>         wp.capture_launch(self.graph)
>
>     def _push(self, flags_changed):
>         """Write the host copy of the box poses to the GPU; zero the velocity of every box moved by hand."""
>         self.state.body_q.assign(self._q.reshape(-1, 7))
>         if self._touched.any():
>             qd = self.state.body_qd.numpy().reshape(self.n, 3, 6)
>             qd[self._touched] = 0.0
>             self.state.body_qd.assign(qd.reshape(-1, 6))
>             self._touched[:] = False
>         if flags_changed:
>             self.model.body_flags.assign(self.flags)
>             self.solver.notify_model_changed(newton.ModelFlags.BODY_PROPERTIES)
>
>     def _pull(self):
>         """Read the box poses from the GPU and update sq (bottom-centers)."""
>         self._q = self.state.body_q.numpy().reshape(self.n, 3, 7)
>         self.sq[..., 0] = np.where(self.gone, -1.0, self._q[..., 0])
>         self.sq[..., 1] = np.where(self.gone, 0.0, self._q[..., 2] - HALF)
>
>     def _set_flag(self, i, k, kinematic):
>         """Mark box k of machine i kinematic or dynamic; returns True if the flag changed."""
>         f = int(newton.BodyFlags.KINEMATIC if kinematic else newton.BodyFlags.DYNAMIC)
>         j = 3 * i + k
>         changed = self.flags[j] != f
>         self.flags[j] = f
>         return changed
>
>     # -- ClawGrab API -----------------------------------------------------------------------------
>     def reset(self, mask):
>         """Start new episodes on the machines selected by the boolean array mask."""
>         self._pull()
>         changed = False
>         for i in np.flatnonzero(mask):
>             while True:
>                 x = self.rng.uniform(0.25, 0.92, 3)
>                 if np.abs(x[:, None] - x[None] + 2 * np.eye(3)).min() > 0.14:
>                     break
>             self._q[i] = 0.0
>             self._q[i, :, 0], self._q[i, :, 2], self._q[i, :, 6] = x, HALF, 1.0
>             for k in range(3):
>                 changed |= self._set_flag(i, k, False)
>             self._touched[i] = True
>         k = mask.sum()
>         self.gone[mask] = False
>         self.claw[mask] = START
>         if self.random_start:
>             self.claw[mask] = self.rng.uniform([0.2, 0.35], [0.95, 0.9], size=(k, 2))
>         self.closed[mask] = False
>         self.held[mask] = -1
>         self.target[mask] = self.rng.integers(3, size=k)
>         self.template[mask] = self.rng.integers(len(TEMPLATES), size=k)
>         for a in (self.t, self.misses, self.slips, self.drops):
>             a[mask] = 0
>         self.wrong[mask] = False
>         self._push(True)
>         self._pull()
>
>     def support(self):
>         """Lowest z the claw tip can reach at its x, and the index of the square under it (-1 for the floor)."""
>         free = (np.arange(3)[None] != self.held[:, None]) & ~self.gone
>         under = free & (np.abs(self.sq[:, :, 0] - self.claw[:, None, 0]) < HALF)
>         top = np.where(under, self.sq[:, :, 1] + SIDE, -1.0)
>         k, z = top.argmax(1), top.max(1)
>         return np.where(z < 0, 0.02, z), np.where(z < 0, -1, k)
>
>     def observe(self):
>         """Camera image and instruction of every machine; the image is drawn on the GPU."""
>         img = render_torch(self.sq, self.claw, self.closed, self.device)
>         if not self.as_torch:
>             img = img.cpu().numpy()
>         return img, TEXT_TABLE[self.target, self.template]
>
>     def goal(self):
>         """Bottom-center of the named square on every machine, shape (n, 2)."""
>         return self.sq[np.arange(self.n), self.target]
>
>     def step(self, action):
>         """Apply (dx, dz, grip) on every machine, then advance the physics by one control step.
>
>         Returns:
>             reward: 1 where the named square was delivered, else 0.
>             done: True where a square was delivered or the step limit was reached.
>         """
>         d = np.clip(action[:, :2], -MAX_STEP, MAX_STEP)
>         close = action[:, 2] > 0.5
>         self.claw[:, 0] = np.clip(self.claw[:, 0] + d[:, 0], 0.03, 0.97)
>         floor, _ = self.support()
>         self.claw[:, 1] = np.clip(self.claw[:, 1] + d[:, 1], floor, 0.95)
>         holding = self.held >= 0
>         # closing an open claw on a square under it may catch the square
>         floor, k = self.support()
>         grab = close & ~self.closed & (k >= 0) & (self.claw[:, 1] - floor < 0.02)
>         g = np.flatnonzero(grab)
>         off = self.claw[g, 0] - self.sq[g, k[g], 0]
>         caught = self.rng.random(len(g)) < np.exp(-(off / CATCH_WIDTH) ** 2)
>         changed = False
>         for i, kk, o in zip(g[caught], k[g[caught]], off[caught]):
>             self.held[i], self.offset[i] = kk, o
>             changed |= self._set_flag(i, kk, True)
>             self._touched[i, kk] = True
>         self.misses[g[~caught]] += 1
>         # opening, or a slip, releases the held square
>         p_slip = self.slip * (SLIP_BASE + SLIP_GAIN * (self.offset / 0.02) ** 2)
>         slipped = holding & close & (self.rng.random(self.n) < p_slip) & (np.abs(d).sum(1) > 0)
>         drop = holding & (~close | slipped)
>         self.slips += slipped
>         delivered = np.zeros(self.n, bool)
>         dropped = self.held.copy()
>         for i in np.flatnonzero(drop):
>             j = self.held[i]
>             if self.claw[i, 0] - self.offset[i] < CHUTE_X:
>                 delivered[i] = True
>                 self.gone[i, j] = True
>                 self._q[i, j, :3] = (-2.0, 0.0, HALF + 0.2 * j)    # parked out of the machine
>                 changed |= self._set_flag(i, j, True)
>             else:
>                 self.drops[i] += ~slipped[i]
>                 changed |= self._set_flag(i, j, False)            # falls under gravity from where it hangs
>             self._touched[i, j] = True
>             self.held[i] = -1
>         # held squares hang from the prongs
>         h = np.flatnonzero(self.held >= 0)
>         self._q[h, self.held[h], 0] = self.claw[h, 0] - self.offset[h]
>         self._q[h, self.held[h], 1] = 0.0
>         self._q[h, self.held[h], 2] = self.claw[h, 1] - HALF
>         self._q[h, self.held[h], 3:] = (0.0, 0.0, 0.0, 1.0)
>         self._touched[h, self.held[h]] = True
>         self._push(changed)
>         self._simulate()
>         self._pull()
>         reward = (delivered & (dropped == self.target)).astype(np.float32)
>         self.wrong |= delivered & (dropped != self.target)
>         self.closed = close
>         self.t += 1
>         return reward, delivered | (self.t >= T_MAX)
> ```
>
> ```python theme={null}
> class TwinClaw(NewtonClawGrab):
>     """The Newton claw machine with two squares of the named color and the claw starting midway between them.
>
>     Boxes 0 and 1 are the two squares, at least MIN_GAP apart; box 2 is parked outside the machine.
>     The claw starts midway between the squares at a random height, so its first move decides which
>     square it goes for. Delivering either square earns reward 1. Slips are off.
>
>     Args:
>         n: number of machines.
>         seed: seed of the layouts and of the grasp outcomes.
>         as_torch: observe() returns a CUDA tensor.
>     """
>
>     def __init__(self, n, seed=0, as_torch=False):
>         self.first_grab = np.zeros(n, int)          # 0: no grab yet, 1: over a square, 2: elsewhere
>         self.catches = np.zeros(n, int)             # catches that succeeded in this episode
>         self.aim = np.full(n, np.nan, np.float32)   # the operator's aiming error for its current attempt
>         super().__init__(n, seed=seed, slip=0.0, as_torch=as_torch)
>
>     def reset(self, mask):
>         """Start new episodes on the machines selected by mask, with the twin layout."""
>         super().reset(mask)
>         changed = False
>         for i in np.flatnonzero(mask):
>             while True:
>                 x = self.rng.uniform(0.25, 0.92, N_SQ)
>                 if abs(x[0] - x[1]) > MIN_GAP:
>                     break
>             self._q[i, :N_SQ, 0] = x
>             self._q[i, 2, :3] = (-2.0, 0.0, 0.6)       # box 2 is parked outside the machine
>             self.gone[i, 2] = True
>             changed |= self._set_flag(i, 2, True)
>             self.claw[i] = (x.mean(), self.rng.uniform(0.5, 0.9))   # midway between the squares
>         self._touched[mask] = True
>         self.first_grab[mask], self.catches[mask], self.aim[mask] = 0, 0, np.nan
>         self._push(True)
>         self._pull()
>
>     def copy_layout(self, block=None):
>         """Repeat layouts: every group of block consecutive machines gets the layout, start and instruction
>         of its first machine (block=None makes one group of all machines)."""
>         block = block or self.n
>         first = np.arange(self.n) // block * block
>         self._q[:] = self._q[first]
>         for a in (self.target, self.template, self.claw):
>             a[:] = a[first]
>         self._touched[:] = True
>         self._push(False)
>         self._pull()
>
>     def observe(self):
>         """Camera image and instruction of every machine; both squares get the named color."""
>         sq = torch.as_tensor(self.sq, device=self.device)
>         claw = torch.as_tensor(self.claw, device=self.device)
>         closed = torch.as_tensor(self.closed, device=self.device)
>         c = (torch.arange(IMG, device=self.device, dtype=torch.float32) + 0.5) / IMG
>         gx, gz = c[None, None, :], (1 - c)[None, :, None]
>         img = torch.full((self.n, 3, IMG, IMG), 0.86, device=self.device)
>         img[:, :, (gz < 0.02).expand(1, IMG, IMG)[0]] = 0.55
>         img[:, :, ((gx < CHUTE_X) & (gz < 0.12)).expand(1, IMG, IMG)[0]] = 0.3
>         rgb = torch.as_tensor(COLOR_RGB, device=self.device)[torch.as_tensor(self.target, device=self.device)]   # (n, 3)
>         for k in range(N_SQ):
>             x, z = sq[:, k, 0, None, None], sq[:, k, 1, None, None]
>             m = (torch.abs(gx - x) < HALF) & (gz >= z) & (gz < z + SIDE)
>             img = torch.where(m[:, None], rgb[:, :, None, None], img)
>         x, z = claw[:, 0, None, None], claw[:, 1, None, None]
>         px = 1.0 / IMG
>         cable = (torch.abs(gx - x) < 0.6 * px) & (gz > z + 0.05)
>         body = (torch.abs(gx - x) < 4 * px) & (gz > z + 0.035) & (gz <= z + 0.05)
>         spread = torch.where(closed, 2.0, 4.0)[:, None, None] * px
>         prongs = (torch.abs(torch.abs(gx - x) - spread) < 0.6 * px) & (gz > z) & (gz <= z + 0.05)
>         img = torch.where((cable | body | prongs)[:, None], torch.tensor(0.12, device=self.device), img)
>         if not self.as_torch:
>             img = img.cpu().numpy()
>         return img, TEXT_TABLE[self.target, self.template]
>
>     def step(self, action):
>         """Step as NewtonClawGrab; reward 1 when either square is delivered, and log the first grab."""
>         start = (action[:, 2] > 0.5) & ~self.closed & (self.held < 0)
>         held_before, gone_before = self.held.copy(), self.gone.copy()
>         _, done = super().step(action)
>         _, k = self.support()
>         over = (k >= 0) | (self.held >= 0)
>         self.first_grab = np.where(start & (self.first_grab == 0), np.where(over, 1, 2), self.first_grab)
>         self.catches += (held_before < 0) & (self.held >= 0)
>         reward = (self.gone & ~gone_before).any(1).astype(np.float32)
>         return reward, done
>
> def operator_action(env, choice, rng, aim_noise=0.015):
>     """Scripted operator: go to square choice[i] (0 or 1 in left-to-right order), grab it, deliver it.
>
>     The operator aims at the square's center with a random error of at most aim_noise, drawn anew
>     for each attempt, so that some catches fail. It descends at full speed until the claw rests on
>     the square, closes, and after a miss opens, rises one step and tries again.
>
>     Args:
>         env: the TwinClaw batch.
>         choice: which of the two named squares each machine's operator fetches.
>         rng: generator of the aiming errors.
>         aim_noise: largest aiming error.
>
>     Returns:
>         float array (n, 3) of actions (dx, dz, grip).
>     """
>     rows = np.arange(env.n)
>     order = np.argsort(env.sq[:, :N_SQ, 0], 1)                  # left to right
>     goal_idx = order[rows, choice]
>     g = env.sq[rows, goal_idx]
>     a = np.zeros((env.n, 3), np.float32)
>     x, z = env.claw[:, 0], env.claw[:, 1]
>     carry = env.held >= 0
>     up = carry & (z < 0.75)
>     a[up, 1] = MAX_STEP
>     move = carry & ~up & (x >= CHUTE_X - 0.05)
>     a[move, 0] = -MAX_STEP
>     a[up | move, 2] = 1                                          # over the chute the grip opens
>     missed = ~carry & env.closed
>     a[missed, 1] = MAX_STEP
>     env.aim[missed | carry] = np.nan
>     ready = ~carry & ~env.closed
>     new = ready & np.isnan(env.aim)
>     env.aim[new] = rng.uniform(-aim_noise, aim_noise, new.sum())
>     tx = g[:, 0] + env.aim
>     far = ready & (np.abs(tx - x) > 0.01)
>     a[far, 0] = np.clip(tx - x, -MAX_STEP, MAX_STEP)[far]
>     a[far, 1] = np.clip(0.6 - z, -MAX_STEP, MAX_STEP)[far]
>     top = g[:, 1] + SIDE
>     near = ready & ~far
>     landed = z - top < 0.02
>     a[near & ~landed, 1] = -MAX_STEP                            # the square's top stops the claw
>     a[near & landed, 2] = 1
>     return a
>
>
> def normalize(a):
>     """Map actions (..., 3) to [-1, 1]^3: dx and dz in units of MAX_STEP, the grip as -1 (open) or 1 (closed)."""
>     return np.concatenate([a[..., :2] / MAX_STEP, 2 * a[..., 2:] - 1], -1).astype(np.float32)
>
>
> def denormalize(u):
>     """Inverse of normalize, with the grip thresholded at 0."""
>     return np.concatenate([np.clip(u[..., :2], -1, 1) * MAX_STEP, (u[..., 2:] > 0).astype(np.float32)], -1)
> ```

Sixteen operator episodes on each of four layouts. Blue paths go to the left square and orange paths to the right one. Every path starts at the same point, so the first image of an episode is the same whichever square the operator picked. After one move the claw is on one side, and from then on each image belongs to one of the two choices.

![Four layouts, each with two squares of the named color on either side of the claw start. Each panel shows sixteen operator paths from the same start point: blue paths go to the left square and orange paths to the right square.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/generative-action-heads/images/cell_5_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=de61316c813124e20efc034689b097d7)

## Action chunks

Three of the heads predict an action chunk per query, as defined in [Action representations II: regression and chunks](https://aegean.ai/aiml-common/lectures/vla/action-chunks/index.md): a chunk $A_t = (a_t, \ldots, a_{t+H-1})$ of length $H$, of which the policy executes the first $E \le H$ actions before it looks at the camera again. Here $H = 8$ and $E = 4$. Each action is rescaled to $[-1, 1]^3$: the two moves in units of the largest step, and the grip as $-1$ (open) or $1$ (closed).

> [accordion] Code
>
> ```python theme={null}
> H = 8                    # chunk length: actions predicted per query
> E = 4                    # actions executed from each chunk before the policy is queried again
>
>
> def collect_demos(n_episodes, seed):
>     """Operator demonstrations with a random choice of named square per episode.
>
>     Returns:
>         images (N, 3, IMG, IMG) as uint8, instructions (N, L_TEXT), and the normalized action chunks
>         (N, H, 3) that start at each step; chunks that run past the end repeat the last action.
>     """
>     env = TwinClaw(n_episodes, seed=seed)
>     rng = np.random.default_rng(seed + 1)
>     choice = rng.integers(2, size=n_episodes)
>     imgs, texts, acts, alive_log = [], [], [], []
>     alive = np.ones(n_episodes, bool)
>     while alive.any():
>         img, text = env.observe()
>         a = operator_action(env, choice, rng)
>         imgs.append((img * 255).astype(np.uint8)); texts.append(text); acts.append(normalize(a)); alive_log.append(alive.copy())
>         _, done = env.step(a)
>         alive &= ~done
>     acts, alive_log = np.stack(acts, 1), np.stack(alive_log, 1)              # (n, T, 3), (n, T)
>     length = alive_log.sum(1)
>     t_idx = np.minimum(np.arange(acts.shape[1])[:, None] + np.arange(H)[None], length[:, None, None] - 1)  # (n, T, H)
>     chunks = acts[np.arange(n_episodes)[:, None, None], t_idx]               # (n, T, H, 3)
>     keep = alive_log
>     img_all = np.stack(imgs, 1)[keep]
>     text_all = np.stack(texts, 1)[keep]
>     return img_all, text_all, chunks[keep]
> ```

## One backbone, different heads

Every policy uses the MiniVLA backbone of the behavioral cloning section: FiLM-conditioned convolutions and a small transformer that reduce the image and the instruction to a summary vector $h$. The backbone is trained once, end to end with the token head, and then frozen. Each head is trained on the frozen $h$ of the demonstration steps, which plays the role of a pretrained VLA backbone with a new action head on top. All heads get the same 20,000 training steps.

> [accordion] Code
>
> ```python theme={null}
> class Encoder(nn.Module):
>     """The MiniVLA backbone: FiLM-conditioned convolutions, then a transformer over a summary token,
>     64 patch tokens and the instruction tokens. Returns the summary vector h (B, d).
>     """
>
>     def __init__(self, d=128, layers=3, heads=4):
>         super().__init__()
>         self.convs = nn.ModuleList([nn.Conv2d(5, 32, 4, 2, 1), nn.Conv2d(32, 64, 4, 2, 1), nn.Conv2d(64, d, 4, 2, 1)])
>         self.norms = nn.ModuleList([nn.GroupNorm(8, c.out_channels) for c in self.convs])
>         self.film = nn.ModuleList([nn.Linear(d, 2 * c.out_channels) for c in self.convs])
>         ys, xs = torch.meshgrid(torch.linspace(1, 0, IMG), torch.linspace(0, 1, IMG), indexing="ij")
>         self.register_buffer("coords", torch.stack([xs, ys])[None])
>         self.word = nn.Embedding(len(VOCAB), d, padding_idx=0)
>         self.img_pos = nn.Parameter(0.02 * torch.randn(1, 64, d))
>         self.txt_pos = nn.Parameter(0.02 * torch.randn(1, L_TEXT, d))
>         self.cls = nn.Parameter(0.02 * torch.randn(1, 1, d))
>         layer = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.0, batch_first=True, norm_first=True)
>         self.encoder = nn.TransformerEncoder(layer, layers, enable_nested_tensor=False)
>         self.norm = nn.LayerNorm(d)
>
>     def forward(self, img, text):
>         """Summary vector of images img (B, 3, IMG, IMG) in [0, 1] and instructions text (B, L_TEXT)."""
>         w = self.word(text)
>         keep = (text != 0).unsqueeze(-1).float()
>         u = (w * keep).sum(1) / keep.sum(1)
>         x = torch.cat([img, self.coords.expand(len(img), -1, -1, -1)], 1)
>         for conv, norm, film in zip(self.convs, self.norms, self.film):
>             gamma, beta = film(u).chunk(2, -1)
>             x = F.gelu(norm(conv(x)) * (1 + gamma[:, :, None, None]) + beta[:, :, None, None])
>         tokens = torch.cat([self.cls.expand(len(img), -1, -1),
>                             x.flatten(2).transpose(1, 2) + self.img_pos, w + self.txt_pos], 1)
>         pad = torch.cat([torch.zeros(len(img), 65, dtype=torch.bool, device=img.device), text == 0], 1)
>         return self.norm(self.encoder(tokens, src_key_padding_mask=pad)[:, 0])
>
>
> def mlp(i, o, width=512):
>     """Three-layer perceptron from i to o features."""
>     return nn.Sequential(nn.Linear(i, width), nn.SiLU(), nn.Linear(width, width), nn.SiLU(), nn.Linear(width, o))
>
>
> def time_embedding(s, dim=64):
>     """Sinusoidal embedding (B, dim) of times s (B,) in [0, 1]."""
>     f = torch.exp(torch.linspace(0, np.log(1000.0), dim // 2, device=s.device))
>     return torch.cat([torch.sin(s[:, None] * f), torch.cos(s[:, None] * f)], -1)
> ```

## Five ways to turn $h$ into an action

The regression head is a perceptron trained with the squared error on the next action. For an observation $o$, the function that minimizes the expected squared error is the conditional mean,

$$
f^\star(o) = \arg\min_f \mathbb{E}\big[\lVert a - f(o) \rVert^2\big] = \mathbb{E}[a \mid o].
$$

At the start state half the demonstrations move left and half move right, so the conditional mean of the first move is zero, a move that no demonstration makes.

The token head is the one from the behavioral cloning section: $dx$, $dz$ and the grip become three tokens, and the head outputs a categorical distribution over each, conditioned on the tokens before it. A categorical distribution can put its mass on two separate bins. Taking the most likely token picks one of them; sampling can pick either.

The conditional VAE follows ACT. An encoder $q_\phi(z \mid h, A_t)$ compresses the demonstrated chunk into a latent $z$, and a decoder $D_\theta$ maps $(h, z)$ back to a chunk. Training minimizes

$$
\mathcal{L} = \lVert A_t - D_\theta(h, z) \rVert_1 + \beta\, \mathrm{KL}\big(q_\phi(z \mid h, A_t) \,\Vert\, \mathcal{N}(0, I)\big).
$$

The latent can carry the operator's choice, which the start image cannot. ACT uses the L1 error, weights the KL term with $\beta = 10$, discards the encoder after training and sets $z$ to the prior mean, zero, at test time (Zhao et al., 2023). You run that variant, and one that draws $z$ from the prior. The [VAE architecture section](https://aegean.ai/aiml-common/lectures/vae/vae-architecture/index.md) derives the same objective for images.

The diffusion head follows Diffusion Policy, which uses a DDPM (Chi et al., 2023; Ho et al., 2020). Write $x^0 = A_t$ for a demonstrated chunk, flattened, and $k = 1, \ldots, K$ for the diffusion step, so that it does not clash with the time step $t$. The forward process adds Gaussian noise in the closed form of the [DDPM section](https://aegean.ai/aiml-common/lectures/diffusion/ddpm/index.md),

$$
x^k = \sqrt{\bar\alpha_k}\, x^0 + \sqrt{1 - \bar\alpha_k}\, \epsilon,
\qquad \epsilon \sim \mathcal{N}(0, I),
$$

and a network $\epsilon_\theta(x^k, k, h)$ learns to predict the noise with the loss $\lVert \epsilon - \epsilon_\theta(x^k, k, h) \rVert^2$. Sampling starts from pure noise and runs $K = 50$ denoising steps. Different starting noise ends in different chunks, so the head can return either choice. You run it with chunks and with single actions ($H = E = 1$).

The flow-matching head uses the straight path of the [flow matching section](https://aegean.ai/aiml-common/lectures/flow-matching/index.md). With flow time $\tau \in [0, 1]$, noise $x_0$ and a demonstrated chunk $x_1$,

$$
x_\tau = (1 - \tau)\, x_0 + \tau\, x_1,
$$

and a network $v_\theta(x_\tau, \tau, h)$ learns the velocity $x_1 - x_0$ with a squared error. Sampling integrates $v_\theta$ from noise in 10 Euler steps. Like diffusion, it maps different noise to different chunks.

> [accordion] Code
>
> ```python theme={null}
> class Policy(nn.Module):
>     """Base class: an encoder and a head that maps the summary vector to a chunk of normalized actions.
>
>     Subclasses define loss(h, chunk) and sample(h) -> (B, horizon, 3), and set horizon (actions per
>     query) and evals (head evaluations per query, for the inference cost).
>
>     Args:
>         enc: the encoder; several policies can share one frozen encoder.
>     """
>     horizon, evals = 1, 1
>
>     def __init__(self, enc):
>         super().__init__()
>         self.enc = enc
>
>
> class Regression(Policy):
>     """Deterministic head trained with the squared error on the next action."""
>
>     def __init__(self, enc):
>         super().__init__(enc)
>         self.head = mlp(128, 3)
>
>     def loss(self, h, chunk):
>         """Training loss of the head on summary vectors h (B, d) and demonstrated chunks (B, H, 3)."""
>         return F.mse_loss(self.head(h), chunk[:, 0])
>
>     def sample(self, h):
>         """Normalized action chunk (B, horizon, 3) for summary vectors h (B, d)."""
>         return self.head(h)[:, None]
>
>
> N_BINS = 21
>
>
> class Tokens(Policy):
>     """The autoregressive token head of the behavioral cloning section: dx, dz and grip as three tokens."""
>     sizes = [N_BINS, N_BINS, 2]
>
>     def __init__(self, enc, greedy=True):
>         super().__init__(enc)
>         self.greedy, self.evals = greedy, 3
>         self.heads = nn.ModuleList([mlp(128, k) for k in self.sizes])
>         self.tok = nn.ModuleList([nn.Embedding(k, 128) for k in self.sizes[:-1]])
>
>     @staticmethod
>     def to_tokens(u):
>         """Tokens (B, 3) of normalized actions u (B, 3)."""
>         b = torch.round((u[:, :2].clamp(-1, 1) + 1) / 2 * (N_BINS - 1)).long()
>         return torch.cat([b, (u[:, 2:] > 0).long()], 1)
>
>     def loss(self, h, chunk):
>         """Training loss of the head on summary vectors h (B, d) and demonstrated chunks (B, H, 3)."""
>         z, c, loss = self.to_tokens(chunk[:, 0]), h, 0.0
>         for j, head in enumerate(self.heads):
>             loss = loss + F.cross_entropy(head(c), z[:, j])
>             if j < 2:
>                 c = c + self.tok[j](z[:, j])
>         return loss
>
>     def sample(self, h):
>         """Normalized action chunk (B, horizon, 3) for summary vectors h (B, d)."""
>         c, z = h, []
>         for j, head in enumerate(self.heads):
>             l = head(c)
>             zj = l.argmax(-1) if self.greedy else torch.distributions.Categorical(logits=l).sample()
>             z.append(zj)
>             if j < 2:
>                 c = c + self.tok[j](zj)
>         z = torch.stack(z, 1).float()
>         return torch.cat([z[:, :2] / (N_BINS - 1) * 2 - 1, 2 * z[:, 2:] - 1], 1)[:, None]
>
>
> class CVAE(Policy):
>     """ACT-style conditional VAE over action chunks.
>
>     The encoder q(z | h, chunk) is used only in training. The decoder maps (h, z) to a chunk. The
>     loss is the L1 reconstruction error plus beta times the KL divergence to N(0, I).
>
>     Args:
>         z_at_test: "zero" decodes with the prior mean, as ACT does; "sample" draws z from the prior.
>     """
>
>     def __init__(self, enc, z_dim=16, beta=10.0, z_at_test="zero"):
>         super().__init__(enc)
>         self.horizon, self.z_dim, self.beta, self.z_at_test = H, z_dim, beta, z_at_test
>         self.q = mlp(128 + 3 * H, 2 * z_dim)
>         self.dec = mlp(128 + z_dim, 3 * H)
>
>     def loss(self, h, chunk):
>         """Training loss of the head on summary vectors h (B, d) and demonstrated chunks (B, H, 3)."""
>         mu, logvar = self.q(torch.cat([h, chunk.flatten(1)], 1)).chunk(2, -1)
>         z = mu + torch.randn_like(mu) * (0.5 * logvar).exp()
>         rec = (self.dec(torch.cat([h, z], 1)) - chunk.flatten(1)).abs().sum(1).mean()
>         kl = 0.5 * (mu ** 2 + logvar.exp() - 1 - logvar).sum(1).mean()
>         return rec + self.beta * kl
>
>     def sample(self, h):
>         """Normalized action chunk (B, horizon, 3) for summary vectors h (B, d)."""
>         z = torch.zeros(len(h), self.z_dim, device=h.device)
>         if self.z_at_test == "sample":
>             z = torch.randn_like(z)
>         return self.dec(torch.cat([h, z], 1)).view(-1, H, 3)
>
>
> class Diffusion(Policy):
>     """DDPM over action chunks: a network predicts the noise added to a chunk at diffusion step k.
>
>     Args:
>         horizon: chunk length (1 gives a single-action policy).
>         steps: number K of diffusion steps, in training and in sampling.
>     """
>
>     def __init__(self, enc, horizon=H, steps=50):
>         super().__init__(enc)
>         self.horizon, self.K, self.evals = horizon, steps, steps
>         beta = torch.linspace(1e-4, 0.2, steps)                   # short linear schedule for a short chain
>         self.register_buffer("beta", beta)
>         self.register_buffer("abar", torch.cumprod(1 - beta, 0))
>         self.eps = mlp(3 * horizon + 64 + 128, 3 * horizon)
>
>     def predict(self, x, k, h):
>         """Predicted noise eps_theta(x^k, k, h) for noisy chunks x (B, 3 horizon) at diffusion steps k (B,)."""
>         return self.eps(torch.cat([x, time_embedding(k.float() / self.K), h], 1))
>
>     def loss(self, h, chunk):
>         """Training loss of the head on summary vectors h (B, d) and demonstrated chunks (B, H, 3)."""
>         x0 = chunk[:, :self.horizon].flatten(1)
>         k = torch.randint(0, self.K, (len(x0),), device=x0.device)
>         noise = torch.randn_like(x0)
>         ab = self.abar[k][:, None]
>         return F.mse_loss(self.predict(ab.sqrt() * x0 + (1 - ab).sqrt() * noise, k, h), noise)
>
>     def sample(self, h):
>         """Normalized action chunk (B, horizon, 3) for summary vectors h (B, d)."""
>         x = torch.randn(len(h), 3 * self.horizon, device=h.device)
>         for k in reversed(range(self.K)):                          # ancestral sampling, Ho et al. (2020)
>             kk = torch.full((len(h),), k, device=h.device)
>             eps = self.predict(x, kk, h)
>             ab, ab_prev = self.abar[k], (self.abar[k - 1] if k > 0 else torch.tensor(1.0, device=h.device))
>             x0 = ((x - (1 - ab).sqrt() * eps) / ab.sqrt()).clamp(-1, 1)   # predicted clean chunk, kept in range
>             # mean of q(x^{k-1} | x^k, x^0), the forward posterior
>             x = (ab_prev.sqrt() * self.beta[k] * x0 + (1 - self.beta[k]).sqrt() * (1 - ab_prev) * x) / (1 - ab)
>             if k > 0:
>                 x = x + ((1 - ab_prev) / (1 - ab) * self.beta[k]).sqrt() * torch.randn_like(x)
>         return x.view(-1, self.horizon, 3)
>
>
> class Flow(Policy):
>     """Conditional flow matching over action chunks with the straight path x_tau = (1 - tau) x_0 + tau x_1.
>
>     x_0 is Gaussian noise and x_1 a demonstrated chunk; the network learns the velocity x_1 - x_0 and
>     sampling integrates it with Euler steps.
>
>     Args:
>         steps: Euler steps in sampling.
>     """
>
>     def __init__(self, enc, steps=10):
>         super().__init__(enc)
>         self.horizon, self.evals = H, steps
>         self.v = mlp(3 * H + 64 + 128, 3 * H)
>
>     def velocity(self, x, tau, h):
>         """Predicted velocity v_theta(x_tau, tau, h) for points x (B, 3 H) at flow times tau (B,)."""
>         return self.v(torch.cat([x, time_embedding(tau), h], 1))
>
>     def loss(self, h, chunk):
>         """Training loss of the head on summary vectors h (B, d) and demonstrated chunks (B, H, 3)."""
>         x1 = chunk.flatten(1)
>         x0 = torch.randn_like(x1)
>         tau = torch.rand(len(x1), device=x1.device)
>         x = (1 - tau[:, None]) * x0 + tau[:, None] * x1
>         return F.mse_loss(self.velocity(x, tau, h), x1 - x0)
>
>     def sample(self, h):
>         """Normalized action chunk (B, horizon, 3) for summary vectors h (B, d)."""
>         x = torch.randn(len(h), 3 * H, device=h.device)
>         dt = 1.0 / self.evals
>         for i in range(self.evals):
>             x = x + dt * self.velocity(x, torch.full((len(h),), i * dt, device=h.device), h)
>         return x.view(-1, H, 3)
> ```

## Training and rollouts

The code below trains the backbone and the heads, and runs a policy on a batch of machines. A policy that returns a chunk executes its first four actions and then queries again. The rollout records whether a square was delivered and which way the claw went in its first ten steps.

> [accordion] Code
>
> ```python theme={null}
> def train(policy, data, steps=6000, lr=3e-4, batch=128, seed=0):
>     """Fit encoder and head end to end with AdamW and a one-cycle schedule. Returns the final smoothed loss."""
>     img, text, chunk = [torch.as_tensor(x, device=DEV) for x in data]
>     opt = torch.optim.AdamW(policy.parameters(), lr=lr, weight_decay=1e-4)
>     sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.1)
>     g = torch.Generator().manual_seed(seed)
>     running = None
>     for _ in range(steps):
>         j = torch.randint(len(chunk), (batch,), generator=g)
>         loss = policy.loss(policy.enc(img[j].float() / 255, text[j]), chunk[j])
>         opt.zero_grad(); loss.backward(); opt.step(); sched.step()
>         running = loss.item() if running is None else 0.98 * running + 0.02 * loss.item()
>     return running
>
>
> @torch.no_grad()
> def encode(enc, data, batch=2048):
>     """Summary vectors (N, d) of all demonstration steps under a frozen encoder."""
>     img, text = data[0], data[1]
>     out = [enc(torch.as_tensor(img[i:i + batch], device=DEV).float() / 255, torch.as_tensor(text[i:i + batch], device=DEV))
>            for i in range(0, len(img), batch)]
>     return torch.cat(out)
>
>
> def train_head(policy, h_all, chunks, steps=20000, lr=1e-3, batch=512, seed=0):
>     """Fit only the head on cached summary vectors h_all (N, d). Returns the final smoothed loss."""
>     chunk = torch.as_tensor(chunks, device=DEV)
>     params = [p for n, p in policy.named_parameters() if not n.startswith("enc.")]
>     opt = torch.optim.AdamW(params, lr=lr, weight_decay=1e-4)
>     sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=lr, total_steps=steps, pct_start=0.05)
>     g = torch.Generator().manual_seed(seed)
>     running = None
>     for _ in range(steps):
>         j = torch.randint(len(chunk), (batch,), generator=g)
>         loss = policy.loss(h_all[j], chunk[j])
>         opt.zero_grad(); loss.backward(); opt.step(); sched.step()
>         running = loss.item() if running is None else 0.98 * running + 0.02 * loss.item()
>     return running
>
>
> @torch.no_grad()
> def rollout(policy, n=500, seed=123, block=None):
>     """Run the policy on n machines; each query returns a chunk, of which the first E actions run (all, if shorter).
>
>     Args:
>         block: if given, groups of block consecutive machines share one layout (see TwinClaw.copy_layout).
>
>     Returns:
>         a dict with the delivery rate, per-episode outcomes, the side each episode went to (-1 left,
>         +1 right, 0 neither), the claw paths (T + 1, n, 2), the first machine's start image, and the
>         head evaluations per executed action.
>     """
>     policy.eval()
>     env = TwinClaw(n, seed=seed, as_torch=True)
>     if block:
>         env.copy_layout(block)
>     start = env.observe()[0][0].cpu().numpy()
>     alive, succ = np.ones(n, bool), np.zeros(n, bool)
>     path, plan, queries, executed = [env.claw.copy()], None, 0, 0
>     while alive.any():
>         if plan is None or len(plan) == 0:
>             img, text = env.observe()
>             u = policy.sample(policy.enc(torch.as_tensor(img, device=DEV), torch.as_tensor(text, device=DEV)))
>             plan = list(denormalize(u.cpu().numpy()).transpose(1, 0, 2)[:min(E, policy.horizon)])
>             queries += 1
>         a = plan.pop(0)
>         a[~alive] = 0
>         r, done = env.step(a)
>         executed += 1
>         succ |= (r > 0) & alive
>         alive &= ~done
>         path.append(env.claw.copy())
>     policy.train()
>     path = np.array(path)
>     moved = path[min(10, len(path) - 1), :, 0] - path[0, :, 0]
>     side = np.where(np.abs(moved) > 0.1, np.sign(moved), 0)      # where the claw went in its first 10 steps
>     return dict(delivery=succ.mean(), success=succ, side=side, catches=env.catches, drops=env.drops, misses=env.misses,
>                 first_grab=env.first_grab, committed=(env.first_grab == 1).mean(), path=path,
>                 start=start, evals=policy.evals * queries / executed)
> ```
>
> ```python theme={null}
> t0 = time.time()
> demos = collect_demos(1500, seed=1)
> print(f"{len(demos[2])} steps from 1500 operator episodes")
> torch.manual_seed(0)
> backbone = Tokens(Encoder()).to(DEV)
> loss = train(backbone, demos, steps=6000)
> enc = backbone.enc.requires_grad_(False)
> h_all = encode(enc, demos)
> print(f"backbone trained with the token loss {loss:.3f}; summary vectors {tuple(h_all.shape)}  [{time.time() - t0:.0f} s]")
> trained = {}
> for name, make in [("regression", Regression), ("tokens", Tokens), ("CVAE", CVAE),
>                    ("diffusion, one action", lambda e: Diffusion(e, horizon=1)), ("diffusion, chunk", Diffusion),
>                    ("flow matching, chunk", Flow)]:
>     torch.manual_seed(0)
>     trained[name] = make(enc).to(DEV)
>     loss = train_head(trained[name], h_all, demos[2])
>     print(f"{name}: final loss {loss:.4f}  [{time.time() - t0:.0f} s]")
> ```

```output theme={null}
63711 steps from 1500 operator episodes
backbone trained with the token loss 0.086; summary vectors (63711, 128)  [220 s]
regression: final loss 0.0070  [290 s]
tokens: final loss 0.0092  [471 s]
CVAE: final loss 0.6171  [615 s]
diffusion, one action: final loss 0.0180  [705 s]
diffusion, chunk: final loss 0.0352  [795 s]
flow matching, chunk: final loss 0.0676  [881 s]
```

## Delivery and choice

Each policy runs on 20 layouts, 16 times per layout, with fresh grasp outcomes and fresh samples on every run. The table reports the delivery rate over the 320 episodes. It also reports how often both squares were chosen across the 16 runs of a layout, and the minority share: the fraction of runs that went to the less chosen square, averaged over layouts. A policy that splits evenly on every layout has a minority share of 0.5.

> [accordion] Code
>
> ```python theme={null}
> variants = {
>     "regression": trained["regression"],
>     "tokens, greedy": trained["tokens"],
>     "tokens, sampled": copy.copy(trained["tokens"]),
>     "CVAE, z = 0 (ACT)": trained["CVAE"],
>     "CVAE, z sampled": copy.copy(trained["CVAE"]),
>     "diffusion, one action": trained["diffusion, one action"],
>     "diffusion, chunk": trained["diffusion, chunk"],
>     "flow matching, chunk": trained["flow matching, chunk"],
> }
> variants["tokens, sampled"].greedy = False
> variants["CVAE, z sampled"].z_at_test = "sample"
> LAYOUTS, REPEATS = 20, 16
> results = {}
> print(f"{'policy':24s} {'delivery':>8s} {'both squares':>12s} {'minority':>8s} {'head evals/step':>15s}")
> for name, pol in variants.items():
>     r = rollout(pol, n=LAYOUTS * REPEATS, seed=123, block=REPEATS)
>     side = r["side"].reshape(LAYOUTS, REPEATS)
>     left, right = (side < 0).sum(1), (side > 0).sum(1)
>     r["both"] = ((left > 0) & (right > 0)).mean()                      # layouts on which both squares were chosen
>     r["minority"] = (np.minimum(left, right) / REPEATS).mean()          # 0.5 is an even split on every layout
>     results[name] = r
>     print(f"{name:24s} {r['delivery']:8.2f} {r['both']:12.2f} {r['minority']:8.2f} {r['evals']:15.2f}")
> for name, r in results.items():
>     f = ~r["success"]
>     print(f"  {name:22s} failed episodes: {f.sum()}, with a square released outside the chute {(r['drops'][f] > 0).mean():.2f}, "
>           f"mean failed catches {r['misses'][f].mean():.2f}")
> print(f"[{time.time() - t0:.0f} s]")
> ```

```output theme={null}
policy                   delivery both squares minority head evals/step
regression                   0.93         0.00     0.00            1.00
tokens, greedy               0.84         0.00     0.00            3.00
tokens, sampled              0.90         0.25     0.04            3.00
CVAE, z = 0 (ACT)            0.82         0.00     0.00            0.25
CVAE, z sampled              0.82         0.00     0.00            0.25
diffusion, one action        0.80         0.95     0.26           50.00
diffusion, chunk             0.65         1.00     0.31           12.50
flow matching, chunk         0.73         0.85     0.25            2.50
  regression             failed episodes: 24, with a square released outside the chute 0.96, mean failed catches 1.96
  tokens, greedy         failed episodes: 52, with a square released outside the chute 0.06, mean failed catches 1.56
  tokens, sampled        failed episodes: 33, with a square released outside the chute 0.21, mean failed catches 3.39
  CVAE, z = 0 (ACT)      failed episodes: 58, with a square released outside the chute 0.22, mean failed catches 2.12
  CVAE, z sampled        failed episodes: 58, with a square released outside the chute 0.16, mean failed catches 1.98
  diffusion, one action  failed episodes: 64, with a square released outside the chute 0.17, mean failed catches 0.88
  diffusion, chunk       failed episodes: 111, with a square released outside the chute 0.26, mean failed catches 0.77
  flow matching, chunk   failed episodes: 86, with a square released outside the chute 0.31, mean failed catches 1.30
[903 s]
```

The histograms show the first move $dx$ that each head returns on 256 new start states, with eight samples per state.

![Eight histograms, one per policy: regression, greedy tokens, sampled tokens, CVAE with z set to zero, CVAE with sampled z, diffusion with one action, diffusion with chunks, and flow matching with chunks. Each shows the first horizontal move, from -1 to 1 in units of the largest step. Diffusion and flow matching show two separate peaks, and regression spreads its moves across the range.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/generative-action-heads/images/cell_12_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=7b00b799755553fa409f40fffee77744)

Sixteen runs of each policy on one layout. Blue paths delivered a square and orange paths did not.

![Eight panels, one per policy, each with sixteen claw paths on the same layout. Blue paths delivered a square and orange paths did not. Regression, greedy tokens and the CVAE send every run toward the same square, while diffusion and flow matching send runs toward both squares.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/generative-action-heads/images/cell_13_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=0910d87735a78a78b07ff816390e1389)

## What the heads did

Delivery does not separate the heads much. Regression delivers 0.93 of the episodes, and most of the other heads between 0.73 and 0.90. With 320 episodes per policy, differences of a few points are within the evaluation noise. Delivery also moves between training runs. In an earlier run of the same code, the delivery of single heads changed by more than ten points, while the choice of square did not, so the table does not rank the heads by delivery. Most failures come from the physics of the grab: a square released outside the chute, or catches that fail repeatedly. The chunked diffusion head is lowest at 0.65. It executes four actions without looking, and its moves are less precise than those of the closed-loop heads, so more of its catches land off center.

The square each head chose separates them more clearly. Regression, greedy tokens and the conditional VAE always went to the same square on a given layout. Diffusion and flow matching went to both squares on 85% to 100% of the layouts, and sampled tokens on 25%. None of the generative heads split evenly: the minority share of diffusion and flow matching is 0.25 to 0.31, and that of sampled tokens 0.04, against 0.5 for the operator.

Regression did not get stuck midway, although its training target at the start state is a zero move. Its first moves in the histogram are spread between the two modes, and many are far from zero. Each training layout contributes one start state with one direction, so the network does not see the even split on any single layout, and on a new layout it returns some value between the modes. It is rarely exactly zero, and one move away from the midpoint, the image belongs to one of the two choices, and the regression head follows it. The midway point is an unstable balance, and in this task the averaged action costs little. When the two choices stay ambiguous for many steps, as when a robot can pass an obstacle on either side, the conditional mean points between them for as long as the ambiguity lasts.

The conditional VAE ignored its latent. Drawing $z$ from the prior gives the same first moves and the same choices as setting it to zero, so the decoder learned to predict the chunk from $h$ alone. On the layout in the paths figure, both variants sent all 16 runs to the right square, and none of them delivered. ACT notes that a larger $\beta$ transmits less information through $z$ (Zhao et al., 2023). With $\beta = 10$ and demonstrations whose only variation is one binary choice, the KL term made it cheaper to ignore $z$. ACT motivates the CVAE with noisy human demonstrations, and reports the objective as essential for learning precise tasks from them.

Diffusion with single actions can switch modes between steps, because each step draws fresh noise. In the paths above, most of its runs keep the direction of their first move, since after one move the image no longer looks like the start. Chunks commit to a choice for $E$ steps by construction, which is how Diffusion Policy keeps one mode within a rollout in its Push-T example (Chi et al., 2023).

The heads also differ in cost per action. Diffusion with single actions runs the denoiser 50 times per executed action, and the chunked version 12.5 times, since each query of 50 steps yields four actions. Flow matching needs 2.5 velocity evaluations per action, and the conditional VAE one decoder pass per four actions. Diffusion Policy reduces this cost with DDIM, training with 100 diffusion steps and sampling with 10 (Chi et al., 2023).

These results come from one task, one scripted operator whose two modes are clean, and heads that were not tuned individually. The backbone was trained with the token loss, which may favor the token head. The minority shares come from 16 runs per layout, so each layout's share has a standard error of about 0.12, and only the average over 20 layouts is stable.

## References

* Chi, C., Xu, Z., Feng, S., Cousineau, E., Du, Y., et al. (2023). *Diffusion Policy: Visuomotor policy learning via action diffusion*. arXiv \[cs.RO]. [Link](http://arxiv.org/abs/2303.04137)
* Ho, J., Jain, A., Abbeel, P. (2020). *Denoising Diffusion Probabilistic Models*. arXiv \[cs.LG]. [DOI](https://doi.org/10.48550/arXiv.2006.11239)
* Lipman, Y., Chen, R., Ben-Hamu, H., Nickel, M., Le, M. (2022). *Flow Matching for generative modeling*. arXiv \[cs.LG]. [Link](http://arxiv.org/abs/2210.02747)
* Zhao, T., Kumar, V., Levine, S., Finn, C. (2023). *Learning fine-grained bimanual manipulation with low-cost hardware*. arXiv \[cs.RO]. [DOI](https://doi.org/10.48550/arXiv.2304.13705)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/vla/generative-action-heads).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.