AI Research Library

Contrastive and Multimodal Representation Learning

Paired views do not teach a model what the world is; they teach which changes should count as the same.

Rajesh Ranjan Mahapatra

Why positive pairs define a model's invariances, why negatives define its distinctions, and how to audit what a contrastive representation preserves or erases.

© 2026 Rajesh Ranjan Mahapatra. 28 min read

Contrastive and Multimodal Representation Learning

Paired views do not teach a model what the world is; they teach which changes should count as the same.

TLDR

  1. A contrastive model learns an equivalence relation chosen by its pairs. Positive views are pulled together; everything that varies between them is pressured to matter less.
  2. Multimodal alignment learns mainly from information shared across modalities. Captions, reports and audio descriptions act as selective labels, preserving mentioned concepts while neglecting unspoken detail.
  3. Negatives decide which distinctions remain visible. Random negatives support coarse retrieval; false negatives can tear semantic neighbours apart, while well-designed hard negatives can force attributes, relations and order into the representation.
  4. Feature loss is not inevitable or caused by the loss alone. Capacity, architecture, optimisation and auxiliary objectives can preserve view-private information, so matched controls are required before blaming contrastive training.
  5. The design decision moves upstream. Audit the pair generator, augmentation policy and evaluation probes as an invariance contract before choosing batch size, temperature or model scale.

The traffic light that became colourless

Imagine training a street-scene encoder from pairs of photographs and captions. Every photograph of a traffic light is paired with text such as “traffic light at a junction”. To make training robust, each photograph is also subjected to heavy colour jitter. The model sees the same lamp under warmer, colder and partially desaturated renderings, and every one of those views is declared a positive match.

For an object-retrieval system, this is useful. The representation should recognise the same physical category under shade, camera variation and weather. Now reuse the encoder in a driving controller that must distinguish a red signal from a green one. The very transformation that protected object identity has made the control state unreliable. The model did not mysteriously forget colour. Its training procedure repeatedly supplied evidence that colour changes should not alter identity, while the captions supplied no countervailing reason to preserve the signal state.

One pair policy, two incompatible decisions Red and green traffic-light views merge for object recognition but must remain separate for traffic control. Positive views Object decision Control decision red view green view traffic light merge is useful STOP GO merge is unsafe
Figure 1. An invariance is useful only relative to a decision.Illustrative thought experiment. Colour variation should collapse for category retrieval but remain separable for signal control. No empirical measurements are shown.

Change one causal feature at a time. Keep the photographs, architecture and optimiser fixed, but replace the captions with “red traffic light” and “green traffic light”. Colour now helps solve the pairing task. Or keep the original captions and change only the downstream decision from signal control to object retrieval. The representation can now appear excellent without changing at all. The success or failure belongs to the relation between the pair policy and the later decision, not to an abstract quantity called representation quality.

This is the central answer of contrastive learning. A positive pair says, “treat these observations as the same for the purpose of this objective”. A negative comparison says, “retain enough difference to choose one over the other”. In multimodal learning, the overlap between image, text, sound or structured data determines what can support alignment. Details available to only one view receive weak or absent cross-modal supervision. The resulting representation is powerful precisely because it discards variation, but the discarded variation may be the next task's evidence.

Part IThe pair is the task

A supervised classifier receives an explicit target such as “cat”, “pneumonia” or “late payment”. Contrastive learning often looks less prescriptive because it can work without class labels. Yet it still receives a target. The target is encoded in the pairing rule. Two crops from one photograph, two adjacent segments of speech, an image and its caption, or a document and its translation are declared related. Other items in the comparison set are treated as alternatives.

That declaration is a small programme of invariance. A crop pair says that some translation, occlusion and scale change should preserve what matters. An audio-transcript pair says that voice, microphone response and background noise should not block access to the linguistic content. An image-caption pair says that the visual scene should be recoverable through the concepts selected by the caption. None of these statements is universal. A speaker-identification task needs voice; an acoustic-fault detector may need background vibration; an image-forensics task may need the exact crop boundary.

Published evidence SimCLR found that the composition of data augmentations materially changed what its visual representations learned, rather than serving as harmless preprocessing. Later work framed view construction as an information-selection problem: useful views should remove nuisance dependence while retaining task-relevant information.[2][4]

A graph before a geometry

It helps to picture the training data as a graph before picturing an embedding space. Each observation is a node. A positive edge joins two views that should agree. A batch supplies competing nodes that should not win the same match. Training then constructs a geometry that makes those graph relations easy to recover.

Cross-modal alignment constellation Image circles and text diamonds form paired constellations around shared concepts, while image-only details extend along faint private directions. bicycle dog kettle ○ image embedding ◇ text embedding image-only colour or texture paired bonds organise shared concepts
Figure 2. Cross-modal alignment constellation.Conceptual figure. Circles are image embeddings, diamonds are text embeddings, and connecting lines denote paired observations. Shared concepts form neighbourhoods; view-private detail can occupy a weaker direction or disappear from the consumed representation. Geometry is illustrative, not measured.

