Where Images Meet Words: Multimodal Alignment and Fusion

From paired retrieval to visual question answering, inspect the information supplied by each modality.

1. Search for an image with a sentence

Typing “a black cat by a window” into a photo library should find suitable pictures even if their filenames contain none of those words. Meeting captions connect sound to visible speakers, while robots may combine cameras, touch, and language instructions. Each task connects modalities that record the world in different ways. Pixels, words, sound samples, and sensor readings do not begin with a shared coordinate system. Multimodal learning builds relationships useful for comparison, complementary evidence, or reasoning. Placing several kinds of files in one dataset does not by itself establish those relationships.

Image–text retrieval provides a clear starting point. An image encoder converts pixels into a vector, a text encoder converts words into another vector, and training brings matching pairs closer in a shared space. Text can then retrieve images, and images can retrieve descriptions. Closeness is learned for a purpose: two pictures may have different colors while both showing a person riding a bicycle. Two sentences may use different words to describe the same scene. The distinctions retained by the vectors depend on the training pairs and on what the evaluation considers relevant.

This chapter begins with paired data and contrastive objectives, then connects retrieval to fusion, visual question answering, and caption generation. The complete experiment trains small image and two-word text encoders on nine color–shape combinations, with every image generated by code. We remove color, change descriptions, and replace images with zeros to observe which capabilities remain. This makes cross-modal computation inspectable. Larger vision–language models are introduced by explaining their connecting modules, training signals, and generated outputs rather than treating a model name as a description of the entire system.

2. Pairs define what counts as the same thing

An image paired with a description provides supervision that is weaker than pixel-level annotation but richer than having no labels. A caption usually mentions only part of a scene. “A child playing football” does not identify clothing colors or locate the ball. Unmentioned objects should not automatically be interpreted as absent. Conversely, text near a web image may be commentary, background, or a quotation unrelated to visible content. Dataset construction should establish the unit of association, duplicates, and mismatch rates before deciding which pairs to treat as positives.

Audio and video also require synchronization. Video may contain dozens of frames per second, audio thousands of samples, and subtitles variable-length sentences. Matching equal array indices does not align these signals. Preserve timestamps and connect modalities through event windows, segments, or learned alignment. A half-second delay between speech and mouth movement can teach an incorrect relationship. Multiple physical sensors similarly need clocks, spatial calibration, and definitions of latency. Whether the measurements are correctly paired is a question to resolve before increasing network complexity.

Earlier sensor-fusion methods often used a shared physical coordinate system to combine measurements into a state estimate. Image captioning and cross-media retrieval pushed toward connections at the semantic level. CLIP's 2021 work combined large-scale image–text pairing, two encoders, and a batch contrastive objective, then represented categories through text for transfer without fitting a new classification head to each target dataset. The question shifted from assigning an image a fixed identifier to matching it with linguistic concepts. Retrieval and classification could consequently use the same learned representations.

Separate image and text encoders learn diagonal matches and compare new images with candidate descriptions.
Figure 1Official CLIP diagram: batch contrastive training on the left, and text-category encoding with new-image matching on the right. Unmodified. OpenAI / Alec Radford et al., 2021, CLIP repository, MIT; Copyright (c) 2021 OpenAI.

The left side of the original diagram shows training. Images and texts form a matrix of all pairwise similarities, with the observed pairs on its diagonal. The right side shows use: candidate categories are written as descriptions, encoded, and compared with a new image. Training and inference are connected but serve different roles. Candidate labels, prompt wording, and evaluation data remain task choices. If the correct category is absent, the system still selects the closest available candidate. A retrieval pipeline needs a decision that distinguishes relative similarity from actual relevance to the request.

3. A batch of pairs becomes a set of comparisons

The two encoders can initially produce vectors on different scales. Dividing each vector by its length gives unit vectors whose dot product is cosine similarity, focusing the comparison on direction. An image vector (3,4) becomes (0.6,0.8); a text vector (0,2) becomes (0,1), producing similarity 0.8. This describes directional agreement in the current representation, not a direct probability that the description is correct. Learning changes vector directions so that relevant images and descriptions become easier to retrieve among the available alternatives.

