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

# PPO settings for a cloned VLA policy

> One PPO setting changed at a time, from the same cloned policy

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

In [BC versus RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl/index.md), PPO fine-tuned a cloned MiniVLA with nothing but the delivery reward, and the policy learned to center its grabs. The fine-tuning in that section fixed one setting for each design choice: the discount, the temperature at which rollouts sample the policy, how the critic attaches to the network, when an update stops, and how many passes each batch of experience gets. This section changes those choices one at a time, always starting from the same cloned policy, and measures what each one does.

The general algorithm is on the [PPO](https://aegean.ai/aiml-common/lectures/reinforcement-learning/policy-based-algorithms/PPO/index.md) page. What changes for a VLA is the policy. It is an autoregressive model that emits several action tokens per step, and it was pretrained by imitation, so RL has to improve it without destroying the features that imitation built.

> [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, MiniVLA, BC and the evaluation are those of the claw-machine section.

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

## The token-level ratio

MiniVLA emits three tokens per step: the $\Delta x$ bin, the $\Delta z$ bin and the grip. Each token is conditioned on the observation summary $h_t$ and on the tokens before it. The probability of the whole action is the product of the token probabilities, so its log is a sum:

$$
\log \pi_\theta(a_t \mid o_t, \ell) = \sum_{j=1}^{3} \log p_\theta(z_{t,j} \mid h_t, z_{t,<j}).
$$

PPO's probability ratio between the current policy and the rollout policy is the exponential of the difference of these sums:

$$
\begin{aligned}
\rho_t(\theta) &= \exp\big(\log \pi_\theta(a_t \mid o_t, \ell) - \log \pi_{\theta_{old}}(a_t \mid o_t, \ell)\big), \\
L(\theta) &= \mathbb E_t\big[\min\big(\rho_t \hat A_t,\ \mathrm{clip}(\rho_t, 1 - \epsilon, 1 + \epsilon)\,\hat A_t\big)\big],
\end{aligned}
$$

with $\epsilon = 0.2$ and advantages $\hat A_t$ from generalized advantage estimation (GAE). The ratio covers the whole action, so one clip limits all three tokens together. [OpenVLA as a stochastic policy](https://aegean.ai/aiml-common/lectures/vla/openvla-policy/index.md) writes the same sum for OpenVLA's seven action tokens, and PPO fine-tuning of OpenVLA uses it in the same way (Liu et al., 2025).

The PPO loop below is the one from the claw-machine section with two switches added: whether the value loss can send gradient into the shared network, and a seed for the machines and the sampling.

> [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,
>         detach_critic=True, seed=0):
>     """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.
>
>     Args:
>         model: the MiniVLA to fine-tune, in place.
>         iters: PPO iterations; each collects horizon steps on n_envs machines.
>         gamma: discount factor. lam: GAE parameter. clip: clipping range of the ratio.
>         epochs: passes over each batch. max_kl: early-stop threshold, None to disable.
>         temp: sampling temperature of the rollout policy.
>         detach_critic: stop the value loss gradient at h; False lets it reshape the shared trunk.
>         seed: seed of the machines and of the sampling.
>
>     Returns:
>         list of (iteration, delivery rate of the sampled policy in the rollouts, greedy delivery rate on new machines).
>     """
>     model.temp = temp
>     torch.manual_seed(seed)
>     env = ClawGrab(n_envs, seed=2024 + seed)
>     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() if detach_critic else h).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}, "
>                   f"approx KL {np.mean(kls):.4f}")
>     model.temp = 1.0
>     return history
> ```

## One cloned policy, many fine-tuning runs

BC is trained once on the operator's successful episodes, and its weights are saved. Every variant below loads those weights, runs 60 PPO iterations of 128 machines for 64 steps each, and is scored by its greedy delivery rate on 500 new machines. The baseline is the claw-machine section's setting: $\gamma = 0.99$, GAE $\lambda = 0.95$, rollout temperature 0.5, a critic on detached features, five iterations of critic warm-up, four passes over each batch, and an early stop once the approximate KL divergence from the rollout policy exceeds 0.01. Each variant changes one of these settings.

> [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)
> bc_state = copy.deepcopy(bc.state_dict())       # every PPO variant starts from these weights
> R["bc"] = evaluate(bc)
> print(f"BC: greedy delivery {R['bc']:.2f}  [{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: greedy delivery 0.73  [419 s]
```

