Vision-language models: architecture and training
Study visual encoders, connectors and language models, vision–language objectives, LLaVA-style training stages and a small QLoRA VLM.
After this lesson you can
- Describe visual encoder, connector and LLM architecture and calculate visual-token budgets.
- Compare MLP projectors, Q-Formers and resamplers by tokens, parameters and quality.
- Explain vision–language pretraining objectives and their contributions.
- Reproduce LLaVA-style training stages and justify frozen components.
- Build and tune a small VLM with QLoRA on a local GPU.
Before you start
An image enters a language model
A description or visual answer combines perception and language, but a text model does not receive pixels directly. A common vision–language architecture uses a visual encoder to transform the image, a connector to adapt its representation, and a language model to generate text autoregressively. This structure can lead toward a policy that also emits actions, although a correct linguistic answer does not demonstrate safe robotic control.
Image preprocessing must match what the frozen encoder expects: resizing, cropping, and normalization are part of the model. If an image of side is divided into square patches of side , without padding or special tokens there are patches. A per-patch projector retains that count; a connector with queries can reduce it to tokens. Available context must also reserve instructions, separators, and response.
The connector decides what reaches language
The vision–language connector translates dimensions and organizes information. A per-patch MLP is simple, but its output grows with resolution. The Q-Former of BLIP-2 uses learned queries to extract visual-encoder information; its objectives and attention masks vary across stages. A cross-attention resampler uses latents to read patches and produces fixed length. Compression can reduce cost and also lose small text or objects; comparing parameter counts is insufficient.
KV cache per sequence, for tokens, layers, key/value heads, dimension and bytes per number, occupies approximately . The two counts keys and values; batch, text cache, and overhead must be added. Do not confuse query heads with KV heads when using grouped attention.
Token count also changes prefill work: in dense attention, scores between positions grow quadratically with total sequence length. Going from one image to several costs more than encoding each image: those tokens also participate in decoder context. A single global token reduces that cost but discards explicit correspondence between each spatial position and its representation. That matters especially when asked to read a small digit or locate a corner.
Q-Former queries are not response words. They are vectors that learn to extract information from a visual sequence via cross-attention; their number fixes bottleneck width. A latent resampler shares the idea of fixed output length, but this does not mean all models use the same masks, objectives, or text interaction. Compare accessible information and the stage in which each part trains, as well as token counts.
Objectives and stages
Pretraining objectives provide different signals. Contrast brings image–text pairs closer relative to others; matching classifies whether they correspond; captioning predicts words conditioned on an image; prefix LM predicts a continuation from a visible prefix. None alone guarantees factual fidelity or instruction following. Negatives can be ambiguous, and generative loss must exclude image, instructions, and padding from supervised labels.
In a batch contrastive loss, an image representation competes to assign its paired text higher probability than other batch texts. If two captions correctly describe the same scene, treating one as negative can introduce a contradictory signal. Captioning instead optimizes probability of a specific sequence; different valid responses do not necessarily receive equal scores. Matching can use hard negatives, but their quality depends on how they are built.
In a causal decoder, supervision and attention masks serve different functions. The former decides which positions contribute to loss; the latter decides which positions each token can consult. The visual token and instruction can be visible when predicting the answer even if their labels are -100. If the instruction is also supervised, the model may spend capacity copying the question; if the image is hidden from attention, it cannot use it to answer.
In visual instruction tuning, the model learns to answer turns associated with an image. LLaVA generated instruction data with a language model from textual image information. In its training-stage scheme, the connector is first aligned with image–text pairs while towers remain frozen, then conversational behavior is tuned. Freezing reduces parameters and protects existing representations, but does not guarantee language preservation; mixing text data and measuring before and after helps detect degradation.
The first stage still propagates gradients through the frozen LLM: its weights are not updated, but it calculates how the connector’s input must change to reduce loss. In the second, LoRA adds trainable low-rank matrices to selected projections; NF4 quantization reduces base-weight storage, while activations, adapters, optimizer, and caches retain their own costs. Total memory therefore cannot be inferred by multiplying parameter count by four bits.
MM1 ablations found strong influence from encoder, resolution, and token count, while connector design was comparatively less decisive under their conditions. Prismatic and Idefics2 show results also depend on data and training. Do not turn that finding into a universal rule for high-resolution documents or every budget.
Toy lab: answer mask
Precomputed synthetic features identify three colors and three shapes; they are not images or a complete transformer. The projector and one-answer decoder learn to solve two questions on held-out examples of the same combinations. The mask illustrates supervised positions; a real causal decoder shifts logits and labels to predict the next token.
import numpy as np
# Características conocidas de formas y colores, no imágenes reales.
rng = np.random.default_rng(25)
colors = ['rojo', 'azul', 'verde']
shapes = ['círculo', 'cuadrado', 'triángulo']
x, q, y = [], [], []
for color in range(3):
for shape in range(3):
for sample in range(10):
feat=np.zeros(6);feat[color]=1;feat[3+shape]=1
feat+=rng.normal(0,.04,6)
for question in range(2):
x.append(feat);q.append(question);y.append(color if question==0 else 3+shape)
x=np.array(x);q=np.array(q);y=np.array(y)
# 8 de cada 10 ejemplos por pareja se reservan para entrenamiento.
train=np.array([i for i in range(len(y)) if (i//2)%10<8]);test=np.array([i for i in range(len(y)) if (i//2)%10>=8])
W=rng.normal(0,.2,(6,12));b=np.zeros(12);Q=rng.normal(0,.2,(2,12));D=rng.normal(0,.2,(12,6));c=np.zeros(6)
for step in range(500):
h=np.tanh(x[train]@W+Q[q[train]]+b);logits=h@D+c
logits-=logits.max(axis=1,keepdims=True);p=np.exp(logits);p/=p.sum(axis=1,keepdims=True)
loss=-np.log(p[np.arange(len(train)),y[train]]).mean()
dz=p.copy();dz[np.arange(len(train)),y[train]]-=1;dz/=len(train)
dh=(dz@D.T)*(1-h*h);dD=h.T@dz;dc=dz.sum(0);dW=x[train].T@dh;db=dh.sum(0);dQ=np.zeros_like(Q);np.add.at(dQ,q[train],dh)
for param,grad in ((W,dW),(b,db),(Q,dQ),(D,dD),(c,dc)):param-=.25*grad
if step in (0,99,499): print('paso',step+1,'pérdida',round(float(loss),5))
pred=np.argmax(np.tanh(x[test]@W+Q[q[test]]+b)@D+c,axis=1)
print('exactitud retenida:',round(float((pred==y[test]).mean()),4),'n=',len(test))
# Sólo la posición de respuesta supervisa el objetivo de lenguaje.
ids=np.array([-100,-100,-100,2,-100]);active=ids!=-100
print('máscara de pérdida:',active.astype(int),'tokens supervisados:',active.sum())Local lab: a small VLM
The following experiment combines frozen OpenCLIP, an MLP projector and Qwen2.5-0.5B-Instruct. It uses the global visual representation as one token; it does not reconstruct LLaVA’s patch sequence. First it trains only the connector on 256 Flickr8k captions, then adds LoRA adapters to the NF4-quantized LLM for instructions on 500 CIFAR-10 images. Evaluation uses 200 CIFAR test images and six synthetic shapes with two questions. The score is normalized exact match on short answers, not a complete VQA evaluation. The experiment is short and demonstrates neither generalization nor language preservation.
In one RTX 3060 run with seed 25 and batches of four, 120 alignment and 200 instruction updates were performed. Exact match on 200 held-out CIFAR images was 0/200 initially, 0/200 after alignment, and 170/200 after instruction tuning. The zero-visual-vector control gave 0/40, 0/40 and 4/40 on a balanced subset; it does not compare exactly the same quantities as the 200-image test. The model answered shape images with words such as “oval” or “circle” even when asked about color, as the figure shows. A ten-label classifier is not a general VLM, and visual pretraining may have seen CIFAR-related data.
Displayed losses are from three batches per stage, not an epoch average: alignment values were 5.5276, 4.1253 and 3.9180, and instruction values 13.6493, 0.1391 and 0.0932. Peak PyTorch allocated memory was 1010.6 MiB, excluding all memory reserved by the process or other programs. Evaluation is greedy with at most six tokens; match requires the whole normalized answer to equal the label, so a correct word accompanied by additional text counts as an error.
To run, install CUDA PyTorch, torchvision, open_clip_torch==4.2.2, transformers, peft, bitsandbytes, huggingface_hub, pyarrow and Pillow in a compatible environment. Models and Flickr download at pinned revisions; CIFAR-10 uses its official download. Preprocessing is OpenCLIP’s. Execution needs a GPU compatible with bitsandbytes quantization and may take several minutes; full training was checked separately and is omitted from the automatic checker because of cost.
from pathlib import Path
from io import BytesIO
import os, time, gc, json
import numpy as np
from PIL import Image, ImageDraw
import pyarrow.parquet as pq
import torch
import open_clip
from torchvision.datasets import CIFAR10
from huggingface_hub import snapshot_download
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training
assert torch.cuda.is_available(), 'Se necesita una GPU CUDA compatible con bitsandbytes.'
torch.manual_seed(25);np.random.seed(25);torch.set_num_threads(2)
device='cuda';root=Path(os.environ.get('VLM_LAB_DIR','vlm-lab-data'));root.mkdir(parents=True,exist_ok=True)
clipdir=os.environ.get('VLM_CLIP_DIR') or snapshot_download('laion/CLIP-ViT-B-32-laion2B-s34B-b79K',revision='1a25a446712ba5ee05982a381eed697ef9b435cf',local_dir=root/'clip',allow_patterns=['open_clip_model.safetensors'])
flickr=os.environ.get('VLM_FLICKR_DIR') or snapshot_download('jxie/flickr8k',repo_type='dataset',revision='56f58c967835f7c508d684f36bd7897cca9d7634',local_dir=root/'flickr',allow_patterns=['data/train*.parquet'])
qwen=os.environ.get('VLM_QWEN_DIR') or snapshot_download('Qwen/Qwen2.5-0.5B-Instruct',revision='7ae557604adf67be50417f59c2c2f167def9a775',local_dir=root/'qwen',allow_patterns=['*.json','*.safetensors','*.txt'])
clip,_,preprocess=open_clip.create_model_and_transforms('ViT-B-32',pretrained=str(Path(clipdir)/'open_clip_model.safetensors'),device=device);clip.eval()
images=[];captions=[]
for path in sorted((Path(flickr)/'data').glob('train*.parquet')):
for batch in pq.ParquetFile(path).iter_batches(batch_size=32,columns=['image','caption_0']):
for row in batch.to_pylist():
images.append(Image.open(BytesIO(row['image']['bytes'])).convert('RGB'));captions.append(row['caption_0'])
if len(images)>=256:break
if len(images)>=256:break
if len(images)>=256:break
cifar_train=CIFAR10(root=os.environ.get('VLM_CIFAR_DIR',str(root/'cifar')),train=True,download=True);cifar_test=CIFAR10(root=os.environ.get('VLM_CIFAR_DIR',str(root/'cifar')),train=False,download=True)
def balanced(ds,n):
return [i for label in range(10) for i in [j for j,y in enumerate(ds.targets) if y==label][:n]]
tr=balanced(cifar_train,50);te=balanced(cifar_test,20)
for i in tr: images.append(cifar_train[i][0])
for i in te: images.append(cifar_test[i][0])
shape_answers=[]
for name,rgb in [('red',(230,30,30)),('blue',(30,30,230)),('green',(30,180,30))]:
for shape in ('circle','square'):
im=Image.new('RGB',(224,224),'white');draw=ImageDraw.Draw(im)
(draw.ellipse if shape=='circle' else draw.rectangle)((50,50,174,174),fill=rgb)
images.append(im);shape_answers.append((name,shape))
features=[]
with torch.no_grad():
for i in range(0,len(images),16):
v=clip.encode_image(torch.stack([preprocess(im) for im in images[i:i+16]]).to(device),normalize=True);features.append(v.cpu())
features=torch.cat(features);del clip;gc.collect();torch.cuda.empty_cache()
print('Características Flickr/CIFAR train/test/formas:',len(captions),len(tr),len(te),len(shape_answers),flush=True)
tok=AutoTokenizer.from_pretrained(qwen);tok.pad_token=tok.eos_token
quant=BitsAndBytesConfig(load_in_4bit=True,bnb_4bit_quant_type='nf4',bnb_4bit_use_double_quant=True,bnb_4bit_compute_dtype=torch.float16)
llm=AutoModelForCausalLM.from_pretrained(qwen,quantization_config=quant,device_map={'':0},dtype=torch.float16)
llm.config.use_cache=False;llm=prepare_model_for_kbit_training(llm)
llm=get_peft_model(llm,LoraConfig(r=8,lora_alpha=16,lora_dropout=.05,target_modules=['q_proj','v_proj'],task_type='CAUSAL_LM'))
for name,p in llm.named_parameters():p.requires_grad_('lora_' in name)
projector=torch.nn.Sequential(torch.nn.Linear(512,512),torch.nn.GELU(),torch.nn.Linear(512,llm.config.hidden_size)).to(device)
offset_train=len(captions);offset_test=offset_train+len(tr);offset_shapes=offset_test+len(te)
prompts=['Describe the image briefly.']*len(captions)+['What is the main object? Answer with one word.']*len(tr)
answers=captions+[cifar_train.classes[cifar_train.targets[i]] for i in tr]
def tokens(prompt,answer):
prefix=tok.encode('User: '+prompt+'\nAssistant:',add_special_tokens=False)
suffix=tok.encode(' '+answer,add_special_tokens=False)[:32]+[tok.eos_token_id]
return prefix,suffix
def batch_loss(ids):
sequences=[];labels=[]
for i in ids:
pre,answer=tokens(prompts[i],answers[i]);tid=torch.tensor(pre+answer,device=device)
visual=projector(features[i:i+1].to(device)).to(llm.get_input_embeddings().weight.dtype)
em=llm.get_input_embeddings()(tid).detach();sequences.append(torch.cat([visual,em],dim=0))
labels.append(torch.tensor([-100]*(1+len(pre))+answer,device=device))
size=max(len(x) for x in labels);emb=torch.stack([torch.nn.functional.pad(x,(0,0,0,size-len(x))) for x in sequences]);lab=torch.stack([torch.nn.functional.pad(x,(0,size-len(x)),value=-100) for x in labels]);mask=torch.stack([torch.arange(size,device=device)<len(x) for x in labels])
return llm(inputs_embeds=emb,attention_mask=mask,labels=lab).loss
def generate(idx,prompt):
pre=tok.encode('User: '+prompt+'\nAssistant:',add_special_tokens=False);tid=torch.tensor([pre],device=device)
with torch.no_grad():
vis=projector(features[idx:idx+1].to(device)).to(llm.get_input_embeddings().weight.dtype)
em=torch.cat([vis.unsqueeze(0),llm.get_input_embeddings()(tid)],1)
for _ in range(6):
out=llm(inputs_embeds=em,attention_mask=torch.ones(em.shape[:2],device=device,dtype=torch.long)).logits[:,-1].argmax(-1)
if int(out.item())==tok.eos_token_id:break
tid=torch.cat([tid,out[:,None]],1);em=torch.cat([em,llm.get_input_embeddings()(out[:,None])],1)
return tok.decode(tid[0,len(pre):],skip_special_tokens=True).strip()
def normal(s):return ' '.join(''.join(ch.lower() if ch.isalnum() else ' ' for ch in s).split())
def generate_batch(indices,prompt,zero_image=False):
pre=tok.encode('User: '+prompt+'\nAssistant:',add_special_tokens=False)
tid=torch.tensor([pre]*len(indices),device=device)
with torch.no_grad():
feat=features[indices].to(device);feat=torch.zeros_like(feat) if zero_image else feat
vis=projector(feat).to(llm.get_input_embeddings().weight.dtype).unsqueeze(1)
em=torch.cat([vis,llm.get_input_embeddings()(tid)],1);finished=torch.zeros(len(indices),dtype=torch.bool,device=device);generated=[]
for _ in range(6):
out=llm(inputs_embeds=em,attention_mask=torch.ones(em.shape[:2],device=device,dtype=torch.long)).logits[:,-1].argmax(-1)
out=torch.where(finished,torch.full_like(out,tok.eos_token_id),out);generated.append(out);finished|=out.eq(tok.eos_token_id)
if bool(finished.all()):break
em=torch.cat([em,llm.get_input_embeddings()(out[:,None])],1)
ids=torch.stack(generated,1).cpu().tolist()
return [tok.decode(row[:row.index(tok.eos_token_id)] if tok.eos_token_id in row else row,skip_special_tokens=True).strip() for row in ids]
def evaluate():
llm.eval();projector.eval();examples=[];correct=0
for start in range(0,len(te),8):
answers_batch=generate_batch(list(range(offset_test+start,offset_test+min(start+8,len(te)))),'What is the main object? Answer with one word.')
for k,a in enumerate(answers_batch):
j=start+k;i=te[j];target=cifar_test.classes[cifar_test.targets[i]];correct+=normal(a)==normal(target)
if j<5:examples.append((target,a))
if start%40==0:print('evaluados',min(start+8,len(te)),'/',len(te),flush=True)
shape=[]
for j,(color,form) in enumerate(shape_answers):
for question,target in [('What color is the shape? Answer with one word.',color),('What shape is shown? Answer with one word.',form)]:shape.append((target,generate(offset_shapes+j,question)))
print('CIFAR test:',correct,'/',len(te),'ejemplos:',examples,'formas:',shape,flush=True)
null_correct=0;control=[j for j in range(len(te)) if j%20<4]
for start in range(0,len(control),8):
subset=control[start:start+8];outputs=generate_batch([offset_test+j for j in subset],'What is the main object? Answer with one word.',zero_image=True)
for j,a in zip(subset,outputs):null_correct+=normal(a)==normal(cifar_test.classes[cifar_test.targets[te[j]]])
print('control vector visual nulo:',null_correct,'/40',flush=True)
return {'accuracy':correct/len(te),'correct':correct,'total':len(te),'examples':examples,'shapes':shape,'zero_image_correct':null_correct,'zero_image_total':40}
if os.environ.get('VLM_PILOT')=='1':
llm.eval();projector.eval();prompt='What is the main object? Answer with one word.'
single=[generate(offset_test+j,prompt) for j in range(4)];batch=generate_batch(list(range(offset_test,offset_test+4)),prompt)
assert single==batch,(single,batch)
print('PILOT: generación individual y en lote idéntica',single,flush=True)
llm.train();projector.train()
optim=torch.optim.AdamW(list(projector.parameters())+[p for p in llm.parameters() if p.requires_grad],lr=2e-4)
loss=batch_loss([0,1,2,3]);loss.backward();optim.step()
print('PILOT loss',float(loss),'max allocated MiB',torch.cuda.max_memory_allocated()/2**20,'max reserved MiB',torch.cuda.max_memory_reserved()/2**20,flush=True)
raise SystemExit
metrics={'stages':[]}
print('evaluación inicial');initial=evaluate();metrics['stages'].append({'name':'inicial','evaluation':initial,'losses':[]});start=time.perf_counter()
for stage,indices,steps in [('alineación',np.arange(len(captions)),120),('instrucciones',np.arange(offset_train,offset_test),200)]:
for name,p in llm.named_parameters():p.requires_grad_(stage=='instrucciones' and 'lora_' in name)
optim=torch.optim.AdamW(list(projector.parameters())+[p for p in llm.parameters() if p.requires_grad],lr=2e-4)
llm.train();projector.train();losses=[]
for step in range(steps):
ids=np.random.choice(indices,size=4,replace=False);loss=batch_loss(ids);optim.zero_grad();loss.backward();optim.step()
if step in (0,steps//2-1,steps-1):
losses.append({'step':step+1,'loss':float(loss.detach())});print(stage,'paso',step+1,'loss',round(float(loss.detach()),4),flush=True)
print('evaluación tras',stage,flush=True);evaluation=evaluate();metrics['stages'].append({'name':stage,'evaluation':evaluation,'losses':losses})
(root/'stage-results.json').write_text(json.dumps(metrics,ensure_ascii=False,indent=2),encoding='utf8')
llm.save_pretrained(root/'adapters');torch.save(projector.state_dict(),root/'projector.pt')
print('Adaptadores y proyector guardados en',root,flush=True)
print('tiempo entrenamiento/evaluación s:',round(time.perf_counter()-start,2),'memoria pico MiB:',round(torch.cuda.max_memory_allocated()/2**20,1),flush=True)
metrics['peak_allocated_mib']=torch.cuda.max_memory_allocated()/2**20
(root/'stage-results.json').write_text(json.dumps(metrics,ensure_ascii=False,indent=2),encoding='utf8')npm run lab and open the connection link.Exercises
def build_vlm_inputs(image_tokens, text_ids, image_positions):
passdef accuracy(predicciones, referencias):
pass