SymbolMeaning and units
Image i and text j; image input has channel×height×width shape and text is a sequence of token indices.
Image and text encoders with parameters theta and phi, both producing d-dimensional vectors.
Euclidean norm, the square root of the sum of squared components.
Normalized unit vectors of shape d with no physical units.
Cosine similarity and transpose notation; s is dimensionless between −1 and 1.

Normalization makes both lengths one, so the dot product depends only on their angle. Image vector (3,4) has norm five and text vector (0,2) has norm two; their normalized dot product is 0.8. A batch stores image and text embeddings as B×d matrices and produces a B×B similarity matrix. Implementations floor very small norms to avoid division by zero. The example checks the norms of its resulting embeddings.

In a batch of B image–text pairs, each image is compared with B texts and each text with B images. Dividing similarities by a temperature and applying softmax produces normalized scores within the current candidate set. Image-to-text cross entropy encourages the paired caption to receive more weight in its row. Text-to-image cross entropy applies the same idea to columns, and the two directions are averaged. A training batch therefore supplies both observed matches and comparisons with its other candidates, helping define how those matches should be distinguished.

SymbolMeaning and units
Pair count and image, text, and summed candidate indices; integers, with positive pairs on the diagonal.
Dimensionless cosine similarity of image i and text j.
Positive dimensionless temperature, fixed at 0.12 in the experiment.
Dimensionless scores normalized across text candidates in a row or image candidates in a column.
Mean negative-log loss over both retrieval directions; log is natural and loss is in nats.

The correct pair enters the logarithm, so its loss approaches zero as its normalized score approaches one. For B=2, similarities one on the diagonal and zero elsewhere, and temperature one, every correct score is e/(e+1), about 0.731. The symmetric loss is −ln(0.731), about 0.313. Division by 2B averages over both directions and all pairs. Stable implementations subtract the maximum logit before exponentiation; cross-entropy routines include equivalent numerical stabilization.

Temperature controls how sharply scores concentrate. A smaller temperature magnifies similarity differences, while a larger temperature produces a flatter distribution. Changing temperature does not change the ranking of fixed similarities, but it does change the loss and gradients. The candidate set also changes normalized scores. With scores 1,0,−1, the first softmax value is approximately 0.665. Removing the last candidate raises it to about 0.731 even though the first two scores remain unchanged. Report candidate count, temperature, and filtering rules when interpreting retrieval scores rather than treating them as context-free probabilities.

Other pairs in a batch are not always true negatives. Two images can both depict a black cat, and different captions can express the same meaning. Rewarding one match while penalizing all semantically equivalent matches creates conflicting supervision. Multiple-positive objectives, deduplication, or semantic sampling can address this. Each training batch in our experiment contains one image from each of nine classes and one unique color–shape description for each class. At test time, one description corresponds to twelve images; all twelve are then considered valid retrieval results rather than penalizing arbitrary alternative instances.

The text representation determines which distinctions a contrastive model can learn. Averaging word embeddings is sufficient for our fixed two-token color–shape descriptions because their roles are unambiguous. It discards word order, however: exchanging “dog chases cat” and “cat chases dog” would leave a simple bag of word vectors unchanged. A contextual text encoder can represent those roles, but the training data and objective must still reward distinguishing them. Similarly, a global image vector may emphasize the presence of a dog and a cat without retaining who is chasing whom. Hard negatives that change a relation while preserving familiar objects make that distinction part of the learning problem.

Direction, temperature, and the candidate set change scores

Move the image vector around a unit circle. Three text candidates point at 0°, 90°, and 180°. Dot products give cosine similarities; the right panel normalizes them with the chosen temperature. Removing C leaves the other similarities unchanged but changes their normalized scores. These two-dimensional vectors are a hand-checkable example.

4. Shared vectors support retrieval, but relevance needs a definition

A dual encoder allows the candidate library to be encoded in advance. A collection of one hundred thousand images can store one vector per image; a new text query only needs its own encoding followed by a neighbor search. Exact dot products are straightforward for smaller collections, while approximate nearest-neighbor indexes can reduce query time at scale. Approximation trades speed and memory against retrieval recall. Evaluate the semantic ranking of the encoder separately from the index's recovery of actual nearest neighbors, so that representation errors and search-engine errors can be distinguished.