Suppose repeated positive edges connect an object across camera angles, crops and captions. In an idealised limit, those edges generate an equivalence relation: observations connected by the permitted transformations belong to one class. The learned map compresses each class into a neighbourhood while keeping rival classes distinguishable. Mathematicians would call the resulting object a quotient of the original observation space. The useful intuition is that the representation operates on “world observations modulo the changes declared irrelevant”.

The analogy has limits. Real positive relations can be noisy and non-transitive. A model rarely maps every positive view to exactly one point. Finite capacity, optimisation, projection heads and auxiliary losses can leave view-specific detail intact. Still, the quotient picture exposes the causal burden: every edge added to the positive graph is a vote for invariance, and every missing distinction must be recovered from some other signal.

From a pair graph to quotient neighbourhoods Raw observations connected by positive edges pass through a narrow mapping and form three compact latent islands. Observation graph Latent neighbourhoods pair-conditioned map class A class B class C positive edges propose what may collapse negatives keep neighbourhoods apart
Figure 3. From pair graph to quotient neighbourhoods.Conceptual model. Positive edges suggest equivalence classes; the learned map contracts each class and separates competing classes. Exact transitive collapse is an analogy, not a property guaranteed by neural optimisation.

Part IIWhat the loss actually asks

Consider a batch of N paired observations. An image encoder maps item xi to a normalised vector zi. A text encoder maps its paired caption yi to a normalised vector wi. Their dot product is cosine similarity. A common symmetric contrastive objective is:

The first term asks each image to identify its paired text among the batch. The second asks each text to identify its paired image. The temperature τ controls how sharply similarity differences affect the probabilities. A smaller temperature concentrates pressure on the nearest competitors. A larger one spreads credit and blame across more of the batch. Changing τ changes optimisation geometry, but it does not tell the system whether colour, count or causal order deserves preservation.

The gradient has two visible jobs. It pulls the positive score zi·wi upward and pushes competing scores downward in proportion to their current softmax probabilities. Wang and Isola described related asymptotic properties as alignment of positive pairs and uniformity of the representation distribution on the hypersphere.[3] This language is useful because collapse avoidance and pair agreement are separate pressures. A representation that maps every input to one point has perfect agreement but cannot identify a partner.

InfoNCE pressure field A fixed image embedding is attracted to its positive text and repelled from several negative texts, with sharper or broader temperature contours. zᵢ paired wᵢ competing texts Temperature low τ nearest rivals dominate higher τ pressure is more diffuse
Figure 4. The contrastive pressure field.Conceptual mechanism. A query embedding is attracted to its paired target and repelled from alternatives. Temperature changes the concentration of that pressure; it does not repair a semantically wrong pair or negative.

Contrastive predictive coding introduced a probabilistic contrastive objective for extracting information useful to predict future observations.[1] InfoNCE is therefore often discussed as a mutual-information estimator or lower bound. That connection is informative, but it should not become a metaphysics of representation. Variational mutual-information bounds can develop severe bias or variance in high-dimensional settings, and a high estimate does not identify which semantic factor has been preserved.[5] Mutual information is a lens on dependence, not a list of the distinctions a decision will require.

The operational interpretation is simpler. The loss rewards any feature combination that reliably identifies partners. If object category alone separates most items, category may dominate. If every batch contains many instances of the same category but different attributes, the system must use finer distinctions. If captions repeatedly omit a factor, the cross-modal loss offers little reason for the text interface to expose it. The loss optimises discriminability under the sampled comparisons, not semantic completeness.

The argument in one passChart · flow
flowchart TD
  A["The traffic light that became<br/>colourless"] --> B["Part I The pair is the task"]
  B --> C["Part II What the loss actually<br/>asks"]
  C --> D["Part III The shared signal is<br/>a bargain"]
  D -. "re-test" .-> A
  classDef first fill:#0a1424,stroke:#5B5CF6,stroke-width:2px,color:#e6f3ff
  classDef step fill:#0a1424,stroke:#3f7da0,stroke-width:1px,color:#e6f3ff
  class A first
  class B,C,D step
A structural route through Contrastive and Multimodal Representation Learning, from The traffic light that became colourless to Sources. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Part IIIThe shared signal is a bargain

Multimodal contrastive learning adds a productive asymmetry. An image can contain colour, texture, count, spatial layout, camera artefacts and objects. A caption may name only the objects and one relation. The caption contains syntax, emphasis and cultural knowledge that pixels do not directly carry. The pair overlaps on a latent set of shared causes, but each view also contains private information.

