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

# Behavioral cloning and RL on a claw machine

> Train a small VLA on demonstrations, then fine-tune it with PPO

[![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/bc-vs-rl/index.ipynb)

A vision-language-action (VLA) model is a robot policy $\pi_\theta(a \mid o, \ell)$. It reads a camera observation $o$ and an instruction $\ell$ in natural language, and it outputs the next action $a$: an end-effector move, a gripper command, or a short sequence of both. Three parts make up most VLAs. A vision encoder, often a vision transformer pretrained on image-text pairs, turns the image into patch features. A language model reads the instruction together with those features. An action head turns the joint representation into motor commands.

| Model | Publisher | Core idea |
| - | - | - |
| RT-1 | Google | Tokenize actions; train a transformer on 130k robot episodes |
| RT-2 | Google | Fine-tune a vision-language model end to end on robot data |
| OpenVLA | Stanford, Berkeley | Open VLA: Llama 2 with DINOv2 and SigLIP image features |
| π₀ | Physical Intelligence | Flow-matching action expert on a vision-language backbone |

Large VLAs are built in stages. A vision-language backbone is pretrained on web-scale image-text data, which gives it broad visual and semantic knowledge. The backbone and an action head are then trained by behavioral cloning on robot demonstrations, such as Open X-Embodiment or BridgeData V2 (Brohan et al., 2023). The central difficulty is grounding: the policy has to tie the words of the instruction ("the red cup") to the right image regions and then to the right motion (Paul et al., 2018; Walsman et al., 2018). More and more systems add a last stage, reinforcement learning (RL) against a task reward.

This section builds each of those stages at a scale that trains in minutes. You train a small VLA on demonstrations, watch where behavioral cloning fails, fix one failure with DAgger, and then improve the policy beyond its demonstrations with PPO. The task, the model and the training code stay the same through the rest of the chapter.

> [accordion] Code
>
> ```python theme={null}
> import os
> os.environ.setdefault("CUBLAS_WORKSPACE_CONFIG", ":4096:8")
> 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)
> R = {}   # results quoted in the text
> ```

## The ClawGrab task

ClawGrab is a claw machine seen through its glass front. Three colored squares rest on the floor of the bin. A claw hangs on a cable from a gantry and starts above the chute in the left corner. The instruction names one square ("grab the red square", "get the blue one", "pick up the green block"), and the episode pays a reward of 1 only when that square drops into the chute. Everything else pays 0.

Each step the policy chooses three things: a horizontal move $\Delta x$, a vertical move $\Delta z$, both at most 0.05 in a machine that is 1 wide and 1 tall, and whether the claw is open or closed. Closing the claw over a square catches it with a probability that depends on how well the claw is centered:

$$
P(\text{catch}) = \exp\!\big(-(o / 0.03)^2\big),
$$

where $o$ is the horizontal offset between the claw and the center of the square. A caught square can also slip out on any step it is carried, with probability $0.002 + 0.01\,(o/0.02)^2$, so an off-center catch is both less likely and less secure. Opening the claw releases the held square. The squares are rigid boxes in a physics simulation (Newton), so a released square falls under gravity and lands on the floor or on another square, from which it can slide off. A square released over the chute is delivered and ends the episode. Many machines run at once as parallel worlds on the GPU, and the camera image is drawn from the simulated poses.

An episode has 60 steps of 0.1 s each. A clean grab and delivery takes about 50, so one miss or one slip usually costs the episode, and a well-centered grasp pays off.

The demonstrations come from a scripted operator. Like a person at a real machine, it judges the alignment by eye: before each descent it aims to the right of the square's center by a random amount up to 0.04, and it stops correcting once it is above its aim point. When a catch fails it opens, rises and tries again, and when a square slips it goes back for it.

> [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)])
>
>
> 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 ClawGrab:
>     """A batch of n claw machines, simulated with Newton 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)
>
>
> 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)
> ```

The figure shows one delivered operator episode, titled with its instruction: the approach, the descent, the catch of the named square, the carry and the drop into the chute.

```output theme={null}
operator delivers 0.70; the same controller aimed at the center delivers 0.93; the operator from random claw positions delivers 0.83
filmed episode: "grab the red square", 53 steps, delivered: True
```

![Six frames of one operator episode, titled with its instruction, grab the red square. The claw moves right, descends, catches the red square, carries it up and to the left, and drops it over the chute in the lower left corner.](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/bc-vs-rl/images/cell_3_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=624dd295c86819022c5a713f344e29ec)

## MiniVLA

MiniVLA has the parts of a large VLA at a size that trains on one GPU in a few minutes. Three stride-2 convolutions turn the 64 x 64 image into an 8 x 8 grid of patch features. Two extra input channels hold the $x$ and $z$ coordinate of every pixel, so that position is easy to read. A transformer then reads a summary token, the 64 patch tokens and the instruction's word tokens, and its output at the summary token is a vector $h$ that describes the observation and the instruction together.

The action head follows RT-1 and OpenVLA. Each motion axis is split into 21 bins, the grip is a binary token, and the head emits the three tokens one after the other, each conditioned on the ones before it:

$$
\log \pi_\theta(z_{1:3} \mid o, \ell) = \sum_{j=1}^{3} \log p_\theta(z_j \mid h, z_{<j}).
$$

The same sum of token log-probabilities is what PPO uses later, in the same way RL methods for OpenVLA use the log-probabilities of its action tokens.

The instruction also modulates the image features before the transformer sees them, through feature-wise linear modulation (FiLM) (Perez et al., 2017), as in RT-1. After each convolution the feature map $x$ is rescaled channel by channel, $x \leftarrow (1 + \gamma(\ell))\,x + \beta(\ell)$, where $\gamma$ and $\beta$ are linear functions of the mean word embedding. The color word can then decide which features the image encoder emphasizes.

> [accordion] Code
>
> ```python theme={null}
> TOKEN_SIZES = [N_BINS, N_BINS, 2]      # dx, dz, grip
>
>
> class MiniVLA(nn.Module):
>     """A small vision-language-action policy with an autoregressive action-token head.
>
>     The image passes through three stride-2 convolutions, each modulated by the instruction
>     (FiLM), which leaves an 8 x 8 grid of patch features. A transformer reads a summary token,
>     the 64 patch tokens and the instruction tokens. Its output at the summary token, h, gives the
>     distribution of the dx token, then of the dz token given dx, then of the grip token given both.
>
>     Args:
>         d: width of the tokens.
>         layers: transformer layers.
>         heads: attention heads.
>         use_film: condition the convolutions on the instruction.
>     """
>
>     def __init__(self, d=128, layers=3, heads=4, use_film=True):
>         super().__init__()
>         self.use_film = use_film
>         self.temp = 1.0          # sampling temperature: the policy is softmax(logits / temp)
>         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])   # x and z of every pixel, as two channels
>         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)
>         self.heads = nn.ModuleList([nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, k)) for k in TOKEN_SIZES])
>         self.tok = nn.ModuleList([nn.Embedding(k, d) for k in TOKEN_SIZES[:-1]])
>         self.value = nn.Sequential(nn.Linear(d, d), nn.GELU(), nn.Linear(d, 1))   # critic, used by PPO
>
>     def context(self, img, text):
>         """Summary vector h of observation img (B, 3, IMG, IMG) and instruction text (B, L_TEXT)."""
>         w = self.word(text)
>         keep = (text != 0).unsqueeze(-1).float()
>         u = (w * keep).sum(1) / keep.sum(1)                       # mean word embedding
>         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):
>             x = norm(conv(x))
>             if self.use_film:
>                 gamma, beta = film(u).chunk(2, -1)
>                 x = x * (1 + gamma[:, :, None, None]) + beta[:, :, None, None]
>             x = F.gelu(x)
>         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 log_prob(self, h, z):
>         """log pi(z | o, l) = sum_j log p(z_j | h, z_<j) for action tokens z (B, 3).
>
>         Returns:
>             the log-probability (B,) and the list of logits of the three tokens.
>         """
>         lp, logits, c = 0.0, [], h
>         for j, head in enumerate(self.heads):
>             l = head(c) / self.temp
>             logits.append(l)
>             lp = lp + F.log_softmax(l, -1).gather(1, z[:, j:j + 1]).squeeze(1)
>             if j < len(self.tok):
>                 c = c + self.tok[j](z[:, j])
>         return lp, logits
>
>     @torch.no_grad()
>     def act(self, img, text, greedy=True):
>         """Action tokens (B, 3): the most likely ones, or a sample when greedy is False."""
>         c, z = self.context(img, text), []
>         for j, head in enumerate(self.heads):
>             l = head(c) / self.temp
>             zj = l.argmax(-1) if greedy else torch.distributions.Categorical(logits=l).sample()
>             z.append(zj)
>             if j < len(self.tok):
>                 c = c + self.tok[j](zj)
>         return torch.stack(z, 1)
>
>
> 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)
> ```

## Behavioral cloning

Behavioral cloning (BC) treats the demonstrations as labeled data: given the observation and the instruction, predict the operator's action tokens. You minimize the cross-entropy

$$
\mathcal L(\theta) = -\,\mathbb E_{(o,\ell,z) \sim \mathcal D}\big[\log \pi_\theta(z \mid o, \ell)\big]
$$

over the dataset $\mathcal D$ of operator steps, which is the BC objective from [Behavioral cloning](https://aegean.ai/aiml-common/lectures/imitation-learning/behavioral-cloning/index.md) with a token head. The motion targets are smoothed: 10% of the target probability is spread evenly over the bins, which keeps some probability on neighboring moves for RL to explore later. The grip target is not smoothed, because a sampled grip error opens the claw in the middle of a carry and drops the square.

Only the operator's successful episodes go into $\mathcal D$, as is common with real demonstrations. You train the same model twice, with and without FiLM.

> [accordion] Code
>
> ```python theme={null}
> def collect_demos(n_episodes, seed, keep_failures=False):
>     """Run the operator on n_episodes machines and record (image, instruction, action tokens) per step.
>
>     Args:
>         keep_failures: also keep the episodes that ran out of time; by default only deliveries are kept.
>
>     Returns:
>         images, instructions and tokens, concatenated over the kept episodes.
>     """
>     env = ClawGrab(n_episodes, seed=seed)
>     rng = np.random.default_rng(seed + 1)
>     steps, alive, success = [], np.ones(n_episodes, bool), np.zeros(n_episodes, bool)
>     while alive.any():
>         img, text = env.observe()
>         a = from_tokens(to_tokens(expert_action(env, rng)))
>         steps.append((img, text, to_tokens(a), alive.copy()))
>         r, done = env.step(a)
>         success |= (r > 0) & alive
>         alive &= ~done
>     keep = np.ones(n_episodes, bool) if keep_failures else success
>     out = [np.concatenate([s[k][s[3] & keep] for s in steps]) for k in range(3)]
>     print(f"operator delivered {success.mean():.2f} of {n_episodes} episodes; kept {keep.sum()} episodes, {len(out[2])} steps")
>     return out
>
>
> def train_bc(model, data, steps, lr=5e-4, batch=128, smoothing=0.1, seed=0):
>     """Behavioral cloning: minimize the cross-entropy of the operator's tokens, with label smoothing.
>
>     Args:
>         model: the MiniVLA to train, in place.
>         data: (images, instructions, tokens) from collect_demos.
>         steps: gradient steps.
>         smoothing: share of the target probability spread evenly over the bins of dx and of dz.
>
>     Returns:
>         the smoothed training loss at the end.
>     """
>     img, text, z = [torch.as_tensor(x, device=DEV) for x in data]
>     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(z), (batch,), generator=g)
>         lp, logits = model.log_prob(model.context(img[j], text[j]), z[j])
>         # smooth the two motion tokens only: a sampled grip error would drop the carried square
>         lp_grip = F.log_softmax(logits[2], -1).gather(1, z[j][:, 2:]).squeeze(1)
>         uniform = sum(F.log_softmax(l, -1).mean(-1) for l in logits[:2])
>         loss = -((1 - smoothing) * (lp - lp_grip) + smoothing * uniform + lp_grip).mean()
>         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 evaluate(model, n=500, seed=123, greedy=True, slip=1.0, details=False, record=False, random_start=False):
>     """Delivery rate of the policy on n new machines.
>
>     Args:
>         greedy: take the most likely tokens instead of sampling.
>         slip: scale of the slip probability.
>         random_start: start the claw at a random position.
>         details: also return per-episode success, misses, slips and catch offsets.
>         record: return per-episode success and length, the environment, the claw path (T + 1, n, 2)
>             and the held square per step (T + 1, n) instead of the rate.
>     """
>     env = ClawGrab(n, seed=seed, slip=slip, random_start=random_start)
>     alive, succ = np.ones(n, bool), np.zeros(n, bool)
>     offsets, path, held, length = [], [env.claw.copy()], [env.held.copy()], np.zeros(n, int)
>     while alive.any():
>         a = from_tokens(model.act(*tt(*env.observe()), greedy=greedy).cpu().numpy())
>         a[~alive] = 0
>         length += alive
>         before = env.held.copy()
>         r, done = env.step(a)
>         caught = alive & (before < 0) & (env.held >= 0)
>         offsets.extend(env.offset[caught].tolist())
>         succ |= (r > 0) & alive
>         alive &= ~done
>         path.append(env.claw.copy()); held.append(env.held.copy())
>     if record:
>         return succ, length, env, np.array(path), np.array(held)
>     if details:
>         return succ.mean(), dict(success=succ, misses=env.misses.copy(), slips=env.slips.copy(), offsets=np.array(offsets),
>                                  drops=env.drops.copy(), wrong=env.wrong.copy(), holding=env.held >= 0, claw=env.claw.copy())
>     return succ.mean()
> ```
>
> ```python theme={null}
> t0 = time.time()
> demos = collect_demos(2000, seed=1)
> models = {}
> for film in (False, True):
>     torch.manual_seed(0)
>     models[film] = MiniVLA(use_film=film).to(DEV)
>     loss = train_bc(models[film], demos, steps=8000)
>     R[f"bc_film_{film}"] = evaluate(models[film])
>     print(f"FiLM {'on ' if film else 'off'}: training loss {loss:.3f}, delivery on 500 new machines {R[f'bc_film_{film}']:.2f}")
> bc = models[True]
> print(f"[{time.time() - t0:.0f} s]")
> ```

```output theme={null}
operator delivered 0.69 of 2000 episodes; kept 1389 episodes, 66823 steps
```

```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}
FiLM off: training loss 1.296, delivery on 500 new machines 0.16
FiLM on : training loss 1.260, delivery on 500 new machines 0.74
[201 s]
```

The operator delivered 70% of its episodes, and its 66,823 successful steps form $\mathcal D$. Without FiLM, BC delivers only 16%: the transformer can attend from the word tokens to the image, but in practice the policy learns to go to a square, often the wrong one. With FiLM it delivers 74%, close to the operator it copies. RT-1 grounds language the same way, by conditioning the image features on the instruction.

## Covariate shift

BC learns from the states the operator visited. When the policy makes an error, or starts somewhere the operator never started, it reaches states that the dataset covers poorly. Its errors there are larger, which takes it further from the data. This compounding is called covariate shift (Ross et al., 2010).

Every demonstration starts with the claw above the chute. A real machine starts wherever the previous player left the claw, so the test below starts the claw at a random position above the squares. The operator is unaffected, because it reacts to where the claw is: it delivers 83% from random starts. The cloned policy has seen few images with the claw in those places.

> [accordion] Code
>
> ```python theme={null}
> rate_bc, d_bc = evaluate(bc, details=True)
> rate_bc_random = evaluate(bc, random_start=True)
> R.update(bc=rate_bc, bc_random=rate_bc_random, demos=len(demos[2]))
> print(f"BC delivery with the claw starting above the chute: {rate_bc:.2f}")
> print(f"BC delivery with the claw starting at a random position: {rate_bc_random:.2f} (operator {rate_op_random:.2f})")
> ```

```output theme={null}
BC delivery with the claw starting above the chute: 0.74
BC delivery with the claw starting at a random position: 0.04 (operator 0.83)
```

![Four claw machines with the claw starting at random positions. Black lines trace the claw path of the cloned policy, dotted while the claw is empty and solid while it holds a square. A cross marks the start, and each panel title says whether the episode delivered a square.](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/bc-vs-rl/images/cell_8_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=7b43d8892000924f688b18df5779e96d)

From the usual start BC delivers 74%. From a random start it delivers 4%. The paths show what goes wrong: from a position the demonstrations never showed, the policy often fails to move toward the named square at all.

## DAgger

Dataset aggregation (DAgger) (Ross et al., 2010) collects data in the states that the policy itself visits. Each round runs the current policy from random starts and asks the operator what it would have done in every state the policy reached. Those labeled states join the dataset, and a new policy is trained on the whole aggregate. The training data then covers the states that the policy's own behavior leads to.

> [accordion] Code
>
> ```python theme={null}
> def dagger(model, data, rounds, n_roll=500, steps=8000):
>     """DAgger: run the policy from random claw positions, let the operator label the states it visits,
>     and retrain on all data.
>
>     Each round trains a new MiniVLA from scratch on the aggregated dataset.
>
>     Args:
>         model: the BC policy that runs the first round.
>         data: the initial demonstrations.
>         rounds: number of collect-and-retrain rounds.
>         n_roll: episodes the policy runs in each round.
>         steps: gradient steps of each retraining.
>
>     Returns:
>         the last policy, and a list of (samples, delivery from the chute, delivery from a random start) per round.
>     """
>     img0, text0, z0 = data
>     history = []
>     for r in range(rounds):
>         env = ClawGrab(n_roll, seed=1000 + r, random_start=True)
>         rng = np.random.default_rng(r)
>         alive = np.ones(n_roll, bool)
>         new = ([], [], [])
>         while alive.any():
>             img, text = env.observe()
>             label = to_tokens(expert_action(env, rng))          # what the operator would do here
>             for lst, x in zip(new, (img, text, label)):
>                 lst.append(x[alive])
>             _, done = env.step(from_tokens(model.act(*tt(img, text)).cpu().numpy()))
>             alive &= ~done
>         img0, text0, z0 = (np.concatenate([old] + lst) for old, lst in zip((img0, text0, z0), new))
>         torch.manual_seed(r + 1)
>         model = MiniVLA().to(DEV)
>         train_bc(model, (img0, text0, z0), steps=steps, seed=r + 1)
>         history.append((len(z0), evaluate(model), evaluate(model, random_start=True)))
>         print(f"round {r + 1}: {history[-1][0]} samples, delivery {history[-1][1]:.2f} from the chute, "
>               f"{history[-1][2]:.2f} from a random start")
>     return model, history
>
>
> bc_dagger, dagger_hist = dagger(bc, demos, rounds=3)
> R.update(dagger=dagger_hist[-1][1], dagger_random=dagger_hist[-1][2], dagger_samples=dagger_hist[-1][0])
> ```

```output theme={null}
round 1: 95867 samples, delivery 0.71 from the chute, 0.51 from a random start
round 2: 121838 samples, delivery 0.68 from the chute, 0.54 from a random start
round 3: 148237 samples, delivery 0.61 from the chute, 0.47 from a random start
```

![Top: delivery rate of the cloned policy and of three DAgger rounds, from the usual start above the chute and from a random start, with a dashed line for the operator from a random start. Bottom: claw paths of the final DAgger policy on four machines with random starts, drawn as in the previous figure.](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/bc-vs-rl/images/cell_10_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=ed7a0d34d86e812dd890f7cb1f093f12)

After three rounds DAgger delivers 47% from random starts, up from 4% for BC, with 148,237 labeled steps in the dataset. Most of the gain came in the first round. Delivery from the usual start fell at the same time, from 74% to 61%. This run does not show why. One possibility is that the aggregated dataset now holds many states from the policy's failed episodes and fewer clean operator runs, so the model fits the clean runs less closely. The operator's labels are the other price: someone has to say what the right action is in every state the policy visits.

## Improving on the demonstrations with RL

DAgger fixes states the operator never showed, but it cannot make the policy better than the operator: the labels still aim off center. To improve on the operator you need a training signal that measures the outcome itself. That signal is the reward. RL fine-tuning maximizes the expected discounted return

$$
J(\theta) = \mathbb E_{\pi_\theta}\Big[\sum_{t=0}^{T} \gamma^t r_t\Big]
$$

starting from the BC policy. RL post-training of VLAs follows this recipe. Imitation gives a policy that already succeeds part of the time, and RL raises how often.

The update is [PPO](https://aegean.ai/aiml-common/lectures/reinforcement-learning/policy-based-algorithms/PPO/index.md) (Schulman et al., 2017) with the clipped surrogate objective, where the probability ratio $\pi_\theta(z \mid o, \ell) / \pi_{\theta_{old}}(z \mid o, \ell)$ is computed from the sum of the three token log-probabilities. Four details make it work on a BC policy.

The discount has to reach across the task. With $\gamma$, a reward $k$ steps ahead is weighted by $\gamma^k$, so the policy effectively looks about $1/(1 - \gamma)$ steps ahead. The delivery reward arrives roughly 50 steps after the start. With $\gamma = 0.9$ it is weighted by $0.9^{50} \approx 0.005$, the steps of the approach receive almost no signal, and PPO turns them into noise until delivery collapses. With $\gamma = 0.99$ the weight is $0.99^{50} \approx 0.61$.

Rollouts sample the policy at temperature 0.5, from $\pi_\theta \propto \exp(\text{logits}/0.5)$, and the ratio uses the same temperature. The cloned distribution is wide, because the operator chose a new aim point for every attempt; sampled at temperature 1 the BC policy jitters, closes the claw too early and delivers only a few percent of the time, so RL would start with almost no successes to learn from.

The critic reads $h$ with its gradient stopped, so fitting the value function cannot reshape the features that the pretrained policy relies on, and during the first five iterations only the critic learns. Finally, the epochs of an iteration stop early once the approximate KL divergence from the rollout policy exceeds 0.01.

> [accordion] Code
>
> ```python theme={null}
> def ppo(model, iters, n_envs=128, horizon=64, gamma=0.99, lam=0.95, clip=0.2, lr=3e-5,
>         epochs=4, minibatch=1024, critic_warmup=5, log_every=10, temp=0.5, max_kl=0.01):
>     """PPO fine-tuning of a MiniVLA with the sparse delivery reward.
>
>     Rollouts sample the policy at temperature temp, and the ratio uses the same temperature. The
>     epochs of an iteration stop early once the approximate KL divergence from the rollout policy
>     exceeds max_kl. The ratio pi_theta / pi_old uses the log-probability of all three action tokens. The critic
>     reads the summary vector h with its gradient stopped, so the value loss cannot change the
>     features that the pretrained policy relies on. During the first critic_warmup iterations only
>     the critic learns.
>
>     Returns:
>         list of (iteration, delivery rate of the sampled policy in the rollouts, greedy delivery rate on new machines).
>     """
>     model.temp = temp
>     env = ClawGrab(n_envs, seed=2024)
>     opt = torch.optim.AdamW(model.parameters(), lr=lr)
>     history = []
>     for it in range(iters):
>         I, X, Z, LP, V, R, D = [], [], [], [], [], [], []
>         for _ in range(horizon):
>             img, text = tt(*env.observe())
>             with torch.no_grad():
>                 h = model.context(img, text)
>                 z = model.act(img, text, greedy=False)
>                 lp, _ = model.log_prob(h, z)
>                 v = model.value(h).squeeze(1)
>             r, done = env.step(from_tokens(z.cpu().numpy()))
>             I.append(img); X.append(text); Z.append(z); LP.append(lp); V.append(v)
>             R.append(torch.as_tensor(r, device=DEV)); D.append(torch.as_tensor(done, device=DEV, dtype=torch.float32))
>             env.reset(done)
>         with torch.no_grad():
>             v_next = model.value(model.context(*tt(*env.observe()))).squeeze(1)
>         adv, gae = torch.zeros(horizon, n_envs, device=DEV), torch.zeros(n_envs, device=DEV)
>         for t in reversed(range(horizon)):                     # generalized advantage estimation
>             delta = R[t] + gamma * v_next * (1 - D[t]) - V[t]
>             gae = delta + gamma * lam * (1 - D[t]) * gae
>             adv[t], v_next = gae, V[t]
>         ret = (adv + torch.stack(V)).flatten()
>         adv = adv.flatten(); adv = (adv - adv.mean()) / (adv.std() + 1e-8)
>         img_b, txt_b, z_b, lp_b = torch.cat(I), torch.cat(X), torch.cat(Z), torch.cat(LP)
>         kls = []
>         for _ in range(epochs):
>             perm = torch.randperm(len(z_b), device=DEV)
>             for i in range(0, len(z_b), minibatch):
>                 j = perm[i:i + minibatch]
>                 h = model.context(img_b[j], txt_b[j])
>                 lp, _ = model.log_prob(h, z_b[j])
>                 ratio = torch.exp(lp - lp_b[j])
>                 kls.append(((ratio - 1) - (lp - lp_b[j])).mean().item())
>                 surrogate = torch.min(ratio * adv[j], torch.clamp(ratio, 1 - clip, 1 + clip) * adv[j]).mean()
>                 value_loss = F.mse_loss(model.value(h.detach()).squeeze(1), ret[j])
>                 loss = (0.0 if it < critic_warmup else 1.0) * (-surrogate) + 0.5 * value_loss
>                 opt.zero_grad(); loss.backward(); nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
>             if max_kl is not None and it >= critic_warmup and np.mean(kls[-8:]) > max_kl:
>                 break                                          # stop the epochs early when the policy moved too far
>         finished = torch.stack(D).sum().item()
>         rollout_success = torch.stack(R).sum().item() / max(finished, 1)
>         if it % log_every == log_every - 1 or it == 0:
>             history.append((it + 1, rollout_success, evaluate(model)))
>             print(f"iteration {it + 1}: rollout delivery {rollout_success:.2f}, greedy delivery {history[-1][2]:.2f}")
>     model.temp = 1.0
>     return history
> ```
>
> ```python theme={null}
> t0 = time.time()
> torch.manual_seed(0)
> tuned = copy.deepcopy(bc)
> ppo_hist = ppo(tuned, iters=100)
> rate_ppo, d_ppo = evaluate(tuned, details=True)
> R.update(ppo=rate_ppo, off_ppo=d_ppo["offsets"].mean(), off_bc=d_bc["offsets"].mean(), off_op=offsets_op.mean(),
>          miss_ppo=d_ppo["misses"].mean(), miss_bc=d_bc["misses"].mean(), ppo_sampled=ppo_hist[-1][1])
> print(f"after PPO: delivery {rate_ppo:.2f}, mean catch offset {d_ppo['offsets'].mean():+.3f} "
>       f"(BC {d_bc['offsets'].mean():+.3f}, operator {offsets_op.mean():+.3f}), "
>       f"misses per episode {d_ppo['misses'].mean():.2f} (BC {d_bc['misses'].mean():.2f})  [{time.time() - t0:.0f} s]")
> ```

```output theme={null}
iteration 1: rollout delivery 0.68, greedy delivery 0.74
iteration 10: rollout delivery 0.73, greedy delivery 0.76
iteration 20: rollout delivery 0.61, greedy delivery 0.62
iteration 30: rollout delivery 0.59, greedy delivery 0.67
iteration 40: rollout delivery 0.66, greedy delivery 0.70
iteration 50: rollout delivery 0.72, greedy delivery 0.69
iteration 60: rollout delivery 0.70, greedy delivery 0.74
iteration 70: rollout delivery 0.72, greedy delivery 0.78
iteration 80: rollout delivery 0.74, greedy delivery 0.80
iteration 90: rollout delivery 0.84, greedy delivery 0.83
iteration 100: rollout delivery 0.80, greedy delivery 0.80
after PPO: delivery 0.80, mean catch offset +0.003 (BC +0.016, operator +0.015), misses per episode 0.33 (BC 1.01)  [224 s]
```

![Left: greedy delivery on new machines and sampled delivery during rollouts over 100 PPO iterations, with a dashed line for the operator and a dotted line for the centered operator. Right: histograms of the catch offset, claw x minus square x, for the operator, the cloned policy and the policy after PPO. The PPO histogram sits closer to zero.](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/bc-vs-rl/images/cell_13_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=f625421cd0eb672f502e8dde4c239a6f)

## What each method fixed

BC copied the operator, including its habit of aiming right of center, and delivered 74%. PPO, starting from that policy and trained only on the delivery reward, raised greedy delivery to 80%. The curve is not monotone: delivery dipped between iterations 20 and 50, while the critic and the policy adjusted to each other, was back at the BC level by iteration 60, and rose above it in the last 40 iterations. The catch offset histogram shows how. The operator caught squares at a mean offset of +0.015 and BC copied it at +0.016. After PPO the mean offset is +0.003, and the policy misses 0.33 catches per episode instead of 1.01. Nothing in the reward mentions centering. The policy found that centered grabs are delivered more often before the deadline. The same controller aimed at the center delivers 93%, so PPO recovered part of the gap between the operator and a centered operator, but not all of it.

DAgger and RL fixed different things. DAgger extended the policy to states the demonstrations did not cover, and it needed an expert to label them. RL improved the policy in states it already handled, beyond the quality of the demonstrations, and it needed only a reward. RL post-training of large VLAs follows the same order as this section: clone first, so that the policy succeeds often enough for the reward to say something, then optimize the reward.

The task itself is simple: one gantry, three squares, and grasp physics reduced to two probabilities. The deadline, the stochastic grasp and the gap between the operator and a centered controller were chosen so that BC and RL behave differently. A real claw, a learned grasp model or a long-horizon task would change the numbers. The next sections keep the claw machine and change one part at a time: the action representation, the action head, and the RL algorithm.

[microvla](https://github.com/varununayak/microvla) is a single-file RT-2 style VLA on a related 2D reaching task, and a good place to read a minimal implementation. TorchRL's VLA module (`torchrl.modules.vla`) has a reference token policy and a GRPO objective for RL fine-tuning of action tokens.

## References

* Brohan, A., Brown, N., Carbajal, J., Chebotar, Y., Chen, X., et al. (2023). *RT-2: Vision-language-action models transfer web knowledge to robotic control*. arXiv \[cs.RO]. [Link](http://arxiv.org/abs/2307.15818)
* Paul, R., Barbu, A., Felshin, S., Katz, B., Roy, N. (2018). *Temporal Grounding Graphs for Language Understanding with Accrued Visual-Linguistic Context*. arXiv \[cs.RO]. [Link](http://arxiv.org/abs/1811.06966)
* Perez, E., Strub, F., Vries, H., Dumoulin, V., Courville, A. (2017). *FiLM: Visual Reasoning with a General Conditioning Layer*. arXiv \[cs.CV]. [Link](http://arxiv.org/abs/1709.07871)
* Ross, S., Gordon, G., Andrew Bagnell, J. (2010). *A Reduction of Imitation Learning and Structured Prediction to No-Regret Online Learning*. arXiv \[cs.LG]. [Link](http://arxiv.org/abs/1011.0686)
* Schulman, J., Wolski, F., Dhariwal, P., Radford, A., Klimov, O. (2017). *Proximal Policy Optimization Algorithms*. arXiv \[cs.LG]. [Link](http://arxiv.org/abs/1707.06347)
* Walsman, A., Bisk, Y., Gabriel, S., Misra, D., Artzi, Y., et al. (2018). *Early Fusion for Goal Directed Robotic Vision*. arXiv \[cs.CV]. [Link](http://arxiv.org/abs/1811.08824)

***

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/bc-vs-rl).


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