SymbolMeaning and units
Positive query count and integer query index.
Positive number of highest-ranked candidates retained.
Set of identifiers of the first K candidates returned for query q.
Set of valid positives for query q, defined by the task.
Set intersection, empty set, and indicator; a query scores one when an intersection exists and zero otherwise.

This uses the common retrieval convention of whether each query retrieves at least one positive. If three of four queries have a valid item among their first five results, Recall@5 is 0.75. Each text query in the experiment has twelve matching test images, and any one counts as a hit. This convention differs from set recall, which divides the number of recovered positives by all positives; reporting the positive relation avoids ambiguity.

Recall@K requires a positive set for each query. Retrieving the original description of a particular photograph may have one correct record. Searching for “red circle” may have many valid images. Our text-to-image evaluation uses the second interpretation: twelve test images satisfy each description, and a query succeeds if at least one appears among its first K results. The text-to-image direction has nine queries, whereas the image-to-text direction has 108. Reporting both directions with their denominators makes the different query and library structures explicit.

Prompt wording is also part of the input. “Cat,” “a photograph of a cat,” and “a medical illustration of a cat” provide different contexts to a text encoder. Several predetermined templates can be combined, but template selection and validation belong before final testing. Zero-shot transfer generally means that the target task's labeled training set was not used to fit that classifier; it does not mean the model has never encountered related visual or linguistic concepts. Our small model trains on all nine combinations and evaluates new images of those combinations. It is therefore a paired-retrieval experiment rather than open-world zero-shot recognition.

Retrieval can also supply evidence to a generation system. A fast first stage finds candidate images, video segments, or document figures. A more expensive joint model can rerank each candidate against the question, after which a generator produces an answer grounded in the selected content. Dual encoders support precomputation; cross-encoders perform finer interaction for each query–candidate pair. Their computation occurs in different places. Record whether relevant material entered the candidate set, survived reranking, and influenced the answer. Fluent final wording alone does not locate a failure in that chain.

5. Fusion lets modalities exchange information during computation

Retrieval makes two representations comparable; fusion lets multiple modalities jointly determine an output. Early fusion concatenates aligned features before a shared model. Late fusion combines predictions from separate models. Intermediate fusion exchanges information between their internal representations. These approaches provide useful baselines, but concatenation requires control of dimensions and scales, while late combination can miss local image–text relationships. For “What color is the cup on the left?”, compressing a sentence and an entire image into single global vectors may discard the spatial detail needed to identify the relevant cup.

SymbolMeaning and units
Query matrix of shape n_q×d_k, from text in this example.
Key matrix of shape n_v×d_k, from image regions here.
Value matrix of shape n_v×d_v, describing the corresponding regions.
Positive query count, visual-position count, key dimension, and value dimension.
Row-normalized attention weights of shape n_q×n_v and aggregated output of shape n_q×d_v.
Scaling factor and transpose; neural representations and weights have no assigned physical units.

A query compares itself with each key, then reads values with the resulting weights. With logits ln3 and zero, two regions receive weights 0.75 and 0.25. Values (2,0) and (0,4) then yield output (1.5,1). Scaling controls the typical dot-product magnitude as key dimension increases. Multiple heads can read different relationships, but each follows these shapes. Cross-attention differs from self-attention in taking queries and key–value pairs from different sequences.

Cross-attention connects queries from one modality with keys and values from another. A text query can assign weights to image regions and read their weighted representations. A color question should access the target object's appearance; a counting question must retain multiple instances and their relationships. Attention weights are coefficients in an information-aggregation computation, not a complete explanation of a model's reasoning. Occluding highly weighted regions, replacing objects, or changing the question provides additional tests of whether the output responds to the proposed evidence.

A vision–language model often combines a visual encoder, a connecting module, and a language generator. BLIP-2 uses learned queries to extract language-relevant information from a frozen visual encoder and connect it with a frozen language model, learning representation and generation relationships in stages. Flamingo studies interfaces between pretrained visual and language models that accept interleaved images or video and text. Both address a recurring computational question: when capable models already exist for separate modalities, what interface lets them exchange useful information?

Freezing a backbone does not eliminate its computation. Visual encoding still processes pixels, and language generation still produces tokens. A small number of trainable parameters is different from low inference latency. Image resolution, visual token count, compression in the interface, and context length all affect retained detail and computation. To understand a VLM, trace the representations from pixels to language-compatible vectors, identify which parameters change, and specify the losses used to train them. That description explains the working system more clearly than a list of architecture names.