Let S denote information available in both views, Ux information private to the image, and Uy information private to the text. Cross-modal matching can be solved most reliably through S. This makes language a remarkably scalable source of supervision: words gather visually diverse instances around named concepts. CLIP demonstrated broad zero-shot transfer after training a dual encoder on hundreds of millions of image-text pairs, while ALIGN showed similar scaling with over a billion noisier alt-text pairs.[6][7]

Yet S is not “everything true about the scene”. It is the information that is both present and useful under the pairing distribution. A caption “three red cups beside a plate” can supervise count, colour and relation. A caption “kitchenware” cannot. Even a richly worded caption may be ambiguous about which phrase refers to which region. Language supervision is selective labelling at scale, not lossless translation from the world.

The caption bottleneck Several image factors approach a narrow language lens; object and relation pass through strongly, while texture, exact count, and colour may be attenuated when omitted. Visual factors Caption lens Shared space object relation count colour texture layout what the text chooses to say objects relations sometimes count omission attenuates supervision; it does not prove total deletion
Figure 5. The caption bottleneck.Conceptual lens. Factors named consistently can organise the shared space. Omitted or ambiguous factors receive weaker cross-modal support. Dashed paths indicate conditional, not impossible, preservation.

Four meanings of “the feature is gone”

Teams often say that a representation has “lost” a feature when four different observations are being mixed together. First, the source may never have measured the factor. A caption cannot recover an exact temperature that neither pixels nor text contain. Second, the backbone may encode the factor while the projection removes it from the shared interface. Third, the projected vector may retain a weakly decodable trace that the downstream head does not use. Fourth, the factor may remain available within one modality but lack a cross-modal direction, so a text query cannot address it.

These cases imply different remedies. Missing measurement requires another sensor or source. Projection-level suppression may require a wider or multi-headed interface. A readout failure requires task supervision, calibration or a different decision head. Missing cross-modal addressability requires paired examples, grounded attributes or a tool that retrieves the original evidence. Re-training the whole model is wasteful when the required fact already exists upstream and dangerous when the fact never existed anywhere.

A useful diagnostic records four states for each factor. Is it present in the input? Is it decodable at the backbone? Is it exposed by the shared embedding? Does an intervention on the factor change the deployed decision? The states need not move together. Colour can be highly decodable in an image backbone, weakly exposed after projection and irrelevant to an object-retrieval head. Relation direction can appear in token-level features yet vanish after pooling. Source identity may be deliberately absent from semantic similarity but remain mandatory in a separate evidence receipt.

This is why a single linear probe is insufficient. A successful probe shows that some decoder can recover a statistical signal from a chosen layer; it does not show that the operational head uses the signal. A failed probe may reflect probe capacity, data scarcity or a nonlinear encoding rather than true absence. Pair probes with controlled interventions and inspect the exact interface consumed by the application. “Preserved” should mean available to the required decision under a specified access path, not merely visible somewhere inside the network.

For systems that need both broad alignment and specialised detail, one vector need not carry both burdens. A practical representation can contain a shared component for cross-modal discovery, a modality-private component for within-modal work, and typed metadata for provenance, time and measured values. Auxiliary reconstruction, within-modal contrast or supervised heads can support private factors, but each extra objective changes the contract and needs its own controls. The design goal is not maximal retention. It is deliberate retention with a known retrieval path.

A minimal worked example

Create synthetic images with four shapes and four colours. Pair each image with text that names the shape but never the colour. The cross-modal task can be solved by aligning “triangle” with every triangular image. Colour varies freely within those positive groups and contributes nothing to text matching. A zero-shot colour prompt such as “blue” has no reliable cross-modal bridge, even though colour is plainly present in the image vector.

Now mention colour in one caption out of ten. That small intervention changes the learning signal. The system receives some examples in which “blue” must align with blue images across shapes. Colour need not dominate every match, but it acquires a cross-modal direction. Mention it in every caption and the direction strengthens further. Shuffle the image-text pairs and both shape and colour alignment should approach chance. This is the executable experiment later in the article.

A production-shaped case: the inspection record

Worked scenario The following inspection case is synthetic. It is designed to expose the mechanism and is not a report of a deployment, customer system or measured operational result.

A maintenance team wants one representation for thermal images, vibration traces and technician notes. Most notes say things such as “bearing fault suspected” or “pump running hot”. Pairing these records can create an excellent retrieval system for defect families. A search for “bearing fault” finds images and traces associated with that language even when the sensor signatures vary.

The later decision is more demanding: choose whether to stop the pump now, schedule maintenance, or continue monitoring. That decision depends on exact temperature, rate of increase, sensor position, load, confidence in the instrument and whether the anomaly is motor-side or shaft-side. Technicians often omit those details because the structured system already stores them or because the note is written after inspection. If the shared embedding becomes the only evidence interface, a successful defect-family match can conceal the absence of decision-critical detail.

