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

# GRPO for a VLA policy

> Group-relative advantages in place of a critic

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

In [BC versus RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl/index.md) you fine-tuned a cloned MiniVLA with PPO. PPO needs a critic: a value head $V_\phi(o, \ell)$ that predicts the return, so that each step's advantage can be estimated. The critic has to be trained alongside the policy, it starts out wrong, and it shares features with a policy you would rather not disturb. That section stopped the critic's gradient at the summary vector and gave it five iterations to warm up before the policy moved.

Group relative policy optimization (GRPO) (Shao et al., 2024) drops the critic. It runs several episodes from the same start and uses their average outcome as the baseline. It was introduced for training language models on math problems, where the reward is 1 for a correct answer and 0 otherwise, and it carries over to robot policies whose reward is 1 for a completed task. SimpleVLA-RL uses it to fine-tune OpenVLA-OFT. The general method is on the [GRPO](https://aegean.ai/aiml-common/lectures/reinforcement-learning/policy-based-algorithms/GRPO/index.md) page; this section applies it to the claw machine and compares it with PPO from the same starting policy.

> [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 machine and the policy

The task is ClawGrab, the claw machine of the BC and RL section: three squares, an instruction that names one of them, a stochastic grasp whose success depends on how well the claw is centered, and a reward of 1 when the named square drops into the chute within 60 steps. The code below is the same.

> [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)
> ```

## Groups of identical starts

GRPO compares episodes that started in the same state, so that a difference in outcome comes from the policy's actions and the grasp's chance, not from an easier layout. A group is $G$ machines with the same square positions, the same named square and the same wording of the instruction. The grasp still draws its random numbers per machine, and the policy samples its tokens independently, so the $G$ episodes of a group can end differently.

> [accordion] Code
>
> ```python theme={null}
> class GroupClawGrab(ClawGrab):
>     """ClawGrab whose machines come in groups of identical start states.
>
>     Machines 0..group-1 form the first group, the next group machines the second, and so on. After
>     reset_groups() every machine of a group has the same square positions, named square and
>     instruction wording as the first machine of its group. The grasp rule still draws its random
>     numbers per machine, so the episodes of a group can end differently.
>
>     Args:
>         n: number of machines, a multiple of group.
>         group: machines per group, G.
>         seed: seed of the layouts and of the grasp rule.
>     """
>
>     def __init__(self, n, group, seed=0, **kwargs):
>         assert n % group == 0
>         self.group = group
>         super().__init__(n, seed=seed, **kwargs)
>
>     def reset_groups(self):
>         """Start new episodes on all machines, with one random layout per group."""
>         self.reset(np.ones(self.n, bool))
>         leader = (np.arange(self.n) // self.group) * self.group
>         self._q[:] = self._q[leader]
>         self.claw[:] = self.claw[leader]
>         self.target[:] = self.target[leader]
>         self.template[:] = self.template[leader]
>         self._touched[:] = True
>         self._push(False)
>         self._pull()
> ```

MiniVLA and the behavioral cloning code are unchanged from the BC and RL section. The policy emits three tokens per step, $\Delta x$, $\Delta z$ and the grip, and its log-probability is the sum of the three token log-probabilities.

> [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)
>
>
> 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()
> ```

Both methods start from the same BC policy, trained on the operator's successful episodes.

> [accordion] Code
>
> ```python theme={null}
> t0 = time.time()
> demos = collect_demos(2000, seed=1)
> torch.manual_seed(0)
> bc = MiniVLA().to(DEV)
> train_bc(bc, demos, steps=8000)
> R["bc"] = evaluate(bc)
> bc.temp = 0.5
> R["bc_sampled"] = evaluate(bc, greedy=False)
> bc.temp = 1.0
> print(f"BC: delivery {R['bc']:.2f} greedy, {R['bc_sampled']:.2f} sampled at temperature 0.5  [{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}
BC: delivery 0.74 greedy, 0.73 sampled at temperature 0.5  [138 s]
```

## The PPO baseline

The baseline is the PPO recipe of the BC and RL section: rollouts of 64 steps on 128 machines sampled at temperature 0.5, generalized advantage estimation with $\gamma = 0.99$ and $\lambda = 0.95$, a critic on the stopped summary vector, and early stopping of an iteration's epochs once the approximate KL divergence from the rollout policy exceeds 0.01. Machines that finish an episode restart at once, so a rollout cuts across episode boundaries and the critic has to estimate the value of the unfinished ones.

> [accordion] Code
>
> ```python theme={null}
> def ppo(model, max_steps, n_envs=128, horizon=64, gamma=0.99, lam=0.95, clip=0.2, lr=3e-5,
>         epochs=4, minibatch=1024, critic_warmup=5, eval_every=8, temp=0.5, max_kl=0.01):
>     """PPO fine-tuning of a MiniVLA with the sparse delivery reward, the recipe of the BC and RL section.
>
>     Rollouts sample at temperature temp, the critic reads the summary vector with its gradient
>     stopped and learns alone for critic_warmup iterations, and an iteration's epochs stop early
>     once the approximate KL divergence from the rollout policy exceeds max_kl.
>
>     Args:
>         max_steps: stop after this many environment steps.
>         eval_every: evaluate the greedy policy every eval_every iterations.
>
>     Returns:
>         list of (environment steps so far, seconds so far, rollout delivery, greedy delivery on new machines).
>     """
>     model.temp = temp
>     env = ClawGrab(n_envs, seed=2024)
>     opt = torch.optim.AdamW(model.parameters(), lr=lr)
>     history, steps, t0, it = [(0, 0.0, float("nan"), evaluate(model))], 0, time.time(), 0
>     while steps < max_steps:
>         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)
>         steps += horizon * n_envs
>         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
>         rollout = torch.stack(R).sum().item() / max(torch.stack(D).sum().item(), 1)
>         it += 1
>         if it % eval_every == 0 or steps >= max_steps:
>             history.append((steps, time.time() - t0, rollout, evaluate(model)))
>             print(f"PPO   {steps:7d} steps: rollout delivery {rollout:.2f}, greedy delivery {history[-1][3]:.2f}")
>     model.temp = 1.0
>     return history
> ```

## GRPO

GRPO runs every episode to its end. Episode $i$ of a group earns the return $R_i \in \{0, 1\}$, and its advantage is the return measured against the group:

$$
\hat A_i = \frac{R_i - \operatorname{mean}(R_1, \dots, R_G)}{\operatorname{std}(R_1, \dots, R_G)}.
$$

Every step of the episode shares $\hat A_i$. The update is PPO's clipped surrogate, with the probability ratio of the step's three action tokens:

$$
\begin{aligned}
J(\theta) &= \mathbb E_{i,t}\Big[\min\big(\rho_{i,t}\hat A_i,\ \operatorname{clip}(\rho_{i,t}, 1 - \epsilon, 1 + \epsilon)\,\hat A_i\big)\Big], \\
\rho_{i,t} &= \frac{\pi_\theta(z_{i,t} \mid o_{i,t}, \ell)}{\pi_{\theta_{old}}(z_{i,t} \mid o_{i,t}, \ell)}.
\end{aligned}
$$

There is no value function, no discount and no bootstrapping: the group mean plays the role of the baseline that the critic provides in PPO.

With a binary reward the group advantage has a simple form. If $k$ of the $G$ episodes succeed, write $p = k/G$. A successful episode gets $\hat A = \sqrt{(1-p)/p}$ and a failed one $\hat A = -\sqrt{p/(1-p)}$, so a rare success in a group that mostly fails receives a large push, and a rare failure in a group that mostly succeeds receives a large penalty. When all $G$ episodes succeed, or all fail, the standard deviation is zero, every advantage is zero and the group contributes no gradient. For a start state where the policy succeeds with probability $p$, that happens with probability $p^G + (1 - p)^G$. At $p = 0.75$ this is 0.32 for $G = 4$ and 0.01 for $G = 16$.

The comparison runs PPO and GRPO, with $G = 4$ and $G = 16$, for the same number of environment steps and with the same temperature and KL limit. All three use a learning rate of $10^{-5}$, a third of the rate in [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl/index.md).

> [accordion] Code
>
> ```python theme={null}
> def grpo(model, max_steps, group=16, n_envs=128, clip=0.2, lr=3e-5, epochs=4, minibatch=1024,
>          temp=0.5, max_kl=0.01, eval_every=8, seed=7):
>     """GRPO fine-tuning of a MiniVLA with the sparse delivery reward.
>
>     Every iteration starts all machines at once, in groups of `group` identical start states, and
>     runs every episode to its end. An episode's return is 1 if it delivered the named square and 0
>     otherwise. Its advantage is the return minus the mean return of its group, divided by the
>     group's standard deviation, and every step of the episode shares it. A group whose episodes
>     all succeeded or all failed has advantage 0 and contributes no gradient. The update is PPO's
>     clipped surrogate on the summed token log-probabilities, with no critic.
>
>     Args:
>         max_steps: stop after this many environment steps (steps of running episodes only).
>         group: episodes per start state, G.
>         n_envs: machines per iteration, a multiple of group.
>
>     Returns:
>         list of (environment steps so far, seconds so far, rollout delivery, greedy delivery,
>         share of groups that all succeeded, share of groups that all failed).
>     """
>     model.temp = temp
>     env = GroupClawGrab(n_envs, group, seed=seed)
>     opt = torch.optim.AdamW(model.parameters(), lr=lr)
>     history, steps, t0, it = [(0, 0.0, float("nan"), evaluate(model), float("nan"), float("nan"))], 0, time.time(), 0
>     degenerate = []
>     while steps < max_steps:
>         env.reset_groups()
>         alive, ret = np.ones(n_envs, bool), np.zeros(n_envs, np.float32)
>         I, X, Z, LP, E = [], [], [], [], []
>         while alive.any():
>             img, text = tt(*env.observe())
>             with torch.no_grad():
>                 z = model.act(img, text, greedy=False)
>                 lp, _ = model.log_prob(model.context(img, text), z)
>             keep = torch.as_tensor(alive, device=DEV)
>             I.append(img[keep]); X.append(text[keep]); Z.append(z[keep]); LP.append(lp[keep])
>             E.append(torch.as_tensor(np.flatnonzero(alive), device=DEV))
>             a = from_tokens(z.cpu().numpy())
>             a[~alive] = 0
>             r, done = env.step(a)
>             ret += r * alive
>             steps += alive.sum()
>             alive &= ~done
>         g = ret.reshape(-1, group)
>         std = g.std(1, keepdims=True)
>         adv_ep = np.where(std > 0, (g - g.mean(1, keepdims=True)) / (std + 1e-6), 0.0).reshape(-1)
>         all_ok, all_fail = (g.min(1) == 1).mean(), (g.max(1) == 0).mean()
>         degenerate.append((all_ok, all_fail))
>         img_b, txt_b, z_b, lp_b, ep = torch.cat(I), torch.cat(X), torch.cat(Z), torch.cat(LP), torch.cat(E)
>         adv = torch.as_tensor(adv_ep, device=DEV, dtype=torch.float32)[ep]
>         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]
>                 lp, _ = model.log_prob(model.context(img_b[j], txt_b[j]), 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()
>                 opt.zero_grad(); (-surrogate).backward(); nn.utils.clip_grad_norm_(model.parameters(), 1.0); opt.step()
>             if max_kl is not None and np.mean(kls[-8:]) > max_kl:
>                 break
>         it += 1
>         if it % eval_every == 0 or steps >= max_steps:
>             ok, fail = np.mean(degenerate, 0)
>             degenerate = []
>             history.append((int(steps), time.time() - t0, ret.mean(), evaluate(model), ok, fail))
>             print(f"GRPO G={group:2d} {int(steps):7d} steps: rollout delivery {ret.mean():.2f}, greedy delivery {history[-1][3]:.2f}, "
>                   f"groups all delivered {ok:.2f}, all failed {fail:.2f}")
>     model.temp = 1.0
>     return history
> ```
>
> ```python theme={null}
> BUDGET = 400_000          # environment steps per method
> LR = 1e-5                 # learning rate of every method
> runs = {}
> torch.manual_seed(0)
> runs["PPO"] = ppo(copy.deepcopy(bc), BUDGET, lr=LR)
> for G in (4, 16):
>     torch.manual_seed(0)
>     runs[f"GRPO, G = {G}"] = grpo(copy.deepcopy(bc), BUDGET, group=G, lr=LR)
> for name, h in runs.items():
>     print(f"{name:12s}: final greedy delivery {h[-1][3]:.2f}, best {max(x[3] for x in h):.2f}, "
>           f"{h[-1][0]} steps in {h[-1][1]:.0f} s")
> R.update(ppo=runs["PPO"][-1][3], g4=runs["GRPO, G = 4"][-1][3], g16=runs["GRPO, G = 16"][-1][3],
>          ppo_s=runs["PPO"][-1][1], g4_s=runs["GRPO, G = 4"][-1][1], g16_s=runs["GRPO, G = 16"][-1][1],
>          budget=BUDGET, best_ppo=max(x[3] for x in runs["PPO"]), best_g4=max(x[3] for x in runs["GRPO, G = 4"]),
>          best_g16=max(x[3] for x in runs["GRPO, G = 16"]))
> for G in (4, 16):
>     h = runs[f"GRPO, G = {G}"][1:]
>     R[f"g{G}_ok"] = float(np.mean([x[4] for x in h]))
>     R[f"g{G}_fail"] = float(np.mean([x[5] for x in h]))
> ```

```output theme={null}
PPO     65536 steps: rollout delivery 0.77, greedy delivery 0.80
PPO    131072 steps: rollout delivery 0.74, greedy delivery 0.79
PPO    196608 steps: rollout delivery 0.77, greedy delivery 0.81
PPO    262144 steps: rollout delivery 0.86, greedy delivery 0.79
PPO    327680 steps: rollout delivery 0.71, greedy delivery 0.83
PPO    393216 steps: rollout delivery 0.78, greedy delivery 0.83
PPO    401408 steps: rollout delivery 0.78, greedy delivery 0.82
GRPO G= 4   52805 steps: rollout delivery 0.78, greedy delivery 0.77, groups all delivered 0.41, all failed 0.02
GRPO G= 4  105557 steps: rollout delivery 0.71, greedy delivery 0.81, groups all delivered 0.46, all failed 0.02
GRPO G= 4  156715 steps: rollout delivery 0.87, greedy delivery 0.82, groups all delivered 0.51, all failed 0.01
GRPO G= 4  208396 steps: rollout delivery 0.88, greedy delivery 0.83, groups all delivered 0.55, all failed 0.02
GRPO G= 4  259290 steps: rollout delivery 0.85, greedy delivery 0.85, groups all delivered 0.51, all failed 0.02
GRPO G= 4  311325 steps: rollout delivery 0.77, greedy delivery 0.84, groups all delivered 0.51, all failed 0.03
GRPO G= 4  362911 steps: rollout delivery 0.81, greedy delivery 0.86, groups all delivered 0.55, all failed 0.01
GRPO G= 4  401444 steps: rollout delivery 0.79, greedy delivery 0.84, groups all delivered 0.55, all failed 0.02
GRPO G=16   53266 steps: rollout delivery 0.63, greedy delivery 0.79, groups all delivered 0.05, all failed 0.02
GRPO G=16  103827 steps: rollout delivery 0.88, greedy delivery 0.84, groups all delivered 0.14, all failed 0.03
GRPO G=16  154871 steps: rollout delivery 0.81, greedy delivery 0.83, groups all delivered 0.17, all failed 0.02
GRPO G=16  207034 steps: rollout delivery 0.88, greedy delivery 0.86, groups all delivered 0.19, all failed 0.02
GRPO G=16  258490 steps: rollout delivery 0.73, greedy delivery 0.86, groups all delivered 0.20, all failed 0.00
GRPO G=16  309483 steps: rollout delivery 0.80, greedy delivery 0.87, groups all delivered 0.19, all failed 0.02
GRPO G=16  359806 steps: rollout delivery 0.70, greedy delivery 0.82, groups all delivered 0.20, all failed 0.02
GRPO G=16  405100 steps: rollout delivery 0.80, greedy delivery 0.84, groups all delivered 0.14, all failed 0.00
PPO         : final greedy delivery 0.82, best 0.83, 401408 steps in 103 s
GRPO, G = 4 : final greedy delivery 0.84, best 0.86, 401444 steps in 111 s
GRPO, G = 16: final greedy delivery 0.84, best 0.87, 405100 steps in 113 s
```

## Results

The figure plots the greedy delivery rate on 500 fixed layouts against the environment steps each method consumed. The BC policy delivers 74% of the time with greedy actions and 73% when it samples at temperature 0.5. After 400,000 steps, PPO delivers 82% and GRPO delivers 84% with $G = 4$ and 84% with $G = 16$. The best evaluations along the way were 83%, 86% and 87%.

All three methods improve the cloned policy by eight to ten points, and most of the gain arrives in the first 150,000 steps. The gap between GRPO and PPO is two points at the end and three at the best evaluation. With 500 evaluation episodes the standard error of a delivery rate near 85% is about 1.6 points, and each method ran with one seed. That gap is within the noise, so the run shows only that GRPO matches PPO on this task.

Wall time was close as well: 103 seconds for PPO, 111 for GRPO with $G = 4$ and 113 with $G = 16$. GRPO saves the critic's forward and backward passes, but it waits for the slowest machine of each batch to finish its episode, while PPO's machines restart as soon as they finish.

The right panel counts the groups that taught nothing. With $G = 4$, an average of 51% of the groups delivered in every episode and 2% failed in every episode, so about half of the episodes GRPO collected had zero advantage. With $G = 16$ those shares were 16% and 1%. The all-delivered share grows during training because the policy improves, which is the $p^G$ term of the formula above. Even so, $G = 4$ finished level with $G = 16$. One explanation is that at this budget the number of informative episodes does not limit learning, and the policy is close to what its grasp precision allows. The run does not test that explanation.

![Left: greedy delivery against environment steps, in thousands, for PPO and for GRPO with group sizes 4 and 16, with the level of the cloned policy marked. Right: the share of groups in which every episode delivered or every episode failed, for group sizes 4 and 16, over training.](https://mintcdn.com/aegeanaiinc/ZYNwCUJVJkvLdMMz/aiml-common/lectures/vla/grpo-vla/images/cell_9_output_1.svg?fit=max\&auto=format\&n=ZYNwCUJVJkvLdMMz\&q=85\&s=34f0b631f86e0e24b70a14608154aa25)

## Choosing between GRPO and PPO

GRPO fits a task when you can restart from the same state several times and the reward arrives once, at the end of the episode. A simulator gives you repeated starts for free. The binary outcome then needs no critic to turn it into an advantage, and you avoid the critic's failure modes: a value head that starts wrong, competes with the policy for shared features, and has to estimate the value of episodes cut off at the rollout boundary. PPO fits when starts cannot be repeated, as on a real robot where every reset is a new scene, or when the reward is dense enough that a per-step advantage carries information a whole-episode outcome does not.

SimpleVLA-RL [(Li et al., 2025)](https://arxiv.org/abs/2509.09674) fine-tunes OpenVLA-OFT with GRPO and a binary success reward. Three of its changes target the zero-advantage groups you measured above. It discards groups in which every episode succeeded or every episode failed, and samples again until each group in the batch is mixed. It raises the upper clip bound from 1.2 to 1.28, so the probability of a rare successful action can grow faster. It raises the rollout temperature from 1.0 to 1.6 so that groups are more likely to be mixed. It also drops the KL penalty. With these changes the average LIBERO success of OpenVLA-OFT rose from 91.0% to 99.1%, and on LIBERO-Long with a single demonstration per task it rose from 17.1% to 91.7%.

The comparison has gone the other way elsewhere. Liu et al. fine-tuned OpenVLA with LoRA on a pick-and-place task and found that PPO consistently outperformed GRPO, which used groups of eight trajectories from a common initial state (Liu et al., 2025). Their hypothesis is that in a robot task each action changes the state the next action sees, which may make the group-relative advantage estimates unstable. On the claw machine the two methods ended level, so this section gives no evidence either way.

TorchRL's VLA tutorial implements the same update as `ClipPPOLoss` with `critic_network=None`, fed with advantages computed per group. [PPO for a VLA](https://aegean.ai/aiml-common/lectures/vla/ppo-vla/index.md) takes up the critic side: how to train a value head on a pretrained VLA without damaging it.

## References

* Liu, J., Gao, F., Wei, B., Chen, X., Liao, Q., et al. (2025). *What can RL bring to VLA generalization? An empirical study*. arXiv \[cs.LG]. [DOI](https://doi.org/10.48550/arXiv.2505.19789)
* Shao, Z., Wang, P., Zhu, Q., Xu, R., Song, J., et al. (2024). *DeepSeekMath: Pushing the limits of mathematical reasoning in open language models*. arXiv \[cs.CL]. [Link](http://arxiv.org/abs/2402.03300)

***

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/grpo-vla).


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