Lesson 6.2 — Vision-Language Models
Previous lesson · 6.1 Large Language Models and Model Adaptation · Course overview · Next lesson · 6.3 Imitation Learning
Image–Text Representations
A vision-language model can align images and text in a common embedding space for retrieval, or generate text conditioned on images. These objectives can share a visual encoder. Retrieval accuracy and correct use of visual evidence during generation are measured separately.

Both scenes have identical color totals. A representation that records only “red present, blue present” would give the same result for both. To match the caption red top left, blue bottom right, the image representation must preserve which color occupies which quadrant.
Now keep the left image fixed. The prompt token red should lead to top left, while blue should lead to bottom right. This time the image features stay fixed and the requested location changes. These two comparisons distinguish what the alignment stage learns to match from what the decoder must learn to read. The labels R and B in the figure are annotations.
The teaching images are with two color channels. Each image contains one red and one blue block in distinct quadrants. The positions within the quadrants and the brightness vary. Pool each quadrant by summing each channel and dividing by four, preserving block intensity while discarding location within the patch. Captions encode red and blue quadrant labels as two concatenated one-hot vectors.
The position-specific image map and text map are linear. L2 normalization turns the dot product into cosine similarity when both vectors are nonzero. Implementations use a norm floor for numerical stability. Each training contrastive batch uses distinct captions, avoiding duplicate captions being treated as negatives in this experiment.
Inspect the patch features and the pooled retrieval embedding
Image–Text Representation Space
CLIP and Contrastive Alignment
Place paired image and text embeddings on the same index of a batch. Then the positive logits lie on the diagonal of the image-by-text matrix. Row normalization predicts texts from images, and column normalization predicts images from texts. The lab uses a fixed inverse temperature of five.
The normalization Jacobian for the image embedding is . It removes the radial component of the gradient before propagating it into the unnormalized vector. With all else fixed, lower temperature sharpens each softmax. The label permutation in the lab breaks matches while keeping the diagonal as the supervised target.
Image–Text Similarity Matrix
| Row | Caption 0 | Caption 1 | Caption 2 | Caption 3 |
|---|---|---|---|---|
| Image 0 | 4.9916 | 0.5445 | -0.9818 | -0.3245 |
| Image 1 | 0.3859 | 4.9826 | -0.3925 | -0.3744 |
| Image 2 | -1.0841 | -0.2894 | 4.9881 | 0.4208 |
| Image 3 | -0.3908 | -0.3203 | 0.4613 | 4.9934 |
SigLIP and Pairwise Logistic Loss
SigLIP assigns each image–text pair a binary match label. In this example, matched pairs have label , unmatched pairs have label , and the biased logit is the scaled cosine similarity plus . Each pair contributes one softplus term. The sum is normalized by the number of paired examples .
Pairwise sigmoid scores need not sum to one. An explicitly formed matrix still has entries. The demonstration evaluates both objectives on the same representation. The training lab learns two representations from identical initialization using the two respective objectives.
Softmax vs. Sigmoid Loss
| Row | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| 0 | 2.9916 | -1.4555 | -2.9818 | -2.3245 |
| 1 | -1.6141 | 2.9826 | -2.3925 | -2.3744 |
| 2 | -3.0841 | -2.2894 | 2.9881 | -1.5792 |
| 3 | -2.3908 | -2.3203 | -1.5387 | 2.9934 |
Visual Tokens in PaliGemma v1
The original PaliGemma combines a SigLIP So400m/14 vision encoder with a Gemma 2B text decoder. Square images at resolutions 224, 448, and 896 produce 256, 1024, and 4096 patch positions at stride 14. A projection maps each continuous width-1152 visual token to width 2048 for the decoder.
Here is the number of equally sized images encoded independently. At 224 pixels, three images concatenate to 768 visual tokens, before prompt tokens and any padding. The projector matrix has 2,359,296 weights, with an additional 2048 scalars when using a bias. The course lab counts patches and projection shapes from the configuration.
Calculate token counts for a particular image resolution
Multi-image Patch Token Inspector
Visual Prefixes and Cross-attention
A projector brings visual features into the decoder width. Concatenating them with text tokens forms a visual prefix processed by self-attention. In a cross-attention design, text queries read projected visual keys and values directly.
Follow the red block through the two stages. For retrieval, the teaching encoder combines the four position-specific patch contributions into one image vector and compares it with a whole caption. For generation, the decoder receives those contributions separately as visual tokens. The color prompt and the visual tokens jointly determine the answer distribution. Keeping the tokens separate gives the decoder access to spatial evidence. The swapped-image and swapped-prompt evaluations check whether it uses that evidence.
The trained teaching VLM uses the visual prefix design. The global alignment embedding is the sum of four patch contributions. Freeze the trained image matrix and use each contribution as its own token. A trainable projector transforms those tokens, and a prefix Transformer processes them with the question and start marker. The cross-attention lab is a separate calculation for comparing fusion designs.
Projector & Cross-attention Explorer
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Top left | 4.060e-4 | -0.3749 | -0.4622 | 0.3409 | -0.2232 | -0.0156 | -0.0553 | -0.2146 |
| Top right | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
| Bottom left | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
| Bottom right | 0.2561 | -0.5124 | -0.1499 | 0.4177 | -0.0152 | -0.8046 | -0.6736 | 0.3161 |
| Row | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Top left | 0.1970 | 0.3141 | 0.3204 | -0.6555 | -0.6654 | 0.7246 | 0.2353 | -0.6687 |
| Top right | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
| Bottom left | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 | 0.0000 |
| Bottom right | -0.2620 | 0.3334 | 0.4386 | -1.4072 | -0.2919 | 0.3854 | -0.5515 | 0.3153 |
Prefix Attention
Prefix positions attend bidirectionally to one another. A suffix position can read the entire prefix and preceding suffix positions including itself. Prefix positions are isolated from the suffix. Let be the length of the prefix, and use zero-based row and column indices.
Apply padding constraints separately. Because prefix states do not depend on the suffix, a compatible implementation can reuse their cached keys and values across decoding steps. Mask structure, position encoding, and cache indices must agree.
Visual Prefix & Attention Mask
Visual Instruction Tuning
Each demonstration has an image, a question token, and an answer token. The sequence is four image tokens, the question, a start token, and then the answer. At the start token position predict the answer. At the answer position predict the end token. The earlier targets are ignored. The start token cannot read the answer during training.
The task vocabulary has four quadrant labels, two colors, a start token, and an end token. Measure both answer accuracy and complete answer-plus-end exact match. Teacher-forced cross-entropy receives the true previous token. For free generation, the model predicts it first.
Multimodal SFT & Label Mask
| Position | Input | Target | Loss mask |
|---|---|---|---|
| 0 | Top left | — | 0 |
| 1 | Top right | — | 0 |
| 2 | Bottom left | — | 0 |
| 3 | Bottom right | — | 0 |
| 4 | red | — | 0 |
| 5 | BOS | TL | 1 |
| 6 | TL | EOS | 1 |
Engineering Experiment · Two-stage Mini VLM
There are twelve ordered pairs of distinct red and blue quadrants. Train on the eight pairs whose quadrant-index difference modulo four is one or three, and hold out the four pairs with difference two. One draw and two questions per training scene give 16 training examples. Four draws and two questions per held-out scene give 32 evaluation examples.
Stage 1 trains the 128 image and text weights for 120 full-batch Adam updates at learning rate 0.03. Stage 2 freezes the 64 image weights and trains a projector and one-layer prefix Transformer. The width-eight, single-head model uses an FFN of width 16, two affine LayerNorms, eight vocabulary entries, and an output bias. It has 744 trainable parameters and uses 180 full-batch Adam updates at learning rate 0.02. The text encoder from Stage 1 does not enter generation.
Live Mini VLM Training
PyTorch benchmark · Seed 3
| Alignment | Held retrieval | Train suffix CE | Held CE | Answer acc. | Image shuffle | Question swap | Image mask |
|---|---|---|---|---|---|---|---|
| clip | 100.00% | 0.142110 | 2.222760 | 43.75% | 28.12% | 18.75% | 25.00% |
| siglip | 100.00% | 0.175469 | 3.088718 | 25.00% | 40.62% | 9.38% | 25.00% |
Both encoders retrieve all four held-out captions. The generative models answer 43.75% and 25.00% of held-out questions correctly. Image shuffling and question swapping keep the original target while breaking the matching condition. These are sensitivity measurements. The SigLIP-style model's accuracy increases under this image shuffle on the fixed split, so retrieval alone cannot establish that its decoder uses the image reliably.
Reproducible PyTorch implementation
The script implements both objectives and the two training stages in CPU float64. The browser uses the same synthetic split. Inspect the label mask and the three condition perturbations when comparing checkpoints.
import torch, math, json
import torch.nn.functional as F
torch.set_num_threads(1);torch.set_default_dtype(torch.float64)
D=8; V=8
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 scenes(held=False,repeat=1,seed=3):
r=RNG(seed);out=[]
for a in range(4):
for b in range(4):
if a==b or ((b-a)%4==2)!=held:continue
for _ in range(repeat):
im=torch.zeros(8,8,2)
for c,p in enumerate([a,b]):
y=p//2*4+int(r()*3);x=p%2*4+int(r()*3);im[y:y+2,x:x+2,c]=.8+.4*r()
f=torch.stack([im[i//2*4:i//2*4+4,i%2*4:i%2*4+4].sum((0,1))/4 for i in range(4)])
text=F.one_hot(torch.tensor([a,b]),4).flatten().double();out.append(dict(im=im.tolist(),f=f.tolist(),text=text.tolist(),pos=[a,b]))
return out
def init(shapes,seed):
r=RNG(seed);return {k:torch.tensor([[1. if k.startswith('g') else 0. if k.startswith('b') else .8*(r()-.5) for _ in range(n)] for _ in range(m)],requires_grad=True) for k,m,n in shapes}
def alignment(p,ds,mode):
x=torch.tensor([s['f'] for s in ds]).flatten(1);y=torch.tensor([s['text'] for s in ds]);u=F.normalize(x@p['I'],dim=-1);v=F.normalize(y@p['T'],dim=-1);S=5*u@v.T;labels=torch.arange(len(ds));loss=(F.cross_entropy(S,labels)+F.cross_entropy(S.T,labels))/2 if mode=='clip' else F.softplus(-(2*torch.eye(len(ds))-1)*(S-2)).sum()/len(ds)
return loss,S
def align(seed=3,mode='clip',steps=120,lr=.03):
p=init([('I',8,8),('T',8,8)],seed+100);opt=torch.optim.Adam(p.values(),lr=lr);ds=scenes(seed=seed);vs=scenes(True,seed=seed+1000);hist=[]
for t in range(steps+1):
loss,S=alignment(p,ds,mode)
if t%10==0 or t==steps:
with torch.no_grad():
vl,A=alignment(p,vs,mode);hist.append(dict(t=t,loss=float(loss.detach()),val=float(vl),acc=float((A.argmax(1)==torch.arange(len(vs))).double().mean())))
if t==steps:break
opt.zero_grad();loss.backward();opt.step()
return p,hist
SHAPES=[('P',8,8),('E',8,8),('Q',8,8),('K',8,8),('V',8,8),('O',8,8),('U',8,16),('W',16,8),('g1',1,8),('b1',1,8),('g2',1,8),('b2',1,8),('R',8,8),('rb',1,8)]
def pos(n):
i=torch.arange(n)[:,None];j=torch.arange(D)[None,:];x=i/10000**(2*(j//2)/D);return torch.where(j%2==0,x.sin(),x.cos())
def forward(p,I,fs,q,a=None):
B=len(fs);iv=torch.einsum('bpc,pcd->bpd',fs,I.reshape(4,2,8));ids=torch.stack([q,torch.full_like(q,2)],dim=1)
if a is not None:ids=torch.cat([ids,(a+3)[:,None]],1)
X=torch.cat([iv@p['P'],p['E'][ids]],1);T=X.shape[1];X=X+pos(T);n=F.layer_norm(X,(D,),p['g1'].flatten(),p['b1'].flatten(),1e-5);Q,K,Vv=[n@p[k] for k in ['Q','K','V']];S=Q@K.transpose(1,2)/math.sqrt(D);i=torch.arange(T)[:,None];j=torch.arange(T)[None,:];mask=(j<6)|((i>=6)&(j<=i));A=S.masked_fill(~mask,-torch.inf).softmax(-1);Y=X+(A@Vv)@p['O'];m=F.layer_norm(Y,(D,),p['g2'].flatten(),p['b2'].flatten(),1e-5);Z=Y+F.gelu(m@p['U'],approximate='tanh')@p['W'];return Z@p['R']+p['rb']
def batch(ds):
return torch.tensor([s['f'] for s in ds for _ in range(2)]),torch.tensor([q for s in ds for q in range(2)]),torch.tensor([s['pos'][q] for s in ds for q in range(2)])
def evaluate(p,I,ds):
f,q,a=batch(ds)
with torch.no_grad():
z=forward(p,I,f,q,a);loss=F.cross_entropy(z[:,5:].reshape(-1,V),torch.stack([a+3,torch.full_like(a,7)],1).flatten());pred=forward(p,I,f,q)[:,-1].argmax(-1);end=forward(p,I,f,q,(pred-3).clamp(0,3))[:,-1].argmax(-1);acc=lambda x:float((x==a+3).double().mean());return dict(ce=float(loss),acc=acc(pred),seq=float(((pred==a+3)&(end==7)).double().mean()),image_shuffle=acc(forward(p,I,f.roll(8,0),q)[:,-1].argmax(-1)),text_shuffle=acc(forward(p,I,f,1-q)[:,-1].argmax(-1)),image_mask=acc(forward(p,I,torch.zeros_like(f),q)[:,-1].argmax(-1)))
def run(seed=3,mode='clip',steps=180,lr=.02):
ap,ah=align(seed,mode);I=ap['I'].detach();p=init(SHAPES,seed+200);opt=torch.optim.Adam(p.values(),lr=lr);ds=scenes(seed=seed);vs=scenes(True,4,seed+1000);fs,q,a=batch(ds);hist=[]
for t in range(steps+1):
z=forward(p,I,fs,q,a);loss=F.cross_entropy(z[:,5:].reshape(-1,V),torch.stack([a+3,torch.full_like(a,7)],1).flatten())
if t%10==0 or t==steps:hist.append(dict(t=t,train=float(loss.detach()),**evaluate(p,I,vs)))
if t==steps:break
opt.zero_grad();loss.backward();opt.step()
return dict(align=ah,I=I.tolist(),T=ap['T'].detach().tolist(),hist=hist,p={k:v.detach().tolist() for k,v in p.items()},params=sum(v.numel() for v in p.values()))
if __name__=='__main__':
results={m:run(mode=m) for m in ['clip','siglip']};print({m:(r['align'][-1],r['hist'][0],r['hist'][-1],r['params']) for m,r in results.items()});json.dump(results,open('/tmp/result0602.json','w'))
References and Model Source
- Contrastive and sigmoid image–text objectives. CLIP · SigLIP
- Visual instruction tuning. LLaVA
- Visual patch projection and prefix modeling. PaliGemma · Google source documentation · Transformers v4.41.0 reference
- The VLA lesson follows these mechanisms into an action expert. OpenPI
The next lesson learns actions from demonstrations and tests them in closed loop.
Previous lesson · 6.1 Large Language Models and Model Adaptation · Course overview · Next lesson · 6.3 Imitation Learning