A multimodal inspection record can align on a coarse defect while losing action evidence Thermal contours, vibration waveform, and a technician note converge on bearing fault, but exact location, severity, and trend remain separate evidence needed for the action. Three views Shared match Action evidence thermal image vibration trace Technician note “Bearing fault suspected; pump running hot.” bearing fault family exact locationand severity temperaturetrend and load sensor qualityand time retrieval success does not certify action sufficiency
Figure 6. Coarse alignment can hide missing action evidence.Synthetic production-shaped scenario. Three modalities support the defect family, while location, severity, trend and sensor quality must remain available through typed evidence rather than being inferred from proximity alone.

The safe architecture is not to demand that one vector contain every fact. Keep the shared embedding for discovery and candidate retrieval. Preserve calibrated measurements, provenance, timestamps and structured attributes outside it. Compile those sources into the decision context when an action is proposed. This separates the useful invariance of defect-family retrieval from the distinctions required by the maintenance decision.

Shared space does not require one geometric cloud

Image and text embeddings can remain separable by modality even when paired retrieval works. Research on the modality gap found that independently encoded modalities may occupy different regions of the nominally shared space, influenced by initialisation and contrastive optimisation.[17] That finding should not be converted into a rule that zero gap is always desirable. A geometry may preserve modality-specific uncertainty or support the trained matching function without pointwise identity. The relevant test is whether the geometry supports the required comparisons without systematic bias, not whether image and text distributions look visually merged.

There is also a strong negative control against simplistic erasure claims. Locked-image text tuning freezes a pretrained image encoder and learns a text interface to read from its representation.[8] The cross-modal objective cannot overwrite the frozen visual features. Likewise, a trainable projection head may absorb much of the invariance while an earlier backbone layer retains private detail. Pairing creates selection pressure; architecture and capacity determine where that pressure is expressed.

Part IVNegatives carve the boundary

Positive pairs say what may remain close. Negatives say what must be distinguishable in the current comparison. This second half of the objective is easy to underestimate because “all other items in the batch” sounds neutral. It is not neutral. A batch is a sampled boundary around every example.

If an image of a dog chasing a person is contrasted mostly with captions about buses, kitchens and oceans, the words “dog”, “person” and “chasing” are enough. A bag-of-words representation can win. Replace one easy negative with “a person chasing a dog”. The nouns no longer identify the positive. Word order and relation direction become decision-relevant. Nothing about the architecture changed. The sampled alternative changed what the model had to know.

Negative sampling creates different decision boundaries Three landscapes show an easy negative that permits coarse separation, a false negative that tears one semantic cluster, and a compositional hard negative that requires relation direction. Easy negative False negative Compositional hard negative coarse noun boundary wins a semantic neighbour is repelled dog →person person →dog relation direction must separate cheap, but may reward shortcuts hardness without truth is damage useful only when the contrast is valid
Figure 7. Negatives carve three different boundaries.Illustrative comparison. Easy negatives permit coarse shortcuts; false negatives repel genuine neighbours; valid compositional negatives force a finer distinction. “Hard” describes model confusion, not semantic correctness.

Benchmarks have exposed this gap. ARO was designed around attributes, relations and word order, showing that strong vision-language systems could perform poorly when success required composition rather than unordered concept overlap.[15] Winoground used two images and two captions containing the same words in different orders, so a correct match required relational understanding.[16] Such tests do not prove that one benchmark fully isolates composition, but they demonstrate why ordinary retrieval accuracy can reward a weaker solution.

The reverse problem is a false negative. Two different photographs may both depict the same disease pattern, product type or intent. Instance-level contrastive training treats them as competitors merely because they are not the designated pair. Debiased contrastive learning analysed this mismatch and proposed correcting for negatives that may share the latent class.[10] In specialised domains, false negatives are especially common because many cases legitimately share semantics while only one report is paired to one record.

Hard-negative mining therefore needs a truth test. Select examples that are close under the current model but genuinely different under the required decision. A colour-swapped caption is useful when colour must be retained. It is harmful when the image is monochrome or the colour word is metaphorical. A relation-swapped sentence is useful when the scene visually establishes the relation. It is noise when the image is ambiguous. Hardness is an optimisation property; validity is an evidence property.

Batch size and temperature affect how many competitors matter, but they do not solve semantic sampling. SigLIP replaced the globally normalised softmax with pairwise sigmoid losses and showed that strong image-text learning need not depend on the same giant-batch regime.[9] This is an important systems alternative. It still requires a defensible account of which pairs are positive and which are negative.

The strongest objection: pressure is not destiny

The argument so far can be overstated as “anything absent from a caption is erased”. That statement is false. A high-capacity image encoder can preserve colour while using shape for cross-modal alignment. A projection head can expose an invariant interface while the backbone retains detail. Pretraining may already encode a feature, and a later objective may not remove it. Training dynamics and inductive bias decide which of many loss-minimising solutions is reached.