The cloned policy delivers 73% when it always takes its most likely tokens. PPO, however, learns from sampled actions, so what matters at the start of RL is how often the sampled policy succeeds. The next cell samples the same cloned policy at three temperatures, where temperature $\tau$ samples from $\mathrm{softmax}(\text{logits}/\tau)$.

> [accordion] Code
>
> ```python theme={null}
> for temp in (1.0, 0.5, 0.3):
>     bc.temp = temp
>     key = f"bc_t{round(temp * 10):02d}"
>     R[key] = evaluate(bc, greedy=False)
>     print(f"BC sampled at temperature {temp}: delivery {R[key]:.2f}")
> bc.temp = 1.0
> ```

```output theme={null}
BC sampled at temperature 1.0: delivery 0.07
BC sampled at temperature 0.5: delivery 0.77
BC sampled at temperature 0.3: delivery 0.75
```

At temperature 1 the cloned policy delivers only 7%. At 0.5 it delivers 77%, and at 0.3 75%. The cloned distribution is wide because the operator's demonstrations vary from one attempt to the next. Sampled at full width, the token noise is large enough that almost every episode fails.

Each variant goes through the same function, which copies the saved weights, fine-tunes them and records the greedy delivery every ten iterations.

> [accordion] Code
>
> ```python theme={null}
> RUNS = {}
> ITERS = 60
>
>
> def run_variant(name, **kwargs):
>     """Fine-tune a copy of the BC policy with PPO under one setting and record its curve and final delivery.
>
>     Args:
>         name: label of the variant.
>         kwargs: arguments passed to ppo, which override the baseline settings.
>
>     Returns:
>         the greedy delivery rate after fine-tuning.
>     """
>     t0 = time.time()
>     model = MiniVLA().to(DEV)
>     model.load_state_dict(bc_state)
>     print(f"{name}:")
>     hist = ppo(model, iters=ITERS, **kwargs)
>     final = evaluate(model)
>     RUNS[name] = (hist, final)
>     print(f"  final greedy delivery {final:.2f}  [{time.time() - t0:.0f} s]")
>     return final
>
>
> def plot_group(names, title):
>     """Plot greedy delivery against PPO iteration for the named variants, with the BC level dashed."""
>     fig, ax = plt.subplots(figsize=(6.5, 3.0))
>     for name in names:
>         it, _, greedy = map(np.array, zip(*RUNS[name][0]))
>         ax.plot(np.r_[0, it], np.r_[R["bc"], greedy], "o-", ms=3, label=name)
>     ax.axhline(R["bc"], color=FIG_GRAY, ls="--", lw=1)
>     ax.set_xlabel("PPO iteration"); ax.set_ylabel("greedy delivery"); ax.set_ylim(0, 1)
>     ax.set_title(title, fontsize=10); ax.legend(fontsize=8, loc="lower left"); ax.grid(True)
>     plt.tight_layout()
>     plt.show()
> ```

## The discount factor

With discount $\gamma$, a reward $k$ steps ahead enters the return with weight $\gamma^k$. The weights sum to $1/(1 - \gamma)$, which is the policy's effective horizon: about 10 steps for $\gamma = 0.9$ and 100 steps for $\gamma = 0.99$. A delivery takes about 50 steps from the start. With $\gamma = 0.9$ the reward is invisible from the approach phase ($0.9^{50} \approx 0.005$), so the advantages of those steps are mostly noise from the critic, and PPO pushes the approach around at random.

> [accordion] Code
>
> ```python theme={null}
> R["base"] = run_variant("baseline: gamma 0.99")
> R["base_s1"] = run_variant("baseline, second seed", seed=1)
> R["g09"] = run_variant("gamma 0.9", gamma=0.9)
> ```