6. Captions, questions, and audiovisual events need different evidence

Image captioning generates text conditioned on an image, commonly learning to predict a reference description one token at a time. Visual question answering additionally receives a question and must provide the information it requests. A picture with two cups can reasonably be captioned “Cups are on the table,” yet that sentence does not answer “How many cups are there?” Multiple descriptions may be valid for one image. Word-overlap metrics can miss equivalent phrasing while rewarding a similar-sounding sentence with incorrect facts. Evaluation should also inspect objects, attributes, counts, and relationships against the visual evidence.

SymbolMeaning and units
Image and question text; captioning may omit the question.
Answer token at position t and the preceding answer prefix.
Answer length, including the defined end token, and integer token position.
Dimensionless token probability conditioned on image, question, and prefix.
Sequence negative natural-log likelihood, in nats; training may average over valid tokens.

The chain rule expresses a sequence probability as conditional next-token probabilities. If two required tokens receive probabilities 0.8 and 0.5, their sequence probability is 0.4 and negative log likelihood is about 0.916. Training often supplies the reference prefix, whereas generation uses previously generated tokens, producing different prefix distributions. The objective rewards the supervised answer; visual dependence is further assessed with occlusion, question-only baselines, and factual evaluation.

Visual preprocessing can be decisive for document questions. Resizing a whole page into a small square preserves its overall layout but may erase individual letters. Tiling it into patches retains detail at the cost of more visual tokens and a need to preserve patch positions. A useful response may need to identify a region, extract its text, and then interpret a number rather than treating the page as one scene. Grounded answers can return a box or page location with the text, allowing the proposed evidence to be checked. These output requirements should influence image resolution and annotation design before a generator is selected.

Some errors arise from an overly influential language prior. If “What color is the banana?” is usually answered “yellow” in training, a model may repeat that answer without inspecting the image. Controlled tests can change the object's color, occlude a crucial region, or introduce contradictory text. Change one factor at a time and compare the result with a question-only baseline. For chart reading, preserve units, axes, and uncertainty information. If image resolution has already removed small text, a language generator cannot recover a reliable reading from pixels that are no longer present.

Audiovisual understanding adds temporal relationships. A visible door movement may precede its sound, mouth motion should align with the corresponding speech segment, and event retrieval may need start and end times. Models can encode frames, short audio segments, and text separately, then connect them using temporal positions and cross-attention. Sparse frame sampling can miss short events, while averaging audio over an entire clip can erase their order. Video subtitles, event descriptions, sound-source localization, and affect estimation require different supervision granularities; a clip-level topic label is not a substitute for all of them.

7. Make color and shape meet in two learned spaces

The script generates nine combinations from red, green, and blue with circles, squares, and triangles. Each combination has 32 training images, eight validation images, and twelve test images. Independent seeds vary position, size, brightness, background, and pixel noise. Images are 28×28 pixels. A two-convolution image encoder produces 24-dimensional vectors. The text encoder averages learned embeddings for two words, one color and one shape, and applies a linear projection to the same dimension. Both sides are normalized, and the temperature is fixed at 0.12.

One held-out image per color–shape class, at the actual 28×28 resolution. Position, size, brightness, and noise vary with independent seeds.
Figure 2One held-out image per color–shape class, at the actual 28×28 resolution. Position, size, brightness, and noise vary with independent seeds.

Image–text contrastive learning and missing-information experiments

Train a small convolutional image encoder and two-word text encoder from scratch without large weights. Save bidirectional semantic retrieval, contradictory-color comparisons, ablations, figures, arrays, and summary.json.

"""Small paired image-text experiment with explicit candidate sets and ablations."""
import argparse,copy,json
from pathlib import Path
import numpy as np
import torch
from torch import nn
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib.path import Path as PolygonPath
from sklearn.decomposition import PCA

torch.set_num_threads(2)
COLORS=np.array([[.85,.2,.18],[.18,.65,.3],[.15,.35,.85]])
CAPTIONS=['red circle','red square','red triangle','green circle','green square','green triangle','blue circle','blue square','blue triangle']
TOKENS=torch.tensor([[c,s+3]for c in range(3)for s in range(3)])