Research supports this caution. Shortcut analyses found that contrastive objectives can suppress predictive features while favouring alternatives that separate sampled pairs.[11] Other work documented subclass collapse and suppression of harder class-relevant features, with embedding dimension and augmentation quality affecting the result.[12] Yet theoretical analysis also showed that augmentations and loss alone are insufficient to explain generalisation without the function class and training algorithm.[13] Feature Dropout further complicates a simple preservation rule: in multi-task foundation-model settings, augmentations that destroy one label can sometimes prevent that feature from dominating and improve transfer to other tasks.[14]

Failure boundary The pair-policy explanation ceases to be sufficient when view-private information is preserved elsewhere, when the consumed layer differs from the probed layer, when auxiliary losses dominate, or when optimisation selects a richer solution than the pairing task requires. A low linear-probe score alone does not prove causal erasure.

A serious negative control

Train two systems on identical paired data. In the first, fine-tune the complete image encoder with the contrastive loss. In the second, freeze the same pretrained image encoder and train only the text encoder and projection. Evaluate colour, count and relation at three locations: the image backbone, the projected embedding and the actual downstream interface. Also include a non-contrastive reconstruction or supervised head using the same backbone capacity and data where appropriate.

If colour disappears from the projected embedding but remains decodable in the frozen backbone, the correct claim is interface-level suppression, not destruction of visual knowledge. If colour disappears only in the fully fine-tuned system, contrastive updates become a plausible cause. If both systems retain colour yet the downstream application ignores it, the failure belongs to readout or task design. If every matched control loses colour, the dataset or architecture may be the common cause.

Decodability is still not causal use. A probe may extract information that the deployed head never consults. Add interventions: alter colour while preserving shape, trace the resulting embedding and decision change, and compare it with a colour-preserving control. The aim is not to locate an essence called “the representation”. It is to determine which factor changes which consumed state under a controlled intervention.

Part VThe invariance contract

Contrastive projects often begin with model family, batch size and compute budget. The causal decision comes earlier: what transformations are allowed to preserve identity, and what distinctions must survive? Write that answer as an invariance contract before training. It is a compact agreement between the pair generator, the representation interface and the downstream decision.

Factor Positive-pair policy Decision requirement Counter-signal Release probe
Object identity May vary crop, lighting and viewpoint within an object. Must remain stable for retrieval. Same-view negatives from other objects. Retrieval under held-out viewpoint and weather.
Signal colour Do not use hue transforms that cross operational states. Must separate red, amber and green. Colour-labelled positives and colour-swapped valid negatives. Intervention test with fixed shape and changed state.
Count Crops may not remove counted instances without changing the label. Must distinguish one, two and many. Count-specific captions or auxiliary count loss. Balanced count probe plus occlusion stress test.
Relation and order Geometric transforms must update relation text consistently. Must preserve subject, object and direction. Relation-swapped hard negatives verified against the image. Paired captions with identical words and different order.
Modality provenance Alignment need not erase source identity. Must retain source, time and confidence for review. Typed metadata outside the embedding. Evidence receipt can reconstruct each source.
Rare subtype Do not treat another subtype as a negative merely because it is unpaired. Must remain discoverable despite low frequency. Group-aware sampling and subtype supervision. Per-subtype recall with confidence intervals.

The table is not a universal taxonomy. It forces five questions to meet in one place: the latent factor, the transformation applied to positives, the later decision, the evidence that preserves a distinction, and the test that can reject the design. A useful contract contains explicit contradictions. Lighting should be invariant for object identity, but signal colour should not. Crop should be invariant for texture classification, but not when it changes count.

  1. Define the consumed decision. Name the action, retrieval or classification that will use the representation. “General embedding” is not a decision. Record the harm of merging two states and the cost of keeping them separate.
  2. Inventory latent factors. Enumerate attributes, relations, quantities, source conditions and temporal variables that could vary. Mark each as must-merge, must-separate, conditionally relevant or currently unknown.
  3. Interrogate every positive generator. For each augmentation, pairing rule or temporal window, ask which factors can change across the pair. Run transformation-specific probes rather than one average score.
  4. Audit the negative population. Estimate false-negative rates by group, inspect nearest mined negatives, and add valid counterfactual negatives for distinctions that random batches rarely test.
  5. Localise retention. Probe the backbone, projection, shared embedding and downstream head. Use controlled interventions as well as decoders. Compare frozen, fine-tuned and auxiliary-objective controls.
  6. Release against a factor ledger. Report retrieval or zero-shot quality beside must-keep factor scores, subgroup uncertainty, out-of-distribution transformations and known unresolved distinctions. Withdraw the representation from a decision when its contract is violated.
