> ## 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 I: discrete bins

> How many bins each action axis needs

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

In [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl.md) you trained MiniVLA on the claw machine with 21 bins per motion axis, and that choice went unexamined. This section looks at the data a VLA learns from, at how actions are normalized, and at the first way to represent an action: as discrete bins, one class label per action dimension. Every comparison uses the same trunk, the same demonstrations and the same training budget, so only the number of bins changes.

> [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 an autoregressive token head over binned actions.
>
>     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 predicts the
>     dx bin, then the dz bin given dx, then the grip given both.
>
>     Args:
>         n_bins: bins per motion axis.
>         d: width of the tokens.
>         layers: transformer layers.
>         heads: attention heads.
>     """
>
>     def __init__(self, n_bins=21, d=128, layers=3, heads=4):
>         super().__init__()
>         self.n_bins = n_bins
>         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))
>         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)])
>
>     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):
>         """Cross-entropy of the operator's binned action tokens.
>
>         Args:
>             act: float tensor (B, 3) of operator actions (dx, dz, grip).
>         """
>         h = self.context(img, text)
>         z = to_bins(act, 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()
>
>     @torch.no_grad()
>     def act(self, img, text):
>         """Actions (B, 3) at the centers of the most likely bins: dx, dz and the grip as 0 or 1."""
>         z, c = [], self.context(img, text)
>         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)
>
>
> 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)
> ```

## Robot demonstration datasets

A demonstration dataset is a set of episodes. Each episode is one attempt at a task, recorded as a sequence of time steps, and each step holds an observation, the instruction and the action the operator took. The observation is usually one or more camera images plus the robot's proprioceptive state, such as joint angles or the gripper opening. The instruction is constant within an episode.

The large public collections share this layout. Open X-Embodiment combined more than 70 robot datasets with over 2 million trajectories when OpenVLA was built, and OpenVLA was trained on a curated 970 thousand of them (Kim et al., 2024). Each episode is a sequence of steps with an observation dictionary, an action, a reward and flags that mark the first and last step. The [LeRobot dataset format](https://huggingface.co/docs/lerobot/lerobot-dataset-v3) keeps the low-dimensional signals, such as states, actions and timestamps, in Parquet tables with one row per frame, and encodes the camera streams as MP4 video. Its metadata records the schema and frame rate of every feature, the mean, standard deviation, minimum and maximum of each feature for normalization, the task descriptions with their integer IDs, and where each episode starts and ends inside the shared files.

The dataset below has the same fields. The operator from [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl.md) plays 1,600 episodes, and only the deliveries are kept, as a lab keeps the demonstrations that worked.

> [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 train(model, data, steps=8000, lr=5e-4, batch=128, seed=0):
>     """Behavioral cloning of the operator with the model's cross-entropy loss; returns the final smoothed loss."""
>     img = torch.as_tensor(data["image"], device=DEV)
>     text = torch.as_tensor(data["instruction"], device=DEV)
>     act = torch.as_tensor(data["action"].astype(np.float32), 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])
>         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):
>     """Delivery rate on n new machines, mean steps of a delivery, and mean model calls per episode."""
>     env = ClawGrab(n, seed=seed, as_torch=True)        # images stay on the GPU
>     alive, succ = np.ones(n, bool), np.zeros(n, bool)
>     calls, steps = np.zeros(n), np.zeros(n)
>     for t in range(T_MAX):
>         a = model.act(*tt(*env.observe())).cpu().numpy()
>         calls += alive
>         a[~alive] = 0
>         r, done = env.step(a)
>         succ |= (r > 0) & alive
>         steps += alive
>         alive &= ~done
>         if not alive.any():
>             break
>     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)
> ```
>
> ```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,)
```

The figure shows one delivered episode: six frames, the action at every step, and below it the distribution of the motion actions over the whole dataset.

![Six frames of one delivered episode, the claw moving out, down, catching the blue square and carrying it to the chute; below, the dx, dz and grip actions over the episode's steps, and a log-scale histogram of all motion actions with spikes at minus 0.05, 0 and plus 0.05](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/action-representations/images/cell_6_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=4269534eecf302bae8f5ca2cfdccd9c4)

Most steps sit at the bounds $\pm 0.05$ or at exactly 0. The claw travels at full speed along one axis while the other axis stays still, and only the last few steps of an approach take intermediate values. Those rare values decide where the claw stops.

## Action normalization

Robots differ in units and ranges: a joint velocity in radians per second, a gripper opening in millimeters, an end-effector displacement in meters. Before a network sees them, each action dimension is mapped to a common range, usually $[-1, 1]$:

$$
\tilde a = 2\,\frac{a - a_{\mathrm{lo}}}{a_{\mathrm{hi}} - a_{\mathrm{lo}}} - 1 .
$$

The bounds $a_{\mathrm{lo}}$ and $a_{\mathrm{hi}}$ come from the training data. The minimum and maximum are the simplest choice, but a single outlier then stretches the range and wastes resolution. OpenVLA uses the 1st and 99th quantiles of each dimension instead (Kim et al., 2024). Other pipelines standardize with the mean and standard deviation. The policy predicts $\tilde a$, and the inverse map turns it back into robot units before execution.

On the claw machine the bounds are known exactly, $\pm 0.05$ for both motion axes, so normalization is a division by 0.05. The grip is already binary.

## Discrete action bins

A token head splits the normalized range of each dimension into $B$ equal bins and predicts the index of a bin, so an action becomes a short sequence of class labels. MiniVLA predicts three tokens per step, as OpenVLA predicts seven, one per dimension of its action, with 256 bins each (Kim et al., 2024). The executed action is the bin center, so the quantization error on an axis of width $a_{\mathrm{hi}} - a_{\mathrm{lo}}$ is at most half a bin:

$$
|a - \hat a| \le \frac{a_{\mathrm{hi}} - a_{\mathrm{lo}}}{2(B - 1)} .
$$

You can measure what quantization alone costs by rounding the operator's own actions to the bin centers before they are executed. No learning is involved.

> [accordion] Code
>
> ```python theme={null}
> def operator_with_bins(n_bins, n=2000, seed=0):
>     """Delivery rate of the operator when its actions are rounded to bin centers (None: no rounding)."""
>     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():
>         a = expert_action(env, rng)
>         if n_bins:
>             a = from_bins(to_bins(torch.as_tensor(a), n_bins), n_bins).numpy()
>         r, done = env.step(a)
>         succ |= (r > 0) & alive
>         alive &= ~done
>     return succ.mean()
>
>
> BIN_COUNTS = [3, 5, 9, 21, 101, 256]
> operator_rate = {b: operator_with_bins(b) for b in BIN_COUNTS}
> operator_rate[None] = operator_with_bins(None)
> print("operator delivery with rounded actions:", {k: round(v, 2) for k, v in operator_rate.items()})
> print("odd and even neighbors:", {b: round(operator_with_bins(b), 2) for b in (20, 21, 22, 255, 256)})
> ```

```output theme={null}
operator delivery with rounded actions: {3: np.float64(0.0), 5: np.float64(0.52), 9: np.float64(0.72), 21: np.float64(0.72), 101: np.float64(0.71), 256: np.float64(0.69), None: np.float64(0.72)}
odd and even neighbors: {20: np.float64(0.42), 21: np.float64(0.72), 22: np.float64(0.67), 255: np.float64(0.72), 256: np.float64(0.69)}
```

From 9 bins up, rounding costs the operator nothing: it delivers 0.72, 0.72 and 0.71 with 9, 21 and 101 bins, the same as with exact actions (0.72). With 5 bins the smallest move is 0.025 and with 3 bins it is 0.05, both coarser than the alignment the operator waits for before it lowers the claw. Delivery falls to 0.52 with 5 bins, and with 3 bins the operator never delivers.

The parity of the bin count matters too. With an odd count, one bin is centered on zero; with an even count, none is, so no token means "hold this axis still". Rounding to 20, 22 or 256 bins gives 0.42, 0.67 and 0.69, while 21 and 255 bins both give 0.72. OpenVLA's 256 bins span the 1st to the 99th quantile of each dimension, so whether one of them sits at zero depends on the data.

Training a policy on the bins adds a cost that rounding alone does not show. More bins mean less rounding, but every bin is a separate class, so each class sees fewer examples and neighboring classes are hard to tell apart. Each run below trains the same MiniVLA for 8,000 steps on the same dataset.

> [accordion] Code
>
> ```python theme={null}
> results, models = {}, {}
> for b in [5, 21, 101, 256]:
>     torch.manual_seed(0)
>     m = MiniVLA(n_bins=b).to(DEV)
>     loss = train(m, data)
>     rate, steps, calls = evaluate(m)
>     results[f"{b} bins"], models[f"{b} bins"] = (rate, steps, calls, loss), m
>     print(f"{b:4d} 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}
   5 bins: loss 0.033, delivery 0.71, steps per delivery 49.5  [146 s]
  21 bins: loss 0.064, delivery 0.72, steps per delivery 49.6  [246 s]
 101 bins: loss 0.094, delivery 0.69, steps per delivery 48.8  [346 s]
 256 bins: loss 0.123, delivery 0.62, steps per delivery 49.0  [447 s]
```

![Delivery rate against bins per motion axis on a log scale: the operator with rounded actions rises from 0 at 3 bins and 0.52 at 5 bins to 0.72 from 9 bins on and dips to 0.69 at 256; the trained MiniVLA stays between 0.69 and 0.72 up to 101 bins and drops to 0.62 at 256](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/action-representations/images/cell_9_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=9e31e51f9c3678f2826189751bbd5dd0)

The trained policies deliver 0.71, 0.72 and 0.69 with 5, 21 and 101 bins, the same as the operator they copy, and flat across a twentyfold change in resolution. Each number comes from one training run evaluated on 500 machines, so differences of a few hundredths carry no weight. The 5-bin policy is the clear case. It delivers 0.71, while the operator rounded to 5 bins delivers 0.52, because the policy does not round the operator's actions: it learns from them which coarse move to make in each state. With 256 bins delivery drops to 0.62, consistent with the even-count effect above combined with 256 classes per axis that each see fewer examples.

Discrete bins work on the claw machine when a bin sits at zero and there are enough of them. From 5 to 101 bins the trained policy matches the operator. Rounding the operator's own actions costs delivery only at 5 bins or fewer and at even bin counts, most of all at 20 bins. [Action representations II: regression and chunks](https://aegean.ai/aiml-common/lectures/vla/action-chunks.md) replaces the bins with a continuous output and then with chunks of several future actions.

## References

* Kim, M., Pertsch, K., Karamcheti, S., Xiao, T., Balakrishna, A., et al. (2024). *OpenVLA: An Open-Source Vision-Language-Action Model*. arXiv \[cs.RO]. [Link](http://arxiv.org/abs/2406.09246)

***

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-representations).


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