Vision–language models: visual interfaces, masks and grounded answers
视觉语言模型
Learn a small visual bridge and test spatial bindings, frozen modules and supervised token selection.
vision-language-modelsA language model needs a usable visual interface
Two objects appear in a scene: a red square on the left and a blue circle on the right. “Describe the left object” and “describe the right object” require different answers. A representation that remembers the set of colors and shapes but loses their bindings to positions cannot reliably answer either question.
Vision–language models connect visual information with language tasks, including retrieval, captioning and question answering. Their interfaces differ. BLIP-2 learns a query-based bridge between a frozen image encoder and a frozen language model. The initial LLaVA paper connects visual features through a linear projection and then performs visual instruction tuning. These are useful architectural contrasts, not one architecture shared by every VLM. Read CLIP, attention and Transformer first.
Projection, compression and token prediction
Let an image encoder return N visual tokens with dimension dv. A linear bridge to a language model of embedding dimension dL is:
This adapts dimensions and learned coordinates, but does not reduce the number of visual tokens. Nor can it recover information that the encoder discarded. LLaVA’s initial architecture and first training stage use a linear projection; the later projector implementation also supports MLP and identity options. A later option should not be attributed to the initial paper.
A query bridge can instead extract M output tokens from N visual tokens. One cross-attention operation, omitting multiple heads and residual layers for clarity, is:
Q contains learned query vectors. This equation explains a building block, not the entire Q-Former. BLIP-2’s §3.1–3.3 combines query/text transformers, different attention masks and staged objectives. Its generative stage projects query outputs into language embeddings and uses them as a visual prefix; the fixed OPT implementation shows that projection and prefix concatenation.
Autoregressive answer generation conditions each token on the visual state, the instruction q and preceding answer tokens:
Training typically supplies the correct previous tokens, a procedure called teacher forcing. The inputs must be shifted relative to prediction targets. A causal mask allowing a position to attend to itself is safe only when that position does not already contain the token it is supposed to predict.
Not every input position contributes a language loss. Image tokens, prompt tokens and padding can be context without being answer targets:
The OPT bridge masks visual-prefix and padding labels, and optionally prompt labels. The LLaVA input preparation inserts ignored labels for visual embeddings. Loss masking and attention masking do different jobs: the former selects supervised predictions, while the latter controls what information can influence them.
BLIP-2’s first stage illustrates that distinction. For contrastive learning, query and text tokens cannot interact through self-attention. For image–text matching they can interact bidirectionally. For image-grounded generation, queries cannot read the text and each text position can read queries and past text. With M query positions followed by L shifted text inputs, the last case can be written:
This mask prevents future text from leaking through a query token. Other architectures can use other interfaces; do not assume this exact matrix describes every visual prefix model.
Finally, “frozen” needs a named stage and module. BLIP-2 learns its bridge while keeping the image encoder and LLM frozen. Initial LLaVA first trains the projection with both backbones frozen; its instruction-tuning stage updates the projection and LLM while keeping the visual encoder frozen. These schedules are specified in the respective papers, not interchangeable defaults.
Learn a bridge and test whether it uses the right object
Save as vision_language_models.py, using Python 3.12 and NumPy 1.26.4. Each synthetic scene has two objects, a signed position and two signed attributes. A fixed linear transform mixes the attributes into visual features. A question selects left or right through fixed positional attention. A learned 2×2 bridge feeds a frozen binary head for each of two answer tokens.
The decoder is deliberately simpler than an LLM: the two token decisions are conditionally independent given the visual prefix. The program demonstrates a visual interface and supervised token selection, not a learned Q-Former, tokenizer or general autoregressive language model. It enumerates all 16 scenes and two questions per scene, giving 64 supervised attribute tokens.
The bridge trains with binary logistic loss:
Here z is the pooled visual feature and W has four learned entries. The factor 4 belongs to the fixed decoder. A linear token bridge costs O(Ndv dL); cross-attention costs O(MNdk) for scores plus value aggregation, and stores O(MN) affinities per head. Appending tokens to a dense decoder can increase its self-attention cost with the square of total sequence length. The tiny example is too small to estimate real VLM throughput.
"""Original visual bridge: synthetic objects and a frozen two-token decoder."""
import itertools,json
import numpy as np
MIX=np.array([[.4,1.],[-.8,.2]])
def data():
records=[];questions=[];targets=[]
for values in itertools.product([-1.,1.],repeat=4):
objects=np.array(values).reshape(2,2)
for index in [0,1]:
records.append(np.c_[[-1.,1.],objects@MIX]);questions.append([-1.,1.][index]);targets.append(objects[index])
return np.array(records),np.array(questions),np.array(targets)
def pool(tokens,question,sharpness=2.):
tokens=np.asarray(tokens,float);question=np.asarray(question,float)
if tokens.ndim!=3 or tokens.shape[1:]!=(2,3) or question.shape!=(len(tokens),) or not np.isfinite(tokens).all() or not np.isfinite(question).all() or not np.isfinite(sharpness) or not 0<=sharpness<=20:raise ValueError('Invalid scene/question')
logits=sharpness*question[:,None]*tokens[:,:,0];logits-=logits.max(axis=1,keepdims=True);w=np.exp(logits);w/=w.sum(axis=1,keepdims=True)
return np.sum(w[:,:,None]*tokens[:,:,1:],axis=1),w
def objective(theta,features,target):
theta=np.asarray(theta,float);features=np.asarray(features,float);target=np.asarray(target,float)
if theta.shape!=(2,2) or features.ndim!=2 or features.shape[1]!=2 or target.shape!=features.shape or not len(features) or not np.isfinite(theta).all() or not np.isfinite(features).all() or not np.isin(target,[-1,1]).all():raise ValueError('Invalid bridge or binary-token target')
logits=4*features@theta;z=-target*logits;loss=np.logaddexp(0,z).mean();sigmoid=np.exp(-np.logaddexp(0,-z));gradient=features.T@(-4*target*sigmoid)/target.size
return float(loss),gradient,logits
def attention_mask(queries,text,mode):
if not all(isinstance(n,int) and not isinstance(n,bool) and 1<=n<=16 for n in [queries,text]):raise ValueError('Invalid lengths')
n=queries+text;m=np.zeros((n,n),bool);m[:queries,:queries]=True
if mode=='matching':m[:]=True
elif mode=='contrastive':m[queries:,queries:]=True
elif mode=='generation':m[queries:,:queries]=True;m[queries:,queries:]=np.tri(text,dtype=bool)
else:raise ValueError('Unknown objective')
return m
def masked_token_loss(logits,targets,mask):
logits=np.asarray(logits,float);targets=np.asarray(targets);mask=np.asarray(mask)
if logits.ndim!=2 or targets.shape!=(len(logits),) or mask.shape!=targets.shape or mask.dtype!=bool or not mask.any() or targets.dtype.kind not in 'iu' or np.any(targets[mask]<0) or np.any(targets[mask]>=logits.shape[1]) or not np.isfinite(logits).all():raise ValueError('Invalid supervised tokens')
z=logits[mask];y=targets[mask];z=z-z.max(axis=1,keepdims=True)
return float(np.mean(np.log(np.exp(z).sum(axis=1))-z[np.arange(len(z)),y]))
def train(updates=600):
if not isinstance(updates,int) or isinstance(updates,bool) or not 0<=updates<=2000:raise ValueError('Invalid update count')
tokens,q,target=data();x,_=pool(tokens,q);theta=np.eye(2)*.1;history=[]
for step in range(updates+1):
loss,g,_=objective(theta,x,target)
if step%100==0 or step==updates:history.append(loss)
if step<updates:theta-=.2*g
return theta,history
def mean_pool_bound():
tokens,q,y=data();pooled=tokens[:,:,1:].mean(axis=1);groups={}
for features,question,targets in zip(pooled,q,y):
key=tuple(np.round(features,12))+(question,);groups.setdefault(key,[]).append(targets)
correct=sum(np.maximum((np.array(values)==1).sum(axis=0),(np.array(values)==-1).sum(axis=0)).sum() for values in groups.values())
return float(correct/y.size)
def demo():
theta,history=train();tokens,q,y=data();x,w=pool(tokens,q);logits=objective(theta,x,y)[2];wrong=objective(theta,*[pool(tokens,-q)[0],y])[2];blind=objective(theta,np.zeros_like(x),y)
return dict(training_loss=history,token_accuracy=float(np.mean(np.sign(logits)==y)),opposite_object_accuracy=float(np.mean(np.sign(wrong)==y)),blind_loss=blind[0],attention_weights=w[:2].tolist(),projection=theta.tolist(),mean_pool_information_bound=mean_pool_bound(),supervised_tokens=int(y.size),scope='Four trained bridge parameters, fixed positional pooling and binary-token head; no pretrained image encoder, LLM or Q-Former training.')
if __name__=='__main__':print(json.dumps(demo(),indent=2))
After 600 updates at rate .2, loss falls from .651836 to .00129024 and all attribute tokens are correct. Change the question to the opposite object while retaining the original target and accuracy falls to .5. Remove the visual information and the binary loss is log(2). These tests distinguish fitting the data from using the intended input.
The selected object’s attention weight is about .982014. If instead the two objects are averaged without retaining their positions, the best possible per-attribute accuracy in this balanced task is .75: half the pairs agree and are identifiable; half disagree, leaving a coin flip. The program calculates the bound by grouping indistinguishable observations. More decoder capacity cannot undo this lost binding.
An answer can be fluent while the visual evidence is absent
The finite experiment checks only two objects and two attributes. Real encoders may lose small text, fine spatial detail or uncommon objects before language generation begins. Resolution, cropping, number of visual tokens and their ordering can change what is recoverable. A longer answer is not evidence of better grounding.
Evaluate against text-only and image-shuffled baselines, ask questions whose answer changes when the image changes, and separate recognition, localization, counting and instruction following. A model may exploit recurring language patterns even when image inputs are ignored. The exact synthetic mean-pooling bound does not transfer as a .75 limit to arbitrary VLMs; it follows from this declared observation map and data law.
The model interface is also distinct from multimodal fusion as a general task design and from text-to-image generation, which predicts visual outputs. Model families and training stages should be named when discussing capabilities.
Check what survives the interface
- Calculation. Project 16 visual tokens of width 32 into a language space of width 64. What are W’s shape and parameter count without bias? Answer: W is 32×64 and has 2,048 entries. The output still has 16 tokens; projection alone does not compress token count.
- Prediction. Why does reversing the left/right question reduce accuracy to .5 in the complete synthetic table? Answer: The model selects the other object. For each attribute the two independently chosen signs agree in half the scenes, so half the answers still match by chance.
- Boundary. If a visual prefix position has an ignored loss label, can it still influence the answer? Answer: Yes. Loss masking removes that position’s direct prediction target, not its embedding or its attention connections to answer positions.
- Transfer. Can an arbitrarily strong decoder exceed .75 per-attribute accuracy from unordered mean-pooled objects in this task? Answer: No. Identical pooled observations hide which side holds each disagreeing attribute. The bound follows from lost information, not optimization. Retaining positions or changing the observation map changes the problem.
Compare what is frozen and what each loss can see
Read BLIP-2 §3.1–3.3 and LLaVA v1 §4.1–4.2, including the query masks and training-stage definitions. Compare the fixed OPT bridge, LLaVA projector and visual-label insertion. The selected BLIP-2 and LLaVA PDF pages 3 and 4 were viewed; the code is from later maintained commits. No language-model or visual-question-answering benchmark is reproduced here.
Make a prediction, then check
Does masking a visual token out of the loss remove its effect on answers?
Learning objectives
- Compare projection with a query bottleneck.
- Separate loss masks from attention masks.
- Track stage-specific frozen modules.
- Test whether answers use the right visual object.
Prerequisites & connections
Explore related knowledge →References
- BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models (ICML2023)
Junnan Li; Dongxu Li; Silvio Savarese; Steven Hoi · 2023 - Visual Instruction Tuning (v1)
Haotian Liu; Chunyuan Li; Qingyang Wu; Yong Jae Lee · 2023 - blip2-opt reference at 0ef3a2c
salesforce/LAVIS contributors · 2026 - llava-projector reference at c121f04
haotian-liu/LLaVA contributors · 2024 - llava-bridge reference at c121f04
haotian-liu/LLaVA contributors · 2024
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-20 · Single AI author checked BLIP2 sections3.1-3.3 and LLaVA v1 sections4.1-4.2 plus fixed bridge/masking code. Six paired equations and four explained exercises; original four-parameter bridge with frozen positional pooling and binary heads, all gradients, three attention masks, ignored targets and enumerated mean-pooling information bound. No LLM or Q-Former training.
- Single AI author checked BLIP2 sections3.1-3.3 and LLaVA v1 sections4.1-4.2 plus fixed bridge/masking code. Six paired equations and four explained exercises; original four-parameter bridge with frozen positional pooling and binary heads, all gradients, three attention masks, ignored targets and enumerated mean-pooling information bound. No LLM or Q-Former training.
- Four computed SVG variants per topic. Thirteen numeric/geometry tests and36 responsive cases passed; twelve final Chinese-mobile/English-desktop screenshots actually inspected. English spacing correction and initial test-mixin discovery error preserved. Full article acceptance recorded separately.
Source locations checked:
- BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models (ICML2023) · Read3.1-3.3 selected query architecture, three masks and frozen generative bridge; PDF page3 viewed. No full Q-Former or LLM training.
- Visual Instruction Tuning (v1) · Read v1 April17 section4.1-4.2, linear projection, answer-token objective and both training stages; PDF page4 viewed. Later MLP options distinguished.
- blip2-opt reference at 0ef3a2c · 56-96,105-162: freeze settings, queries, projection, visual-prefix/label masks. BSD3 heading/opening read only. Fixed public code, reference only; no copying/execution.
- llava-projector reference at c121f04 · Projector builder read: linear, MLP and identity options. Apache2 heading/opening only; later implementation, not v1 architecture. Fixed public code, reference only; no copying/execution.
- llava-bridge reference at c121f04 · 140-143,245-264: encoder/projector interface and ignored image labels. Apache2 heading/opening only. Fixed public code, reference only; no copying/execution.
Related topics