Practitioner synthesis A shared embedding should usually be treated as an index into evidence, not as the evidence itself. Keep source identity, measured values, time, entitlement and uncertainty in typed records so a later decision can recover distinctions the embedding was designed to ignore.

Dataset curation belongs inside this contract. DataComp held the training procedure and compute budget comparatively fixed while varying selection from a large candidate pool, demonstrating how data design changes downstream outcomes.[18] The lesson is broader than ranking filtering methods. The pair population is part of the model specification because it defines the empirical equivalence relation the optimiser sees.

How the claim changes under pressureChart · state
stateDiagram-v2
  [*] --> Claim
  state "A graph before a geometry" as Claim
  state "Four meanings of “the feature<br/>is gone”" as Test
  state "A minimal worked example" as Revision
  Claim --> Test: expose mechanism
  Test --> Decision: evidence survives
  Test --> Revision: rival survives
  Revision --> Claim: narrow or rebuild
  Decision --> [*]
The revision loop begins with A graph before a geometry and keeps counterexamples inside the reasoning path. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Run the contrastive invariance lab

The companion Python lab makes the paper's claim falsifiable on synthetic data. Each “image” vector contains a one-hot shape, a one-hot colour and noise. Each “text” vector always contains shape but contains colour with probability 0, 0.1 or 1. Two linear encoders produce six-dimensional normalised embeddings and train with the symmetric loss above.

After training, text prototypes test zero-shot shape and colour recognition from held-out image vectors. The positive case predicts that shape remains strong when every caption names it, while colour approaches chance when captions omit it and rises when even a minority of captions mention it. The negative case shuffles pairings. No meaningful cross-modal direction should survive.

python -m pip install torch
python contrastive_invariance_lab.py
ConditionShape accuracyColour accuracyInterpretation
Colour omitted99.9% ± 0.227.7% ± 1.4Shared shape aligns; private colour stays near 25% chance.
Colour in 10% of captions100.0% ± 0.084.1% ± 1.0Sparse cross-modal evidence creates a usable colour direction.
Colour always mentioned96.0% ± 4.293.6% ± 3.8Both factors are shared, with some finite-capacity trade-off.
Shuffled pairs27.3% ± 5.622.5% ± 6.0Broken correspondence destroys both alignments.
Synthetic lab results for shape and colour retention Grouped bars show shape near 100 percent when pairs are valid, colour near chance when omitted, colour rising with caption coverage, and both factors near chance when pairs are shuffled. Held-out zero-shot accuracy (%) 0255075100 chance = 25% colouromitted colour in 10%of captions colour alwaysmentioned shuffledpairs shape colour whiskers: ± population SD
Figure 8. Sparse mention changes what crosses the modalities.Measured synthetic result from the companion lab: mean ± population standard deviation across three seeds, with 256 held-out examples per seed. Four classes make chance 25%. These values test the mechanism; they are not a benchmark for real encoders.

The first condition is the minimal positive case: shape is consistently shared and reaches 99.9%, while colour remains 27.7%, close to the 25% chance level. Mentioning colour in only 10% of captions raises colour accuracy to 84.1% without hurting shape. Always mentioning colour supports both factors, although a six-dimensional embedding and small synthetic sample produce greater variance. Shuffling pairs collapses both scores towards chance.

This result does not establish that real multimodal models erase every unmentioned factor. The image encoder here is linear, trained from scratch and evaluated through text prototypes. Those assumptions deliberately make the cross-modal bottleneck visible. Change the capacity, pretraining, layer or auxiliary objective and the result can change. The lab's value is causal transparency: pair coverage is the only intended difference across the first three conditions.

Open hypothesis For a fixed architecture and compute budget, a factor-level pair-coverage matrix will predict downstream retention better than aggregate image-text retrieval accuracy. The hypothesis is testable by systematically varying which factors appear in positives and valid hard negatives, then evaluating interventions on held-out compositions.
Full executable Python artefact

The script requires Python 3.10 or later and PyTorch 2.x. It uses synthetic data, three fixed seeds, positive assertions and a shuffled-pair negative assertion.

"""Synthetic contrastive-invariance lab for paper 55.

Python 3.10+ with PyTorch 2.x. The data are synthetic teaching fixtures.
The positive case preserves shape across image and text. Colour is either
omitted, mentioned in some captions, or always mentioned. The negative case
shuffles image-text pairings. Results are averaged over three seeds.
"""

from __future__ import annotations

from dataclasses import dataclass
from statistics import mean, pstdev

import torch
import torch.nn.functional as F

N = 256
N_SHAPES = 4
N_COLOURS = 4
NOISE_DIMS = 4
EMBED_DIM = 6
STEPS = 300
TAU = 0.07
SEEDS = (0, 1, 2)