```output theme={null}
baseline: gamma 0.99:
  iteration 1: rollout delivery 0.73, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.69, greedy delivery 0.77, approx KL 0.0072
  iteration 20: rollout delivery 0.77, greedy delivery 0.74, approx KL 0.0467
  iteration 30: rollout delivery 0.72, greedy delivery 0.75, approx KL 0.0071
  iteration 40: rollout delivery 0.65, greedy delivery 0.75, approx KL 0.0038
  iteration 50: rollout delivery 0.71, greedy delivery 0.75, approx KL 0.0030
  iteration 60: rollout delivery 0.66, greedy delivery 0.73, approx KL 0.0060
  final greedy delivery 0.73  [428 s]
baseline, second seed:
  iteration 1: rollout delivery 0.72, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.78, greedy delivery 0.76, approx KL 0.0182
  iteration 20: rollout delivery 0.67, greedy delivery 0.73, approx KL 0.0127
  iteration 30: rollout delivery 0.68, greedy delivery 0.72, approx KL 0.0109
  iteration 40: rollout delivery 0.75, greedy delivery 0.76, approx KL 0.0071
  iteration 50: rollout delivery 0.72, greedy delivery 0.75, approx KL 0.0066
  iteration 60: rollout delivery 0.79, greedy delivery 0.75, approx KL 0.0052
  final greedy delivery 0.75  [347 s]
gamma 0.9:
  iteration 1: rollout delivery 0.73, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.57, greedy delivery 0.44, approx KL 0.0153
  iteration 20: rollout delivery 0.71, greedy delivery 0.60, approx KL 0.0203
  iteration 30: rollout delivery 0.51, greedy delivery 0.46, approx KL 0.0076
  iteration 40: rollout delivery 0.53, greedy delivery 0.54, approx KL 0.0076
  iteration 50: rollout delivery 0.57, greedy delivery 0.53, approx KL 0.0081
  iteration 60: rollout delivery 0.56, greedy delivery 0.53, approx KL 0.0085
  final greedy delivery 0.53  [331 s]
```

![Greedy delivery rate over 60 PPO iterations for the baseline with discount 0.99, run with two seeds, and for discount 0.9. The discount 0.9 curve falls below the baseline curves and stays lower.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/ppo-vla/images/cell_10_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=2f806a602d482434f9de6321cc3c8ff7)

