Lesson 6.5 — Vision-Language-Action Models
Previous lesson · 6.4 Diffusion Policy · Course overview · Next lesson · 6.6 World Models
From Vision and Language to Robot Actions
A vision-language-action model uses visual observations, language, and optional robot state to predict actions. It can emit discrete action tokens, continuous values, or a probability distribution over action chunks.
The π₀ family combines a PaliGemma backbone with a continuous flow-matching action expert. OpenVLA predicts discretized actions autoregressively. π₀-FAST uses a compressed sequence of action tokens. π₀.₅ studies transfer across tasks, robots, and open environments through heterogeneous training data and semantic supervision.
The architecture labs trace the OpenPI JAX implementation. The trainable experiment implements a small two-stream attention model using synthetic images and point-mass trajectories. Its source checkpoint comes from the toy control task.
VLM vs. VLA Architecture
Continuous Commands and Discrete Action Tokens
Robot data specifies the units, coordinate frame, sampling period, and actuator interpretation of each command. A padded model action dimension and the number of physical axes can differ. The OpenPI configuration below can represent up to 32 action channels and 50 positions per chunk by default. The dataset and policy transforms specify which entries a particular system uses. OpenPI configuration
The point-mass example normalizes acceleration by dividing by two. The quantization lab maps a normalized scalar in to one of uniformly spaced values, including the endpoints. The maximum rounding error is half the bin spacing, . FAST uses a frequency-domain representation and sequence tokenization. The lab focuses on the scalar rounding operation.
Compute the rounding error of a discretized action
Continuous vs. Discrete Actions
Layerwise Backbone and Action Expert
The OpenPI JAX variants use width 2048 for the backbone and width 1024 for the action expert. Both have 18 layers, eight query heads, one key/value head, and head dimension 256. Their projections map the two streams into a common head space, enabling attention despite different input widths. The two feedforward widths are 16,384 and 4096. OpenPI Gemma implementation
| Tensor (row-vector convention) | VLM prefix | Action expert suffix |
|---|---|---|
| Hidden state | B × P × 2048 | B × H × 1024 |
| Q projection (flatten heads) | 2048 × 2048 | 1024 × 2048 |
| K, V each (flatten heads) | 2048 × 256 | 1024 × 256 |
| Attention output projection | 2048 × 2048 | 2048 × 1024 |
The table flattens the head axes into matrices. The real attention joins the projected tensors along the token axis and uses RoPE on queries and keys. With prefix tokens and action tokens, Q has shape and K and V each have shape for the two-block illustration. Each query head reads the shared key/value head. Where a separate state token exists, it also occupies one sequence position.
The toy model uses two width-eight streams, one head, and two attention layers. Each layer applies a tanh to the residual and its projected attention output. Its six prefix tokens are four image patches, one instruction, and one continuous state. The suffix contains four noisy actions. Because the last-layer suffix only reads prefix keys and values, the final prefix query and output projections receive zero gradient from its action loss.
VLM Backbone & Action Expert Dataflow
Block Attention and the Prefix Cache
Freeze one camera frame and its instruction. Imagine changing only the noisy action proposal, such as moving the gripper left instead of right. The table follows a single attention layer in the three-block case with a separate robot-state token. Each row names the token doing the reading.
| Reading token | Image and instruction | Robot state | Noisy action chunk |
|---|---|---|---|
| Image or instruction | Can read | Blocked | Blocked |
| Robot state | Can read | Can read | Blocked |
| Action slot | Can read | Can read | Can read all slots |
Start with the top row. No route leads from a revised action to that row, and the same rule holds in every layer. The visual and language features therefore stay fixed throughout this policy call. Now follow the bottom row. An action slot can use the observed scene and the other proposed actions, including later slots in execution order. Those later slots contain the model’s current guesses during sampling. No future robot observation is available.
This asymmetry is what makes a prefix cache valid. Save the per-layer keys and values of the fixed prefix. At each sampling step, recompute the changing action stream against them. A fresh camera frame or instruction starts a different conditioning problem and requires the affected prefix features to be computed again.
Assign block IDs by cumulatively summing boundary flags. A valid query can read valid keys in the same block or an earlier block. In π₀, image and language form a bidirectional prefix. A separate continuous state token can read that prefix. The noisy action tokens share a block, attend to each other bidirectionally, and can read the state and prefix. In the π₀.₅ input convention, the state is encoded in the prompt. OpenPI mask and embedding source
Only normalize over valid keys of a valid query. Since prefix states cannot read noisy actions, layer-wise prefix keys and values can be reused throughout a sampling call with fixed observations and weights. The action rows change as the sampler updates the chunk.
For batch one, 18 layers, three 224-pixel images with 256 visual tokens each, and 200 text positions, . With BF16 and one 256-dimensional key/value head, the cache contents occupy about 17.02 MiB. The lab compares prefix-only and full forwards numerically while changing the action suffix.
Inspect individual token rows and compare a cached pass with a full pass
Prefix–Suffix Attention Mask Inspector
Action Velocity and ODE Sampling
OpenPI uses generation time for noise and for data. This reverses the convention in Lesson 5.5 and the original π₀ paper. The clean action chunk and a same-shaped Gaussian draw form a linear training path.
OpenPI uses a beta draw with shape parameters 1.5 and 1, scaled and shifted into the interval from 0.001 to 1. The teaching experiment uses uniform time. The population squared-error minimizer is the conditional expectation of the target velocity given the noisy actions, time, and observations. OpenPI objective and sampler
Euler subtracts the predicted velocity because the clock decreases. An inferred chunk comes from integrating this field from initial noise with the observation fixed. The learned velocity lives in normalized action space per unit of generation time. OpenPI's default sampler uses ten updates; the toy experiment uses eight. The expert chunk shown in the lab serves as a reference.
Action Velocity & ODE Generation
Discrete State and Adaptive RMSNorm in π₀.₅
The π₀.₅ study combines heterogeneous data and semantic subtasks to improve transfer to new environments. Knowledge Insulation is a related training approach that stops selected expert-to-backbone gradients to preserve semantic learning. The architecture table concerns specific OpenPI implementation choices.
| OpenPI implementation | π₀ | π₀.₅ |
|---|---|---|
| State input | Continuous state suffix | Discrete state in prompt |
| Time conditioning | Action + time embedding MLP | Time MLP → adaRMSNorm |
| Action output | Flow velocity | Flow velocity |
For a state component in , OpenPI assigns a bin index . It writes the resulting integer into the prompt and then applies the language tokenizer. The integer text can correspond to multiple vocabulary tokens. The application must handle the chosen normalization and out-of-range values. State tokenization source
Adaptive RMSNorm scales the root-mean-square-normalized features without subtracting their mean. A layer's time-conditioned modulation provides a scale, shift, and gate. The same modulation is broadcast across action tokens.
The gate controls how much the residual branch contributes. The OpenPI modulation projection starts at zero, and the teaching lab uses explicit numerical settings to illustrate the calculation. The trained toy model uses a separate time feature. Adaptive RMSNorm source
State Tokenization & Adaptive RMSNorm
Dataset Transforms, LoRA, and Gradient Paths
Record visual observations, instructions, robot state, actions, timestamps, coordinates, and units in aligned episodes. Split by episode and estimate normalizers on the training data. The model's output must be mapped back to the intended robot action representation.
OpenPI selects frozen paths by backbone and expert variant and leaves LoRA weights trainable. The listed Gemma variants use rank and scale numerator pairs 16/16 for the backbone and 32/32 for the small expert, in both attention and feedforward layers. The toy model targets only Q and V of one stream with rank two. Its expert-only setting trains the action input and output maps and the expert projections. Freeze filter · Gemma variants
This row-vector convention writes the factors in the opposite order from Lesson 6.1's column-vector convention. At initialization , so the base output is preserved and the first gradient for vanishes. Freezing the base prevents an optimizer update to the weight while retaining derivatives through its inputs. A stop-gradient operation can remove an entire activation-gradient route.
Dataset, LoRA & Freeze Filter Inspector
| Tensor | Trainable | Gradient L₂ | Update L∞ |
|---|---|---|---|
| p_img | No | — | — |
| a_out | No | — | — |
| p0Q | No | — | — |
| p0V | No | — | — |
| a0Q | No | — | — |
| a0V | No | — | — |
| p0Q_A | Yes | — | — |
| p0Q_B | Yes | — | — |
| p0V_A | Yes | — | — |
| p0V_B | Yes | — | — |
Engineering Experiment · Mini VLA in Closed Loop
A two-channel image contains red and blue blocks in distinct quadrants. The instruction names one color. Pixel pooling yields four tokens with red and blue counts, fixed patch coordinates, and a constant component. The world targets are m. The model receives the current position and velocity and predicts a four-step normalized acceleration chunk. The architecture has 1176 base parameters, including prefix projections that do not contribute to the last-layer action loss.
The source task uses and . The adaptation task uses and . Rollouts last 40 steps at 10 Hz. By default execute two actions per plan and use eight Euler updates per sample. Demonstrations include three extra expert steps for full chunk labels. The source has 32 training episodes and 16 held-out episodes with the two objects in diagonally opposed quadrants. It trains for 600 Adam updates at 0.004. Adaptation starts from the same trained source weights for each method, with 240 updates at 0.003 and 16 windows per batch.
The target development evaluation uses 16 perturbed episodes with held-out color layouts and fixed sampling seeds. Success checks both final goal distance below 0.25 m and final speed below 0.35 m/s. Choice records whether the final position is closer to the instructed target than to the other target. Image masking removes the colors but retains position tokens. Instruction swapping flips the color while keeping the evaluation target fixed.
Live Mini VLA Training
PyTorch benchmark · Seed 3
Source pretraining changes the held-out velocity MSE from 1.004615 to 0.252464. The shared checkpoint begins target adaptation at 0.342151. Expert final goal error is 0.0638 m and expert success is 16 of 16.
| Method | Trainable params | Held-out velocity MSE | Goal error (m) | Success | Choice |
|---|---|---|---|---|---|
| Frozen baseline | 0 | 0.342151 | 1.5241 | 0.00% | 50.00% |
| Frozen backbone / train expert | 568 | 0.273304 | 1.6681 | 6.25% | 43.75% |
| Full fine-tuning | 1176 | 0.249176 | 1.7883 | 6.25% | 43.75% |
| Backbone Q/V LoRA | 128 | 0.323536 | 1.5119 | 6.25% | 50.00% |
| Action expert Q/V LoRA | 128 | 0.339437 | 1.4952 | 0.00% | 50.00% |
Condition ablation · Choice rate
| Method | Intact | Image mask | Instruction swap |
|---|---|---|---|
| Frozen baseline | 50.00% | 68.75% | 62.50% |
| Frozen backbone / train expert | 43.75% | 56.25% | 56.25% |
| Full fine-tuning | 43.75% | 56.25% | 43.75% |
| Backbone Q/V LoRA | 50.00% | 75.00% | 50.00% |
| Action expert Q/V LoRA | 50.00% | 62.50% | 62.50% |
The experiment leaves several explanations open, including insufficient use of color by the velocity objective, the held-out object arrangements, the capacity of the small visual encoder, and closed-loop distribution shift. The measured outcomes establish the behavior of these toy configurations.
Reproducible PyTorch implementation
The CPU float64 script produces the source checkpoint, trains the adaptation variants, executes perturbed rollouts, and writes the condition ablations to result0605.json.
import math,json,torch
from torch import nn
torch.set_default_dtype(torch.float64);torch.set_num_threads(1)
D=8;H=4;P=6;T=40;L=2;R=2
class RNG:
def __init__(self,s):self.s=s
def __call__(self):self.s=(1664525*self.s+1013904223)%2**32;return self.s/2**32
def u(self,a):return a*(2*self()-1)
def z(self):return math.sqrt(-2*math.log(max(self(),1e-15)))*math.cos(2*math.pi*self())
GOALS=[[-1.,-1.],[1.,-1.],[-1.,1.],[1.,1.]]
def cases(seed,n,held=False,shift=False):
r=RNG(seed);pairs=[(a,b) for a in range(4) for b in range(4) if a!=b and ((a^b)==3)==held];out=[]
for i in range(n):
a,b=pairs[(i//2)%len(pairs)];q=i%2;out.append(dict(pos=[a,b],q=q,s=[r.u(.35),r.u(.35),r.u(.1),r.u(.1)],gain=.065 if shift else .1,drag=.96 if shift else .95,shock=[r.u(.15),r.u(.15)] if shift else [0,0]))
return out
def image(c):
im=[[[0.,0.] for j in range(8)] for i in range(8)]
for color,p in enumerate(c['pos']):
y=(p//2)*4+1;x=(p%2)*4+1
for i in range(y,y+2):
for j in range(x,x+2):im[i][j][color]=1.
return im
def features(c,ablate='none'):
im=image(c);f=[]
for p,(x,y) in enumerate(GOALS):
a,b=p//2*4,p%2*4;v=[sum(im[i][j][k] for i in range(a,a+4) for j in range(b,b+4))/4 for k in range(2)]
f.append(([0,0] if ablate=='image' else v)+[x,y,1])
q=1-c['q'] if ablate=='text' else c['q'];return f,[float(q==0),float(q==1)]
def step(s,a,c):
v=[c['drag']*s[i+2]+c['gain']*a[i] for i in range(2)];return [s[i]+.1*v[i] for i in range(2)]+v
def clip(v):return max(-2.,min(2.,v))
def expert(s,c):
g=GOALS[c['pos'][c['q']]];return [clip(2.4*(g[i]-s[i])-1.8*s[i+2]) for i in range(2)]
def demo(c):
f,q=features(c);s=c['s'][:];ss=[];aa=[]
for k in range(T+H-1):
ss.append(s);a=expert(s,c);aa.append([v/2 for v in a]);s=step(s,a,c)
return [(f,q,ss[k],aa[k:k+H]) for k in range(T)]
def data(cs):return [d for c in cs for d in demo(c)]
SH=[('p_img',5,D),('p_lang',2,D),('p_state',5,D),('a_in',5,D),('a_out',D,2)]+[(f'{g}{l}{w}',D,D) for l in range(L) for g in ['p','a'] for w in 'QKVO']
class VLA(nn.Module):
def __init__(self,seed=3,base=None,mode='full'):
super().__init__();r=RNG(seed+100);self.w=nn.ParameterDict();self.adapters=nn.ParameterDict();self.mode=mode
for k,m,n in SH:
v=torch.tensor(base[k]) if base else torch.tensor([[r.u(.3) for j in range(n)] for i in range(m)])
self.w[k]=nn.Parameter(v,requires_grad=mode=='full' or (mode=='expert' and k.startswith('a')))
if mode in ('backlora','explora'):
g='p' if mode=='backlora' else 'a'
for l in range(L):
for w in 'QV':
k=f'{g}{l}{w}';self.adapters[k+'_A']=nn.Parameter(torch.tensor([[r.u(.2) for j in range(R)] for i in range(D)]));self.adapters[k+'_B']=nn.Parameter(torch.zeros(R,D))
def weight(self,k):return self.w[k]+self.adapters[k+'_A']@self.adapters[k+'_B'] if k+'_A' in self.adapters else self.w[k]
def forward(self,f,q,s,x,t,trace=False):
B=x.shape[0];state=torch.cat([s,torch.ones_like(s[:,:1])],-1);X=torch.cat([f@self.w['p_img'],(q@self.w['p_lang'])[:,None,:],(state@self.w['p_state'])[:,None,:]],1).tanh()
a=torch.cat([x,t[:,None,None].expand(B,H,1),torch.arange(H)[None,:,None].expand(B,H,1)/(H-1),torch.ones(B,H,1)],-1);Y=(a@self.w['a_in']).tanh();tr=[]
for l in range(L):
Q,K,V=[torch.cat([X@self.weight(f'p{l}{w}'),Y@self.weight(f'a{l}{w}')],1) for w in 'QKV'];S=Q@K.transpose(-1,-2)/math.sqrt(D);S=S.masked_fill((torch.arange(P+H)[:,None]<P)&(torch.arange(P+H)[None,:]>=P),-torch.inf);A=S.softmax(-1);O=A@V;X=(X+O[:,:P]@self.weight(f'p{l}O')).tanh();Y=(Y+O[:,P:]@self.weight(f'a{l}O')).tanh();tr.append((X,Y,A))
out=Y@self.w['a_out'];return (out,tr) if trace else out
def export(self):return {k:v.detach().tolist() for k,v in self.w.items()}|{k:v.detach().tolist() for k,v in self.adapters.items()}
def batch(ds,r,n):
d=[ds[int(r()*len(ds))] for _ in range(n)];f,q,s,a=map(torch.tensor,zip(*d));ts=[];zs=[]
for _ in range(n):ts.append(r());zs.append([[r.z() for j in range(2)] for i in range(H)])
t=torch.tensor(ts);z=torch.tensor(zs);x=t[:,None,None]*z+(1-t[:,None,None])*a;return f,q,s,x,t,z-a
def train(seed,mode,updates,lr,base=None,shift=False):
ds=data(cases(seed,32,False,shift));vs=data(cases(seed+1000,16,True,shift));vb=batch(vs,RNG(seed+300),128);p=VLA(seed,base,mode);params=[w for w in p.parameters() if w.requires_grad];opt=torch.optim.Adam(params,lr=lr) if params else None;r=RNG(seed+200);hist=[]
for i in range(updates+1):
if i%40==0 or i==updates:
with torch.no_grad():hist.append([i,float((p(*vb[:-1])-vb[-1]).square().mean())])
if i==updates:break
b=batch(ds,r,16);loss=(p(*b[:-1])-b[-1]).square().mean()
if opt:opt.zero_grad();loss.backward();opt.step()
return p,hist,len(ds),sum(w.numel() for w in params)
@torch.no_grad()
def sample(p,c,s,r,n=8,ablate='none'):
f,q=features(c,ablate);f=torch.tensor([f]);q=torch.tensor([q]);s=torch.tensor([s]);x=torch.tensor([[[r.z() for j in range(2)] for i in range(H)]]);path=[x[0].tolist()]
for k in range(n):x=x-p(f,q,s,x,torch.tensor([1-k/n]))/n;path.append(x[0].tolist())
return path
@torch.no_grad()
def rollout(p,c,E=2,n=8,seed=4,ablate='none'):
s=c['s'][:];ss=[s];aa=[];queue=[];r=RNG(seed);g=GOALS[c['pos'][c['q']]]
for k in range(T):
if k==15:s=s[:2]+[s[i+2]+c['shock'][i] for i in range(2)];ss[-1]=s
if p is None:a=expert(s,c)
else:
if not queue:queue=[[clip(2*v) for v in a] for a in sample(p,c,s,r,n,ablate)[-1][:E]]
a=queue.pop(0)
s=step(s,a,c);ss.append(s);aa.append(a)
return ss,aa
def metrics(p,cs,ablate='none',E=2,n=8):
vals=[]
for i,c in enumerate(cs):
ss,aa=rollout(p,c,E,n,900+i,ablate);s=ss[-1];g=GOALS[c['pos'][c['q']]];other=GOALS[c['pos'][1-c['q']]];err=math.dist(s[:2],g);speed=math.hypot(*s[2:]);vals.append([err,speed,float(err<.25 and speed<.35),float(err<math.dist(s[:2],other))])
return dict(zip(['goal','speed','success','choice'],[sum(v[i] for v in vals)/len(vals) for i in range(4)]))
if __name__=='__main__':
base,hist,nd,np=train(3,'full',600,.004);b=base.export();print('BASE',hist[0],hist[-1],np,flush=True);cs=cases(5003,16,True,True);res={'base':b,'pretrain':hist,'expert':metrics(None,cs),'modes':{}}
for mode in ['frozen','expert','full','backlora','explora']:
p,h,_,n=train(3,mode,240,.003,b,True);out={'p':p.export(),'hist':h,'params':n,'metrics':metrics(p,cs),'image':metrics(p,cs,'image'),'text':metrics(p,cs,'text')};res['modes'][mode]=out;print(mode,h[0],h[-1],n,out['metrics'],out['image'],out['text'],flush=True)
json.dump(res,open('result0605.json','w'))
References and OpenPI Source Trace
- The continuous and discrete VLA families. π₀ · π₀.₅ · OpenVLA · FAST
- Training and initialization. Knowledge Insulation · Flow Matching · LoRA · PaliGemma
- Data assembly and policy transforms. Training configurations · Observation and action transforms
| Source | Read / inspect |
|---|---|
| pi0_config.py | Pi0Config, inputs_spec, get_freeze_filter |
| pi0.py | make_attn_mask, embed_prefix, embed_suffix, compute_loss, sample_actions |
| gemma.py | get_config, RMSNorm, Attention, Block, KVCache |
| tokenizer.py | PaligemmaTokenizer, state discretization, prompt |
| training/config.py | data config, checkpoint, freeze and optimizer setup |
| transforms.py | normalization, action/state transform, prompt/tokenizer |
The table refers to the JAX implementation. Branch links can evolve, so a reproduction records the code revision, checkpoint, and data transforms. The next lesson learns to predict environmental dynamics from candidate actions.
Previous lesson · 6.4 Diffusion Policy · Course overview · Next lesson · 6.6 World Models