def dataset(perclass,seed):
    rng=np.random.default_rng(seed);images=[];labels=[];yy,xx=np.mgrid[:28,:28]
    for c in range(9):
        color,shape=divmod(c,3)
        for _ in range(perclass):
            cx,cy=rng.uniform(12,16,2);rad=rng.uniform(6,9)
            if shape==0:mask=(xx-cx)**2+(yy-cy)**2<=rad**2
            elif shape==1:mask=(abs(xx-cx)<=rad)&(abs(yy-cy)<=rad)
            else:mask=PolygonPath([[cx,cy-rad],[cx-rad,cy+rad],[cx+rad,cy+rad]]).contains_points(np.c_[xx.ravel(),yy.ravel()]).reshape(28,28)
            im=np.ones((28,28,3))*rng.uniform(.03,.15);im[mask]=COLORS[color]*rng.uniform(.8,1.1);im=np.clip(im+rng.normal(0,.025,im.shape),0,1)
            images.append(im.transpose(2,0,1));labels.append(c)
    return torch.tensor(np.array(images),dtype=torch.float32),np.array(labels)

class PairModel(nn.Module):
    def __init__(self):
        super().__init__();self.image=nn.Sequential(nn.Conv2d(3,12,3,padding=1),nn.ReLU(),nn.MaxPool2d(2),nn.Conv2d(12,24,3,padding=1),nn.ReLU(),nn.AdaptiveAvgPool2d((4,4)),nn.Flatten(),nn.Linear(384,24))
        self.words=nn.Embedding(6,24);self.text=nn.Linear(24,24,bias=False)
    def encode_image(self,x):return nn.functional.normalize(self.image(x),dim=1)
    def encode_text(self,t):return nn.functional.normalize(self.text(self.words(t).mean(1)),dim=1)
    def forward(self,x,t):return self.encode_image(x)@self.encode_text(t).T/.12

def recall_at(similarity,querylabels,candidatelabels,k):
    top=np.argsort(-similarity,axis=1)[:,:k]
    return float(np.mean(np.any(candidatelabels[top]==querylabels[:,None],axis=1)))

