<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vahid Naghshin on Medium]]></title>
        <description><![CDATA[Stories by Vahid Naghshin on Medium]]></description>
        <link>https://medium.com/@vnaghshin?source=rss-e4d0892f3ac9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*DzqwRGNKb16nIFg1.</url>
            <title>Stories by Vahid Naghshin on Medium</title>
            <link>https://medium.com/@vnaghshin?source=rss-e4d0892f3ac9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:47:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vnaghshin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What Should a Sequence Model Remember? Mamba and the Case for Selective Compression]]></title>
            <link>https://vnaghshin.medium.com/what-should-a-sequence-model-remember-mamba-and-the-case-for-selective-compression-45817530c6c6?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/45817530c6c6</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Tue, 17 Nov 2026 02:51:29 GMT</pubDate>
            <atom:updated>2026-11-17T02:51:29.876Z</atom:updated>
            <content:encoded><![CDATA[<p>Mamba, selective state spaces, and the economics of context</p><p>Every sequence model answers the same question, whether or not its designers phrase it that way: what do you do with the past?</p><p>A Transformer answers by refusing to choose. It keeps every token’s keys and values around and lets each new token look at all of them. A recurrent network answers by compressing: the entire history is squeezed into a fixed-size state, and whatever doesn’t fit is gone. The first approach is generous and expensive. The second is thrifty and forgetful.</p><p>Gu and Dao’s Mamba paper is, at its core, an argument about thrift. Its claim is that compression is not the problem. Bad compression is. And the specific badness they identify is that earlier efficient models compressed without looking at what they were compressing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idT_SUfmFb1hMb7ROw7d2w.jpeg" /></figure><h3>The problem before the paper</h3><p>Start with the Transformer’s costs, because it is easy to attribute them to the wrong thing.</p><p>Storing the queries and keys for a sequence of length <em>L</em> and model dimension <em>d </em>takes memory proportional to <em>Ld</em>. That is linear. The quadratic cost comes from the attention score matrix, <em>QK</em>, which has one entry for every pair of tokens: an <em>L</em>x<em>L</em> object. Doubling the context quadruples the pairwise interactions. (FlashAttention avoids materializing that matrix in memory, but the compute remains quadratic.)</p><p>At inference time there is a second cost. Generating token by token, you cache the keys and values of everything seen so far, so the cache grows linearly with the number of tokens. Only the keys and values are cached; each step needs just the current token’s query. Per-step compute rises with context length, and so does memory.</p><p>Several families of subquadratic alternatives existed: linear attention, gated convolutions, recurrent networks, and structured state space models (SSMs) such as S4. They were efficient. They were also, on discrete and information-dense data like text, consistently weaker than attention. The paper’s diagnosis is specific. These models were <strong>linear time-invariant (LTI)</strong>.</p><h3>What “time-invariant” costs you</h3><p>A state space model carries a hidden state <em>h_t</em> forward through time. In continuous form:</p><p><em>h’(t) = A h(t) + B x(t),</em></p><p><em>y(t) = C h(t)</em></p><p>Discretized with a step size \Delta (the paper uses a zero-order hold), this becomes a recurrence. Refer to iamge below for equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tVi4YcyjsRYwIPZKcmY8tg.jpeg" /></figure><p>In S4, the parameters <em>(\Delta, A, B, C) </em>are fixed once training ends. The same recurrence is applied at every position. That has a lovely consequence: the whole thing unrolls into a convolution with one fixed kernel, which can be computed efficiently in parallel. It also has a fatal consequence for language. The weight a past token receives depends only on <strong>how far back it is</strong>, never on <strong>what it is</strong>.</p><p>A useful picture is a fixed-coefficient filter, like an audio equalizer. It is excellent when timing structure carries the signal. It cannot read the signal and adapt.</p><p>The paper makes this concrete with two synthetic tasks. In <strong>Selective Copying</strong>, the tokens to be reproduced are scattered among filler tokens at varying positions, so the model must filter by content. A fixed kernel can learn “take the token seven steps back,” but not “take whichever tokens aren’t filler.” In <strong>Induction Heads</strong>, the model sees a pattern like <em>A, B, A</em> and must predict <em>B</em>, which requires noticing that the current token matches an earlier one and recalling what followed it. The original, fixed-spacing Copying task is solvable by LTI models, which is exactly why the selective variant is a useful probe.</p><p>This is a limitation of the model class, not an assumption about the data. An LTI model can exploit position-based structure. It cannot exploit content-based structure.</p><h3>What the paper changed</h3><p>The central move is almost embarrassingly simple to state: <strong>make the parameters functions of the input.</strong></p><p>In Mamba’s selective SSM (S6), <em>B</em>, <em>C</em>, and the step size \Delta are computed from the current token <em>x_t</em> through linear projections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NxWphrapG6Ntc3QjAnJ1LQ.jpeg" /></figure><p><em>A</em> itself stays input-independent, but its discretized form $\bar{A}_t = \exp(\Delta_t A)$ varies with the token through $\Delta_t$. A diagonal <em>A</em> with the S4D-Real initialization keeps this tractable.</p><p>Read the recurrence again with those subscripts in place:</p><p>h_t = \bar{A}_t h_{t-1} + \bar{B}_t x_t,</p><p>y_t = C_t h_t</p><p>Now $\Delta_t$ acts as a gate. A large $\Delta_t$ drives $\exp(\Delta_t A)$ toward zero (with <em>A</em> negative), washing out the old state and focusing on the current token. A small $\Delta_t$ leaves the state nearly untouched and barely writes the new input, which amounts to skipping the token. The model decides, token by token, what to remember and what to ignore.</p><p>One terminology point deserves care, because it is easy to flip. S4 is time-<strong>invariant</strong>. Mamba is time-<strong>varying</strong>: its coefficients are recomputed at every step from the input. The system remains linear in the state, but it is no longer the same linear system at each position.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUqDDlpMaHVzHTC4AwwLDQ.jpeg" /></figure><h3>The price of input dependence</h3><p>Selection solves the modeling problem and creates an engineering one. Because the coefficients change at every step, there is no single fixed kernel, so the convolutional shortcut that made S4 fast is gone. A naive recurrence would be sequential and, worse, would materialize the expanded state, with its extra factor of state dimension, in slow GPU memory.</p><p>The paper’s answer is hardware-aware computation. It computes the recurrence with a parallel scan, implemented as a fused kernel that keeps the expanded state in fast on-chip SRAM rather than writing it to HBM, in the same spirit as FlashAttention. In the backward pass it recomputes intermediate states instead of storing them. The point of the algorithm is that the model’s modeling advantage doesn’t arrive with a speed penalty that cancels it.</p><p>This is easy to underrate. The selection mechanism and the kernel are separate contributions, and the first would be impractical without the second.</p><h3>A block, not a layer</h3><p>The Mamba block merges two earlier ideas into one homogeneous unit: the H3 block and the gated MLP. Both are worth understanding on their own terms.</p><h4>The gated MLP</h4><p>A standard Transformer MLP computes $W_2 \sigma(W_1 x)$. A gated MLP uses two parallel projections of the same input:</p><p><em>y = W_3 (\sigma(W_1 x) .(W_2 x))</em></p><p>One branch passes through a nonlinearity and acts as a gate; the other carries the content; the elementwise product lets the gate decide, feature by feature, how much content passes. SwiGLU, used in many modern LLMs, is this pattern with a SiLU activation.</p><p>It is tempting to see this as attention in disguise, since both are multiplicative and input-dependent, and the main visible difference seems to be that attention’s weights are softmax-normalized. The difference runs deeper, along a different axis. Attention mixes across tokens: token <em>i</em>‘s output is a weighted sum over other tokens’ values, through an <em>L</em>x<em>L</em> matrix. A gated MLP operates independently at each position: token <em>t</em>’s output depends only on <em>x_t</em>. Information moves between channels, never between positions. A stack of gated MLPs with no sequence mixer can never relate token five to token two. In Mamba’s block, the SSM is the sequence mixer, and the gating provides input-dependent control over channels.</p><h3>H3</h3><p>H3 (Fu et al., 2022) was designed to close the recall gap between SSMs and attention. It borrows attention’s vocabulary: three projections Q, K, V, with a shift-structured SSM applied to K (so each position can see what came just before), a multiplication with V, a diagonal SSM to carry the result forward as long-term memory, and a final multiplication with Q to read from it. The multiplications are where the content-dependent interaction happens.</p><p>The contrast with Mamba is instructive. H3 gets content dependence by wrapping LTI SSMs in multiplicative interactions. Mamba gets it by making the SSM itself input-dependent. Content dependence lives around the SSM in one design and inside it in the other, and the latter changes the temporal dynamics rather than merely the features output at a given step.</p><p>The Mamba block then looks like this: project the input into two branches. One goes through a short causal convolution, SiLU, and the selective SSM. The other passes through SiLU and serves as a gate. Multiply, then project back. There is no attention and no separate MLP block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K15SSpCJUav6byW3ZVSTiQ.jpeg" /></figure><h3>What gating really does</h3><p>A thread running through all of this is the word “gating,” and it is worth saying precisely what it buys.</p><p>Gating makes a system content-dependent if and only if the gate is computed from the input. A multiplicative gate <em>g(x) . v(x)</em> means the effective weighting of the value changes with the content. But where the gate sits matters enormously.</p><p>In a gated MLP or in H3’s multiplications, the gate acts on features at the output: content decides which channels pass through at this position. In Mamba, the gate acts inside the recurrence: content decides how much of the old state survives and how much of the new token is written. That is the same role a forget gate plays in an LSTM or GRU, and the paper explicitly connects selection to RNN gating, noting the classical gate as a special case.</p><p>So the lineage is clear. Earlier work added content dependence around a fixed-dynamics core. Mamba moved it into the dynamics.</p><h3>Where this sits among its relatives</h3><p>It is tempting to say that Mamba and linear attention are the same kind of thing, and there is a real connection, but it needs stating carefully.</p><p>Linear attention replaces softmax with a feature map $\phi$, so that attention can be computed as a running matrix state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ucE07SEIl_UhVDHNKGonJg.jpeg" /></figure><p>Add a decay factor $g_i$, $S_i = g_i S_{i-1} + \phi(k_i)v_i^\top$, and you have gated linear attention, which has the same form as Mamba’s state update: a multiplicative factor on the old state plus a write of the new token. Attention-like models and SSM-like models can thus both be written as input-dependent linear recurrences or structured matrix operations over the sequence. This is the theme later developed in Mamba-2’s “state space duality.” That framework is a later contribution, not part of the original Mamba paper, and it should not be read back into it.</p><p>The same care applies to gating itself. Linear attention is not a gated MLP “applied across tokens.” The gate in gated linear attention acts on the state along the time axis, while the gate in a gated MLP is an elementwise product within a single position. Both involve multiplication by an input-dependent quantity, but they are different operations in different places.</p><h3>What the paper shows, and what it doesn’t</h3><p>The reported results are strong for their scale, and worth stating without inflation.</p><p>On synthetic tasks, Mamba solves Selective Copying and Induction Heads, and the induction-heads result extrapolates well beyond the training length. In language modeling, Mamba-3B outperforms Transformers of the same size and matches Transformers about twice its size on pretraining perplexity and downstream zero-shot evaluations. The paper reports roughly 5× higher inference throughput than comparable Transformers, and shows continued improvement on sequences up to a million tokens. Results on audio and genomics also favor Mamba, with gains growing with context length. Ablations point to the selective $\Delta$ as the most important of the selective parameters.</p><p>The limitations follow directly from the premise. A fixed-size state is a bottleneck for tasks needing exact recall over long contexts, because anything the state discarded is gone. Evaluation was mostly at up to roughly 3B parameters, so behavior at larger scale was not established in the paper. And the paper itself notes tradeoffs on continuous-signal modalities, where an LTI structure can be a better fit than selection.</p><p>That last point is a useful reminder that “time-invariant” is not an insult. When the signal’s structure is genuinely about timing, a fixed filter is the right inductive bias.</p><h3>From the paper to what came after</h3><p>Subsequent work bears out the recall limitation rather than erasing it. Mamba-2 (Dao &amp; Gu, 2024) refined the architecture through the state space duality framework. Pure SSM language models followed, including Falcon Mamba 7B and Codestral Mamba. But many of the strongest Mamba-based systems are hybrids, interleaving attention layers with Mamba layers: Jamba, Zamba, Samba, and NVIDIA’s hybrid work among them. The pattern is consistent with the paper’s own framing. Attention is good at lossless retrieval; Mamba layers are cheap and carry constant-size state; a few attention layers patch the weakness while most of the efficiency gain stays. Model details and benchmark figures for these systems should be checked against their own papers or model cards.</p><p>Most frontier LLMs remain Transformer-based, so none of this amounts to a replacement story. It is better read as a map of a tradeoff.</p><h3>A more useful way to think</h3><p>Return to the opening question. What do you do with the past?</p><p>Transformers keep all of it in lossless storage, so their memory is the context, growing as the context grows. Mamba keeps a fixed-size summary, so its memory is a decision. The paper’s contribution is to make that decision learnable and content-aware, and to make it fast enough to matter.</p><p>Seen this way, the old “efficiency versus effectiveness” framing becomes sharper. The real axis is how good the compression is. A model that compresses blindly, applying the same dynamics to every token, loses what matters along with what doesn’t. A model that compresses selectively can match a much larger store on many tasks, and still loses to explicit storage when the task is to retrieve a specific item verbatim. Whether that residual weakness matters depends on what you are asking the model to do.</p><p>That is a more useful question to carry away than “is Mamba better than attention?” Ask instead: for this task, what must be remembered, and what is safe to forget?</p><h3>References</h3><p>1. Gu, A., &amp; Dao, T. (2023). *Mamba: Linear-Time Sequence Modeling with Selective State Spaces.* arXiv.</p><p>2. Fu, D. Y., et al. (2022). *Hungry Hungry Hippos: Towards Language Modeling with State Space Models* (H3).</p><p>3. Gu, A., Goel, K., &amp; Ré, C. (2021). *Efficiently Modeling Long Sequences with Structured State Spaces* (S4).</p><p>4. Dao, T., et al. (2022). *FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness.*</p><p>5. Dao, T., &amp; Gu, A. (2024). *Transformers are SSMs: Generalized Models and Efficient Algorithms Through Structured State Space Duality* (Mamba-2).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45817530c6c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Student Who Studies Its Own Notes]]></title>
            <link>https://vnaghshin.medium.com/the-student-who-studies-its-own-notes-2b216fb35978?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b216fb35978</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Mon, 09 Nov 2026 23:11:17 GMT</pubDate>
            <atom:updated>2026-11-09T23:11:17.753Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How BYOL learns visual representations without ever being told what is different</em></p><p>You can find the basic implementation <a href="https://github.com/vahidNaghshin/BYOL_Basic_implementation.git">here</a>.</p><p>Here is a learning problem that sounds like it should not work. You want a network to produce useful descriptions of images. You have no labels. You also refuse to supply negative examples, the pairs of images that a model is told are different. All you will give it is two slightly altered versions of the same picture and one instruction: make your description of the first agree with your description of the second.</p><p>The trouble is obvious the moment you say it out loud. There is a perfect, effortless way to satisfy that instruction. Output the same vector for every image, always. The two descriptions agree, the loss is zero, and the network has learned nothing at all.</p><p><strong><em>Bootstrap Your Own Latent</em></strong> (Grill et al., 2020), usually called BYOL, is a paper about why this trivial solution does not swallow the method, and about how much of modern self-supervised learning rested on an assumption that turned out to be unnecessary.</p><h3><strong>The problem before the paper</strong></h3><p>Self-supervised learning tries to get useful representations from unlabeled data by inventing a task whose answer the data already contains. For images, a popular recipe is to take one image, produce two augmented views of it (different crops, color shifts, blurs), and train a network so that the two views end up with similar representations.</p><p>The recipe has a famous failure mode, which is the collapse described above. Methods in the contrastive family, such as SimCLR and MoCo, handled it with <strong>negative pairs</strong>. Alongside “make these two views agree,” they added “make this view disagree with views of other images.” A constant output now gets punished, because it makes every image look like every other.</p><p>Negatives work, but they come with costs. Contrastive methods tend to want many of them, which pushes toward large batches or memory banks. And their results are sensitive to the choice of augmentations. BYOL’s pitch is that you can keep the first half of the instruction and drop the second.</p><h3><strong>What the paper changed</strong></h3><p>BYOL uses two networks with a deliberately asymmetric relationship.</p><p>The <strong>online network</strong> has three stages: an encoder, a projector, and a predictor. The <strong>target network</strong> has the same encoder and projector architecture but no predictor. Given one image, two augmented views are produced. One goes through the online network, the other through the target network, and the roles are then swapped so both views serve in each role.</p><p>The loss is computed in representation space. If $q$ is the online network’s prediction for one view and $z’$ is the target network’s projection of the other view, both are L2-normalized and the loss is their mean squared error.<em> </em>Read plainly, this is a cosine-similarity objective: maximize the alignment between the online prediction and the target projection. The final loss sums this over both view assignments.</p><p>Two details carry most of the weight. First, <strong>only the online network receives gradients</strong>. The target is treated as a fixed quantity during each update, which is the stop-gradient. Second, the target’s weights are not trained at all. They are an <strong>exponential moving average</strong> of the online weights. The target is therefore a lagged, smoothed shadow of the online network: similar to it, but not identical to it at any given moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ix0fjaf9eMPDgekVVYfpUw.jpeg" /></figure><h3><em>Why “bootstrap”?</em></h3><p>The title uses <strong>bootstrap</strong> in its idiomatic sense, from pulling yourself up by your own bootstraps, not in the statistician’s sense of resampling data with replacement. The meaning fits the structure of the method. The training signal is not a label, and it is not a separate teacher. It is a slower version of the model itself. The online network learns by predicting what its own earlier self makes of another view of the same image. Better online weights feed into a better target, which gives a better signal to learn from next. Improvement feeds on itself, with the moving average acting as a stabilizer so the target does not thrash.</p><p>A natural first guess about the mechanism, and one worth correcting, is that the online network is learning to undo the augmentation and recover the original image. It is not. There is no decoder and no pixel-level loss anywhere in BYOL. The predictor maps one view’s representation to the other view’s representation, and that is all. This distinction matters because it separates BYOL from reconstruction-style methods: the objective never asks the network to remember the image, only to agree with a representation of a different view of it.</p><h3><em>The mechanism, and a thought experiment</em></h3><p>Why should predicting the other view force anything useful? Consider what the predictor has to do. Two views of the same photograph differ: one crop might show a dog’s head, another its tail. The target’s output for the second view cannot be predicted perfectly from the first. The best the predictor can do is output something like the average of the plausible targets given what it sees. To make that average good, the encoder has to retain information that carries across views, and that information is mostly the semantic content of the image.</p><p>The augmentations are what define “carries across views.” Color jitter and crop position change between the two views, so they cannot help prediction and get discarded. The object’s identity and structure persist, so they get kept. In this way the choice of augmentations quietly defines what counts as essence and what counts as nuisance. The method has no other source of opinion about what matters.</p><p>A small analogy, offered as an analogy rather than anything from the paper: imagine two people looking at one scene through differently tinted and framed windows. One writes a description; the other must predict it from their own view. To succeed, both have to focus on what is actually in the scene instead of the tint and the framing. Add that the first person is a calmer, slower-changing version of the second, and you have the rough shape of online and target.</p><h3><em>The deeper lesson: collapse is a dynamics problem</em></h3><p>This brings us back to the opening worry. The collapsed solution does minimize the loss. So why does training not slide into it?</p><p>The paper’s answer is that BYOL is not doing gradient descent on one joint loss over both networks. The online network is updated to match a target that it does not directly control, and the target moves only slowly. Combined with the predictor, which exists only on the online side, this asymmetry keeps the training dynamics from settling at the constant solution. The paper supports this with ablations: removing the predictor, or setting the moving-average rate so the target simply copies the online network, leads to collapse, while intermediate rates work.</p><p>It is important to be candid about the status of this explanation. It is a mixture of empirical evidence and heuristic reasoning, not a proof that collapse cannot occur. Follow-up work has tried to analyze the dynamics more formally, and one early discussion asked whether batch normalization was quietly providing a form of implicit negatives. The authors’ further experiments indicated BYOL can work without it, but the broader point stands: the method works well, and a complete theory of why is still more a research question than a settled fact.</p><p>This is a useful thing for practitioners to hold onto. A method can be robustly effective while its mechanism is only partly understood, and the right response is neither to dismiss it nor to over-trust the story told about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9MIUoSkPf9xB4tZEOjJtSQ.jpeg" /></figure><h3><em>From this paper to what came after</em></h3><p>BYOL belongs to a lineage, and it helps to place it carefully. The contrastive methods that preceded it (SimCLR, MoCo) shared its high-level goal of aligning representations of two views, but relied on negatives to prevent collapse. MoCo is also notable for using a momentum-updated encoder, so the slowly moving target is an idea with prior art in that line of work; what BYOL did differently was combine it with a predictor and remove negatives entirely. It would be a mistake to say BYOL invented the moving-average encoder.</p><p>Later work explored related asymmetric designs and other ways to avoid collapse without negatives. I’d treat the specifics of that literature as something to verify against the papers rather than rely on my summary, because the details of who showed what, and when, are easy to blur. The safe conceptual statement is that BYOL helped establish that explicit negatives are not strictly necessary for strong self-supervised image representations, and prompted a wave of analysis into what does prevent collapse.</p><h3>What this teaches, and what it does not</h3><p>Three practical lessons seem defensible. Representation quality is governed by what the training signal treats as irrelevant, so augmentation design is a modeling decision, not a preprocessing detail. The predictor and the moving-average target are not decorative; they are tied to the method’s stability, so they should not be treated as interchangeable with other components. And you keep the online encoder after pretraining; the projector and predictor are scaffolding.</p><p>Several things the approach does not give you. It offers no formal guarantee against collapse. Its representations are shaped by the augmentations you chose and may not transfer to a task that depends on exactly the information those augmentations destroy. And strong benchmark numbers in the paper describe specific settings, such as ImageNet with a particular architecture and evaluation protocol, so they should not be read as universal claims.</p><h3>A more useful way to think</h3><p>We began with an instruction that a lazy network could satisfy by learning nothing. The surprising part of BYOL is not that it found a trick to forbid laziness. It is that the right kind of asymmetry, a predictor on one side and a slow, gradient-free shadow of the model on the other, makes the lazy solution a place the training does not drift toward.</p><p>A representation, in this light, is what a model keeps when it is made to explain one view of the world using another, with a patient version of itself as the judge. What it keeps is decided less by the loss than by what we chose to vary between the two views.</p><p><em>— -</em></p><h3><em>References</em></h3><p><em>- Grill, J.-B., Strub, F., Altché, F., Tallec, C., Richemond, P. H., Buchatskaya, E., Doersch, C., Pires, B. A., Guo, Z. D., Azar, M. G., Piot, B., Kavukcuoglu, K., Munos, R., &amp; Valko, M. (2020). *Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning.* NeurIPS 2020.</em></p><p><em>- Chen, T., Kornblith, S., Norouzi, M., &amp; Hinton, G. (2020). *A Simple Framework for Contrastive Learning of Visual Representations* (SimCLR). ICML.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b216fb35978" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Frozen Giants and a 32-Token Bridge: How BLIP-2 Teaches Vision to Talk to Language]]></title>
            <link>https://vnaghshin.medium.com/two-frozen-giants-and-a-32-token-bridge-how-blip-2-teaches-vision-to-talk-to-language-d9a4e4e505df?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a4e4e505df</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 20:46:48 GMT</pubDate>
            <atom:updated>2026-11-08T20:46:48.183Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A vision model that can see and a language model that can reason have never met. BLIP-2 introduces them through a very small intermediary.</em></p><blockquote>You can find the code implementation <a href="https://github.com/vahidNaghshin/BLIP_2_Simple_Implementation.git">here</a>.</blockquote><p>Suppose you hold two experts. One has spent its life looking at images and has an excellent eye, but no words. The other has read a large share of the internet and can reason in fluent prose, but has never seen a pixel. You want them to collaborate, and retraining either from scratch is too expensive to contemplate.</p><p>That is the situation BLIP-2 (Li et al., 2023) addresses. Both experts exist, both are enormous, and the sensible plan is to leave them alone. The interesting question is what you put between them. The answer, a small transformer called the Q-Former, turns out to be a lesson in what it means for a representation to be <em>useful</em> rather than merely <em>rich</em>.</p><h3>Why you cannot simply plug one into the other</h3><p>A frozen image encoder emits a long sequence of patch features, hundreds of vectors describing local pieces of the image. A frozen language model expects a sequence of token embeddings living in its own space, shaped by text it has read. The two sequences differ in length, in dimension, and in meaning. Nothing about a patch vector tells a language model what to do with it.</p><p>Training a bridge end-to-end against a language-modeling loss alone is possible, but it asks the bridge to learn two things simultaneously: <em>which</em> visual information matters, and <em>how</em> the language model wants to receive it. BLIP-2 splits this into two stages, and the split is the paper’s central design decision.</p><h3>The bridge: 32 questions asked of an image</h3><p>The Q-Former is built around a small set of learnable query embeddings, 32 in the paper. They are not derived from any input. They are parameters, trained like weights, and they play the role of fixed questions the model learns to ask of every image.</p><p>Mechanically, the queries attend to the frozen image encoder’s patch features through cross-attention. The queries supply the <em>queries</em> of the attention operation, and the image features supply the <em>keys and values</em>. Whatever the image contains, the output is exactly 32 vectors.</p><p>That is the bottleneck. Hundreds of patch tokens go in; 32 query vectors come out. The compression is in sequence length, not in the dimension of each vector, which is a distinction worth keeping straight, since it is tempting to read “bottleneck” as “smaller vectors.” The paper compresses the number of tokens the language model must read. A small, fixed number of queries has to decide, through training, which parts of the image are worth keeping.</p><p>The queries also talk to each other. The Q-Former contains two submodules, an image transformer and a text transformer, which are not separate networks. They share the same self-attention layers, and the cross-attention to the image is inserted only on the query side. Text tokens never see the image directly. Image information can reach text only by passing through the queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CO_KvCGWGNJFbaK4SwxcQ.jpeg" /></figure><h3>Stage one: teaching the queries to see in the language of text</h3><p>The first stage trains the Q-Former against the image encoder alone, with no language model in the loop. Three objectives share the same weights and differ only in which tokens are allowed to see which. The attention mask is the whole trick.</p><p>Image-text contrastive learning (ITC) aligns image and text representations. The masking is <em>unimodal</em>: queries see only queries, text sees only text. The two sides never exchange information inside the network, so each produces its own representation, and they meet only at a similarity score. Since there are 32 query outputs rather than one, the paper computes the similarity between the text representation and each query output and takes the maximum. The loss is an InfoNCE-style objective: within a batch, the matching pair is the positive and every other pairing is a negative.</p><p>ITC is late fusion. It trains the image side and the text side to be comparable independently, which is what makes cheap retrieval possible: encode every image once, store the vectors, and compare any new text with dot products.</p><p>Image-text matching (ITM) is a binary classification of whether a pair matches, using a <em>bidirectional</em> mask. Queries and text attend to each other at every layer, so image and text are mixed inside the network, before any decision is made. This is early fusion. The comparison is not a fixed operation on two finished vectors; it is learned, and it lives in the attention layers. The classifier then reads the fused query outputs (as I recall, averaging per-query logits).</p><p>A point that came up in our discussion deserves emphasis here, because it is easy to get wrong. ITM’s advantage is often described as “short-range” or “local” mixing. It is neither. With a bidirectional mask every query can attend to every text token, so the interaction is dense and all-to-all. “Fine-grained” refers to the <em>granularity</em> of the interaction, token by token, not its distance.</p><p>Why keep ITC if ITM is more expressive? Because expressiveness is not the only property that matters. ITM requires a full forward pass for every image-text pair. Score one text query against a million candidate images and you run the network a million times; nothing from one text query carries over to the next, because the text changes what the network computes. ITC, by contrast, caches the image side. The two are complementary, which is why a common pattern is to shortlist by contrastive similarity and rerank by matching. ITC also supplies the similarity scores from which the hard negatives for ITM are mined.</p><p>Image-grounded text generation (ITG) uses a <em>multimodal causal</em> mask: queries are blind to text, while each text token sees all the queries and the earlier text tokens only. The task is next-token prediction. The input is the caption shifted right by one position and the target is the caption itself, standard teacher forcing. Because the text cannot reach the image except through the queries, lowering this loss forces the queries to carry whatever the caption needs.</p><p>This is the objective that closes a gap the other two leave open. A contrastive loss only requires the representation to be good enough to <em>discriminate</em> the right text from other texts in a batch. That can be satisfied by a few coarse cues, and it never requires the representation to be rich enough to <em>generate</em> the caption. Counts, positions, and attributes can be ignored and the contrastive loss would not notice. Generation cannot ignore them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpaCHaKZRgHZ6ysYlhtaUw.jpeg" /></figure><h3>Stage two: from a good representation to a readable one</h3><p>After stage one, the queries encode text-aligned visual information, but nothing yet makes it legible to a language model. Stage two connects the Q-Former to the frozen LLM through a single linear projection that maps the 32 query outputs into the LLM’s embedding dimension. These projected vectors are prepended to the text input as a soft visual prompt, and the LLM is trained with its ordinary language-modeling loss.</p><p>For a decoder-only model such as OPT, the visual embeddings are prefixed to the input and the model generates the continuation. For an encoder-decoder model such as FlanT5, they are prefixed to the text fed to the encoder, and the decoder produces the output. The paper evaluates both families, along with two frozen vision encoders: the ViT-L/14 from CLIP and the ViT-g/14 from EVA-CLIP, using features from the second-to-last layer.</p><p>Two corrections from our discussion belong here. First, the LLM is not “queried” the way a database is. The projected embeddings function as extra context tokens that condition generation, much like a prompt. Second, “the 32 embeddings are trained in both stages” is true but incomplete: what trains is the entire Q-Former, which includes the transformer weights as well as the queries, plus the new projection, while the image encoder and the LLM stay frozen. Stage two does not treat the projection as the whole alignment. Because the Q-Former keeps training, what the queries extract can shift to suit the language model.</p><h3>What the design teaches about representations</h3><p>The Q-Former is easy to describe as a connector. The more interesting reading is that it shows how a training objective shapes what a representation contains.</p><p>Consider what each loss rewards. Contrastive learning rewards representations that separate matching from non-matching pairs. That is useful, but it is a statement about <em>discrimination</em>, and discrimination can be achieved with less information than generation requires. A matching objective with hard negatives raises the bar further, because near-miss pairs force attention to relations. Generation raises it again. The three objectives are not redundant; each closes a loophole left open by the others.</p><p>There is a limit to this argument, and it is worth stating plainly. Late interaction in ITC limits what the <em>supervision</em> can teach, not what the encoder can store. A single pair-level score never says which region corresponds to which word. That is a property of the training signal, not an architectural impossibility, and it is why a CLIP-style model can have useful spatial features yet behave somewhat like a bag of words on relation-heavy benchmarks. (This is general background rather than a claim from the BLIP-2 paper, and the benchmark specifics should be verified before citing.) By the same logic, BLIP-2 is not primarily a localization model, and nothing in these losses supplies word-to-region supervision.</p><p>The second lesson is about the interface. A frozen LLM has strong priors about what its inputs look like. The two-stage design first learns <em>what</em> to extract from the image without any language model in the loop, then learns <em>how</em> to present it. Splitting those problems is what makes it practical to keep both giants frozen.</p><h3>Where to be careful</h3><p>A few boundaries apply to everything above. The conclusion that the bottleneck forces useful compression is a statement about the design intent and what the objectives reward, not a guarantee that 32 queries capture every detail of every image. Counts, fine spatial relations, and text in images are natural places for information to be lost. The objectives also depend on the quality of the image-text pairs used for training; noisy captions teach the model to align with noise.</p><h3>A different way to hold the whole thing in your head</h3><p>The abstract picture is a small set of fixed questions asked of an image, whose answers are first trained to be useful for <em>comparing and describing</em> images in text (stage one) and then trained to be useful as <em>context</em> for a language model (stage two). The frozen models contribute competence; the Q-Former contributes the translation. Its small size is the point: what survives a 32-token bottleneck is whatever the training objectives decided was worth keeping.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a4e4e505df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Flamingo Threads Video Through the Heart of a Language Model]]></title>
            <link>https://vnaghshin.medium.com/how-flamingo-threads-video-through-the-heart-of-a-language-model-9f5b063f6e96?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f5b063f6e96</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Sun, 08 Nov 2026 20:46:36 GMT</pubDate>
            <atom:updated>2026-11-08T20:46:36.113Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A frozen language model, a frozen vision encoder, and a small set of carefully gated layers that connect them</strong></p><p>You can find the code <a href="https://github.com/vahidNaghshin/Flamingo_basic_implementation.git">here</a>.</p><p>Suppose you have a language model that is very good at language, and you want it to watch a video. You could retrain it from scratch on text and pixels together, which is expensive and risks wrecking what the model already knows. You could convert the video into a caption and hand the caption over, which throws away most of what makes video interesting. Or you could try something more delicate: leave the model alone and give it a new way to look.</p><p>Flamingo (Alayrac et al., DeepMind, 2022) took the third route. Its central design question is easy to state and surprisingly hard to answer: <strong>how do you let a frozen language model see, without disturbing the thing that makes it a good language model?</strong></p><p>That question is really a question about representation. A video is a pile of pixels; a language model works in a space of token embeddings. Something has to translate between the two, and what that translation preserves and discards determines what the combined system can understand. This article follows the question through Flamingo’s architecture, and then compares Flamingo’s answer with BLIP-2, which answered the same question differently.</p><h3>Two frozen giants and a small bridge</h3><p>Flamingo starts with two pretrained models and refuses to change either.</p><p>The first is a language model, Chinchilla, available in 1.4B, 7B, and 70B variants, which underlie the 3B, 9B, and 80B Flamingo models. The second is a vision encoder, a Normalizer-Free ResNet of the F6 variety. NFNets drop batch normalization in favor of scaled weight standardization and adaptive gradient clipping, which makes training stable at scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oUSljJk8VTTKZJGAc01h4g.jpeg" /></figure><p>This encoder was pretrained <strong>contrastively</strong> on image-text pairs, in the CLIP/ALIGN tradition, using a two-tower setup with a separate text encoder. That step matters, but it is easy to misplace. It happens <em>before</em> Flamingo. After it, the vision encoder is frozen and the contrastive text encoder is discarded; Flamingo’s text understanding comes entirely from the language model. Flamingo’s own training objective is not contrastive at all. It is ordinary next-token prediction.</p><p>This distinction is worth dwelling on, because it is a clean example of how a training signal shapes a representation. The contrastive pretraining taught the vision encoder to produce features that are <em>aligned with language</em>: images and their captions land near each other. That is why a frozen encoder can be useful to a language model at all. The features were organized by a language-flavored objective before Flamingo ever touched them.</p><p>Everything Flamingo actually <em>learns</em> lives in the bridge between the two giants, and that bridge has two parts.</p><h3>Compressing the world into 64 tokens</h3><p>A video is a lot of data. Sample it at one frame per second, run each frame through the NFNet, and you get a spatial grid of features per frame. Concatenate across frames and the sequence length depends on how long the video is.</p><p>Language models do not enjoy variable, enormous inputs, and the cross-attention layers we will meet shortly would scale with that length. So Flamingo needs a funnel.</p><p>The <strong>Perceiver Resampler</strong> is that funnel. It holds a fixed set of learned latent vectors, 64 in Flamingo, that act as queries. These cross-attend to the frozen vision features and return exactly 64 visual tokens, whether the input was one image or a minute of footage. In each block, the latents supply the queries, while the keys and values come from the input features concatenated with the latents themselves, followed by a feed-forward layer and residual connections.</p><p>Video gets very little special treatment. There is no 3D convolution or temporal modeling in the encoder. Each frame is encoded independently, a learned temporal embedding is added so the model knows the frame order, and the Resampler digests the whole concatenation. An image is simply a one-frame video, which is why the same machinery handles both and why images and video can be mixed freely in one sequence.</p><p>The Resampler starts from random initialization and is trained with Flamingo’s single language-modeling loss, jointly with the layers described next. It has no pretraining stage and no auxiliary objective of its own.</p><h3>Cross-attention, and why the gate starts shut</h3><p>Now the main event. How do the 64 visual tokens reach the language model?</p><p>Flamingo inserts new <strong>gated cross-attention and feed-forward blocks</strong> between the existing frozen LM layers. In each, the queries come from the text hidden states and the keys and values from the visual tokens.</p><p>Read the gate as a dimmer switch. The new layers contribute <em>nothing</em> at the start of training, and the model computes exactly what the original language model would. A randomly initialized cross-attention layer would otherwise inject noise into hidden states that Chinchilla spent enormous compute organizing. The gate lets vision fade in only as quickly as the gradients find it useful.</p><p>Two observations make this more than a stability trick. First, the gate is <em>learned</em>, so each inserted layer decides for itself how much vision to admit, rather than following a fixed schedule. Second, tanh keeps that contribution bounded in (-1, 1) while still having a nonzero gradient at zero, so the gate can actually open. A bare scalar multiplier could drift without limit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTKRW0OfnesLAfAKALUf4w.jpeg" /></figure><p>There is a coupling here worth noticing. The Resampler starts random and the gates start closed, so early in training the Resampler receives almost no gradient signal; it only starts learning as the gates begin to open. The two components warm up together, and the gating protects the language model from meaningless Resampler outputs in the meantime.</p><p>Two further details complete the picture. The blocks are not placed at every LM layer; they are inserted at an interval that depends on model size, and the paper ablates how density trades performance against cost. And each text token cross-attends only to the visual tokens of the <strong>single most recent preceding image</strong>. Earlier images remain reachable indirectly, because the LM’s self-attention carries information from earlier text positions that already looked at them. This masking is what lets Flamingo take arbitrarily interleaved image-text sequences without the attention cost exploding.</p><p>This is what “deep fusion” means here. Visual information is not handed over once at the input. Every inserted layer gets a fresh look at the visual tokens, at a different depth in the network.</p><h3>What the model is trained on</h3><p>How do you teach a model to use these layers? Flamingo’s answer is mostly in the data.</p><p>Inputs are sequences of text with special markers: `&lt;image&gt;` marks where a visual input appears, and `&lt;EOC&gt;` (end of chunk) marks the end of the text belonging to it. A sequence might look like</p><blockquote>&lt;image&gt; A cat on a sofa.&lt;EOC&gt; &lt;image&gt; Two dogs in the snow.&lt;EOC&gt;</blockquote><p>The loss is the log-likelihood of the text tokens given the preceding text and the images before them, with nothing predicted for the pixels.</p><p>The training mixture combines three sources: M3W, roughly 43 million webpages with images and text interleaved in their natural order; image-text pairs (ALIGN and LTIP); and video-text pairs. The interleaved web pages are the crucial ingredient. Caption pairs teach captioning. Interleaved documents teach the model to continue a sequence conditioned on several images and passages, which is exactly the skill that few-shot prompting relies on at inference time.</p><p>The mixture is combined as a weighted sum of per-dataset losses, and the optimization strategy is specific: at every update the model draws a batch from <em>each</em> dataset, computes gradients for all of them, and accumulates the weighted sum before stepping. This differs from randomly picking one dataset per step according to sampling ratios, and from round-robin cycling. The paper reports that accumulating across datasets performed better.</p><p>It is tempting to compare this to interleaved practice in human learning, and as an intuition the comparison is fine. But it is only an intuition. The paper reports the empirical result without explaining the mechanism, and the likelier explanation is statistical: a gradient averaged across diverse data is more stable and less biased toward whichever data type came last. There are also two different “interleavings” in Flamingo that are easy to conflate: interleaved <em>data</em>, where images and text alternate within a sequence, and mixed <em>datasets</em> per update, where gradients from different sources are summed. The human-learning analogy fits the second, not the first.</p><h3>The other answer: BLIP-2</h3><p>Flamingo’s design looks less inevitable next to BLIP-2 (Li et al., Salesforce, 2023), which attacks the same problem with a very different bridge.</p><p>BLIP-2 also freezes a vision encoder (CLIP or EVA-CLIP ViT-based) and a language model (OPT or FlanT5). Its bridge is the <strong>Q-Former</strong>: 32 learned query embeddings that cross-attend to the image features, with a text transformer sharing self-attention layers with the query transformer. Stage one trains the Q-Former with three objectives, image-text contrastive (ITC), image-text matching (ITM), and image-grounded text generation (ITG), using different attention masks for each. Stage two connects the query outputs to the language model through a linear projection and trains with a language-modeling loss.</p><p>The difference in philosophy is where fusion happens. BLIP-2 fuses <strong>once, at the input</strong>: the projected query outputs are prepended to the text embeddings as a soft visual prompt, and the language model processes them with its ordinary self-attention. The language model itself is untouched, and it has no dedicated pathway to re-query the image at deeper layers.</p><p>Two points are often garbled in summaries of this comparison, so they are worth stating carefully. First, the Q-Former has no separate frozen text encoder; text and queries live in one shared module, and in stage two, text does not pass through the Q-Former at all. Second, the language model receives <em>continuous embeddings in its input space</em>, not text. The visual information does not become words. It becomes a learned prefix.</p><p>The trade-offs follow from this. BLIP-2 is far cheaper, with roughly 188M trainable parameters, and its paper reports strong zero-shot results, including outperforming Flamingo-80B on zero-shot VQAv2 with many times fewer trainable parameters. But it benefits little from in-context examples and is built around single images. Flamingo is more expensive and closed, and its depth of fusion and interleaved training are plausibly why it excels at few-shot prompting, though that causal story is an interpretation, not something either paper isolates directly.</p><p>Neither model can output images. Both take visual input and emit text through the language model’s ordinary head.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CIGB2Xa7450h3SJoFoOmaw.jpeg" /></figure><h3>What the comparison teaches</h3><p>The two models disagree about where a language model should meet vision, and the disagreement has a clean shape.</p><p>Later systems mostly sided with the input-level style. LLaVA dropped the compressing bottleneck entirely in favor of a simple projection of all patch tokens, and showed that high-quality instruction data mattered more than an elaborate bridge. Meanwhile, deep fusion never disappeared: CogVLM adds trainable visual expert weights inside every layer, and Llama 3.2-Vision inserts cross-attention layers into the language model. The field has not declared a winner, which is informative in itself. Both approaches work, and the choice trades cost and simplicity against flexibility.</p><h3>A better way to think about it</h3><p>Flamingo is easy to describe as “an LLM that can see,” but the interesting content is in how little it changes. The language model’s weights are untouched. The vision encoder’s weights are untouched. What the system learns is a compressor (the Resampler), a set of valves (the gated cross-attention layers), and, through the training mixture, a habit: to treat images as context that precedes and shapes text.</p><p>That framing returns us to the question of representation. The vision features that reach the language model are shaped by two different training signals at two different times: a contrastive objective that organized the encoder’s features by language-aligned similarity, and a next-token objective that taught the bridge which of those features matter for predicting text. What the model “sees” is whatever survived both. Change the objective and you change what counts as worth preserving.</p><p>The zero-initialized gates are the quiet center of the design. They encode a principle that applies well beyond this paper: when you add capability to a model you value, make the new component earn its influence rather than assume it. The model begins as itself and becomes something else only as fast as the evidence warrants.</p><h3>References</h3><p>· Alayrac, J.-B., et al. (2022). <em>Flamingo: a Visual Language Model for Few-Shot Learning.</em> NeurIPS 2022. arXiv:2204.14198.</p><p>· Li, J., Li, D., Savarese, S., Hoi, S. (2023). <em>BLIP-2: Bootstrapping Language-Image Pre-training with Frozen Image Encoders and Large Language Models.</em> ICML 2023. arXiv:2301.12597.</p><p>· Brock, A., De, S., Smith, S. L., Simonyan, K. (2021). <em>High-Performance Large-Scale Image Recognition Without Normalization.</em>ICML 2021. (NFNets)</p><p>· Jaegle, A., et al. (2021). <em>Perceiver: General Perception with Iterative Attention.</em> ICML 2021.</p><p>· Hoffmann, J., et al. (2022). <em>Training Compute-Optimal Large Language Models.</em> (Chinchilla)</p><p>· Radford, A., et al. (2021). <em>Learning Transferable Visual Models From Natural Language Supervision.</em> (CLIP)</p><p>· Liu, H., et al. (2023). <em>Visual Instruction Tuning.</em> NeurIPS 2023. (LLaVA)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f5b063f6e96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Language of Seeing: How CLIP Taught Machines to Understand Images Through Text]]></title>
            <link>https://vnaghshin.medium.com/the-language-of-seeing-how-clip-taught-machines-to-understand-images-through-text-a364c25d1172?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/a364c25d1172</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Thu, 29 Oct 2026 23:18:35 GMT</pubDate>
            <atom:updated>2026-10-29T23:18:35.573Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happens when you stop telling a model what to see, and start letting language show it?</em></p><p>You can find a basic CLIP implementation <a href="https://github.com/vahidNaghshin/CIP_paper_implementation.git">here</a>.</p><p>There is a deceptively simple question at the heart of visual recognition: what makes two images <em>meaningfully similar</em>? Not pixel-similar — a photograph of a dog taken in sunlight and the same dog photographed in shade share almost no pixel values — but similar in the way that matters. Similar in the way a person recognizes them as depicting the same thing without a moment’s hesitation.</p><p>This question turns out to be far more interesting than the classification problem that dominated computer vision for years. Classification asks: <em>which box does this image belong to?</em> Similarity asks something deeper: <em>what does this image mean, and how does that meaning relate to everything else the model knows?</em> CLIP, introduced in OpenAI’s 2021 paper “Learning Transferable Visual Models From Natural Language Supervision,” is one of the most elegant answers to that deeper question yet proposed.</p><h3>The Trouble With Labels</h3><p>To appreciate what CLIP does, it helps to understand what it replaces.</p><p>The dominant paradigm in supervised visual learning is straightforward: collect images, assign labels, train a model to predict those labels. ImageNet, the dataset that catalyzed modern deep learning, contains roughly 1.2 million images across 1,000 carefully curated categories. The model that emerges from training on it is genuinely impressive — but it is impressive in a narrow, brittle way. Ask it to recognize a concept outside its 1,000 categories and it will fail completely. More fundamentally, the representations it learns are <em>shaped by the label set</em>. The model learns to distinguish whatever differences the labels require it to distinguish, and nothing more.</p><p>This is the core limitation. Crowd-labeled datasets are expensive to produce, slow to expand, and inevitably constrained by whoever decided which categories to include. The supervision signal is high-quality but narrow. And narrow supervision produces narrow representations.</p><p>The CLIP paper makes a different bet: that the aggregate supervision available in naturally occurring text on the internet — billions of image-text pairs, written by humans describing things they found worth describing — is richer, broader, and ultimately more useful than any curated label set could be. Not because each individual caption is more precise than a carefully assigned label, but because the <em>scale and diversity</em> of natural language supervision covers the conceptual space of human visual experience far more completely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTnzLpIH8IduRCXqwkzv8w.jpeg" /></figure><h3>Atoms of Learning</h3><p>Before examining how CLIP works, it is worth asking what the <em>unit of learning</em> is in different approaches — what the model is actually trying to predict at each training step.</p><p>In generative image models, the atom is the <em>pixel</em>. The model learns by reconstructing images pixel by pixel, which means it must model every detail of visual appearance, most of which is semantically irrelevant. This produces rich representations, but at enormous computational cost — the CLIP paper notes that generative models require over an order of magnitude more compute than contrastive approaches for equivalent representation quality.</p><p>In predictive language-vision models, the atom is the <em>word</em>. Given an image, predict the exact sequence of words in its caption. This is a harder task than it sounds: the model is penalized for writing “automobile” when the caption says “car,” even though the two are semantically identical. Most of the model’s capacity goes toward learning the grammar and vocabulary of caption generation rather than toward learning visual meaning.</p><p><strong>CLIP’s insight is to raise the atom to the level of the <em>whole description paired with the whole image</em>.</strong> Rather than predicting exact words, CLIP asks a simpler question: <em>which description goes with which image?</em> This is what the paper calls a proxy task — not the ultimate goal, but a training objective that efficiently drives the model toward the representations we actually want. By making the task easier in one dimension (no exact word prediction required), CLIP frees its capacity to learn something more important: the semantic correspondence between visual content and linguistic meaning.</p><h3>The Contrastive Mechanism</h3><p>CLIP trains two encoders jointly: an image encoder (either a ResNet or a Vision Transformer) and a text encoder (a Transformer). Given a batch of <em>N</em> image-text pairs, the image encoder produces <em>N</em> image embeddings and the text encoder produces <em>N</em> text embeddings. The training objective is contrastive: maximize the cosine similarity between the <em>N</em> correct image-text pairs — the diagonal of an <em>N</em>×<em>N</em> similarity matrix — while minimizing the similarity between all <em>N^</em>2−<em>N</em> incorrect pairings.</p><p>The temperature <em>τ</em> deserves a moment’s attention. A small <em>τ</em> produces a peaked distribution — the model is forced to be confident, which sharpens the distinction between correct and incorrect pairs. A large <em>τ</em> spreads probability more evenly, producing softer gradients. CLIP learns <em>τ</em> during training rather than treating it as a fixed hyperparameter, which allows the model to calibrate its own confidence as representations improve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNtcZ--8KuVdx6hhSMRyPQ.jpeg" /></figure><h3>Language as the Geometry of Vision</h3><p>Here is the insight that makes CLIP genuinely interesting, and which rewards careful thought from several angles.</p><p>When CLIP trains its image encoder to align with its text encoder, it is not merely teaching the visual model to recognize objects. It is teaching it to organize visual experience according to the <em>semantic geometry of language</em>. The structure of the text embedding space — where “car” and “automobile” are neighbors, where “tense dramatic scene” and “quiet contemplative moment” are far apart — becomes the organizing principle of the visual embedding space.</p><p>This is what it means to say that text supervision <em>injects meaning</em> into visual representations. A self-supervised visual model trained without language learns that certain images cluster together, but the clusters have no names, no connections to human concepts, no way to be queried except by example. The representations are, in a sense, islands — rich in internal structure but isolated from the vocabulary humans use to describe the world.</p><p>CLIP’s representations are different. Every point in the visual embedding space has a corresponding neighborhood in the text embedding space. The visual encoder learns not just <em>what</em> to group together, but <em>why</em> — because language has already organized the conceptual space, and the image encoder is trained to mirror that organization.</p><p>A natural consequence of this geometric picture is that the visual embedding space inherits language’s capacity for composition. If “dog playing in snow” and “cat sitting by a fireplace” each correspond to regions in the embedding space, then a description that combines both concepts will produce an embedding that lies somewhere between them — a point in the semantic manifold that blends both directions. This is not a special feature of CLIP; it is a direct consequence of training visual representations to track linguistic meaning. It is also, not coincidentally, the geometric principle that powers text-to-image generation models like DALL-E 2, which use CLIP’s embedding space as a semantic compass to guide image synthesis — with a separate diffusion model doing the actual pixel generation that CLIP itself never performs.</p><h3>Zero-Shot Classification as a Geometric Act</h3><p>The most striking demonstration of CLIP’s learned geometry is zero-shot classification — the ability to recognize visual categories the model has never been explicitly trained to classify.</p><p>The mechanism is elegant. To classify an image into one of <em>K</em> categories, construct a text prompt for each category: <em>“A photo of a {class name}.”</em> Encode all <em>K</em> prompts with the text encoder, producing <em>K</em> text embeddings. Encode the image with the image encoder. Compute the cosine similarity between the image embedding and each text embedding, scale by temperature <em>τ</em>, and apply a softmax.</p><p>Assign the image to the class with highest probability. No labeled examples. No fine-tuning. No classifier trained on the target dataset. Just the geometry of a shared embedding space doing the work that labeled data used to require.</p><p>The paper offers a revealing reinterpretation of this procedure. The <em>K</em> text embeddings form a matrix that acts as the weight matrix of a linear classifier — one row per class, each row generated dynamically by the text encoder from a class name description. In this view, the text encoder is a <em>hypernetwork</em>: a network whose output is the weights of another network. Rather than learning a fixed classifier for a fixed set of categories, CLIP generates a new classifier on demand for any set of categories that can be described in language. The image encoder provides the features; the text encoder provides the decision boundaries; and the boundaries can be redrawn for any new task simply by changing the text.</p><p>This is a fundamentally different relationship between a model and its tasks. Traditional supervised models are trained <em>for </em>specific tasks. CLIP is trained <em>toward</em> a representation rich enough to support tasks that did not exist when training began.</p><h3>Beyond Two Modalities: A Field in Motion</h3><p>CLIP’s architecture embodies a set of specific design choices — and understanding those choices becomes more illuminating when you see how the field has varied them. <strong>Every multimodal learning system makes decisions across three dimensions: how modalities are <em>encoded</em>, how their representations are <em>combined</em>, and what <em>loss function</em> drives the alignment.</strong> CLIP’s particular answers are not the only valid ones, and the landscape of alternatives reveals both the generality of the underlying idea and its genuine limitations.</p><h3>The Encoding Question: Separate, Shared, or Bridged</h3><p>CLIP uses entirely separate encoders for image and text, each optimized for its own modality. This is called <em>late fusion</em> — the two representations only meet at the final similarity computation. The advantage is flexibility: each encoder can develop the inductive biases most appropriate for its input type, and the resulting embeddings transfer broadly. The cost is that the encoders never interact during the encoding process itself, which limits the richness of cross-modal reasoning.</p><p>The alternative is <em>early or intermediate fusion</em>, where modalities interact during encoding rather than only at the end. DALL-E 1 takes this to an extreme, treating image patches and text tokens as elements of a single unified sequence and training an autoregressive model to predict the next token regardless of modality. This enables genuine image generation but at the cost of the clean separation that makes CLIP’s zero-shot transfer so flexible. Stable Diffusion takes a middle path: a frozen CLIP text encoder provides semantic guidance through <em>cross-attention</em> into the image generation process, allowing text embeddings to condition every layer of the diffusion model without abandoning the representational clarity of separate encoders.</p><p>A third approach, exemplified by BLIP-2, directly addresses a question that arises naturally from CLIP’s design: what if you want to connect two powerful pre-trained encoders that were trained independently, without retraining either from scratch? BLIP-2’s answer is the Q-Former — a lightweight trainable bridge module that sits between a frozen image encoder and a frozen language model, learning to extract the visual information most relevant to language from fixed visual features. The original encoders are preserved entirely; only the bridge is trained. This is parameter-efficient, avoids catastrophic forgetting, and produces a model that can perform both contrastive alignment and language generation from the same visual features.</p><h3>The Loss Question: What Are You Actually Optimizing?</h3><p>CLIP’s contrastive loss is clean and effective, but it is not the only option — and different losses produce meaningfully different representations.</p><p>Generative losses, as used in DALL-E 1 and the diffusion models, optimize for the ability to reconstruct or generate outputs. They tend to produce representations that capture fine-grained visual detail but require substantially more compute for equivalent semantic quality. The CLIP paper’s observation that generative models need over an order of magnitude more compute than contrastive models for the same representation performance is a direct consequence of this: pixel-level reconstruction is a much harder proxy task than semantic matching.</p><p>Several models combine multiple losses simultaneously to capture different levels of representation. FLAVA trains with contrastive loss, masked image modeling, masked language modeling, and multimodal masked modeling all at once — targeting unimodal, cross-modal, and multimodal representations in a single unified model. BLIP uses three losses in parallel: contrastive alignment, image-text matching (a binary classification of whether a pair is correct), and image-conditioned text generation. Each loss shapes the representation differently, and their combination produces a model that handles both retrieval and generation tasks from the same encoder.</p><p>VICReg takes a different approach entirely, abandoning negative pairs — and therefore the need for large batches — in favor of explicit regularization terms that prevent representational collapse. Its loss penalizes low variance across a batch (preventing all embeddings from collapsing to the same point), enforces invariance between augmented views of the same image, and decorrelates the dimensions of the embedding space. The result is a self-supervised visual model that requires no text supervision at all, demonstrating that the contrastive push-pull dynamic is one solution to the collapse problem, not the only one.</p><h3>Scaling Beyond Two Modalities</h3><p>Perhaps the most direct extension of CLIP’s logic is ImageBind, which aligns six modalities — image, text, audio, depth, thermal, and inertial measurement — into a single shared embedding space. The key architectural insight is to use image as the universal hub: rather than collecting paired data for every possible combination of modalities, ImageBind trains each modality’s encoder against image embeddings using naturally co-occurring pairs (video frames with their audio, RGB images with their depth maps, and so on). The result is <em>transitive alignment</em>: because audio is aligned to image and image is aligned to text, audio and text become implicitly aligned even without a single direct audio-text training pair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qqXpDa4a8CZUcUAwo6iIOw.jpeg" /></figure><p>This transitive property is not magic — it works because the image embedding space is rich enough to serve as a meaningful intermediary between very different modalities. It also suggests a general principle: the choice of hub modality matters enormously. CLIP implicitly uses language to organize visual space; ImageBind uses image to organize everything else. The hub’s semantic structure becomes the organizing principle of the entire multimodal system.</p><h3>The Three Fundamental Tensions</h3><p>Surveying this landscape, three recurring tensions emerge that every multimodal system must navigate:</p><p>The first is flexibility versus expressiveness. Late fusion (CLIP) produces representations that transfer broadly and support zero-shot classification across arbitrary categories. Early and intermediate fusion (DALL-E, Stable Diffusion) produces richer cross-modal interactions but at the cost of task-specific entanglement. There is no free lunch: the architectural choice that enables zero-shot generalization is the same choice that limits cross-modal reasoning depth.</p><p>The second is contrastive versus generative objectives. Contrastive losses are computationally efficient and produce clean semantic representations, but they cannot generate. Generative losses enable synthesis but require substantially more compute and tend to entangle semantic and perceptual detail in ways that complicate transfer. Hybrid approaches like BLIP-2 attempt to have both, at the cost of architectural complexity.</p><p>The third is training from scratch versus bridging pre-trained models. CLIP trains both encoders jointly from the beginning, which allows the representations to co-evolve toward alignment. Bridging approaches like BLIP-2 and adapter-based methods freeze pre-trained encoders and train only a lightweight connection, preserving the original representations while adding cross-modal capability. The trade-off is between representational coherence and practical efficiency — retraining everything is expensive, but frozen encoders may never achieve the depth of alignment that joint training produces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8i2yjwfzX110azAlYHFpA.jpeg" /></figure><h3>What the Training Data Cannot Tell You</h3><p>It would be a mistake to leave this picture without acknowledging its complications.</p><p>CLIP was trained on 400 million image-text pairs scraped from the internet. This is simultaneously its greatest strength and a source of genuine limitations. The visual representations CLIP learns are shaped by what humans on the internet found worth captioning — which is not a neutral or representative sample of visual experience. Concepts that appear rarely in web text will be poorly represented. Biases present in internet language will be inherited by the visual embedding space.</p><p>The paper also addresses a more specific concern: data contamination. When a model is trained on 400 million web-scraped pairs, there is a real possibility that some benchmark test images appeared in the training data, artificially inflating zero-shot performance. The authors conduct a careful overlap analysis, identifying near-duplicate training examples for each evaluation dataset and measuring performance on cleaned subsets with overlapping examples removed. The finding is reassuring but not trivial: overlap exists across nearly all benchmarks, but its effect on measured performance is small and consistent. CLIP’s zero-shot results hold up on cleaned datasets, which supports the conclusion that the performance reflects genuine generalization rather than memorization.</p><p>There is also a subtler limitation that follows directly from the geometric picture developed earlier. Because CLIP’s visual representations are shaped by the geometry of language, they inherit language’s ambiguities. Words that carry multiple meanings — “bank,” “crane,” “bat” — produce text embeddings that blend those meanings, and the visual representations of corresponding images may reflect that blending in unexpected ways. The semantic structure of language is rich, but it is not perfectly suited to organizing every visual distinction that matters. This is not a flaw unique to CLIP; it is an inherent consequence of using any single modality as the organizing principle for another.</p><h3>A More Useful Way to Think About Representations</h3><p>Return, for a moment, to the question that opened this article: what makes two images meaningfully similar?</p><p>The answer, it turns out, depends entirely on what you trained your model to regard as meaningful. A model trained on ImageNet labels learns that the difference between a Labrador and a poodle is important and the difference between a sunny day and a cloudy one is not. A model trained with CLIP’s contrastive objective learns that the differences language captures are important — which is a much larger and more flexible set of distinctions, but still a particular set, shaped by the particular humans who wrote the particular text that ended up in the training data. A model trained with audio supervision, as one can imagine, would learn to regard the differences that sound captures as meaningful: mood, atmosphere, temporal dynamics, emotional register — aspects of visual scenes that language sometimes struggles to articulate.</p><p>This is the deepest lesson that CLIP and its successors offer. Not that language supervision is uniquely correct, but that <em>supervision is always a choice</em> — and that choice determines, more than any architectural decision, what a model learns to see. The geometry of a learned embedding space is not a neutral mathematical object. It is a record of every decision made about what counts as similar and what counts as different, encoded in the distances between points.</p><p>Understanding that geometry — what shaped it, what it captures, and what it inevitably leaves out — is what it means to understand a representation. And that understanding, more than any benchmark number, is what tells you whether a model is genuinely useful for the task you have in mind.</p><p><em>The paper discussed in this article is “Learning Transferable Visual Models From Natural Language Supervision” by Radford et al. (2021), OpenAI. Additional models discussed include ALIGN (Jia et al., 2021), DALL-E 1 and 2 (Ramesh et al., 2021, 2022), Stable Diffusion (Rombach et al., 2022), FLAVA (Singh et al., 2022), BLIP-2 (Li et al., 2023), ImageBind (Girdhar et al., 2023), ALBEF (Li et al., 2021), VICReg (Bardes et al., 2022), and SLIP (Mu et al., 2022).</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a364c25d1172" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeing Without Being Told: How Machines Learn to Understand Images]]></title>
            <link>https://vnaghshin.medium.com/seeing-without-being-told-how-machines-learn-to-understand-images-ced26de50727?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ced26de50727</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[contrastive-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 23:47:38 GMT</pubDate>
            <atom:updated>2026-10-26T23:47:38.782Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A deep dive into the ingredients that make self-supervised visual representation learning work — and why they matter.</strong></p><p>You can find the full implementation of content <a href="https://github.com/vahidNaghshin/SimCLR_Paper_Implementation.git">here</a></p><h3>The Problem With Pixels</h3><p>A photograph of a golden retriever contains roughly 150,000 numbers. Each one encodes the brightness of a single color channel in a single pixel. Somewhere in that sea of integers is the concept of “dog” — but the concept is not written anywhere. It has to be discovered.</p><p>This is the central problem of visual representation learning: how do you compress raw pixel data into something meaningful? How do you build a feature space where a blurry photo of a Labrador and a crisp photo of a poodle end up closer to each other than either does to a photograph of a car?</p><p>For most of deep learning’s history, the answer was supervision. You collect millions of labeled images, train a classifier with cross-entropy loss, and harvest the penultimate layer as your representation. It works remarkably well. It also requires an enormous amount of human annotation — a resource that is expensive, slow, and impossible to scale to the full diversity of visual experience.</p><p>The question that motivated a generation of researchers was sharper: <em>Can a model learn to see without being told what it is looking at?</em></p><h3>Two Philosophies of Understanding</h3><p>Before examining one particularly elegant answer, it helps to understand the two broad traditions that have shaped how researchers think about visual representations.</p><p>The <strong>generative tradition</strong> holds that understanding an image means being able to reconstruct it. Autoencoders compress an image into a compact latent vector and then decode it back to pixels. Variational autoencoders impose probabilistic structure on that latent space. Masked autoencoders, popularized by Kaiming He and colleagues, hide large patches of an image and ask the model to fill them in. The intuition is appealing: if you can generate something, you must understand it.</p><p>The <strong>discriminative tradition</strong> takes a different view. Rather than modeling the full distribution of pixels — a notoriously difficult task — discriminative methods train models to distinguish between things. Supervised classifiers are the most familiar example, but the tradition extends naturally to self-supervised settings where the model learns to distinguish between different images, different views, or different semantic concepts without any human-provided labels.</p><p>These two philosophies are not mutually exclusive, and modern methods increasingly blend them. But for understanding what makes contrastive learning work, the discriminative framing is the right one to hold in mind.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AsNiCEXMjq40vjp-d9dwkA.jpeg" /></figure><h3>SimCLR: A Deceptively Simple Framework</h3><p>In 2020, Ting Chen, Simon Kornblith, Mohammad Norouzi, and Geoffrey Hinton published <em>A Simple Framework for Contrastive Learning of Visual Representations</em> — SimCLR for short. The paper’s title was not false modesty. The framework really is simple. Its contribution was not a novel architecture or a new loss function invented from scratch. It was something more valuable: a rigorous, systematic identification of <em>why</em> contrastive learning works, and what it actually needs to work well.</p><p>The core idea fits in a single sentence. Take an image, create two differently augmented versions of it, and train a neural network to recognize that those two versions came from the same source — even when presented alongside augmented versions of hundreds of other images.</p><p>The mechanics are straightforward. Both views pass through the same encoder (a ResNet, in the paper’s experiments) to produce representation vectors <em>h</em>. Those vectors then pass through a small projection head — a two-layer MLP — to produce vectors <em>z</em> in a lower-dimensional space. The contrastive loss operates on <em>z</em>. At inference time, <em>z</em> is discarded entirely; only <em>h</em> is used for downstream tasks.</p><p>What makes this work? The paper’s real contribution is its answer to that question.</p><h3>The Four Ingredients</h3><h3>Augmentation Is Not Preprocessing — It Is the Curriculum</h3><p>The most important finding in SimCLR is also the most counterintuitive: the choice of data augmentation matters more than almost any other design decision.</p><p>This is not obvious. Augmentation is typically treated as a regularization trick — a way to prevent overfitting by artificially expanding the training set. In contrastive learning, it plays an entirely different role. Augmentation <em>defines the task</em>. It specifies what the model should be invariant to, and therefore what it must learn to be sensitive to.</p><p>SimCLR’s augmentation pipeline combines random cropping and resizing, color jitter (randomizing brightness, contrast, saturation, and hue), random grayscale conversion, and Gaussian blur. The composition matters as much as the individual components. Cropping alone leaves a shortcut: two crops of the same image share similar color statistics, so a model can match them by histogram rather than by semantic content. Color jitter destroys that shortcut, forcing the model to find a more principled basis for similarity. Each augmentation eliminates the shortcuts left by the others.</p><p>To measure each augmentation’s contribution cleanly, the authors designed an asymmetric ablation: one branch of the framework receives only the mandatory crop-and-resize, while the other receives the augmentation under study. This controls for the confounding effects of augmentation composition and allows each transformation to be evaluated on its own merits. The result is a rare thing in deep learning: a genuinely controlled experiment.</p><p>The broader lesson is worth stating directly. <em>Augmentation design is how you encode your prior knowledge about the task.</em> If you are training on medical images where staining variation is irrelevant but tissue morphology is critical, your augmentation pipeline should reflect that. SimCLR made this principle explicit and empirically grounded.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PM1PH9q2SfX-DPaRT0K5g.jpeg" /></figure><h3>The Projection Head: A Buffer for Invariance</h3><p>The second ingredient is more subtle and, in some ways, more theoretically interesting.</p><p>SimCLR inserts a small MLP — the projection head — between the encoder output <em>h</em> and the contrastive loss. The loss is applied to the projected representation <em>z</em>, not to <em>h</em> directly. After training, the projection head is thrown away.</p><p>Why does this help? The contrastive objective creates pressure toward maximal invariance: the model is rewarded for making <em>z_i</em> and <em>z_j</em> as similar as possible regardless of augmentation. If this pressure is applied directly to <em>h</em>, it destroys information that is useful for downstream tasks but irrelevant to the contrastive objective — information about fine-grained visual details, for instance, that augmentation happens to preserve.</p><p>The projection head absorbs this destructive pressure. It is a sacrificial layer, trained to be maximally invariant so that <em>h</em> does not have to be. The encoder is free to retain a richer, more complete representation of the input.</p><p>This connects to a broader principle from information theory. The optimal representation for a task retains as much task-relevant information as possible while discarding the rest. The projection head creates a secondary compression stage that protects the primary representation from over-compression. Removing it — applying the loss directly to <em>h</em> — costs roughly 10 percentage points on linear evaluation accuracy. That is a large price for a component that does not even survive to inference time.</p><h3>Contrastive Loss as a Classification Problem</h3><p>The third ingredient is the loss function itself: NT-Xent, or Normalized Temperature-scaled Cross Entropy. Understanding it requires a small shift in perspective.</p><p>The contrastive task is, at its core, a classification problem. Given an anchor view <em>z_i</em> and a batch of 2N − 1 other views, the model must identify which one is the positive pair — the other augmented view of the same image. The remaining 2(N − 1) views are negatives.</p><p>This is exactly what cross-entropy loss does: it maximizes the probability assigned to the correct answer among a set of candidates. In NT-Xent, the “logits” are cosine similarities between the anchor and each candidate, scaled by a temperature parameter τ:</p><p>ℓ_i = −log [ exp(sim(z_i, z_j) / τ) / Σ_{k≠i} exp(sim(z_i, z_k) / τ) ]</p><p>The temperature τ controls the sharpness of the distribution. A low temperature concentrates the loss on the hardest negatives — the samples that are most similar to the anchor but should be pushed away. A high temperature treats all negatives more uniformly. The optimal value in SimCLR’s experiments was around 0.5, a balance between learning signal strength and training stability.</p><p>What makes NT-Xent preferable to older contrastive losses like the triplet loss? The denominator. Triplet loss considers one negative at a time, which means most training steps involve easy negatives that contribute almost no gradient. NT-Xent considers all 2(N − 1) negatives simultaneously. Hard negatives — those with high cosine similarity to the anchor — contribute large terms to the denominator and therefore dominate the gradient. The loss performs implicit hard negative mining without requiring any explicit selection procedure.</p><h3>Scale Is Not a Luxury</h3><p>The fourth ingredient is the most practically inconvenient: large batch sizes and long training schedules are not optional.</p><p>The reason is structural. In NT-Xent, every other sample in the batch is a negative. A batch of 256 images provides 510 negatives per anchor. A batch of 8,192 provides 16,382. More negatives means a denser sampling of the visual space, which means more hard negatives, which means stronger and more informative gradients.</p><p>Training longer partially compensates for smaller batches — the model encounters more negatives over time — but the relationship is not perfectly substitutable. SimCLR’s best results required batch sizes of 4,096 to 8,192 and training runs of 800 to 1,000 epochs, far longer than the 90-epoch schedules typical in supervised ImageNet training. The indirect nature of the self-supervised signal simply requires more exposure to converge.</p><p>This is not a flaw in the framework so much as an honest accounting of what self-supervised learning costs. The labels that supervised learning relies on are doing a great deal of work. Removing them means the model must discover structure through repetition and contrast, and that takes time.</p><h3>A Hidden Danger: When Normalization Leaks Information</h3><p>Distributed training introduces a subtle failure mode that deserves attention, because it illustrates a general principle about self-supervised learning that is easy to miss.</p><p>In standard data-parallel training, Batch Normalization statistics — the mean and variance used to normalize activations — are computed locally on each device. This is fine for supervised learning, where there is no intentional relationship between samples in a batch. In SimCLR, positive pairs are co-located on the same device. This means that the two augmented views of the same image both contribute to the same local batch statistics, and therefore both are normalized using statistics that carry their shared fingerprint.</p><p>The model can exploit this. Rather than learning to match pairs by semantic content, it can learn to detect the statistical correlation introduced by shared normalization. The contrastive loss decreases, but the representation learns nothing useful.</p><p>SimCLR’s solution is to aggregate Batch Normalization statistics globally across all devices before normalizing. With thousands of samples contributing to the global mean and variance, any single image’s influence becomes negligible — roughly 0.024% in a batch of 4,096. The statistical fingerprint is washed out, and the shortcut disappears.</p><p>This episode illustrates a principle that runs through all of self-supervised learning: <em>the optimizer will find any path to a lower loss, regardless of whether that path corresponds to genuine learning.</em> Designing a self-supervised objective means systematically closing every shortcut until the only remaining path is the one you actually want the model to take.</p><h3>What the Model Actually Learns</h3><p>It is worth pausing to ask what a SimCLR-trained encoder has actually learned by the end of training.</p><p>The answer, revealed by linear evaluation — training a single linear classifier on top of frozen representations — is that the encoder has learned a feature space that is approximately linearly separable by semantic category. Dog images cluster together. Car images cluster together. The clusters are separated by meaningful distances, not arbitrary ones.</p><p>This emerges entirely from the contrastive objective, without a single semantic label. The augmentation pipeline defines what the model should be invariant to; the contrastive loss ensures that invariance is enforced while discrimination between different images is maintained. The projection head protects the richness of the representation. The scale of the batch ensures the discrimination task is hard enough to be informative.</p><p>None of these ingredients is sufficient alone. Together, they create a learning signal strong enough to discover semantic structure from raw visual experience.</p><h3>The Lasting Contribution</h3><p>SimCLR did not invent contrastive learning, and it was not the last word on self-supervised visual representation. BYOL showed that negative pairs might not be necessary at all. DINO extended the ideas to Vision Transformers. MAE challenged the entire augmentation-heavy paradigm by returning to reconstruction. DINOv2 demonstrated that discriminative self-supervised pretraining at scale could match or exceed supervised baselines on a wide range of benchmarks.</p><p>But SimCLR’s lasting contribution is its clarity. By systematically ablating each component of the framework, it transformed a collection of intuitions into a set of empirically grounded principles. It showed that augmentation design is a form of prior knowledge encoding, that representation and contrastive space should be separated by a learned buffer, that cross-entropy over many negatives is a principled and efficient objective, and that scale is not a hyperparameter to be minimized but a genuine requirement of the problem.</p><p>These principles did not become obsolete when newer methods arrived. They became the foundation on which those methods were built — and the lens through which their innovations can be understood.</p><p>Learning to see, it turns out, is less about the architecture and more about the questions you ask. SimCLR asked the right ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ced26de50727" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Seeing in Sequences: How a Simple Idea Rewired Computer Vision]]></title>
            <link>https://vnaghshin.medium.com/seeing-in-sequences-how-a-simple-idea-rewired-computer-vision-13b3b71a75b8?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/13b3b71a75b8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[computer-vision]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 06:45:28 GMT</pubDate>
            <atom:updated>2026-10-23T06:45:28.224Z</atom:updated>
            <content:encoded><![CDATA[<p>There is a particular kind of scientific paper that does not invent something entirely new so much as ask a question nobody thought to ask seriously. The Vision Transformer — ViT, as it is now universally known — is that kind of paper. Its central question is almost embarrassingly simple: <em>what happens if you take the Transformer architecture, change almost nothing, and point it at images?</em></p><p>The answer, it turns out, is that it works. Remarkably well. And that fact alone was enough to unsettle a decade of assumptions about how computer vision should be done.</p><p>You can find the basic implementation of the ViT <a href="https://github.com/vahidNaghshin/ViT_AN_IMAGE_IS_WORTH_16X16_WORDS.git">here</a>.</p><h3>The Architecture That Ate NLP</h3><p>To appreciate what ViT did, you need to understand what it was working against — and what it borrowed from.</p><p>In 2017, Vaswani and colleagues published “Attention Is All You Need,” introducing the Transformer architecture for sequence-to-sequence tasks in natural language processing. The paper’s title was a provocation: recurrent networks, which had dominated NLP for years, were not just being improved upon — they were being declared unnecessary. The Transformer replaced sequential processing with a single, elegant operation called self-attention, and it did so in a way that could be parallelized across entire sequences simultaneously.</p><p>The core idea is worth understanding precisely, because ViT inherits it wholesale. Given a sequence of tokens — words, subwords, or anything you can represent as a vector — self-attention asks each token three questions simultaneously: <em>What am I looking for? </em>(the Query), <em>What do I contain?</em> (the Key), and <em>What do I give if attended to?</em> (the Value). For each token, the model computes a similarity score against every other token’s Key, converts those scores into a probability distribution via softmax, and uses that distribution to take a weighted sum of all Value vectors. The result is a new representation for each token — one that has been enriched by information from every other position in the sequence.</p><p>Mathematically, this is:</p><p><strong>Attention(Q, K, V) = softmax(QKᵀ / √d_k) · V</strong></p><p>The scaling factor √d_k prevents the dot products from growing so large that the softmax saturates. Multi-head attention runs this operation in parallel across several learned subspaces, then concatenates the results — allowing different heads to specialize in different types of relationships.</p><p>What makes this architecture so powerful is its clean separation of responsibilities. Attention is the communication step: tokens exchange information across the entire sequence. The feed-forward network that follows each attention layer is the computation step: each token independently processes what it collected, using the same weights applied to every position. All cross-token interaction in a Transformer happens exclusively through attention. Everything else — the feed-forward layers, the layer normalization, the residual connections — treats each token as an isolated vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8WUkU1GUy6thyV_432oLVw.jpeg" /></figure><p>By 2020, this architecture had become the dominant paradigm in NLP. BERT used the encoder to build rich contextual representations of text. GPT used the decoder to generate language. Both relied on the same pre-train-then-fine-tune recipe: train on a massive corpus with a self-supervised objective, then adapt the learned weights to a specific downstream task by replacing only the final classification layer. The weights of the attention and feed-forward layers — where the model’s general understanding of language lived — transferred remarkably well across tasks.</p><p><strong><em>Computer vision, meanwhile, was doing something different.</em></strong></p><h3>The CNN Orthodoxy</h3><p>Since AlexNet’s decisive victory at ImageNet in 2012, convolutional neural networks had been the unquestioned foundation of computer vision. CNNs are built around a powerful set of assumptions about images: that meaningful patterns are local (edges, textures, and shapes are defined by nearby pixels), that these patterns can appear anywhere in the image (translation equivariance), and that complex visual concepts are built hierarchically from simpler ones (edges compose into textures, textures into parts, parts into objects).</p><p>These assumptions are not wrong. They are, in fact, excellent descriptions of how natural images work. And that is precisely the point. By encoding these assumptions directly into the architecture — through local convolutional kernels, weight sharing, and pooling — CNNs gave themselves a significant head start. They did not need to learn that local structure matters; they were built to exploit it.</p><p>The question Dosovitskiy and colleagues asked, implicitly, was whether this head start was a gift or a constraint. What if a model with no such assumptions, given enough data, could learn richer representations than one whose inductive biases had been chosen in advance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OI0CuMIQbptDw0Mk7ZiZ2g.jpeg" /></figure><h3>Patches Are All You Need</h3><p>The practical obstacle to applying Transformers to images is not conceptual — it is computational. Self-attention computes a similarity score between every pair of tokens, producing an N×N attention matrix. For a sequence of 512 words, that is 262,144 entries. For a 224×224 image treated as individual pixels, that is over 2.5 billion. The quadratic scaling of attention with sequence length makes pixel-level processing infeasible.</p><p>ViT’s solution is elegant in its simplicity: do not use pixels as tokens. Use patches.</p><p>Divide the image into a grid of non-overlapping P×P patches. For a 224×224 image with P=16, this yields N = (224×224)/(16×16) = 196 patches. Each patch is a 16×16×3 cube of pixel values, which is flattened into a vector of length 768. That vector is then projected to the model’s working dimension <em>d</em> via a single learned linear transformation — not a multi-layer network, just one matrix multiplication. The result is a sequence of 196 <em>d</em>-dimensional vectors: the image, expressed as a sequence.</p><p>This is the paper’s central act of translation. An image becomes a sentence. Patches become words. The spatial grid becomes a sequence. And the Transformer, which was built to read sentences, can now read images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ETkVRCi6QrHlCmiRAjYxPQ.jpeg" /></figure><p>There are several details here worth pausing on, because each one is a deliberate design choice rather than an accident.</p><p>The linear projection is intentionally minimal. One might expect a convolutional feature extractor here — a few CNN layers to build up patch representations before handing them to the Transformer. The paper tried this (calling it a “hybrid” architecture) and found it helped slightly on small datasets but became unnecessary at scale. The plain linear projection forces the Transformer to learn low-level visual features from scratch, which it does, given enough data.</p><p>The positional embeddings are learned, not fixed. The original Transformer used sinusoidal encodings derived from a fixed formula. ViT instead assigns each of the 196 positions (plus the [<strong>CLS</strong>] token) a learnable vector of dimension <em>d</em>, trained alongside everything else. The paper experimented with 2D positional encodings that separately encode row and column position, but found that 1D learned embeddings worked nearly as well. When you visualize the similarity structure of the learned positional embeddings, you find that the model has discovered the 2D grid structure on its own — nearby patches have similar positional embeddings, and the row-column structure emerges without being explicitly enforced.</p><p>The [CLS] token is borrowed directly from BERT. It is a learnable d-dimensional vector prepended to the sequence, with no connection to any image patch. Its purpose is to serve as a global summary: by attending to all patch tokens across all layers, it accumulates a representation of the entire image. After the final Transformer block, only this token’s representation is passed to the classification head. The rest of the patch tokens — 196 of them — are discarded at inference time for classification tasks, though they become valuable for dense prediction tasks like segmentation.</p><h3>What the Model Actually Learns</h3><p>Understanding what ViT learns during pre-training is essential to understanding why it transfers so well to new tasks.</p><p>The naive answer is that it learns to classify images. That is true but almost entirely useless as a description. The classification head — the final MLP that maps the [CLS] token to class logits — is discarded when fine-tuning on a new task. What transfers is everything else: the patch projection matrix, the positional embeddings, and most importantly, the attention and feed-forward weights across all L Transformer blocks.</p><p>Think of the Transformer blocks as performing two alternating operations. Attention is the communication step: each token collects information from every other token, weighted by relevance. The feed-forward network is the computation step: each token independently processes what it collected, using the same weights applied identically to every position. These two operations build progressively richer representations across layers.</p><p>In early layers, attention heads tend to behave like local feature detectors — attending to nearby patches, learning edge orientations, color gradients, and texture patterns. This is the same kind of knowledge that lives in the early convolutional layers of a ResNet, except that ViT learned it from data rather than having it architecturally enforced. In middle layers, attention becomes more structured: some heads learn to attend along rows or columns, others learn to group patches by texture or color similarity. In later layers, attention becomes predominantly global and semantic — heads learn to separate foreground from background, identify object boundaries, and group patches that belong to the same visual concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G_1EZLwUV0fAUEb5NPrRPg.jpeg" /><figcaption>Representative examples of attention from the output token to the input space</figcaption></figure><p>The feed-forward layers store something different. Recent interpretability research suggests that the MLP weights function as a kind of key-value memory: the first linear layer acts as a pattern detector (does this token’s representation match a learned concept?), and the second layer retrieves an associated value (if so, add this information to the representation). This is where semantic and factual knowledge gets encoded — not in the attention weights, but in the MLP weights that process each token after attention has done its communication work.</p><p>What transfers when you fine-tune ViT on a new task, then, is not knowledge about specific ImageNet classes. It is a learned procedure for reading images: how to embed raw patches into meaningful vectors, how patches relate to each other spatially and semantically, and how to transform those contextual representations into abstract, task-useful embeddings. The classification task during pre-training was never the goal — it was the pressure that forced the model to develop this general visual understanding.</p><h3>The Inductive Bias Argument</h3><p>The most intellectually interesting claim in the ViT paper is not about accuracy numbers. It is about what those numbers reveal.</p><p>CNNs have strong inductive biases: locality (convolution kernels operate on small neighborhoods), translation equivariance (shifting the input shifts the output correspondingly), and hierarchical composition (stacking layers builds features from simple to complex). These biases are excellent for natural images. They are also constraints — they limit what the model can represent and how it must represent it.</p><p>ViT has almost none of these biases. The only image-specific structure in the architecture is the fact that patches are extracted from a 2D grid. Everything else — spatial relationships, local structure, hierarchical composition — must be learned from data.</p><p>The paper’s empirical finding is clean and striking:</p><p>On small datasets (ImageNet, 1.3 million images), CNNs outperform ViT. The inductive biases act as a form of regularization, helping the model generalize when data is scarce. ViT, without these biases, must learn spatial structure from scratch and does not have enough examples to do so reliably.</p><p>On medium datasets (ImageNet-21k, 14 million images), the two approaches perform comparably. The gap is closing.</p><p>On large datasets (JFT-300M, 300 million images), ViT outperforms CNNs — and does so while using fewer computational resources at inference time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WxYPzhw3D9FdJHD7K3GeZg.jpeg" /></figure><p>The interpretation is important to state carefully. CNNs’ inductive biases are not wrong — they are genuinely useful properties of natural images. But they are useful in the way that regularization is useful: they help when you do not have enough data to learn the underlying structure from scratch. Given sufficient data, a model without those constraints can learn the same structure and then go further, discovering relationships that a convolutional architecture is structurally prevented from representing.</p><p>This is a broader lesson about architectural design. Inductive biases are a trade-off between data efficiency and expressive capacity. The right choice depends on how much data you have — and in the era of large-scale pre-training, the answer increasingly favors capacity over efficiency.</p><h3>The Architecture in Full</h3><p>With the conceptual foundations in place, the full ViT architecture can be stated precisely.</p><p>The input image of shape H×W×C is divided into N = HW/P² patches, each of shape P×P×C. Each patch is flattened to a vector of length P²C and projected to dimension <em>d</em> via a learned linear transformation. A learned [CLS] token of dimension <em>d</em> is prepended to the sequence, and learned positional embeddings of dimension <em>d</em> are added to all <em>N+1</em> vectors. The result is a sequence of <em>N+1</em> <em>d</em>-dimensional vectors.</p><p>This sequence passes through L identical Transformer encoder blocks. Each block applies layer normalization before (not after) the attention and feed-forward operations — a pre-norm design that improves training stability compared to the post-norm used in the original Transformer. The feed-forward network expands the dimension from <em>d</em> to <em>4d</em>, applies a GELU activation (smoother than the ReLU used in the original Transformer), and projects back to <em>d</em>. Residual connections wrap both the attention and feed-forward sub-layers.</p><p>After the final block, the [CLS] token’s representation is extracted and passed to a classification head. During pre-training, this head is a two-layer MLP with a tanh activation. During fine-tuning, it is replaced with a single linear layer.</p><p>Patch size is appended as a suffix: ViT-B/16 denotes ViT-Base with 16×16 patches. Smaller patches produce longer sequences and higher accuracy at greater computational cost.</p><p>One practical detail deserves mention: fine-tuning at higher resolution than pre-training. When the input resolution increases from 224 to 384 pixels with P=16, the number of patches grows from 196 to 576. The pre-trained positional embeddings, which were learned for 196 positions, do not cover the new positions. ViT handles this by reshaping the 1D positional embeddings into a 2D grid and performing bicubic interpolation to the new grid size. This works surprisingly well and is an important practical contribution of the paper.</p><h3>What ViT Did Not Do</h3><p>Intellectual honesty requires acknowledging what the paper does not claim and what it does not solve.</p><p>ViT was not the first Transformer applied to images. Earlier work, including the iGPT paper, had applied Transformers to pixel sequences, but with heavy modifications and limited scalability. ViT’s contribution was showing that a minimally modified Transformer encoder, applied to patch sequences, could match or exceed CNNs at scale — and making the case clearly enough that the community took notice.</p><p>ViT did not demonstrate self-supervised learning for images. The pre-training in the paper is fully supervised, using labeled datasets of up to 300 million images. The self-supervised extensions — DINO, MAE, and their successors — came later and built on ViT’s architecture. They are important developments, but they are not this paper.</p><p>ViT does not handle dense prediction tasks (detection, segmentation) as naturally as classification. The architecture produces a flat sequence of patch representations with no inherent hierarchy or multi-scale structure. CNNs, with their pyramid of feature maps at different resolutions, have a natural advantage for tasks that require spatial precision. The Swin Transformer (2021) addressed this by introducing hierarchical ViT variants, and it became the dominant backbone for dense prediction tasks.</p><p>And ViT requires massive labeled datasets to reach its full potential. On ImageNet alone, it underperforms well-tuned CNNs. The DeiT paper (Touvron et al., 2020) showed that careful training recipes — data augmentation, knowledge distillation, and regularization — could close much of this gap without additional pre-training data. But the fundamental data hunger of the plain ViT remains a real constraint.</p><h3>Why It Matters</h3><p>The significance of ViT is not that it achieved state-of-the-art accuracy on ImageNet. Accuracy records are broken regularly, and the specific numbers in a 2021 paper are already historical artifacts.</p><p>The significance is what it demonstrated about the relationship between architecture and data. For a decade, the field had operated on the assumption that domain-specific inductive biases were necessary for good performance — that vision required convolutions, that language required recurrence, that each modality needed its own architectural vocabulary. ViT showed that a single, general-purpose architecture could work across modalities given sufficient data and scale.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FvZz2h6OEQAXuPc1iffWgQ.jpeg" /></figure><p>This unification has had consequences that extend well beyond image classification. CLIP showed that a Transformer trained on image-text pairs could learn visual representations without any labeled images at all. Stable Diffusion and its successors use Transformer-based architectures to generate images from text. Large multimodal models process images and language through shared architectural components. None of this was inevitable — but ViT made it feel natural.</p><p>The paper’s title, borrowed from the adage that a picture is worth a thousand words, is a small joke about what it actually does: it turns pictures into words, or at least into the kind of sequence that a word-processing architecture can understand. It is a modest reframing that turned out to have immodest consequences.</p><h3>A Note on What Transfers</h3><p>One question worth sitting with, as a practitioner, is what it means for a model to “understand” an image.</p><p>When ViT is pre-trained on JFT-300M and fine-tuned on a medical imaging dataset with a few thousand labeled examples, the fine-tuning is not teaching the model to see. The model already knows how to see — it learned that from 300 million images. What fine-tuning teaches it is what to look for: which visual patterns, in this new context, correspond to which clinical categories.</p><p>The attention and feed-forward weights, trained through the pressure of classifying millions of images correctly, have learned a general visual language: how patches relate spatially, how local textures compose into global structures, how to separate signal from background. This learned procedure transfers because visual understanding is, to a surprising degree, domain-general. Edges, textures, shapes, and spatial relationships are properties of all natural images, not just ImageNet photographs.</p><p>This is perhaps the deepest insight the paper offers — not as an explicit claim, but as an implication of its results. The inductive biases that CNNs encode architecturally are not special properties of vision that must be hard-coded. They are properties of images that a sufficiently capable model, trained on sufficient data, will discover on its own. The architecture does not need to know that images are 2D, that nearby pixels are correlated, or that objects can appear anywhere in a scene. Given enough examples, it will figure all of this out.</p><p>Whether that is reassuring or unsettling probably depends on how much you enjoyed designing convolutional architectures.</p><h3>References</h3><p>Dosovitskiy, A., Beyer, L., Kolesnikov, A., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., &amp; Houlsby, N. (2021). An image is worth 16×16 words: Transformers for image recognition at scale. <em>International Conference on Learning Representations (ICLR 2021)</em>. arXiv:2010.11929.</p><p>Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, Ł., &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in Neural Information Processing Systems (NeurIPS 2017)</em>.</p><p>Devlin, J., Chang, M. W., Lee, K., &amp; Toutanova, K. (2018). BERT: Pre-training of deep bidirectional transformers for language understanding. arXiv:1810.04805.</p><p>Touvron, H., Cord, M., Douze, M., Massa, F., Sablayrolles, A., &amp; Jégou, H. (2020). Training data-efficient image transformers and distillation through attention. arXiv:2012.12877.</p><p>Liu, Z., Lin, Y., Cao, Y., Hu, H., Wei, Y., Zhang, Z., Lin, S., &amp; Guo, B. (2021). Swin Transformer: Hierarchical vision transformer using shifted windows. arXiv:2103.14030.</p><p>Caron, M., Touvron, H., Misra, I., Jégou, H., Mairal, J., Bojanowski, P., &amp; Joulin, A. (2021). Emerging properties in self-supervised vision transformers (DINO). arXiv:2104.14294.</p><p>He, K., Chen, X., Xie, S., Li, Y., Dollár, P., &amp; Girshick, R. (2021). Masked autoencoders are scalable vision learners. arXiv:2111.06377.</p><p>Geva, M., Schuster, R., Berant, J., &amp; Levy, O. (2021). Transformer feed-forward layers are key-value memories. arXiv:2012.14913.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13b3b71a75b8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Architecture of Understanding: How Transformers Learn to See]]></title>
            <link>https://vnaghshin.medium.com/the-architecture-of-understanding-how-transformers-learn-to-see-654dfaa94234?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/654dfaa94234</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[visual-language-model]]></category>
            <category><![CDATA[attention-mechanism]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 21:36:28 GMT</pubDate>
            <atom:updated>2026-10-19T21:36:28.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why the attention mechanism is not just a clever trick — it is a fundamentally different way of thinking about what a neural network should do</h3><p>There is a question that sits quietly beneath most of modern deep learning, rarely asked directly but always present: what does it mean for a model to <em>understand</em> its input? Not to classify it, not to compress it, but to genuinely represent the relationships within it. The transformer architecture, originally designed for language and later extended to vision with remarkable success, offers one of the most compelling answers to that question — and the answer turns out to hinge on a surprisingly simple idea about how information should be organized and retrieved.</p><p>To appreciate why that idea matters, it helps to start not with attention, but with the problem that makes attention necessary.</p><h3>An Image Is a Bad Representation of Itself</h3><p>When you look at a photograph of an impala standing in tall grass, you immediately know what you are looking at. You also know, without effort, that the animal is brown, that it is probably in Africa, and that the grass in the foreground is slightly out of focus. None of this knowledge lives in the raw pixel values. It has to be constructed — assembled from local features, spatial relationships, and prior experience.</p><p>Raw pixels are a poor representation for almost any task that requires reasoning. They encode everything with equal weight: the impala, the grass, the sky, the compression artifacts. A model that operates directly on pixels must somehow learn to separate the meaningful from the incidental, the global from the local, the object from its context.</p><p>The Vision Transformer (ViT), introduced by Dosovitskiy et al. in 2021, takes a disarmingly direct approach to this problem. Rather than processing an image through a hierarchy of convolutional filters, it divides the image into a grid of fixed-size patches — typically 16×16 pixels — and treats each patch as a token, in direct analogy with words in a sentence. Each patch is flattened into a vector and passed through a learned linear projection <em>W_</em>tokenize​ that maps it into a d<em>d</em>-dimensional embedding space:</p><p><strong>z_</strong><em>i </em>​= <em>W_</em>tokenize ​⋅ vec(patch_<em>i</em>​)</p><p>This projection is the same matrix applied to every patch. It is not a convolutional filter sliding across space — it is a single learned transformation that asks, of every patch equally: <em>what is the most useful d-dimensional summary of your content? </em>The diversity of the resulting token representations comes entirely from the diversity of the patches themselves, not from position-specific weights.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RoVJoMkeYXI378H2OIoZ9g.jpeg" /></figure><p>This is already a non-trivial design choice. A 1×1 convolution with d filters does exactly the same thing — it applies a shared linear transformation across all spatial locations, mixing information across channels without any spatial aggregation. The connection is not merely analogical: the two operations are mathematically identical when the input has one spatial dimension per token. What ViT adds is the subsequent mechanism that allows tokens to communicate — and that mechanism is attention.</p><h3>The Retrieval Problem at the Heart of Attention</h3><p>Once you have a set of tokens, the question becomes: how should they influence each other? A convolutional network answers this question with locality — nearby pixels interact, distant ones do not, at least not directly. A transformer answers it differently: every token can interact with every other token, but the <em>strength</em> of that interaction is learned dynamically from the content of the tokens themselves.</p><p>This is the core intuition behind self-attention, and it is worth pausing on the word <em>dynamically</em>. A convolutional filter applies the same spatial pattern regardless of what the image contains. Attention computes different interaction weights for every input. Ask the model “how many heads are in this picture?” and attention will distribute itself differently than if you ask “what colour is the impala?” — even though the underlying network weights are identical. The behavior adapts to the query.</p><p>To make this work, the transformer introduces three projections of each token: a query Q, a key K, and a value V. All three are derived from the same token through learned linear transformations:</p><p>Q=W_q⋅z</p><p>K=W_k⋅z</p><p>V=W_v⋅z</p><p>The attention output for a given query is then:</p><p>Attention(Q,K,V) = <em>softmax</em> ⁣(Q.K^T/ sqrt(d_k)) . V</p><p>where K^T is transpose of matrix K. The mechanics are straightforward. The less obvious question is: <strong><em>why three separate projections? Why not compare the query directly to the values and use those scores to weight the values themselves?</em></strong></p><h3>Why Keys Exist: The Disentanglement Argument</h3><p>This question has a satisfying answer that reveals something important about the design philosophy of the transformer.</p><p>If you use values directly for matching — computing scores as <em>Q</em>⋅<em>V</em> and then weighting <em>V</em> by those scores — you force the value representation to serve two conflicting purposes simultaneously. It must be <em>matchable</em> (easy to align with diverse queries) and <em>informative</em> (rich enough to contribute useful content to the output). These objectives pull in opposite directions during training, and the gradient signals from each will interfere with the other.</p><p>The key projection resolves this tension by disentanglement. A token now has two faces: its key, which is optimized to be <em>found</em> by the right queries, and its value, which is optimized to <em>carry</em> the right information once found. The same patch of brown fur presents itself differently depending on whether it is being asked “are you relevant to a colour query?” (key) or “what do you actually contain?” (value).</p><p>There is a deeper way to think about this, which emerged naturally in developing the intuition for this article. Queries are diverse — they span semantic, spatial, relational, and task-specific dimensions. No single representation of a token can be simultaneously well-aligned with all possible queries while also preserving its full informational content. The key projection is specifically learned to <em>cover the diversity of the query space</em>: to present each token in a form that makes it findable from any direction a query might approach. The value projection is free to do something else entirely — to organize content for downstream use.</p><p>This is not merely a theoretical nicety. It is the reason attention is expressive enough to support the range of tasks transformers are asked to perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcludh5UBzxh09oKY2Aviw.jpeg" /></figure><h3>Multi-Head Attention: Diversity by Encouragement, Not Guarantee</h3><p>The transformer does not run attention once. It runs it several times in parallel, each instance operating on a different learned projection of the tokens. This is multi-head attention, and the standard motivation — that different heads capture different relationships — is correct but incomplete.</p><p>Nothing in the architecture <em>guarantees</em> that heads will specialize. Each head has independent weight matrices, initialized randomly and trained independently, which creates favorable conditions for divergence. If two heads converge to identical representations, the concatenated output is redundant, and the network wastes capacity it could use to reduce loss further. This creates an implicit gradient pressure toward differentiation — but implicit pressure is not a formal constraint.</p><p>Empirical work has confirmed both the promise and the limitation of this design. Attention heads in trained transformers do exhibit interpretable specialization: some attend to local spatial structure, others to global composition, others to semantic similarity between distant patches. But pruning studies have also shown that many heads can be removed with minimal performance loss, suggesting that redundancy is common and diversification is incomplete.</p><p>This is not a flaw so much as an honest reflection of how neural networks learn: through optimization pressure, not architectural mandate. The heads that survive pruning are the ones that found something genuinely useful to attend to. The rest are a tax on capacity — and a reminder that expressiveness and efficiency are not the same thing.</p><h3>Weight Sharing: The Unsung Principle</h3><p>There is a structural feature of both the tokenization step and the Q, K, V projections that deserves more attention than it typically receives: the same weight matrix is applied to every token.</p><p>This is weight sharing, and it has consequences that go beyond parameter efficiency. When <em>W_k</em>​ is shared across all tokens, it encodes a <em>universal rule</em> for how any token should present itself as a key — a rule that must generalize across every patch in every image the model has seen. The diversity of key representations across tokens comes entirely from the diversity of token content, not from position-specific parameters.</p><p>The connection to convolutional networks is exact. A 1×1 convolution with <em>d</em> filters applies a shared linear transformation across all spatial locations, mixing channel information without spatial aggregation. The linear projection in attention does the same thing across tokens. Both operations are instances of the same mathematical structure: a shared matrix multiplication applied uniformly, where spatial or sequential variation in the output reflects variation in the input alone.</p><p>This connection matters because it clarifies what transformers and CNNs share and where they diverge. Both use weight sharing to achieve generalization across positions. CNNs additionally exploit locality and translation equivariance as inductive biases — assumptions baked into the architecture that reduce the amount of data needed to learn spatial structure. Transformers make no such assumptions. Every spatial relationship must be learned from data, which makes transformers more flexible and more data-hungry in roughly equal measure.</p><h3>Causal Attention: When the Future Must Not Speak to the Past</h3><p>In generative settings — language models, autoregressive image generation, sequence prediction — the transformer faces an additional constraint: a token representing position <em>n</em> must not have access to tokens at positions <em>n</em>+1 and beyond. This is the causal requirement, and satisfying it requires more care than simply masking the attention matrix.</p><p>Consider what happens across layers. At the first layer, the input tokens are raw: token <em>t_n^</em>0​ contains no information about any other token. To ensure that the output <em>t_n^</em>1​ depends only on tokens strictly before position <em>n</em>, the attention at layer one must exclude <em>t_n^</em>0​ from its own computation — a <em>shift</em> that prevents each token from attending to itself at the input layer.</p><p>After the first layer, the causal structure is embedded in the representations themselves. Token <em>t_</em>2^1​ already contains only information derived from {<em>t_</em>1^0​}; token <em>t_</em>3^1​ contains only information from {t_1^0, t_2^0}. A subsequent layer can safely allow <em>t_</em>3^2​ to attend to <em>t_</em>2^1​ without violating causality, because <em>t_</em>2^1​ is already causally clean. The shift is only needed once — at the boundary between raw inputs and learned representations.</p><p>What must be applied at every layer, however, is the causal <em>mask</em> — the upper-triangular zeroing of attention scores that prevents any token from directly attending to future tokens within that layer. The mask enforces the constraint locally; the propagation of causal structure through representations handles the rest. These are distinct mechanisms serving complementary roles, and conflating them leads to subtle errors in implementation.</p><p>The payoff of this design is a property that is easy to overlook: the subnetworks that predict each successive output token overlap substantially. Predicting token <em>n</em> requires processing tokens 1 through <em>n</em>−1; predicting token <em>n</em>+1 requires processing tokens 1 through <em>n</em> — which includes all the computation already performed for token <em>n</em>. The transformer solves <em>N</em> prediction problems simultaneously, with each problem sharing the bulk of its computation with all smaller problems. This is not merely efficient. It means that every prediction problem regularizes every other, and the representations learned to support one prediction are continuously refined by the demands of all the others.</p><h3>What the Architecture Is Really Doing</h3><p>Step back from the individual components and a coherent picture emerges. The transformer is a machine for learning <em>which relationships matter</em> — not by assuming locality or hierarchy, but by learning, from data, which tokens should influence which other tokens and how strongly.</p><p>The tokenization step converts raw inputs into a form where content can be compared. The Q, K, V projections disentangle the roles of searching, being found, and contributing information. Weight sharing ensures that the rules governing these roles generalize across all positions. Multi-head attention allows multiple relationship types to be tracked simultaneously. And causal masking, where required, ensures that the flow of information respects the temporal structure of the task.</p><p>None of these components is independently novel. Linear projections, dot-product similarity, softmax normalization, weight sharing — these are standard tools. What the transformer does is assemble them into an architecture where the <em>interaction structure</em> of the input is itself a learned quantity, shaped by the task and the data rather than fixed by the designer.</p><p>That is the deeper lesson of the architecture. A convolutional network encodes a prior belief about images: that nearby pixels are more likely to be related than distant ones. A transformer encodes no such belief. It asks the data to reveal which relationships matter — and it provides a mechanism expressive enough to represent almost any answer.</p><p>Whether that flexibility is a virtue or a liability depends on how much data you have and what you are trying to learn. For large-scale vision tasks, the ViT results suggest that the flexibility wins. For tasks where spatial locality is genuinely the right inductive bias, a convolutional architecture may still be the better choice. The interesting question — still actively debated — is not which architecture is correct, but what the right prior is for a given problem, and how much of that prior should be built in versus learned.</p><h3>A More Useful Way to Think About Representations</h3><p>The attention mechanism is sometimes described as allowing tokens to “communicate” with each other, which is true but undersells the point. What attention really does is allow each token to <em>revise its own representation</em> in light of the global context — to ask, at every layer, “given everything else in this input, what should I be?”</p><p>By the final layer, a token that began as a flat patch of brown pixels has been repeatedly refined by its interactions with every other token in the image. It knows, in some distributed sense, that it is part of an animal, that the animal is an impala, that the impala is the subject of the image. This knowledge is not stored anywhere explicitly. It is encoded in the geometry of the representation — in the distances and directions that separate this token’s final embedding from all the others.</p><p>That geometry is the product of the learning objective, the architecture, and the data. Change any one of them and you change what the model regards as similar, what it treats as irrelevant, and what relationships it learns to track. The weights are not just parameters — they are a record of what the training process found meaningful.</p><p>Understanding that is, perhaps, the most useful thing a practitioner can take from a careful study of how transformers work. The architecture does not discover truth. It discovers what the task, as defined by the loss function and the training data, rewards attending to. Knowing the difference is what separates a practitioner who uses these models from one who understands them.</p><p><em>The ViT architecture is described in: Dosovitskiy, A., et al. “An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale.” ICLR 2021.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=654dfaa94234" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Teaching Machines What Similarity Means: A 2005 Paper That Helps Explain Representation Learning]]></title>
            <link>https://vnaghshin.medium.com/teaching-machines-what-similarity-means-a-2005-paper-that-helps-explain-representation-learning-5e2e752748bc?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e2e752748bc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Thu, 15 Oct 2026 01:57:57 GMT</pubDate>
            <atom:updated>2026-10-15T01:57:57.044Z</atom:updated>
            <content:encoded><![CDATA[<p>What a 2005 face verification paper teaches us about what neural networks learn to care about</p><h3>A Problem More Interesting Than Classification</h3><p>You can find the model implementation <a href="https://github.com/vahidNaghshin/Chopra_2005.git">here</a></p><p>Here is a deceptively simple question: <strong>given two photographs, do they show the same person</strong>?</p><p>Notice what makes this hard. You are not being asked to name the person. You are not being asked to assign either image to a category. You are being asked to compare — to decide whether two things, presented together, share something meaningful. The question is relational, not categorical.</p><p>This distinction turns out to matter enormously. Most of the machinery we reach for in machine learning — softmax classifiers, cross-entropy losses, label prediction — is designed to answer a different kind of question: <em>what is this?</em> The face verification problem asks something subtler: <em>are these the same?</em></p><p>Sumit Chopra, Raia Hadsell, and Yann LeCun noticed this distinction in their 2005 paper, “<a href="https://www.cs.utoronto.ca/~hinton/csc2535_06/readings/chopra-05.pdf">Learning a Similarity Metric Discriminatively, with Application to Face Verification</a>,” and built a framework around it. What they produced was not just a face verification system. It was an early, rigorous articulation of what it means to learn a representation through similarity — an idea that would quietly shape a generation of methods in metric learning, self-supervised learning, and beyond.</p><h3>From Raw Inputs to Meaningful Representations</h3><p>Before we can appreciate what Chopra et al. changed, it helps to understand what they were working against.</p><p>A raw image is a grid of pixel intensities. Two photographs of the same person, taken under different lighting, at different angles, with different expressions, may differ dramatically at the pixel level. Meanwhile, two photographs of different people, shot under identical conditions, may look far more similar in raw pixel space than either pair of genuine matches. The input representation is, to put it plainly, the wrong space in which to measure similarity.</p><p>This is the central motivation for representation learning: find a function that maps raw inputs into a new space — an embedding space — where the relationships you care about become easier to measure. A good embedding does not merely compress the input. <strong>It reorganizes it</strong>. It brings together things that are meaningfully similar and pushes apart things that are not, according to whatever notion of similarity the task demands.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aS7xJdPteSivjNSkWdftg.jpeg" /></figure><p>The question, then, is how to learn such a function. And here is where the 2005 paper makes its first important move.</p><h3>What Chopra et al. Changed About the Problem</h3><p>The conventional approach to face recognition at the time was to train a classifier: given an image, predict an identity. This works reasonably well when you have many training examples per identity. But it breaks down the moment you encounter a face the model has never seen — which is, of course, the situation in any real deployment.</p><p>Chopra et al. reframed the problem. Instead of asking the model to classify individual images, they asked it to compare pairs. The model receives two images, X_1 and X_2, and a label Y in {0, 1}, where Y = 0 indicates a genuine pair (same person) and Y = 1 indicates an impostor pair (different people). The task is to learn a function that assigns low energy to genuine pairs and high energy to impostor pairs.</p><p>The architecture they chose to implement this is a Siamese network: two identical copies of a convolutional network G_W, sharing weights, each processing one of the two inputs. The output of each branch is an embedding vector, and the energy of the pair is defined as the distance between them: E_W(X_1, X_2) = | G_W(X_1) — G_W(X_2) |</p><p>Weight sharing is not a cosmetic choice. It enforces a fundamental symmetry: the same transformation is applied to both inputs. If the network learns to map a face under bright lighting to a particular region of embedding space, it must apply the same mapping to a face under dim lighting. The metric is consistent by construction.</p><p>The final verification decision is then a simple threshold: if E_W &lt; t for some learned threshold t, the pair is declared genuine; otherwise, impostor. The hard work — everything that makes this threshold meaningful — is done by G_W.</p><h3>The Mathematics, Made Intuitive</h3><p>The central technical contribution of the paper is the contrastive loss function used to train G_W. It is worth understanding carefully, because its structure encodes a specific and non-obvious set of geometric commitments.</p><p>Let E_W denote the energy of a pair, and let Q be a constant controlling the upper bound of the energy (related to the dynamic range of the network). The loss for a single labeled pair is:</p><p>L(W, Y, X_1, X_2) = (1 — Y) (1/2Q) E_W² + Y 1/2 Q² \exp((-2.77/Q)* E_W)</p><p>Read this in two parts.</p><p>The first term, active when Y = 0 (genuine pairs), is a simple quadratic penalty on energy. If two images show the same person but the network assigns them high energy — places them far apart in embedding space — this term penalizes that directly. The network is pushed to bring genuine pairs together.</p><p>The second term, active when Y = 1 (impostor pairs), works in the opposite direction. It is a decreasing exponential in E_W: when the energy is low (impostor pair placed too close together), the loss is large; as energy increases, the loss decays toward zero. The constant 2.77 is chosen so that the exponential becomes negligible when E_W ~Q, effectively creating a soft margin without a hard cutoff.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oS3fr11Hh4_a3sJKkku8sg.jpeg" /></figure><p>This is worth contrasting with the more familiar hinge-based formulation used in later work (such as Hadsell et al., 2006), where the impostor term takes the form max(0, m — E_W)² for a hard margin m. The hinge formulation produces exactly zero gradient for well-separated impostor pairs. The exponential formulation in the original Chopra paper always provides a gradient signal, however small — a reflection of the energy-based modeling philosophy in which energies are never truly zero, only made very small.</p><p>The geometric effect of training with this loss is that the embedding space develops a structure: a cluster of genuine pairs pulled tight, and impostor pairs pushed outward until the exponential decay makes further separation unrewarding. The network learns to care about exactly the differences that distinguish genuine pairs from impostors — and to discard everything else.</p><h3>Learning a Geometry Is Learning What Matters</h3><p>This last point deserves to be stated plainly, because it is the conceptual heart of the paper.</p><p>When you train a classifier, the network learns to assign labels. The internal representations it develops are instrumental — they exist to support the final prediction, but the training objective says nothing directly about how examples should relate to one another in representation space. Two images of the same person might end up anywhere in the feature space, as long as both are correctly classified.</p><p>When you train with a contrastive objective, you are doing something different. You are directly shaping the geometry of the embedding space. You are specifying which pairs should be close and which should be far, and the network must find a transformation G_W that satisfies those constraints across the entire training set simultaneously.</p><p>This means the training signal determines what the model learns to regard as meaningful. If your genuine pairs are defined by identity (same person), the network learns to discount lighting, pose, and expression — because those vary within genuine pairs — and to preserve identity-relevant structure, because that is what distinguishes genuine pairs from impostors. <strong>Change the definition of genuine pairs, and you change what the network learns to care about.</strong></p><p>This insight emerged naturally in our discussion of how the labeling scheme shapes the learned representation. Consider a simpler scenario: you want to build a model that recognizes whether two images both contain a cat. Label pairs of cat images as genuine (Y = 0) and pairs of non-cat images as impostor (Y = 1). The network will learn an embedding in which cat images cluster together — not because you told it what a cat looks like, but because the geometry required by your labels forces it to discover that structure. The model learns what matters from the relational signal you provide, not from explicit feature engineering.</p><p>This is a powerful and somewhat underappreciated point. The representation is not a neutral summary of the input. It is a geometric argument about what differences matter.</p><h3>A Note on Local Invariance</h3><p>There is a further geometric subtlety worth examining. Classical approaches to similarity — tangent distance, for instance — addressed the problem of transformation invariance directly. You specify a set of transformations (rotation, translation, scaling), derive the manifold swept by those transformations in input space, and define a metric that measures distance between manifolds rather than between points. The metric is invariant to the specified transformations by analytic construction.</p><p>Chopra’s approach is different in an important way. You still specify what counts as a genuine pair — and in doing so, you implicitly specify which transformations should be discounted. But the invariance is not derived analytically. It is learned. The network discovers, through gradient descent on the contrastive loss, a representation that is approximately invariant to whatever variation exists within genuine pairs in your training data.</p><p>This distinction has practical consequences. The classical approach gives you hard, provable invariance to the transformations you specify, but it cannot generalize beyond them. The learned approach gives you soft, empirical invariance to whatever variation your training data contains — which may generalize more broadly, but depends entirely on the quality and diversity of your training pairs.</p><p>Neither approach is strictly superior. They encode different assumptions about what you know in advance and what you are willing to learn from data.</p><h3>From a 2005 Paper to Modern Representation Learning</h3><blockquote>It would be easy, and misleading, to read Chopra et al. (2005) as a primitive ancestor of <a href="https://arxiv.org/abs/2002.05709">SimCLR</a> or <a href="https://arxiv.org/abs/1911.05722">MoCo</a>. The conceptual lineage is real, but the differences matter.</blockquote><p>The most important difference is the source of the training signal. Chopra et al. use supervised pairwise labels: genuine and impostor pairs are defined by human-annotated identity. Modern self-supervised contrastive methods — SimCLR (Chen et al., 2020) being the canonical example — construct positive pairs automatically, typically by applying two random augmentations to the same image. The model is never given explicit identity labels. It learns a representation by being told, implicitly, that an image and its augmented version should be similar.</p><p>This shift from supervised to self-supervised training is significant, but it does not change the underlying logic. In both cases, the training signal is relational. In both cases, the geometry of the embedding space is shaped by the definition of similarity encoded in the training pairs. In both cases, what the model learns to regard as meaningful is determined by which pairs are called genuine.</p><p>What Chopra et al. established — and what remains true across the entire family of contrastive methods — is that you can learn powerful representations by specifying similarity relationships rather than category labels. The 2005 paper demonstrated this with a supervised signal and a carefully designed loss. Later work extended the idea by automating the construction of positive pairs and scaling to much larger datasets. The core insight survived the transition.</p><p>The Siamese architecture introduced in the paper also proved durable. The idea of processing two inputs through a shared-weight network and comparing their embeddings appears, in various forms, in metric learning for one-shot classification, in sentence embedding models, and in visual search systems. The architecture is a natural expression of the symmetry requirement: whatever transformation you apply to one input, you apply identically to the other.</p><h3>What the Approach Teaches Us — and What It Does Not</h3><p>The practical power of the Chopra framework becomes clear when you consider its inductive property. Once G_W is trained, it can be applied to any new input — including inputs from identities never seen during training. You embed a query image, search for its nearest neighbors in embedding space, and return the closest matches. The model does not need to be retrained; it simply applies the learned transformation.</p><p>This makes the framework naturally suited to search and retrieval problems. A large database of images can be pre-processed into embeddings offline. At query time, you embed the query and perform approximate nearest-neighbor search — a well-studied computational problem for which efficient solutions exist (FAISS, HNSW, and related methods). The embedding space, shaped by the contrastive objective, does the semantic work; the search index does the computational work.</p><p>This is precisely what modern visual search systems do. The conceptual pipeline — embed, index, retrieve — traces directly back to the kind of learned metric that Chopra et al. were building.</p><p>But the approach has real limitations, and they are worth naming.</p><p><strong>The quality of the learned representation depends entirely on the quality and coverage of the training pairs.</strong> If your genuine pairs do not capture the variation present at test time — different lighting conditions, ages, occlusions — the network will not learn to be invariant to those factors. The representation is only as good as the relational signal you provide.</p><p>The definition of similarity is also task-specific in a way that is easy to underestimate. A representation learned for face verification is not automatically useful for emotion recognition, even though both involve faces. The geometry of the embedding space reflects the particular notion of similarity encoded in the training labels. Repurposing it for a different notion of similarity may require retraining, fine-tuning, or at minimum careful evaluation.</p><p>Finally, the contrastive objective optimizes pairwise relationships, not global structure. The network is trained to order pairs correctly — genuine pairs closer than impostor pairs — but this does not guarantee that the embedding space has any particular global geometry. Clusters may be well-separated or poorly organized in ways that affect downstream tasks.</p><h3>A More Useful Way to Think About Representations</h3><p>Return to the question we started with: given two photographs, do they show the same person?</p><p>What Chopra et al. showed is that answering this question well requires learning a representation in which the answer is geometrically accessible — where same-person pairs are close and different-person pairs are far. And learning such a representation requires a training objective that directly encodes the relational structure you care about.</p><p>This is a more useful way to think about what neural networks learn. A representation is not a neutral compression of the input. It is a geometric argument. It reflects a set of commitments about which differences matter and which do not — commitments that are encoded, often implicitly, in the training objective and the training data.</p><p>The choice of loss function is, in this sense, a choice about what the model should regard as meaningful. Change the loss, and you change the geometry. Change the geometry, and you change what the model knows.</p><p>That is a simple observation, but it has consequences that reach well beyond face verification. Every time we design a training objective — whether contrastive, generative, or discriminative — we are making a decision about what structure we want the model to discover. The 2005 paper by Chopra, Hadsell, and LeCun is a precise, early articulation of that decision, made explicit through the mathematics of pairwise similarity.</p><p>It is worth reading carefully, not because it is the last word on representation learning, but because it is one of the clearest early statements of a question the field is still answering.</p><h3>References</h3><p>· Chopra, S., Hadsell, R., &amp; LeCun, Y. (2005). <em>Learning a Similarity Metric Discriminatively, with Application to Face Verification</em>. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR).</p><p>· Hadsell, R., Chopra, S., &amp; LeCun, Y. (2006). <em>Dimensionality Reduction by Learning an Invariant Mapping</em>. CVPR.</p><p>· Chen, T., Kornblith, S., Norouzi, M., &amp; Hinton, G. (2020). <em>A Simple Framework for Contrastive Learning of Visual Representations</em>. ICML.</p><p>· Koch, G., Zemel, R., &amp; Salakhutdinov, R. (2015). <em>Siamese Neural Networks for One-Shot Image Recognition</em>. ICML Deep Learning Workshop.</p><p>· Simard, P., LeCun, Y., &amp; Denker, J. (1993). <em>Efficient Pattern Recognition Using a New Transformation Distance</em>. NeurIPS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e2e752748bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is Pretraining Dead? The Idea That Refused to Die]]></title>
            <link>https://vnaghshin.medium.com/is-pretraining-dead-the-idea-that-refused-to-die-e3ee27eaf7b4?source=rss-e4d0892f3ac9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3ee27eaf7b4</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[pre-training]]></category>
            <category><![CDATA[foundational-model]]></category>
            <dc:creator><![CDATA[Vahid Naghshin]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 07:18:37 GMT</pubDate>
            <atom:updated>2026-10-13T07:18:37.837Z</atom:updated>
            <content:encoded><![CDATA[<h3>How a technique dismissed by the deep learning revolution became the foundation of modern AI</h3><p>There’s a peculiar pattern in machine learning history: ideas don’t die, they hibernate. Pretraining is perhaps the best example. Declared unnecessary by the ImageNet era, quietly buried under the weight of bigger datasets and better optimizers — and then, almost without warning, resurrected as the foundational principle behind the most powerful AI systems ever built. If you want to understand why GPT-4, CLIP, and Gemini work the way they do, you need to understand pretraining: where it came from, why it was abandoned, and why it came back stronger than ever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*61TQ5m9dYKgE4UTc" /><figcaption>Photo by <a href="https://unsplash.com/@brunovdkraan?utm_source=medium&amp;utm_medium=referral">Bruno van der Kraan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The Origin Story: When Neural Networks Needed a Head Start</h3><p>Cast your mind back to the mid-2000s. Deep neural networks were theoretically appealing but practically frustrating. Training them from scratch was notoriously unstable — gradients vanished, weights converged poorly, and deeper networks often performed <em>worse</em> than shallow ones. The field was stuck.</p><p>Geoffrey Hinton and his collaborators offered a way out. Their insight was elegant: instead of initializing a deep network randomly and hoping gradient descent would find something useful, why not <em>pre-shape</em> the weights using the data itself — without any labels?</p><p>The mechanism was the Restricted Boltzmann Machine (RBM) — an undirected, generative model trained to learn the joint probability distribution of its inputs. Stack several RBMs together, train each layer greedily in an unsupervised fashion, and you get a Deep Belief Network (DBN) whose weights already encode meaningful structure before a single label is seen. Supervised fine-tuning then becomes a refinement, not a cold start.</p><p>This was pretraining in its original form: unsupervised, generative, and motivated by necessity. It worked because it gave the network a sensible initialization — a warm start in a landscape that was otherwise treacherous to navigate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*154cA7IFNCNdXKkePW1tnA.png" /><figcaption>Generated by GPT</figcaption></figure><h3>The Fall: Why Pre-training Was Abandoned</h3><p>Then came 2012. AlexNet. ImageNet. And a result so decisive it restructured the field overnight.</p><p>Krizhevsky, Sutskever, and Hinton trained a deep convolutional network from scratch — no unsupervised pretraining — and crushed the competition on ImageNet by a margin that made the runner-up look like a different era of technology. The message seemed clear: with enough labeled data and the right architecture, you didn’t need pretraining. You could just… train.</p><p>What had changed? Several things converged simultaneously:</p><ul><li>ReLU activations replaced saturating sigmoids, largely solving the vanishing gradient problem that pretraining was designed to work around</li><li>Dropout provided effective regularization without needing unsupervised objectives</li><li>Better weight initialization schemes (Xavier, He) gave random starts that were far more stable</li><li>GPU-scale computation made it feasible to train large supervised models end-to-end</li><li>Large labeled datasets like ImageNet provided enough signal that unsupervised feature learning felt redundant</li></ul><p>The community drew a reasonable conclusion: pretraining had been a workaround for problems that were now solved. Computer vision moved on. For most of the 2010s, the standard recipe was supervised training from scratch, and it worked remarkably well.</p><p>Pretraining wasn’t refuted — it was simply made irrelevant by progress. Or so it seemed.</p><h3>The Revival: Language Changes Everything</h3><p>Here’s the thing about language that makes it fundamentally different from images: labeled data is extraordinarily scarce relative to the raw data available.</p><p>You can label millions of images with reasonable effort. But language understanding requires nuance — sentiment, implication, world knowledge, reasoning — that is almost impossible to annotate at scale. The labeled datasets that NLP researchers worked with in the early 2010s were tiny by modern standards, and models trained on them were brittle and narrow.</p><p>Meanwhile, the internet contained an essentially unlimited supply of <em>unlabeled</em> text. The question was whether you could exploit it.</p><p>The answer arrived in two landmark papers. In 2018, ELMo showed that language model representations pretrained on large text corpora transferred powerfully to downstream tasks. Months later, BERT (Bidirectional Encoder Representations from Transformers) demonstrated that a transformer pretrained with a masked language modeling objective — predict the missing word given its context — could be fine-tuned to achieve state-of-the-art results on nearly every NLP benchmark with relatively little labeled data.</p><p>The pretraining paradigm was back, but transformed. Instead of RBMs and greedy layer-wise training, the new pretraining was:</p><ul><li>Self-supervised rather than purely unsupervised — the labels are derived from the data itself (predict the next word, predict the masked word)</li><li>Transformer-based rather than generative graphical models</li><li>Scaled aggressively — more data, more parameters, more compute</li></ul><p>GPT-1, GPT-2, GPT-3, and eventually GPT-4 pushed this logic to its extreme: pretrain on essentially all available text, and the resulting model develops capabilities that no one explicitly trained it for — translation, arithmetic, coding, reasoning. These emergent capabilities are perhaps the most striking vindication of the pretraining philosophy: learn the structure of the data deeply enough, and task-specific behavior emerges without task-specific training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCJDrJV86jba3qNy4NJSaw.jpeg" /><figcaption>Timeline generated by banana 2</figcaption></figure><h3>The Multimodal Frontier: Pretraining Across Modalities</h3><p>If the NLP revival proved that pretraining scales with data, multimodal models proved that it scales <em>across</em> data types.</p><p>CLIP (Contrastive Language-Image Pretraining, OpenAI 2021) pretrained on 400 million image-text pairs scraped from the internet — no manual labels, just the natural co-occurrence of images and their captions. The result was a visual encoder so general that it transferred to dozens of downstream vision tasks zero-shot, often matching or beating supervised models trained specifically for those tasks.</p><p>Flamingo, GPT-4V, Gemini, and LLaVA extended this further: pretrain a language model, pretrain a vision encoder, then learn to connect them. The pretraining of each component does the heavy lifting; the cross-modal alignment is almost a fine-tuning problem by comparison.</p><p>The underlying logic hasn’t changed since Hinton’s original insight: use the structure in unlabeled data to learn representations that transfer. What has changed is the scale, the architecture, and the sophistication of the self-supervised objectives.</p><h3>So Is Pretraining Dead?</h3><p>The original form — greedy layer-wise training with RBMs — is genuinely obsolete. You won’t find it in production systems today. In that narrow sense, yes, it’s dead.</p><p>But the <em>principle</em> of pretraining is more alive than it has ever been. It underpins every large language model, every multimodal foundation model, and an increasingly large share of computer vision research (MAE, DINO, SimCLR all use self-supervised pretraining). The field didn’t abandon pretraining — it found a dramatically better way to do it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zFhmDen-XtA_7JpJJ5jwVA.jpeg" /></figure><p>The deeper lesson is about what pretraining actually buys you. It’s not just better initialization. It’s the compression of structure — linguistic, visual, conceptual — that exists in the world’s data, distilled into weights that can be repurposed. The reason GPT-4 can reason about a medical image, write poetry, and debug code isn’t because it was trained on those tasks. It’s because pretraining at sufficient scale produces representations rich enough to support almost any downstream use.</p><p>Pretraining didn’t die. It grew up.</p><p><em>If you found this useful, the natural next question is: what are the limits of pretraining? When does more data and more compute stop helping — and what comes after? That’s a conversation for another article. Shoot me an email on vnaghshin@gmail.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3ee27eaf7b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>