The baseline ends at 73%, and the same setting with a second seed ends at 75%, against 73% before fine-tuning. Within 60 iterations the baseline moves the greedy policy only a little. The PPO run in [Behavioral cloning and RL on a claw machine](https://aegean.ai/aiml-common/lectures/vla/bc-vs-rl/index.md) uses the same recipe for 100 iterations: it was back at the BC level at iteration 60 and reached 80% only in the last 40 iterations. The curves here also wander by up to 4 points from one evaluation to the next. Those two numbers set the noise floor for every comparison on this page: a difference of a few points between two variants is not evidence of anything.

The discount is different. With $\gamma = 0.9$ delivery falls to 44% after ten iterations and ends at 53%. That gap is several times the noise floor, and it is the failure that the effective horizon predicts.

## Rollout temperature

The temperature sets how far the rollout policy explores around the cloned one. PPO's ratio uses the same temperature, so the policy that PPO improves is the tempered one.

> [accordion] Code
>
> ```python theme={null}
> R["t10"] = run_variant("temperature 1.0", temp=1.0)
> R["t03"] = run_variant("temperature 0.3", temp=0.3)
> ```

```output theme={null}
temperature 1.0:
  iteration 1: rollout delivery 0.06, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.11, greedy delivery 0.70, approx KL 0.0066
  iteration 20: rollout delivery 0.37, greedy delivery 0.73, approx KL 0.0063
  iteration 30: rollout delivery 0.52, greedy delivery 0.76, approx KL 0.0040
  iteration 40: rollout delivery 0.57, greedy delivery 0.71, approx KL 0.0072
  iteration 50: rollout delivery 0.60, greedy delivery 0.66, approx KL 0.0047
  iteration 60: rollout delivery 0.68, greedy delivery 0.73, approx KL 0.0034
  final greedy delivery 0.73  [381 s]
temperature 0.3:
  iteration 1: rollout delivery 0.73, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.77, greedy delivery 0.63, approx KL 0.0105
  iteration 20: rollout delivery 0.68, greedy delivery 0.67, approx KL 0.0261
  iteration 30: rollout delivery 0.65, greedy delivery 0.62, approx KL 0.0217
  iteration 40: rollout delivery 0.67, greedy delivery 0.66, approx KL 0.0095
  iteration 50: rollout delivery 0.73, greedy delivery 0.72, approx KL 0.0084
  iteration 60: rollout delivery 0.76, greedy delivery 0.78, approx KL 0.0046
  final greedy delivery 0.78  [286 s]
```

![Greedy delivery rate over 60 PPO iterations for rollout temperature 0.5, the baseline, and for temperatures 1.0 and 0.3. The three curves end close together.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/ppo-vla/images/cell_12_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=da0cd41f77ef01560018e7bfb652230f)

At temperature 1.0 the greedy policy ends at 73%, no better than the baseline. The rollout delivery changed far more: it starts at 6% and climbs to 68% by iteration 60. Because the greedy policy barely moved, most of that work went into sharpening the token distributions around actions that the greedy policy already takes. At temperature 0.3 the greedy policy ends at 78%, within the noise of the baseline.

RL fine-tuning of OpenVLA used temperature 1.0 and reported that 1.5 hinders training while 0.5 and 1.0 both work well (Liu et al., 2025). The usable temperature depends on how wide the cloned distribution is. A policy cloned from a consistent demonstrator can be sampled at its natural width. MiniVLA, cloned from varied demonstrations, has to be cooled before its samples succeed often enough to learn from.

## Critic, early stopping and epochs

The last three variants change how the update is built. The first lets the value loss send gradient into the shared trunk, the second removes the KL early stop, and the third makes one pass over each batch instead of four.

> [accordion] Code
>
> ```python theme={null}
> R["shared"] = run_variant("critic gradient into the trunk", detach_critic=False)
> R["nokl"] = run_variant("no KL early stop", max_kl=None)
> R["ep1"] = run_variant("one epoch per batch", epochs=1)
> ```

```output theme={null}
critic gradient into the trunk:
  iteration 1: rollout delivery 0.73, greedy delivery 0.65, approx KL 0.0250
  iteration 10: rollout delivery 0.33, greedy delivery 0.26, approx KL 0.0095
  iteration 20: rollout delivery 0.54, greedy delivery 0.55, approx KL 0.0063
  iteration 30: rollout delivery 0.71, greedy delivery 0.70, approx KL 0.0041
  iteration 40: rollout delivery 0.77, greedy delivery 0.76, approx KL 0.0040
  iteration 50: rollout delivery 0.71, greedy delivery 0.80, approx KL 0.0063
  iteration 60: rollout delivery 0.82, greedy delivery 0.76, approx KL 0.0104
  final greedy delivery 0.76  [356 s]
no KL early stop:
  iteration 1: rollout delivery 0.73, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.66, greedy delivery 0.63, approx KL 0.0235
  iteration 20: rollout delivery 0.63, greedy delivery 0.69, approx KL 0.0259
  iteration 30: rollout delivery 0.56, greedy delivery 0.65, approx KL 0.0079
  iteration 40: rollout delivery 0.72, greedy delivery 0.71, approx KL 0.0043
  iteration 50: rollout delivery 0.83, greedy delivery 0.81, approx KL 0.0050
  iteration 60: rollout delivery 0.73, greedy delivery 0.79, approx KL 0.0036
  final greedy delivery 0.79  [409 s]
one epoch per batch:
  iteration 1: rollout delivery 0.73, greedy delivery 0.73, approx KL 0.0000
  iteration 10: rollout delivery 0.82, greedy delivery 0.83, approx KL 0.0011
  iteration 20: rollout delivery 0.78, greedy delivery 0.80, approx KL 0.0012
  iteration 30: rollout delivery 0.78, greedy delivery 0.83, approx KL 0.0008
  iteration 40: rollout delivery 0.69, greedy delivery 0.75, approx KL 0.0002
  iteration 50: rollout delivery 0.75, greedy delivery 0.71, approx KL 0.0013
  iteration 60: rollout delivery 0.73, greedy delivery 0.72, approx KL 0.0006
  final greedy delivery 0.72  [202 s]
```

![Greedy delivery rate over 60 PPO iterations for the baseline, a critic that sends gradient into the shared trunk, no KL early stop, and one epoch per batch. The curve with the critic gradient drops sharply in the first iterations and then recovers, and all four curves end close together.](https://mintcdn.com/aegeanaiinc/uRWiEAMb3Q5tJOOk/aiml-common/lectures/vla/ppo-vla/images/cell_14_output_1.svg?fit=max\&auto=format\&n=uRWiEAMb3Q5tJOOk\&q=85\&s=fc4897ce2613fa7e3b5a912761cdc837)

Letting the critic train the trunk does damage before PPO changes the policy at all. During the five warm-up iterations only the value loss is active, yet the greedy delivery drops from 73% to 65% at the first evaluation and to 26% by iteration 10. The value loss reshapes the features that the action head reads. The policy then recovers and ends at 76%, within the noise of the baseline, after a long detour.

RL fine-tuning of OpenVLA shares the whole transformer between actor and critic, with a three-layer value head on the hidden state of the first action token, and found that a separate critic backbone gave comparable returns while training 35% slower and using 83% more GPU memory (Liu et al., 2025). That setup trains rank-32 LoRA adapters and leaves the pretrained weights frozen, which limits how far any loss can move the pretrained features. This is a plausible reason the shared design works there and hurts here, but this section did not test it.

Without the KL early stop, the approximate KL divergence per iteration reaches 0.026, the greedy delivery dips to 63% and then recovers to 79%. With one pass per batch the policy barely moves: the KL stays near 0.001, the delivery peaks at 83% around iteration 10 and drifts back to 72%. The paper above found that more than one PPO epoch brought no gain for OpenVLA and cost wall-clock time almost linearly, and it uses one epoch throughout. On this task the endpoints of all three variants fall within the noise floor.

The table collects the final greedy delivery of every run.

> [accordion] Code
>
> ```python theme={null}
> rows = [("BC, no fine-tuning", R["bc"])] + [(name, final) for name, (hist, final) in RUNS.items()]
> width = max(len(r[0]) for r in rows)
> for name, final in rows:
>     print(f"{name:<{width}}  {final:.2f}")
> ```

```output theme={null}
BC, no fine-tuning              0.73
baseline: gamma 0.99            0.73
baseline, second seed           0.75
gamma 0.9                       0.53
temperature 1.0                 0.73
temperature 0.3                 0.78
critic gradient into the trunk  0.76
no KL early stop                0.79
one epoch per batch             0.72
```

## What carries over

Only one choice separated cleanly from the noise: the discount has to give the policy a horizon at least as long as the task. A $\gamma$ whose effective horizon $1/(1-\gamma)$ is shorter than the time to the reward turns the early steps into noise, and fine-tuning makes a working policy worse. The argument uses only the definition of the return, so it applies to any VLA policy trained against a delayed sparse reward.

The other choices changed the path more than the end point. A hot rollout temperature spent the budget sharpening the sampled policy. A critic that trains the trunk damaged the policy during warm-up. Removing the KL stop produced a dip. Their final values all lie within a few points of each other, and with one seed per variant, a seed-to-seed gap of 2 points and evaluation-to-evaluation swings of up to 4 points, the ranking among them is not established. Settling it would take several seeds per variant and longer runs.

## 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)

***

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


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