def make_data(n: int, colour_mention_probability: float, seed: int):
    """Create paired image/text vectors with shared shape and optional colour."""
    generator = torch.Generator().manual_seed(seed)
    shape = torch.randint(N_SHAPES, (n,), generator=generator)
    colour = torch.randint(N_COLOURS, (n,), generator=generator)

    image = torch.cat(
        [
            F.one_hot(shape, N_SHAPES).float(),
            F.one_hot(colour, N_COLOURS).float(),
            0.25 * torch.randn(n, NOISE_DIMS, generator=generator),
        ],
        dim=1,
    )

    mentions_colour = (
        torch.rand(n, generator=generator) < colour_mention_probability
    ).float().unsqueeze(1)
    text = torch.cat(
        [
            F.one_hot(shape, N_SHAPES).float(),
            mentions_colour * F.one_hot(colour, N_COLOURS).float(),
            0.25 * torch.randn(n, NOISE_DIMS, generator=generator),
        ],
        dim=1,
    )
    return image, text, shape, colour


class DualEncoder(torch.nn.Module):
    def __init__(self, input_dim: int, embedding_dim: int):
        super().__init__()
        self.image = torch.nn.Linear(input_dim, embedding_dim, bias=False)
        self.text = torch.nn.Linear(input_dim, embedding_dim, bias=False)

    def encode_image(self, x: torch.Tensor) -> torch.Tensor:
        return F.normalize(self.image(x), dim=1)

    def encode_text(self, y: torch.Tensor) -> torch.Tensor:
        return F.normalize(self.text(y), dim=1)


def train(
    colour_mention_probability: float,
    seed: int,
    shuffle_pairs: bool = False,
) -> DualEncoder:
    torch.manual_seed(seed)
    image, text, _, _ = make_data(N, colour_mention_probability, seed)
    if shuffle_pairs:
        permutation = torch.randperm(
            N, generator=torch.Generator().manual_seed(seed + 111)
        )
        text = text[permutation]

    model = DualEncoder(image.shape[1], EMBED_DIM)
    optimiser = torch.optim.AdamW(model.parameters(), lr=0.05, weight_decay=1e-3)
    labels = torch.arange(N)

    for _ in range(STEPS):
        z_image = model.encode_image(image)
        z_text = model.encode_text(text)
        logits = z_image @ z_text.T / TAU
        loss = 0.5 * (
            F.cross_entropy(logits, labels)
            + F.cross_entropy(logits.T, labels)
        )
        optimiser.zero_grad()
        loss.backward()
        optimiser.step()

    return model


def prototypes() -> tuple[torch.Tensor, torch.Tensor]:
    """Text prompts for zero-shot shape and colour classification."""
    shape_prompts = []
    for shape in range(N_SHAPES):
        shape_prompts.append(
            torch.cat(
                [
                    F.one_hot(torch.tensor(shape), N_SHAPES).float(),
                    torch.zeros(N_COLOURS + NOISE_DIMS),
                ]
            )
        )

    colour_prompts = []
    for colour in range(N_COLOURS):
        colour_prompts.append(
            torch.cat(
                [
                    torch.zeros(N_SHAPES),
                    F.one_hot(torch.tensor(colour), N_COLOURS).float(),
                    torch.zeros(NOISE_DIMS),
                ]
            )
        )
    return torch.stack(shape_prompts), torch.stack(colour_prompts)


def evaluate(
    model: DualEncoder,
    colour_mention_probability: float,
    seed: int,
) -> tuple[float, float]:
    image, _, shape, colour = make_data(
        N, colour_mention_probability, seed + 1000
    )
    shape_prompts, colour_prompts = prototypes()

    with torch.no_grad():
        z_image = model.encode_image(image)
        z_shape = model.encode_text(shape_prompts)
        z_colour = model.encode_text(colour_prompts)
        shape_prediction = (z_image @ z_shape.T).argmax(dim=1)
        colour_prediction = (z_image @ z_colour.T).argmax(dim=1)

    shape_accuracy = (shape_prediction == shape).float().mean().item()
    colour_accuracy = (colour_prediction == colour).float().mean().item()
    return shape_accuracy, colour_accuracy


@dataclass(frozen=True)
class Result:
    condition: str
    shape_mean: float
    shape_sd: float
    colour_mean: float
    colour_sd: float


def run_condition(
    name: str,
    colour_mention_probability: float,
    shuffle_pairs: bool = False,
) -> Result:
    scores = []
    for seed in SEEDS:
        model = train(colour_mention_probability, seed, shuffle_pairs)
        scores.append(evaluate(model, colour_mention_probability, seed))

    shape_scores = [score[0] for score in scores]
    colour_scores = [score[1] for score in scores]
    return Result(
        condition=name,
        shape_mean=mean(shape_scores),
        shape_sd=pstdev(shape_scores),
        colour_mean=mean(colour_scores),
        colour_sd=pstdev(colour_scores),
    )


