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

# Action representations II: regression and chunks

> One-step regression and action chunks against a 21-bin policy

[![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/action-chunks/index.ipynb)

[Action representations I: discrete bins](https://aegean.ai/aiml-common/lectures/vla/action-representations.md) showed that a token head matches the operator on the claw machine when it has enough bins and one of them sits at zero. This section replaces the bins with a regression head that outputs continuous actions, and then with action chunks: several future actions predicted from one observation. A 21-bin token head trained on the same demonstrations is the baseline.

> [accordion] Code
>
> ```python theme={null}
> import os
> os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"   # reproducible GPU matrix products
> 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)
> torch.backends.cudnn.benchmark = False
> torch.use_deterministic_algorithms(True, warn_only=True)
> ```

The claw machine is the one from [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl.md). Three colored squares lie on the floor, a claw hangs from a gantry, and the instruction names the square to drop into the chute on the left. An action is a claw move $(\Delta x, \Delta z)$ of at most 0.05 per axis and a grip command, open or closed. The squares are rigid boxes simulated with gravity and contact, so a released square falls and can land on another. A catch succeeds with a probability that falls with the offset between claw and square center, and an episode ends after 60 steps.

> [accordion] Code
>
> ```python theme={null}
> import warp as wp
> import newton
>
> 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 the {} square", "get the {} one", "pick up the {} 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
> N_BINS = 21              # bins per motion axis; the grip token has 2 values, open and closed
> 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 starts above the chute
> T_MAX = 60               # step limit of an episode: a clean grab and delivery takes about 48
> 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
>
>
> 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)])
>
>
> def expert_action(env, rng, bias=(0.0, 0.04)):
>     """Scripted operator who aligns the claw by eye.
>
>     Before each descent the operator picks an aim point to the right of the named square's center,
>     off by a random amount in the interval bias, and stops correcting x once above it. After a
>     missed catch it opens, rises and aims again. It carries the square at height 0.75 to the chute.
>
>     Args:
>         env: the ClawGrab batch.
>         rng: generator of the aiming error.
>         bias: interval of the aiming error.
>
>     Returns:
>         float array (n, 3) of actions (dx, dz, grip).
>     """
>     if not hasattr(env, "aim") or len(env.aim) != env.n:
>         env.aim = np.full(env.n, np.nan, np.float32)
>     a = np.zeros((env.n, 3), np.float32)
>     x, z = env.claw[:, 0], env.claw[:, 1]
>     g = env.goal()
>     holding_target = env.held == env.target
>     holding_other = (env.held >= 0) & ~holding_target
>     free = env.held < 0
>     # carry: rise, then move over the chute, then open
>     up = holding_target & (z < 0.75)
>     a[up, 1] = MAX_STEP; a[up, 2] = 1
>     go = holding_target & ~up & (x >= CHUTE_X - 0.05)
>     a[go, 0] = -MAX_STEP; a[go, 2] = 1
>     # (opening over the chute: grip stays 0)
>     # a wrong square in the claw: open
>     # free claw that is closed: open and rise (the miss)
>     missed = free & env.closed
>     env.aim[missed] = np.nan
>     a[missed, 1] = MAX_STEP
>     # free and open: pick an aim point, align, descend, close
>     ready = free & ~env.closed
>     new = ready & np.isnan(env.aim)
>     env.aim[new] = rng.uniform(*bias, 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
>     a[near, 1] = np.clip(top - z, -MAX_STEP, MAX_STEP)[near]
>     a[near & (z - top < 0.02), 2] = 1
>     env.aim[env.held >= 0] = np.nan
>     return a
>
>
> def to_tokens(a):
>     """Tokens of actions a (n, 3): a bin index 0..N_BINS-1 for dx and dz, and the grip as 0 or 1."""
>     b = np.rint((np.clip(a[:, :2], -MAX_STEP, MAX_STEP) + MAX_STEP) / (2 * MAX_STEP) * (N_BINS - 1)).astype(int)
>     return np.concatenate([b, (a[:, 2:] > 0.5).astype(int)], 1)
>
>
> def from_tokens(z):
>     """Actions (n, 3) at the centers of the bins z."""
>     return np.concatenate([-MAX_STEP + z[:, :2] * (2 * MAX_STEP / (N_BINS - 1)), z[:, 2:]], 1).astype(np.float32)
>
>
> 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)
>
>
> ClawGrab = NewtonClawGrab
> ```
>
> ```python theme={null}
> class MiniVLA(nn.Module):
>     """The MiniVLA trunk with a choice of action head.
>
>     The trunk is the one from the first section: FiLM-conditioned convolutions, a transformer over a
>     summary token, 64 patch tokens and the instruction, and a summary vector h. The head turns h
>     into actions in one of two ways.
>
>     Args:
>         head: "tokens" for an autoregressive head over binned dx, dz and the grip, or "regress"
>             for a head that outputs continuous motions and grip logits for a chunk of steps.
>         n_bins: bins per motion axis, for the token head.
>         chunk: number of future steps the regression head predicts.
>         d: width of the tokens.
>     """
>
>     def __init__(self, head="tokens", n_bins=21, chunk=1, d=128, layers=3, heads=4):
>         super().__init__()
>         self.head, self.n_bins, self.chunk = head, n_bins, chunk
>         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)
>         mlp = lambda k, din=d: nn.Sequential(nn.Linear(din, d), nn.GELU(), nn.Linear(d, k))
>         if head == "tokens":
>             self.heads = nn.ModuleList([mlp(n_bins), mlp(n_bins), mlp(2)])
>             self.tok = nn.ModuleList([nn.Embedding(n_bins, d), nn.Embedding(n_bins, d)])
>         else:
>             self.motion = mlp(2 * chunk)          # normalized dx, dz of each step of the chunk
>             self.grip = mlp(chunk)                # logit of a closed claw at each step of the chunk
>
>     def context(self, img, text):
>         """Summary vector h of images img (B, 3, IMG, IMG) 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 loss(self, img, text, act, mask):
>         """Training loss for a batch of observations and their next `chunk` operator actions.
>
>         Args:
>             act: float tensor (B, chunk, 3) of operator actions (dx, dz, grip).
>             mask: float tensor (B, chunk), 0 for steps past the end of the episode.
>         """
>         h = self.context(img, text)
>         if self.head == "tokens":
>             z = to_bins(act[:, 0], self.n_bins)
>             lp, c = 0.0, h
>             for j, head in enumerate(self.heads):
>                 lp = lp + F.cross_entropy(head(c), z[:, j], reduction="none")
>                 if j < 2:
>                     c = c + self.tok[j](z[:, j])
>             return lp.mean()
>         motion = self.motion(h).view(-1, self.chunk, 2)
>         l1 = (motion - act[..., :2] / MAX_STEP).abs().sum(-1)          # L1 on normalized motions
>         bce = F.binary_cross_entropy_with_logits(self.grip(h), act[..., 2], reduction="none")
>         return ((l1 + bce) * mask).sum() / mask.sum()
>
>     @torch.no_grad()
>     def act(self, img, text):
>         """Actions (B, chunk, 3) in machine units: dx, dz and the grip as 0 or 1."""
>         h = self.context(img, text)
>         if self.head == "tokens":
>             z, c = [], h
>             for j, head in enumerate(self.heads):
>                 z.append(head(c).argmax(-1))
>                 if j < 2:
>                     c = c + self.tok[j](z[-1])
>             return from_bins(torch.stack(z, 1), self.n_bins)[:, None]
>         motion = self.motion(h).view(-1, self.chunk, 2).clamp(-1, 1) * MAX_STEP
>         grip = (self.grip(h) > 0).float()[..., None]
>         return torch.cat([motion, grip], -1)
>
>
> def to_bins(a, n_bins):
>     """Bin indices (B, 3) of actions a (B, 3): uniform bins over [-MAX_STEP, MAX_STEP] for dx, dz; the grip as 0 or 1."""
>     b = torch.round((a[:, :2].clamp(-MAX_STEP, MAX_STEP) + MAX_STEP) / (2 * MAX_STEP) * (n_bins - 1)).long()
>     return torch.cat([b, (a[:, 2:] > 0.5).long()], 1)
>
>
> def from_bins(z, n_bins):
>     """Actions (B, 3) at the centers of the bins z."""
>     return torch.cat([-MAX_STEP + z[:, :2].float() * (2 * MAX_STEP / (n_bins - 1)), z[:, 2:].float()], 1)
> ```

The demonstrations are recorded as in [Action representations I: discrete bins](https://aegean.ai/aiml-common/lectures/vla/action-representations.md): the operator plays 1,600 episodes and only the deliveries are kept. The operator's own delivery rate, measured with exact actions on 2,000 new machines, is the reference for every policy below.

> [accordion] Code
>
> ```python theme={null}
> def record_dataset(n_episodes, seed):
>     """Run the operator and keep its delivered episodes as a dataset of steps.
>
>     Returns:
>         dict of arrays over steps: image (uint8), instruction, action (dx, dz, grip),
>         episode index and step index within the episode.
>     """
>     env = ClawGrab(n_episodes, seed=seed)
>     rng = np.random.default_rng(seed + 1)
>     rec, alive, success = [], np.ones(n_episodes, bool), np.zeros(n_episodes, bool)
>     while alive.any():
>         img, text = env.observe()
>         a = expert_action(env, rng)
>         rec.append(((img * 255).astype(np.uint8), text, a, env.t.copy(), alive.copy()))
>         r, done = env.step(a)
>         success |= (r > 0) & alive
>         alive &= ~done
>     keep = success
>     episode = np.arange(n_episodes)
>     data = {k: np.concatenate([s[i][s[4] & keep] for s in rec]) for i, k in enumerate(["image", "instruction", "action", "step"])}
>     data["episode"] = np.concatenate([episode[s[4] & keep] for s in rec])
>     order = np.lexsort((data["step"], data["episode"]))                  # episode by episode, in time order
>     return {k: v[order] for k, v in data.items()}
>
>
> def chunk_targets(data, chunk):
>     """The next `chunk` actions of every step, and a mask that is 0 past the end of its episode."""
>     n = len(data["action"])
>     idx = np.arange(n)[:, None] + np.arange(chunk)[None]
>     idx_c = np.minimum(idx, n - 1)
>     mask = (idx < n) & (data["episode"][idx_c] == data["episode"][:, None])
>     act = np.where(mask[..., None], data["action"][idx_c], 0.0)
>     return act.astype(np.float32), mask.astype(np.float32)
>
>
> def train(model, data, steps=8000, lr=5e-4, batch=128, seed=0):
>     """Behavioral cloning of the operator with the model's own loss; returns the final smoothed loss."""
>     act, mask = chunk_targets(data, model.chunk)
>     img = torch.as_tensor(data["image"], device=DEV)
>     text = torch.as_tensor(data["instruction"], device=DEV)
>     act, mask = torch.as_tensor(act, device=DEV), torch.as_tensor(mask, device=DEV)
>     opt = torch.optim.AdamW(model.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(act), (batch,), generator=g)
>         loss = model.loss(img[j].float() / 255, text[j], act[j], mask[j])
>         opt.zero_grad(); loss.backward(); nn.utils.clip_grad_norm_(model.parameters(), 1.0); 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 evaluate(model, n=500, seed=123, stride=1, record=False):
>     """Delivery rate on n new machines, mean steps of a delivery, and mean model calls per episode.
>
>     Args:
>         stride: steps executed from each predicted chunk before the model is called again.
>             1 is receding-horizon control; stride = chunk executes every chunk open loop.
>         record: also return the claw path (T + 1, n, 2), the claw state (T + 1, n), per-episode success
>             and the named square's position at the start (n, 2).
>     """
>     env = ClawGrab(n, seed=seed, as_torch=True)        # images stay on the GPU
>     goal = env.goal().copy()
>     alive, succ = np.ones(n, bool), np.zeros(n, bool)
>     plan, calls, steps = None, np.zeros(n), np.zeros(n)
>     path, closed = [env.claw.copy()], [env.closed.copy()]
>     for t in range(T_MAX):
>         if t % stride == 0:
>             plan = model.act(*tt(*env.observe())).cpu().numpy()
>             calls += alive
>         a = plan[:, t % stride].copy()
>         a[~alive] = 0
>         r, done = env.step(a)
>         succ |= (r > 0) & alive
>         steps += alive
>         alive &= ~done
>         path.append(env.claw.copy()); closed.append(env.closed.copy())
>         if not alive.any():
>             break
>     if record:
>         return np.array(path), np.array(closed), succ, goal
>     return succ.mean(), steps[succ].mean() if succ.any() else float("nan"), calls.mean()
>
>
> def tt(img, text):
>     """Move an observation to the device as tensors."""
>     return torch.as_tensor(img, device=DEV), torch.as_tensor(text, device=DEV)
>
>
> def first_grab_error(model, stride=1, n=500):
>     """Horizontal distance between the claw and the named square when the claw first closes.
>
>     Returns:
>         the distances (one per episode that closed the claw at least once) and the share of episodes
>         in which the first close happened over the named square.
>     """
>     path, closed, succ, goal = evaluate(model, n=n, stride=stride, record=True)
>     t = closed.argmax(0)
>     has = closed.any(0)
>     err = np.abs(path[t, np.arange(n), 0] - goal[:, 0])[has]
>     return err, (err < SIDE / 2).mean()
> ```
>
> ```python theme={null}
> t0 = time.time()
> data = record_dataset(1600, seed=1)
> n_ep = len(np.unique(data["episode"]))
> print(f"{n_ep} delivered episodes, {len(data['action'])} steps, "
>       f"{data['image'].nbytes / 1e6:.0f} MB of images")
> for k, v in data.items():
>     print(f"  {k:12s} {str(v.dtype):8s} {v.shape}")
> ```

```output theme={null}
1134 delivered episodes, 54586 steps, 671 MB of images
  image        uint8    (54586, 3, 64, 64)
  instruction  int64    (54586, 5)
  action       float32  (54586, 3)
  step         int64    (54586,)
  episode      int64    (54586,)
```

> [accordion] Code
>
> ```python theme={null}
> def operator_delivery(n=2000, seed=0):
>     """Delivery rate of the operator with exact actions on n machines."""
>     env = ClawGrab(n, seed=seed)
>     rng = np.random.default_rng(seed + 1)
>     alive, succ = np.ones(n, bool), np.zeros(n, bool)
>     while alive.any():
>         r, done = env.step(expert_action(env, rng))
>         succ |= (r > 0) & alive
>         alive &= ~done
>     return succ.mean()
>
>
> operator_rate = operator_delivery()
> print(f"operator delivery: {operator_rate:.3f}")
> ```

```output theme={null}
operator delivery: 0.715
```

The baseline is a token head with 21 bins per motion axis, trained for 8,000 steps.

> [accordion] Code
>
> ```python theme={null}
> results, models = {}, {}
> torch.manual_seed(0)
> m = MiniVLA("tokens", n_bins=21).to(DEV)
> loss = train(m, data)
> rate, steps, calls = evaluate(m)
> results["21 bins"], models["21 bins"] = (rate, steps, calls, loss), m
> print(f"21 bins: loss {loss:.3f}, delivery {rate:.2f}, steps per delivery {steps:.1f}  [{time.time() - t0:.0f} s]")
> ```

```output theme={null}
/workspaces/eng-ai-agents/.venv-container/lib/python3.12/site-packages/torch/autograd/graph.py:1113: UserWarning: Memory Efficient attention defaults to a non-deterministic algorithm. To explicitly enable determinism call torch.use_deterministic_algorithms(True, warn_only=False). (Triggered internally at /__w/pytorch/pytorch/aten/src/ATen/native/transformers/cuda/attention_backward.cu:949.)
  return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
```

```output theme={null}
21 bins: loss 0.064, delivery 0.72, steps per delivery 49.6  [145 s]
```

The baseline delivers 0.72, the same as the operator (0.715). Each delivery rate on this page comes from one training run evaluated on 500 new machines, so differences of a few hundredths carry no weight.

## Continuous regression

A regression head skips the bins. It outputs the normalized motion $\tilde a \in [-1, 1]^2$ directly and is trained with an L1 loss, and a separate logit gives the probability of a closed claw. There is no rounding at all, and the output layer is two numbers instead of one logit per bin. ACT trains its action decoder with the L1 loss because it gave more precise actions than the squared error (Zhao et al., 2023).

## Action chunks

A chunked policy predicts the next $k$ actions from one observation, $\pi_\theta(a_{t:t+k} \mid o_t, \ell)$, instead of a single action (Zhao et al., 2023). The robot can then execute the chunk in two ways. Open-loop execution runs all $k$ actions and calls the model again only at step $t + k$, which cuts the number of model calls by a factor $k$ and, in ACT's words, the effective horizon of the task. Receding-horizon execution calls the model at every step and executes only the first action of each new chunk. Executing $s$ actions per call, with $1 \le s \le k$, spans the range between the two.

The code below trains a regression head with $k = 1$ and one with $k = 8$, with the same trunk and training budget as the baseline, and runs the second with $s = 1$, 4 and 8.

> [accordion] Code
>
> ```python theme={null}
> for k in [1, 8]:
>     torch.manual_seed(0)
>     m = MiniVLA("regress", chunk=k).to(DEV)
>     loss = train(m, data)
>     models[f"regression, chunk {k}"] = m
>     for stride in sorted({1, k // 2, k} - {0}):
>         rate, steps, calls = evaluate(m, stride=stride)
>         results[f"regression, chunk {k}, execute {stride}"] = (rate, steps, calls, loss)
>         print(f"regression chunk {k}, execute {stride}: loss {loss:.3f}, delivery {rate:.2f}, "
>               f"steps per delivery {steps:.1f}, model calls per episode {calls:.1f}  [{time.time() - t0:.0f} s]")
> ```

```output theme={null}
regression chunk 1, execute 1: loss 0.046, delivery 0.07, steps per delivery 59.0, model calls per episode 59.8  [245 s]
regression chunk 8, execute 1: loss 0.075, delivery 0.43, steps per delivery 48.8, model calls per episode 55.2  [366 s]
regression chunk 8, execute 4: loss 0.075, delivery 0.46, steps per delivery 48.4, model calls per episode 13.8  [367 s]
regression chunk 8, execute 8: loss 0.075, delivery 0.40, steps per delivery 49.5, model calls per episode 7.5  [368 s]
```

The single-step regression head delivers 0.07, against 0.72 for the 21-bin baseline. The chunked head with the same output layer delivers between 0.40 and 0.46, depending on how many actions it executes per call. Executing four of every eight predicted actions calls the model 14 times per episode instead of about 55, and executing whole chunks open loop needs only 7.5 calls, at a delivery rate of 0.40.

![Claw x over time in eight episodes for three policies: the 21-bin and chunked policies stop at the named square's x, while the single-step regression policy drives right to about 0.87 in every episode](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/action-chunks/images/cell_9_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=9da1a65e25227d1b8f746e63c0e50cb4)

The claw's horizontal position shows what goes wrong. Each line is one episode, dotted lines mark the named square, and blue episodes were delivered. The single-step regression policy drives right to about $x = 0.87$ in every episode, whatever the instruction says, and closes over whatever square is there. It delivers only when the named square happens to sit there. At its first close, the claw is over the named square in 16% of the episodes, against 98% for the 21-bin head and 92% for the chunked head; the median horizontal miss is 0.269 versus 0.016.

The operator travels at full speed and stops within a step or two of its aim point. A single-step target therefore shows the stop on only one or two steps per episode, and on every other travel step the target is the same full-speed move. With chunks of 8, each of the last eight travel steps carries the coming stop inside its target. That fits the result, but this experiment does not prove it is the cause. The token head learns the stop from single steps, so the failure belongs to the regression head on this data, not to single-step prediction in general.

## Comparison

> [accordion] Code
>
> ```python theme={null}
> print(f"{'representation':38s} {'delivery':>8s} {'steps':>6s} {'calls':>6s}")
> print(f"{'operator (the demonstrations)':38s} {operator_rate:8.3f}")
> for name, (rate, steps, calls, loss) in results.items():
>     print(f"{name:38s} {rate:8.2f} {steps:6.1f} {calls:6.1f}")
> print()
> for name, m, stride in [("21 bins", models["21 bins"], 1), ("regression, chunk 1", models["regression, chunk 1"], 1),
>                         ("regression, chunk 8, execute 4", models["regression, chunk 8"], 4)]:
>     err, over = first_grab_error(m, stride)
>     print(f"{name:32s} first close: median |x - x_target| {np.median(err):.3f}, over the named square {over:.2f}")
> ```

```output theme={null}
representation                         delivery  steps  calls
operator (the demonstrations)             0.715
21 bins                                    0.72   49.6   52.5
regression, chunk 1, execute 1             0.07   59.0   59.8
regression, chunk 8, execute 1             0.43   48.8   55.2
regression, chunk 8, execute 4             0.46   48.4   13.8
regression, chunk 8, execute 8             0.40   49.5    7.5

21 bins                          first close: median |x - x_target| 0.016, over the named square 0.98
regression, chunk 1              first close: median |x - x_target| 0.269, over the named square 0.16
regression, chunk 8, execute 4   first close: median |x - x_target| 0.019, over the named square 0.92
```

The 21-bin token head matches the operator, which is the most behavioral cloning can do here: it copies the demonstrations, including the operator's off-center grabs. Continuous regression failed to ground the instruction with single-step targets. Predicting chunks recovered more than half of the gap to the baseline and cut model calls by up to a factor of eight. ACT predicts chunks to shorten the effective horizon in the same way (Zhao et al., 2023), and later sections of this chapter return to them. Both heads here also predict a single action for a given input, the median or the most likely bin. Neither can represent an operator who sometimes passes an obstacle on the left and sometimes on the right. Heads that sample from a learned distribution over chunks, such as diffusion and flow matching, address that case.

## References

* 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/action-chunks).


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