def run(out,language):
    out.mkdir(parents=True,exist_ok=True);zh=language=='zh';text=lambda z,e:z if zh else e
    plt.rcParams.update({'font.family':'sans-serif','font.sans-serif':['Microsoft YaHei','DejaVu Sans'],'font.size':10,'axes.spines.top':False,'axes.spines.right':False,'svg.fonttype':'none','axes.unicode_minus':False})
    save=lambda fig,name:(fig.savefig(out/f'{name}-{language}.svg',bbox_inches='tight'),fig.savefig(out/f'{name}-{language}.png',dpi=140,bbox_inches='tight'),plt.close(fig))
    torch.manual_seed(19);train,ytrain=dataset(32,19);valid,yvalid=dataset(8,119);test,ytest=dataset(12,219)
    model=PairModel();optimizer=torch.optim.Adam(model.parameters(),lr=.002);trace=[];best=float('inf');selected=0
    for step in range(1,301):
        model.train();idx=torch.arange(9)*32+torch.randint(32,(9,));optimizer.zero_grad();logits=model(train[idx],TOKENS);target=torch.arange(9)
        loss=(nn.functional.cross_entropy(logits,target)+nn.functional.cross_entropy(logits.T,target))/2;loss.backward();optimizer.step()
        if step%5==0:
            model.eval()
            with torch.no_grad():vl=nn.functional.cross_entropy(model(valid,TOKENS),torch.tensor(yvalid)).item()
            trace.append([step,loss.item(),vl])
            if vl<best:best=vl;weights=copy.deepcopy(model.state_dict());selected=step
    model.load_state_dict(weights);model.eval()
    torch.save(model.state_dict(),out/'paired-model.pt')
    (out/'model.json').write_text(json.dumps({'class':'PairModel','image_shape':[3,28,28],'embedding_dimensions':24,'vocabulary':['red','green','blue','circle','square','triangle'],'tokens':TOKENS.tolist(),'captions':CAPTIONS,'temperature':.12,'selected_step':selected},indent=2),encoding='utf-8')
    reloaded=PairModel();reloaded.load_state_dict(torch.load(out/'paired-model.pt',weights_only=True));reloaded.eval()
    with torch.no_grad():reload_error=float((model(test,TOKENS)-reloaded(test,TOKENS)).abs().max())
    with torch.no_grad():
        iz=model.encode_image(test).numpy();tz=model.encode_text(TOKENS).numpy();sim=iz@tz.T
        gray=test.mean(1,keepdim=True).repeat(1,3,1,1);gray_sim=(model.encode_image(gray)@model.encode_text(TOKENS).T).numpy()
        missing_sim=(model.encode_image(torch.zeros_like(test))@model.encode_text(TOKENS).T).numpy()
        shapeonly=model.encode_text(TOKENS[:3,1:]).numpy();shape_sim=(iz@shapeonly.T)[:,np.arange(9)%3]
    pred=sim.argmax(1);i2t=recall_at(sim,ytest,np.arange(9),1);t2i=recall_at(sim.T,np.arange(9),ytest,1)
    gray_pred=gray_sim.argmax(1);shape_pred=shape_sim.argmax(1)
    mean_sim=np.array([sim[ytest==k].mean(0)for k in range(9)])
    image_means=np.array([iz[ytest==k].mean(0)for k in range(9)]);pca=PCA(2);project=pca.fit_transform(np.r_[image_means,tz]);scores=(sim/.12);probs=np.exp(scores-scores.max(1,keepdims=True));probs/=probs.sum(1,keepdims=True)
    # Removing a candidate changes normalized scores but not remaining cosine similarities.
    hand=np.array([1,0,-1]);soft=np.exp(hand);soft/=soft.sum();soft_subset=np.exp(hand[:2]);soft_subset/=soft_subset.sum()
    summary={'train_images':len(train),'validation_images':len(valid),'test_images':len(test),'candidate_captions':9,'selected_step':selected,'i2t_recall1':i2t,'t2i_recall1':t2i,'i2t_recall3':recall_at(sim,ytest,np.arange(9),3),'gray_exact_accuracy':float(np.mean(gray_pred==ytest)),'gray_shape_accuracy':float(np.mean(gray_pred%3==ytest%3)),'missing_image_accuracy':float(np.mean(missing_sim.argmax(1)==ytest)),'shape_only_exact_accuracy':float(np.mean(shape_pred==ytest)),'shape_only_shape_accuracy':float(np.mean(shape_pred%3==ytest%3)),'image_norm_error':float(abs(np.linalg.norm(iz,axis=1)-1).max()),'text_norm_error':float(abs(np.linalg.norm(tz,axis=1)-1).max()),'paired_mean_cosine':float(np.mean(sim[np.arange(len(test)),ytest])),'pca_explained_variance_ratio':pca.explained_variance_ratio_.tolist(),'hand_probabilities':soft.tolist(),'hand_subset_probabilities':soft_subset.tolist(),'semantic_positives_per_text_query':12,'embedding_dimensions':24}
    summary['contradictory_color_mean_cosine']=float(np.mean(sim[np.arange(len(test)),(ytest+3)%9]))
    summary['reload_logits_error']=reload_error
    (out/'summary.json').write_text(json.dumps(summary,indent=2),encoding='utf-8');np.savez_compressed(out/'data.npz',test_images=test.numpy(),test_labels=ytest,image_embeddings=iz,text_embeddings=tz,similarity=sim,gray_similarity=gray_sim,shape_only_similarity=shape_sim,zero_image_similarity=missing_sim,trace=trace,pca=project)
    assert summary['image_norm_error']<1e-6;assert summary['text_norm_error']<1e-6
    labels=[z for z in CAPTIONS];zhlabels=[c+s for c in ['红色','绿色','蓝色']for s in ['圆形','方形','三角形']];names=zhlabels if zh else labels
    fig,axs=plt.subplots(3,3,figsize=(8,8),layout='constrained')
    for k,ax in enumerate(axs.flat):ax.imshow(test[k*12].permute(1,2,0));ax.set_title(names[k]);ax.set(xticks=[],yticks=[])
    save(fig,'pairs')
    fig,axs=plt.subplots(1,2,figsize=(12,4.8),gridspec_kw={'width_ratios':[1.4,1]},layout='constrained')
    im=axs[0].imshow(mean_sim,cmap='RdBu_r',vmin=-1,vmax=1);axs[0].set(xticks=range(9),yticks=range(9),xticklabels=names,yticklabels=names,xlabel=text('文字候选','Text candidate'),ylabel=text('真实图像类别','True image class'));axs[0].tick_params(axis='x',labelrotation=60);fig.colorbar(im,ax=axs[0],label=text('余弦相似度','Cosine similarity'))
    tr=np.array(trace);axs[1].plot(tr[:,0],tr[:,1],label=text('训练:双向','Train: symmetric'),color='#176b91');axs[1].plot(tr[:,0],tr[:,2],label=text('验证:图检索文','Validation: image to text'),color='#bd554c');axs[1].set(xlabel=text('优化步数','Optimization step'),ylabel=text('交叉熵','Cross entropy'));axs[1].legend();save(fig,'alignment')
    fig,axs=plt.subplots(1,2,figsize=(12,4.5),gridspec_kw={'width_ratios':[1,1.15]},layout='constrained');marks=['o','s','^']
    for k in range(9):
        color=COLORS[k//3];v,w=project[k],project[9+k];axs[0].plot([v[0],w[0]],[v[1],w[1]],color=color,alpha=.5);axs[0].scatter(*v,c=[color],marker=marks[k%3],s=70);axs[0].scatter(*w,facecolors='none',edgecolors=[color],marker=marks[k%3],s=110)
    axs[0].set(xlabel=text('主成分 1','Principal component 1'),ylabel=text('主成分 2','Principal component 2'),title=text('实心:图像均值;空心:文本','Filled: mean image; open: text'))
    lab=[text('完整图文','Full pair'),text('灰度图像','Grayscale'),text('仅形状文字','Shape-only text'),text('全零图像','Zero image')];exact=[i2t,summary['gray_exact_accuracy'],summary['shape_only_exact_accuracy'],summary['missing_image_accuracy']];shape=[float(np.mean(pred%3==ytest%3)),summary['gray_shape_accuracy'],summary['shape_only_shape_accuracy'],float(np.mean(missing_sim.argmax(1)%3==ytest%3))]
    yy=np.arange(4);axs[1].barh(yy-.17,exact,height=.3,color='#176b91',label=text('颜色+形状均正确','Color and shape correct'));axs[1].barh(yy+.17,shape,height=.3,color='#bc8440',label=text('形状正确','Shape correct'));axs[1].set(yticks=yy,yticklabels=lab,xlim=(0,1.05),xlabel=text('正确率','Accuracy'));axs[1].invert_yaxis();axs[1].legend(loc='lower right',fontsize=9);save(fig,'ablation')
    print(json.dumps(summary,indent=2))

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('--output',type=Path,default=Path('output'));p.add_argument('--language',choices=['zh','en'],default='en');args=p.parse_args();run(args.output,args.language)

The program also saves paired-model.pt and model.json with selected weights, vocabulary, architecture settings, and temperature. A fresh PairModel loaded from the file reproduces logits exactly on the same image–text inputs. The data archive includes complete shape-only-text and zero-image score matrices for per-example inspection.

Each optimization step samples one image from every class and uses symmetric cross entropy. Training lasts 300 steps, with checkpoint selection based on validation image-to-text cross entropy. In the seeded run, Recall@1 is 1.0 for 108 image queries and 1.0 for nine text queries. The mean cosine similarity of matching descriptions is 0.9591. Replacing only the color word while keeping shape unchanged reduces the mean to 0.2416. This second comparison specifically checks whether color participates in matching instead of relying on a high overall classification score.

Left: mean cosine similarities grouped by true class across 108 test images. Right: symmetric training cross entropy and image-to-text validation cross entropy, distinguished in the legend.
Figure 3Left: mean cosine similarities grouped by true class across 108 test images. Right: symmetric training cross entropy and image-to-text validation cross entropy, distinguished in the legend.

Converting images to grayscale leaves shape accuracy at 1.0 while joint color-and-shape accuracy falls to one third. Keeping only shape words produces the same pattern. The code copies each shape score across its three color candidates and breaks exact ties by candidate order. Replacing every image with zeros gives joint accuracy one ninth. The model does not recover missing information from nowhere, but surviving shape information can still support a prediction. The two-dimensional visualization retains the first two principal components, explaining about 52.8% of variation. Retrieval itself uses all 24 dimensions, not the plotted projection.

Left: joint PCA of image-class means and text vectors; two components explain about 52.8% of variance, with filled/open markers identifying modalities. Right: measured fixed-model accuracies after removing image color, removing color words, or zeroing images.
Figure 4Left: joint PCA of image-class means and text vectors; two components explain about 52.8% of variance, with filled/open markers identifying modalities. Right: measured fixed-model accuracies after removing image color, removing color words, or zeroing images.

The paired experiment also separates training alignment from test-time use. Every training batch has nine unique captions and nine sampled images, so its symmetric objective uses a square matrix. Evaluation compares 108 images with nine captions, producing a rectangular matrix. Its rows answer image-to-text queries, while its columns answer text-to-image queries. Reusing a diagonal-only loss or a one-to-one correctness rule on that rectangular test matrix would misrepresent the twelve valid images per caption. The code therefore carries class labels alongside embeddings and evaluates the semantic positive relation explicitly. Matrix shape is a useful check on whether a proposed metric matches the retrieval task.

These ablations use the fixed trained model rather than retraining separately for every missing-input condition. They measure its present response to input changes, not the best performance achievable after dedicated adaptation. Applications with frequent missing modalities can train with modality dropout, explicit missingness indicators, or availability-based gating, then evaluate the same missingness patterns. Grayscale, blur, occlusion, and complete absence should be tested separately because they retain different information. Calling every degraded input “noise” conceals the specific stage that needs improvement.

8. Test the contribution of each modality and contradictory evidence

Input ablation and retraining answer different causal questions. Removing text from a trained multimodal model asks how that particular model reacts without text. Training an equally resourced image-only model asks how well the task can be solved using images alone. Both comparisons are useful, but their scores should not share an ambiguous label such as “without text.” A more complete study crosses available modalities with training conditions, holds evaluation examples fixed, and reports the parameter or compute differences. This helps distinguish a useful complementary signal from a benefit caused mainly by extra capacity or a different training budget.

A system can accept several modalities while relying mainly on one. Text-only and image-only inputs, shuffled pairs, replacement of irrelevant regions, and removal of critical regions form useful baselines. If shuffling pairs barely changes performance, inspect whether one modality already predicts the labels or whether information leaks between splits. Tasks that truly require complementary evidence can also include examples where neither modality alone determines the answer but the pair does. The gain from fusion then corresponds to the structure of the task rather than merely to increased model size.

Bias analysis benefits from similarly concrete factors. Paired data may repeatedly associate occupations with appearances or objects with particular backgrounds. A model can exploit those correlations without learning the intended attribute. Group errors by scene, language, attribute combination, or recording condition, then alter the background while preserving the object. Split and deduplicate by original image or video so that alternative crops, captions, or compressed copies do not cross the training–test boundary. Compositional generalization additionally requires holding out attribute combinations; new images of combinations seen during training do not establish that capability.

Finally, retain evidence appropriate to the output. Retrieval records should preserve queries, candidate libraries, and rankings. Question answering needs questions, images, and answer-level judgments. Captioning should check semantic coverage and factual consistency. Audiovisual localization needs timing tolerances and synchronization definitions. Latency, memory, and behavior under missing inputs connect predictive quality to practical use. Shared spaces determine how modalities can be compared; fusion determines how they exchange information; task evaluation tests whether that information actually contributes to the answer.

Download complete code and data

Extract and follow the README; the code matches this chapter.

References and further reading

  1. CLIP official repository and original diagram
    Authors’ image/text encoding and zero-shot examples; original diagram reused under MIT.
    MIT; Copyright (c) 2021 OpenAI; https://raw.githubusercontent.com/openai/CLIP/main/LICENSE
  2. Learning Transferable Visual Models From Natural Language Supervision
    Original contrastive objective and transfer evaluation.
  3. BLIP-2
    Frozen visual/language models and query-based bridging.
  4. Flamingo
    Interleaved images, text, video, and few-shot vision–language tasks.

Buy me a coffee

WeChat support QR code
WeChat
Alipay support QR code
Alipay