def main() -> None:
    torch.set_num_threads(2)
    results = [
        run_condition("colour omitted", 0.0),
        run_condition("colour in 10% of captions", 0.10),
        run_condition("colour always mentioned", 1.0),
        run_condition("shuffled image-text pairs", 0.0, shuffle_pairs=True),
    ]

    print("condition                         shape accuracy      colour accuracy")
    for result in results:
        print(
            f"{result.condition:34} "
            f"{100 * result.shape_mean:5.1f}% ± {100 * result.shape_sd:4.1f}   "
            f"{100 * result.colour_mean:5.1f}% ± {100 * result.colour_sd:4.1f}"
        )

    # Positive and negative cases make the causal claim executable.
    assert results[0].shape_mean > 0.95
    assert results[0].colour_mean < 0.40
    assert results[1].colour_mean > 0.70
    assert results[3].shape_mean < 0.45


if __name__ == "__main__":
    main()

Design the equivalence before training it

The traffic-light example fails only when two decisions are confused. For category retrieval, colour invariance can be desirable. For signal control, it destroys the boundary that matters. The inspection example has the same structure. Aligning images, traces and notes around “bearing fault” improves discovery, but it does not authorise a maintenance action without location, severity, trend and source quality.

Contrastive learning is therefore best understood as controlled forgetting in service of discrimination. Positive pairs define the changes that should cease to matter. Negatives define the alternatives that must remain apart. Multimodal pairs privilege what their views share. Capacity, architecture and optimisation decide how completely those pressures reshape each layer.

The changed engineering decision is concrete. Before scaling a model, write the invariance contract. State what may merge, what must separate, where private evidence remains available, which negatives make the boundary real, and which intervention can reject the design. Then choose augmentations, pair sources, loss, temperature, batch and model size. A representation is defensible when its learned equivalences match the decision's permissible equivalences, not when one retrieval score is high.

The evidence conversationChart · sequence
sequenceDiagram
  participant Q as Question
  participant M as Mechanism
  participant E as Evidence
  participant D as Decision
  Q->>M: The traffic light that became colourless
  M->>E: A graph before a geometry
  E-->>M: compare rival explanations
  E->>D: Sources
  D-->>Q: revise scope or act
Question, mechanism, evidence and decision exchange the burdens developed in Contrastive and Multimodal Representation Learning. Reading use: follow the relation, then test it against the surrounding evidence and limits.

Sources

  1. van den Oord, A., Li, Y. and Vinyals, O. (2018). Representation Learning with Contrastive Predictive Coding. arXiv.
  2. Chen, T. et al. (2020). A Simple Framework for Contrastive Learning of Visual Representations. ICML.
  3. Wang, T. and Isola, P. (2020). Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere. ICML.
  4. Tian, Y. et al. (2020). What Makes for Good Views for Contrastive Learning? NeurIPS.
  5. Poole, B. et al. (2019). On Variational Bounds of Mutual Information. ICML.
  6. Radford, A. et al. (2021). Learning Transferable Visual Models From Natural Language Supervision. ICML.
  7. Jia, C. et al. (2021). Scaling Up Visual and Vision-Language Representation Learning With Noisy Text Supervision. ICML.
  8. Zhai, X. et al. (2022). LiT: Zero-Shot Transfer with Locked-image Text Tuning. CVPR.
  9. Zhai, X. et al. (2023). Sigmoid Loss for Language Image Pre-Training. ICCV.
  10. Chuang, C.-Y. et al. (2020). Debiased Contrastive Learning. NeurIPS.
  11. Robinson, J. et al. (2021). Can Contrastive Learning Avoid Shortcut Solutions? NeurIPS.
  12. Xue, Y. et al. (2023). Which Features are Learnt by Contrastive Learning? On the Role of Simplicity Bias in Class Collapse and Feature Suppression. ICML.
  13. Saunshi, N. et al. (2022). Understanding Contrastive Learning Requires Incorporating Inductive Biases. ICML.
  14. Tamkin, A. et al. (2023). Feature Dropout: Revisiting the Role of Augmentations in Contrastive Learning. NeurIPS.
  15. Yuksekgonul, M. et al. (2023). When and Why Vision-Language Models Behave like Bags-of-Words, and What to Do About It? ICLR.
  16. Thrush, T. et al. (2022). Winoground: Probing Vision and Language Models for Visio-Linguistic Compositionality. CVPR.
  17. Liang, W. et al. (2022). Mind the Gap: Understanding the Modality Gap in Multi-modal Contrastive Representation Learning. NeurIPS.
  18. Gadre, S. Y. et al. (2023). DataComp: In Search of the Next Generation of Multimodal Datasets. NeurIPS.