Part V · 第 18 章 无监督与自监督学习 · 18.3Part V · Ch. 18 Unsupervised & Self-Supervised Learning · 18.3

对比学习:SimCLR 与 CLIPContrastive Learning: SimCLR & CLIP

不给标签,怎样让网络学会“这是同一个零件”?对比学习的答案是:把同一场景的两个变体拉近,把其他样本推远。这个“在一堆候选里认出自己的搭档”的分类问题叫 InfoNCE,它的温度决定了网络盯着哪些难负样本;数据增广决定了网络要忽略什么;负样本防止所有表示塌缩成一个点。本节在浏览器里现场训练 SimCLR 和一个小 CLIP,再看机器人如何用时间对比学习从视频里学到状态和奖励。 With no labels, how can a network learn that "this is the same part"? Contrastive learning answers: pull two variants of the same scene together and push every other sample away. This "spot your own partner among the candidates" classification problem is called InfoNCE; its temperature decides which hard negatives the network attends to, the data augmentations decide what the network must ignore, and the negatives keep all representations from collapsing onto one point. This lesson trains SimCLR and a small CLIP live in your browser, then shows how robots use time-contrastive learning to get states and rewards out of video.

约 45 分钟~45 min 前置:18.2 自编码器 · 4.11 信息论 · 16.1 softmax 与交叉熵 · 1.7 点积与余弦相似度Prereqs: 18.2 Autoencoders · 4.11 Information theory · 16.1 Softmax & cross-entropy · 1.7 Dot product & cosine similarity 6 个交互6 interactives

    1为什么机器人需要它Why robots need this

    一台装配机器人的腕部相机每秒拍 30 张图,一天就是几百万张。几乎没有一张带标签:没人告诉它“这是 L 形支架”“这时夹爪离目标还有 3 cm”。可下游的一切(抓取、模仿学习、强化学习的奖励)都需要一个好的表示:把图像变成一个向量,向量只记住任务关心的东西(零件是什么、夹爪在哪),而对光照、背景、相机视角这些干扰因素不敏感。

    18.2 节的自编码器靠重建每个像素来学表示,于是它必须把光照、阴影、背景纹理也一并记下:像素里的大部分信息恰恰是干扰。对比学习换了一个问题:不重建,而是比较。给网络一张图的两个变体(换了光照、加了噪声),再混进一堆别的图,让它认出哪两个来自同一个场景。为了认得准,网络必须抓住在变体之间不变、而在不同场景之间不同的东西。哪些东西算“不变”,由你选择的变换决定:这是对比学习最核心、也最容易被忽视的一点。

    把“同一场景的另一个视角”换成“描述这张图的一句话”,就得到 CLIP:图像和文字被映射进同一个空间,机器人可以直接拿“蓝色的 L 形支架”去和相机画面比相似度,连训练时没见过的类别也能认(零样本分类)。把“另一个视角”换成“同一段视频里相邻的时刻”或“另一台相机同一时刻的画面”,就得到 TCN、R3M、VIP 这类机器人视觉表示,甚至可以直接用表示空间里离目标的距离当奖励。

    The wrist camera of an assembly robot takes 30 images a second, millions a day. Almost none carry a label: nobody tells it "this is an L-bracket" or "the gripper is 3 cm from the goal". Yet everything downstream (grasping, imitation learning, rewards for reinforcement learning) needs a good representation: a map from an image to a vector that keeps what the task cares about (which part, where the gripper is) and is insensitive to nuisance factors such as lighting, background and camera viewpoint.

    The autoencoders of Lesson 18.2 learn by reconstructing every pixel, so they must also memorize the lighting, the shadows and the background texture: most of the information in pixels is exactly the nuisance. Contrastive learning asks a different question: not reconstruct, but compare. Give the network two variants of one image (relit, with added noise), mix in a crowd of other images, and ask it to recognize which two come from the same scene. To answer well, the network must capture what stays the same across the variants and differs between scenes. Which things count as "the same" is decided by the transformations you choose: the most central and the most overlooked point of contrastive learning.

    Replace "another view of the same scene" by "a sentence describing the image" and you get CLIP: images and text are mapped into one space, and a robot can compare "blue L-bracket" directly with its camera image, even for categories it never saw during training (zero-shot classification). Replace "another view" by "a nearby moment in the same video" or "another camera at the same instant" and you get robot visual representations such as TCN, R3M and VIP, where even the distance to a goal in representation space can serve as a reward.

    2直觉:在一群候选里认出自己的搭档Intuition: spot your partner in a crowd

    编码器 \(f_\theta\) 把每张图变成一个向量,再归一化到单位球面上:\(\mathbf z=f_\theta(x)/\|f_\theta(x)\|\)。两张图的相似度就是 1.7 节的余弦相似度 \(s=\mathbf z^\top\mathbf z'\in[-1,1]\)。现在拿一个锚点 \(\mathbf z\),它的正样本 \(\hl{pos}{\mathbf z^+}\)(同一场景的另一个变体),以及若干负样本 \(\hl{neg}{\mathbf z^-_j}\)(别的场景)。把每个候选的相似度除以温度 \(\hl{tau}{\tau}\) 当作 logit,做一次 softmax:这就是一个“\(N+1\) 选 1”的分类器,正确答案是正样本。它的交叉熵(16.1 节)就是 InfoNCE 损失:

    The encoder \(f_\theta\) turns each image into a vector and normalizes it onto the unit sphere: \(\mathbf z=f_\theta(x)/\|f_\theta(x)\|\). The similarity of two images is the cosine similarity of Lesson 1.7, \(s=\mathbf z^\top\mathbf z'\in[-1,1]\). Now take an anchor \(\mathbf z\), its positive \(\hl{pos}{\mathbf z^+}\) (another variant of the same scene) and a few negatives \(\hl{neg}{\mathbf z^-_j}\) (other scenes). Divide each candidate's similarity by a temperature \(\hl{tau}{\tau}\), treat it as a logit and take a softmax: this is an "\(N+1\)-way" classifier whose right answer is the positive. Its cross-entropy (Lesson 16.1) is the InfoNCE loss:

    $$ L=-\log\frac{\exp\!\big(\mathbf z^\top\hl{pos}{\mathbf z^+}/\hl{tau}{\tau}\big)}{\exp\!\big(\mathbf z^\top\mathbf z^+/\tau\big)+\sum_{j=1}^{N}\exp\!\big(\mathbf z^\top\hl{neg}{\mathbf z^-_j}/\tau\big)}=-\log p_+ $$

    (本节用 \(\mathbf z\) 表示嵌入向量,logit 写成 \(\ell=s/\tau\),与 16.1 节把 logit 记作 \(z\) 的写法不同。)损失要变小,只有两条路:让锚点更像正样本(拉近),或者让它更不像负样本(推远)。下面直接拖动单位圆上的点,看分类器给正样本多少概率,以及锚点受到的拉力与推力。

    (In this lesson \(\mathbf z\) is an embedding vector and a logit is written \(\ell=s/\tau\), unlike Lesson 16.1 where logits were called \(z\).) The loss can only shrink in two ways: make the anchor more like the positive (pull), or less like the negatives (push). Drag the points on the unit circle below and watch how much probability the classifier gives the positive, and which pulls and pushes act on the anchor.

    FIG 1InfoNCE 就是一个“N+1 选 1”的分类器InfoNCE is an (N+1)-way classifier
    左:二维嵌入落在单位圆上。琥珀色是锚点,绿色是正样本,紫色是 5 个负样本,全部可以拖动(会被吸回圆上)。从锚点出发的箭头是负梯度 \(-\partial L/\partial\mathbf z\) 的分解:绿箭头指向正样本(拉力,长度正比于 \(1-p_+\)),每个负样本对应一支紫箭头,方向背离它(推力,长度正比于 \(p_j\)),琥珀箭头是它们的合力沿圆周切向的分量(画成 1.6 倍长):锚点真正会移动的方向。真实的梯度还要再乘 \(1/\tau\),为了让箭头放得下,图里省去了这个公共因子。右:分类器给每个候选的概率 \(p\);虚线是“瞎猜”的 \(1/6\)。读数里的“最难负样本份额”是推力中最大一份所占的比例。 Left: 2D embeddings on the unit circle. Amber is the anchor, green the positive, purple the 5 negatives; all can be dragged (they snap back onto the circle). The arrows from the anchor decompose the negative gradient \(-\partial L/\partial\mathbf z\): the green arrow points at the positive (pull, length proportional to \(1-p_+\)); each negative has a purple arrow pointing away from it (push, length proportional to \(p_j\)); the amber arrow is the component of their sum along the circle's tangent (drawn 1.6× longer), the direction the anchor would actually move. The true gradient carries an extra factor \(1/\tau\), left out here so the arrows fit. Right: the probability \(p\) the classifier gives each candidate; the dashed line is the "blind guess" \(1/6\). The readout's "hardest-negative share" is the fraction of the total push that goes to the largest single push.
    试一试Try this
    • 拖动正样本靠近锚点、把负样本拖远,让分类器给正样本 90% 以上的概率(损失低于 0.11)。Drag the positive close to the anchor and the negatives away until the classifier gives the positive more than 90% (loss below 0.11).
    • 把一个负样本拖到离锚点 30° 以内,再把 τ 降到 0.1 或更低:这一个难负样本拿走 80% 以上的推力。然后把 τ 升到 1 或更高:它的份额跌到 50% 以下。Drag one negative within 30° of the anchor and lower τ to 0.1 or less: that one hard negative takes more than 80% of the push. Then raise τ to 1 or more: its share falls below 50%.
    核心洞见Key insight

    InfoNCE 的梯度自带“注意力”:每个负样本受到的推力正比于它的 softmax 概率 \(p_j\),也就是它此刻有多像锚点。温度 \(\tau\) 调节这份注意力有多尖锐:\(\tau\) 小时几乎所有推力都落在最难的那个负样本上(接近只看最近对手的三元组/铰链损失),\(\tau\) 大时所有负样本被一视同仁地推开。预设“全部塌缩”展示另一件事:所有点重合时 \(p\) 处处等于 \(1/6\),损失是 \(\log 6\approx1.79\),远不是最小值:负样本让“所有图都输出同一个向量”这条捷径变得不划算。

    The InfoNCE gradient has built-in "attention": each negative is pushed in proportion to its softmax probability \(p_j\), that is, to how much it currently resembles the anchor. The temperature \(\tau\) sets how sharp this attention is: with small \(\tau\) almost the whole push lands on the hardest negative (close to a triplet/hinge loss that only looks at the nearest rival); with large \(\tau\) all negatives are pushed alike. The preset "all collapsed" shows one more thing: when every point coincides, \(p=1/6\) everywhere and the loss is \(\log 6\approx1.79\), far from its minimum: the negatives make the shortcut "output the same vector for every image" a bad deal.

    3动手:在浏览器里训练 SimCLRPlay: train SimCLR in your browser

    SimCLR(Chen 等,2020)把上面的分类器变成一个完整的训练配方。每一步取 \(N\) 张图,每张图随机增广两次,得到 \(2N\) 个视图;同一张图的两个视图互为正样本,批次里其余 \(2N-2\) 个视图全部当负样本,不需要任何标签。我们的“数据集”是一台俯视托盘的相机拍的 8×8 灰度图:托盘上放着四种零件之一,方块、横销、竖销和 L 形支架,位置有 ±1 像素的抖动,每张图的环境光、零件亮度和光照梯度(光从哪边来)都不同。网络从来看不到零件类别;类别只在评估时用来给点上色和打分。

    先看增广。真实 SimCLR 最重要的两种增广是随机裁剪和颜色失真;我们的编码器是一个小 MLP,学不会平移不变性(那是 17.1 节卷积网络的强项),所以这里用三种适合它的增广:光照抖动(随机改变增益、平移环境光,并叠加一个方向随机的光照梯度)、传感器噪声、随机遮挡(抹掉一个 2×2 的块)。

    SimCLR (Chen et al., 2020) turns the classifier above into a complete training recipe. Each step takes \(N\) images and augments each one twice at random, giving \(2N\) views; the two views of the same image are each other's positive, and the other \(2N-2\) views in the batch are all negatives. No labels are needed. Our "dataset" comes from a camera looking down at a tray: 8×8 grayscale images showing one of four parts, a block, a horizontal peg, a vertical peg or an L-bracket, jittered by ±1 pixel, each image with its own ambient light, part brightness and lighting gradient (which side the light comes from). The network never sees the part class; the class is only used at evaluation time, to colour the points and score them.

    First the augmentations. The two most important ones in the real SimCLR are random cropping and colour distortion; our encoder is a small MLP that cannot learn translation invariance (the strength of the convolutional networks of Lesson 17.1), so we use three augmentations that suit it: lighting jitter (randomly changes the gain, shifts the ambient light and adds a lighting gradient in a random direction), sensor noise, and random erasing (wipes out a 2×2 patch).

    FIG 2一个批次:每张图的两个增广视图,以及像素空间里的配对难度One batch: two augmented views of every image, and how hard pairing is in pixel space
    上排:8 张原图(零件类别用边框颜色标出,仅供你看)。中间两排:每张原图的视图 A 和视图 B,青色越浓 = 越亮。右边的 16×16 方阵是所有视图两两之间的像素余弦相似度(琥珀色越浓 = 越像),对角线(自己和自己)留空;绿框是每一行真正的正样本,红点标出每一行像素最相似的视图。读数给出“像素最近邻恰好是正样本”的比例:本批次,以及固定种子下 400 个批次的平均。 Top row: 8 original images (the part class is shown by the border colour, for your eyes only). Middle rows: view A and view B of each original, more cyan = brighter. On the right, the 16×16 matrix is the pixel cosine similarity between all pairs of views (more amber = more similar), with the diagonal (each view with itself) left blank; green boxes mark each row's true positive and red dots each row's most similar view in pixels. The readout gives how often the pixel nearest neighbour is the positive: for this batch, and averaged over 400 batches with a fixed seed.
    • 先关掉全部增广:两个视图一模一样,像素最近邻 100% 找到搭档,这个预训练任务毫无难度。再只打开“光照抖动”:400 批平均降到 60% 以下:光凭像素已经认不出搭档了。First switch all augmentations off: the two views are identical and the pixel nearest neighbour finds the partner 100% of the time, so the pretext task is trivial. Then switch on only "lighting jitter": the 400-batch average drops below 60%; pixels alone no longer identify the partner.

    这正是要点:增广让预训练任务在像素空间里变难,网络只能去找光照改变不了的东西,也就是零件的形状。下面真正开始训练。编码器是 64 → 32 → 32 → 3 的 tanh MLP,输出归一化后落在三维单位球面上(可以拖动旋转);损失是对 \(2N\) 个视图求平均的 InfoNCE(SimCLR 称之为 NT-Xent)。每 20 步,在 200 张固定的测试图(不增广)上评估一次:用嵌入做 5-近邻分类,看能否猜对零件类别,以及能否猜对光照方向(四个象限之一)。前者高、后者接近瞎猜的 25%,说明表示学到了零件而忽略了光照。

    That is the point: augmentations make the pretext task hard in pixel space, so the network has to find what lighting cannot change, the shape of the part. Now train for real. The encoder is a 64 → 32 → 32 → 3 tanh MLP whose normalized output lies on the 3D unit sphere (drag to rotate it); the loss is InfoNCE averaged over the \(2N\) views (SimCLR calls it NT-Xent). Every 20 steps it is evaluated on 200 fixed test images (not augmented): a 5-nearest-neighbour classifier on the embeddings tries to guess the part class, and separately the lighting direction (one of four quadrants). A high first number and a second near the blind-guess 25% mean that the representation learned the part and ignored the lighting.

    FIG 3SimCLR 现场训练:增广决定表示记住什么SimCLR, trained live: the augmentations decide what the representation keeps
    左:200 张测试图的嵌入在单位球面上(正面的点实心,背面的点小而淡;拖动旋转)。按“零件”着色时,红、绿、蓝、紫分别是方块、横销、竖销、L 形支架;按“光照方向”着色时,同样四种颜色表示光来自的四个象限。右上:训练损失(琥珀色,左轴)和瞎猜水平 \(\log(2N-1)\)(虚线),以及测试集上的 5-近邻准确率:零件(绿色)和光照方向(紫色),右轴 0 到 1。读数里的 \(R\) 是所有测试嵌入平均向量的长度:均匀铺满球面时接近 0,全部塌缩成一点时等于 1。 Left: the embeddings of the 200 test images on the unit sphere (points on the near side are solid, those on the far side small and faint; drag to rotate). Coloured by "part", red, green, blue and purple are block, horizontal peg, vertical peg and L-bracket; coloured by "lighting direction", the same four colours are the four quadrants the light comes from. Top right: the training loss (amber, left axis) with the blind-guess level \(\log(2N-1)\) (dashed), and the 5-nearest-neighbour test accuracy for the part (green) and for the lighting direction (purple), right axis 0 to 1. In the readout \(R\) is the length of the mean of all test embeddings: close to 0 when they spread over the sphere, exactly 1 when they have all collapsed onto one point.
    • 保持默认(InfoNCE、光照抖动 + 噪声)按“训练”:几百步内零件的近邻准确率超过 90%,而光照方向的准确率掉到 40% 以下。(对照:原始像素上的近邻准确率只有 77%。)Keep the defaults (InfoNCE, lighting jitter + noise) and press "Train": within a few hundred steps the part accuracy passes 90% while the lighting accuracy drops below 40%. (For comparison, nearest neighbours on raw pixels reach only 77%.)
    • 关掉“光照抖动”,重置并训练至少 300 步:网络走了捷径,光照方向的准确率升到 70% 以上,零件的准确率却低于 50%。切到“按光照方向着色”看看球面上的点是按什么分组的。Switch "lighting jitter" off, reset and train for at least 300 steps: the network takes a shortcut, lighting accuracy rises above 70% while part accuracy stays below 50%. Switch to "colour by lighting direction" to see what the points on the sphere are grouped by.
    • 把损失换成“只拉近(无负样本)”并训练(从重置开始只需几十步,从训练好的网络出发要几百步):损失降到接近 0,而 \(R\) 升到 0.98 以上:所有图被映射到了同一个点,这就是塌缩。Change the loss to "pull only (no negatives)" and train (a few dozen steps from a reset, a few hundred from a trained network): the loss drops to almost 0 while \(R\) rises above 0.98: every image is mapped to the same point. This is collapse.
    值得注意Things worth noticing

    (1) 随机初始化的网络就已经“认得”光照:训练前光照方向的近邻准确率是 66%,零件只有 37.5%。像素里最显眼的变化是光照,不是零件。 (2) 训练好之后,损失仍远高于 0(默认设置下约 2.3 到 2.7,瞎猜是 \(\log 63\approx4.14\)):同一类零件的两张不同图彼此是负样本,网络既要把它们聚成一团,又被要求区分它们,这是对比学习固有的张力(见误区 1)。 (3) 关掉光照抖动后,损失反而更低(约 2.0 到 2.2),预训练任务完成得更好,表示却对零件几乎没用:损失低不等于表示好。

    (1) A randomly initialized network already "knows" the lighting: before training, the lighting accuracy is 66% while the part accuracy is only 37.5%. The most visible variation in the pixels is the lighting, not the part. (2) After training the loss is still far above 0 (about 2.3 to 2.7 at the defaults; a blind guess gives \(\log 63\approx4.14\)): two different images of the same kind of part are negatives for each other, so the network is asked both to cluster them and to tell them apart, a tension built into contrastive learning (see Pitfall 1). (3) With lighting jitter off the loss is actually lower (about 2.0 to 2.2): the pretext task is solved better, yet the representation is nearly useless for the part. A low loss does not mean a good representation.

    4另外两个视角:互信息的上限,以及 CLIPTwo more views: the mutual-information ceiling, and CLIP

    InfoNCE 在估计互信息,而且被 log N 封顶InfoNCE estimates mutual information, capped at log N

    为什么“认出搭档”能学到有用的东西?4.11 节把互信息 \(I(X;Y)\) 定义为“知道 \(Y\) 之后,关于 \(X\) 的不确定性减少了多少”。van den Oord 等(2018)证明:用 \(N\) 个候选(1 个正样本、\(N-1\) 个负样本)训练出的 InfoNCE 损失给出互信息的一个下界 \(I(X;Y)\ge\hl{logn}{\log N}-L\)。最小化损失就是在最大化两个视图之间互信息的下界。可这个下界有个硬伤:\(L\ge0\),所以估计值永远不超过 \(\log N\)。下图用两组相关的四维高斯变量 \(X,Y\)(真实互信息可以精确算出)和最好的打分函数(真实的密度比)来检验:即使打分函数完美,估计也撞上 \(\log N\) 的天花板。

    Why does "spot your partner" learn something useful? Lesson 4.11 defined the mutual information \(I(X;Y)\) as how much knowing \(Y\) reduces the uncertainty about \(X\). Van den Oord et al. (2018) showed that the InfoNCE loss with \(N\) candidates (1 positive, \(N-1\) negatives) yields a lower bound \(I(X;Y)\ge\hl{logn}{\log N}-L\). Minimizing the loss maximizes a lower bound on the mutual information between the two views. But the bound has a hard limit: \(L\ge0\), so the estimate never exceeds \(\log N\). The figure checks this with two correlated 4-dimensional Gaussian variables \(X,Y\) (whose mutual information is known exactly) and the best possible critic (the true density ratio): even with a perfect critic, the estimate hits the \(\log N\) ceiling.

    FIG 4InfoNCE 估计的互信息:批次大小设定天花板The mutual information InfoNCE can see: the batch size sets the ceiling
    横轴:真实互信息 \(I(X;Y)=-\tfrac d2\log(1-\rho^2)\)(nats,\(d=4\),\(\rho\) 是每一维的相关系数)。纵轴:InfoNCE 估计 \(\log N-L\) 的期望。没有颜色的细对角线是“估计 = 真值”。四条曲线是 \(N=4,16,64,256\) 时的估计(打开页面后在后台逐点采样画出),各自的水平虚线是 \(\log N\)。琥珀色点是你选的设置:每帧采样若干个新批次,点是至今所有批次的平均,竖线是 ±2 个标准误差。 Horizontal: the true mutual information \(I(X;Y)=-\tfrac d2\log(1-\rho^2)\) (nats, \(d=4\), \(\rho\) the per-dimension correlation). Vertical: the expected InfoNCE estimate \(\log N-L\). The thin uncoloured diagonal is "estimate = truth". The four curves are the estimates for \(N=4,16,64,256\) (sampled point by point in the background after the page opens), each with its \(\log N\) as a horizontal dashed line. The amber point is your setting: a few new batches are sampled every frame, the point is the mean over all batches so far and the vertical bar is ±2 standard errors.
    • 选 \(N=16\),把真实互信息拉到 4 nats 以上,至少采样 50 个批次:估计停在 \(\log 16\approx2.77\) 以下,比真值少了三成以上。Choose \(N=16\), raise the true mutual information above 4 nats and sample at least 50 batches: the estimate stays below \(\log 16\approx2.77\), more than 30% short of the truth.
    • 真实互信息在 2.5 到 4 nats 之间时,把 \(N\) 换成 256(至少采样 50 批):估计回到真值的 10% 以内。With the true mutual information between 2.5 and 4 nats, switch to \(N=256\) (sample at least 50 batches): the estimate comes back within 10% of the truth.
    为什么这很重要Why this matters

    这解释了对比学习为什么偏爱大批次:SimCLR 用到上千(最大 8192)的批次,CLIP 用 32768,MoCo(He 等,2020)则用一个动量更新的编码器加一个 65536 长的负样本队列,把负样本数和批次大小解耦。但别把“最大化互信息”当成全部真相:Tschannen 等(2020)指出,表示好不好更多取决于编码器结构和打分函数的归纳偏置,而不只是互信息下界有多紧。FIG 3 的“捷径”就是一例:关掉光照抖动后,两个视图之间的互信息完全可以靠光照拿满。

    This is why contrastive learning likes big batches: SimCLR uses batches in the thousands (up to 8192), CLIP uses 32,768, and MoCo (He et al., 2020) uses a momentum-updated encoder plus a queue of 65,536 negatives to decouple the number of negatives from the batch size. But do not take "maximize mutual information" as the whole story: Tschannen et al. (2020) argued that how good a representation is depends more on the inductive biases of the encoder and the critic than on how tight the mutual-information bound is. The "shortcut" of FIG 3 is a case in point: with lighting jitter off, the mutual information between the two views can be fully collected from the lighting.

    CLIP:拿一句话当“另一个视图”CLIP: a sentence as the "other view"

    CLIP(Radford 等,2021)把正样本对从“同一张图的两个增广”换成“一张图和描述它的文字”。它有两个编码器:图像编码器 \(f\) 和文本编码器 \(g\),都输出单位向量。一个批次里有 \(N\) 对图文,算出 \(N\times N\) 的相似度矩阵,对角线是正确配对。损失是两个方向的 InfoNCE 之和:每张图在 \(N\) 句话里找自己的描述(矩阵的行),每句话在 \(N\) 张图里找自己的图(矩阵的列)。温度也是一个可学习的参数。训练完,零样本分类不需要再训练任何分类器:把每个类别写成一句话(“一个蓝色的 L 形支架”),用文本编码器编码,选和图像余弦相似度最高的那句。

    下面是一个缩小版:彩色 8×8 图像,红、绿、蓝三种颜色 × 四种零件 = 12 种组合;“文本”是两个词(颜色词 + 零件词)的词袋,文本编码器是 7 → 16 → 8 的 MLP,图像编码器是 192 → 32 → 8 的 MLP。关键的考验:“蓝色 L 形支架”和“红色竖销”这两种组合在训练中一次都不出现,模型只见过蓝色的别的零件、别的颜色的 L 形支架。和真实相机一样,三种颜色在 RGB 通道上有重叠(红色是 (1, 0.4, 0.4),依此类推)。

    CLIP (Radford et al., 2021) replaces the positive pair "two augmentations of one image" with "an image and the text describing it". It has two encoders, an image encoder \(f\) and a text encoder \(g\), both producing unit vectors. A batch of \(N\) image–text pairs gives an \(N\times N\) similarity matrix whose diagonal holds the correct pairings. The loss is the sum of InfoNCE in both directions: each image looks for its caption among the \(N\) sentences (the rows of the matrix) and each sentence looks for its image among the \(N\) images (the columns). The temperature is a learned parameter too. After training, zero-shot classification needs no classifier training at all: write each class as a sentence ("a blue L-bracket"), encode it with the text encoder, and pick the sentence with the highest cosine similarity to the image.

    Below is a miniature version: colour 8×8 images, three colours red, green, blue × four parts = 12 combinations; the "text" is a bag of two words (a colour word + a part word), the text encoder a 7 → 16 → 8 MLP and the image encoder a 192 → 32 → 8 MLP. The key test: the combinations "blue L-bracket" and "red vertical peg" never appear in training; the model has only seen other blue parts and L-brackets of other colours. As with a real camera, the three colours overlap in the RGB channels (red is (1, 0.4, 0.4), and so on).

    FIG 5迷你 CLIP:图文对比训练与零样本识别A miniature CLIP: image–text contrastive training and zero-shot recognition
    左上:当前批次(16 对)的相似度矩阵,行是图像(左侧是缩略图),列是文本(上方用一个颜色色块加一个零件图标表示两个词),琥珀色越浓 = 余弦相似度越高,绿框是正确配对。注意同一批次里可能出现两对相同的组合:它们的“负样本”其实是正确答案(误区 1)。左下:用你在下面选的提示词去检索 36 张测试图(12 种组合各 3 张),按相似度排出前 8 名,绿色边框表示检索对了。右:零样本准确率随训练步数的变化:训练中见过的 10 种组合(绿色)、从未见过的 2 种组合(琥珀色)、只用零件词当提示的 4 选 1(蓝色)。 Top left: the similarity matrix of the current batch (16 pairs); rows are images (thumbnails on the left), columns are texts (the two words shown above as a colour swatch plus a part icon), more amber = higher cosine similarity, green boxes are the correct pairings. Note that a batch can contain the same combination twice: their "negatives" are then actually correct answers (Pitfall 1). Bottom left: the prompt you choose below retrieves the top 8 of 36 test images (3 of each of the 12 combinations) by similarity, with a green border when the retrieval is right. Right: zero-shot accuracy over training steps for the 10 combinations seen in training (green), the 2 never-seen combinations (amber), and 4-way classification prompted with the part word alone (blue).
    • 按“训练”:见过的组合很快接近 100%,而从未见过的“蓝色 L 形支架”和“红色竖销”要慢得多;训练到它们的零样本准确率超过 75%(12 选 1,瞎猜只有 8%)。Press "Train": the seen combinations quickly approach 100% while the never-seen "blue L-bracket" and "red vertical peg" take much longer; train until their zero-shot accuracy passes 75% (12-way, a blind guess gives 8%).
    • 训练之后,把提示词设成一个从未见过的组合(“蓝色 + L 形支架”或“红色 + 竖销”):检索出的前 3 张图全部正确。After training, set the prompt to a never-seen combination ("blue + L-bracket" or "red + vertical peg"): the top 3 retrieved images are all correct.
    零样本分类就是一个用文字写出权重的线性分类器Zero-shot classification is a linear classifier whose weights are written in words

    把 \(K\) 个类别的提示词编码成 \(\mathbf t_1,\dots,\mathbf t_K\),零样本分类器就是 \(p(k\mid x)\propto\exp(\mathbf t_k^\top f(x)/\tau)\):一个权重矩阵的行恰好是文本嵌入的 softmax 线性分类器。所以“换一组类别”只是“换一组句子”。提示怎么写很重要:CLIP 论文发现用“a photo of a {label}.”这样的模板、再对几十个模板的文本嵌入取平均(提示集成),比只写类别名准确得多。FIG 5 里只给零件词(“L 形支架”,不带颜色)当提示,就是一个模型在训练中从未见过的句子。

    Encode the prompts for \(K\) classes as \(\mathbf t_1,\dots,\mathbf t_K\); the zero-shot classifier is \(p(k\mid x)\propto\exp(\mathbf t_k^\top f(x)/\tau)\): a softmax linear classifier whose weight rows are exactly the text embeddings. "Switching to a new set of classes" is therefore just "switching to a new set of sentences". How the prompt is written matters: the CLIP paper found that a template such as "a photo of a {label}." and averaging the text embeddings of dozens of templates (prompt ensembling) is clearly more accurate than the bare class name. In FIG 5, prompting with the part word alone ("L-bracket", no colour) is a sentence the model never saw in training.

    5再看数学The math

    InfoNCE 与它的梯度InfoNCE and its gradient

    记候选集合为 \(\{\mathbf z_0=\mathbf z^+,\mathbf z_1,\dots,\mathbf z_N\}\),logit \(\ell_j=\mathbf z^\top\mathbf z_j/\tau\),softmax 概率 \(p_j=e^{\ell_j}/\sum_k e^{\ell_k}\)。损失 \(L=-\ell_0+\log\sum_k e^{\ell_k}\)。对锚点求导(16.1 节 softmax 交叉熵的“\(p-y\)”规则再用一次):

    Write the candidates as \(\{\mathbf z_0=\mathbf z^+,\mathbf z_1,\dots,\mathbf z_N\}\), the logits as \(\ell_j=\mathbf z^\top\mathbf z_j/\tau\) and the softmax probabilities as \(p_j=e^{\ell_j}/\sum_k e^{\ell_k}\). The loss is \(L=-\ell_0+\log\sum_k e^{\ell_k}\). Differentiating with respect to the anchor (the "\(p-y\)" rule of softmax cross-entropy from Lesson 16.1, once more):

    $$ \frac{\partial L}{\partial\mathbf z}=\frac1\tau\Big(\sum_{j=0}^{N}p_j\mathbf z_j-\mathbf z^+\Big)=-\hl{grad}{\frac{1-p_+}{\tau}\,\mathbf z^+}+\sum_{j=1}^{N}\hl{grad}{\frac{p_j}{\tau}\,\mathbf z^-_j},\qquad \frac{\partial L}{\partial\mathbf u}=\frac{(I-\mathbf z\mathbf z^\top)}{\|\mathbf u\|}\,\frac{\partial L}{\partial\mathbf z}\quad(\mathbf z=\mathbf u/\|\mathbf u\|) $$

    第一项是对正样本的拉力,求和里的每一项是对一个负样本的推力(悬停公式,FIG 1 的箭头会加粗)。第二个式子是通过归一化 \(\mathbf z=\mathbf u/\|\mathbf u\|\) 反传:只有与球面相切的分量留下来,这就是 FIG 1 里琥珀色合力沿切向的原因(代码在页面里用 16.3 节的反向传播接着往网络里传)。正样本的 \(\partial L/\partial\mathbf z^+\) 和每个负样本的 \(\partial L/\partial\mathbf z_j^-\) 同理,所以负样本也被推离锚点。

    温度的两个极限。\(\tau\to0\):softmax 变成 max,\(L\approx\max\big(0,\max_j s_j^- -s^+\big)/\tau\),只惩罚比正样本更像锚点的那个最难负样本,就是带零间隔的三元组损失。\(\tau\to\infty\):一阶展开 \(\log\sum_k e^{\ell_k}\approx\log(N+1)+\bar\ell\),于是 \(L\approx\log(N+1)-(s^+-\bar s)/\tau\),\(\bar s\) 是全部 \(N+1\) 个相似度的平均:所有负样本被同等地推开,难样本不再特殊。实践中 \(\tau\) 通常在 0.05 到 0.5 之间,CLIP 则把它当参数从 0.07 开始学。

    The first term is the pull towards the positive and each term of the sum a push away from one negative (hover the formula and the arrows in FIG 1 thicken). The second formula backpropagates through the normalization \(\mathbf z=\mathbf u/\|\mathbf u\|\): only the component tangent to the sphere survives, which is why the amber resultant in FIG 1 runs along the tangent (the page's code then continues into the network with the backpropagation of Lesson 16.3). The positive's \(\partial L/\partial\mathbf z^+\) and each negative's \(\partial L/\partial\mathbf z_j^-\) follow the same way, so the negatives are also pushed away from the anchor.

    The two limits of the temperature. \(\tau\to0\): the softmax becomes a max and \(L\approx\max\big(0,\max_j s_j^- -s^+\big)/\tau\), which only penalizes the hardest negative, the one more similar to the anchor than the positive: a triplet loss with zero margin. \(\tau\to\infty\): to first order \(\log\sum_k e^{\ell_k}\approx\log(N+1)+\bar\ell\), so \(L\approx\log(N+1)-(s^+-\bar s)/\tau\) with \(\bar s\) the mean of all \(N+1\) similarities: every negative is pushed alike and hard ones are no longer special. In practice \(\tau\) is usually between 0.05 and 0.5, and CLIP learns it as a parameter starting from 0.07.

    对齐与均匀:负样本为什么能防塌缩Alignment and uniformity: why negatives prevent collapse

    Wang 与 Isola(2020)证明,当负样本数 \(N\to\infty\) 时,InfoNCE 分成两项:

    Wang and Isola (2020) proved that as the number of negatives \(N\to\infty\), InfoNCE splits into two terms:

    $$ \lim_{N\to\infty}\big(L-\log N\big)=\hl{align}{-\frac1\tau\,\mathbb E_{(x,x^+)}\big[\mathbf z^\top\mathbf z^+\big]}+\hl{unif}{\mathbb E_{x}\Big[\log\mathbb E_{x^-}\,e^{\mathbf z^\top\mathbf z^-/\tau}\Big]} $$

    对齐项希望正样本对重合;均匀项是一个“排斥势”,在球面上的均匀分布处最小(把鼠标停在这两个词上,FIG 3 会画出几对正样本视图的连线,或所有测试嵌入的平均向量)。只留对齐项,最优解就是常数函数:每张图都输出同一个 \(\mathbf z\),对齐损失为 0,这正是 FIG 3 “只拉近”时看到的塌缩,\(R\to1\)。均匀项在塌缩处最大(所有 \(\mathbf z^\top\mathbf z^-=1\)),所以负样本把塌缩从“最优”变成了“最差”。对有限批次,塌缩处的损失恰好等于瞎猜:SimCLR 的 \(2N\) 个视图里每个锚点有 \(2N-1\) 个候选,\(L=\log(2N-1)\)。

    不用负样本也能防塌缩,但要换别的机制:BYOL 和 SimSiam 用预测头加停止梯度(BYOL 还用动量目标编码器),DINO 用对教师输出的中心化与锐化,VICReg 直接惩罚各维方差过小。这些“非对比”方法留给 18.4 节。

    The alignment term wants positive pairs to coincide; the uniformity term is a "repulsive potential" minimized by the uniform distribution on the sphere (hover over these two words and FIG 3 draws lines between a few positive pairs of views, or the mean vector of all test embeddings). Keep only the alignment term and the optimum is a constant function: every image outputs the same \(\mathbf z\) and the alignment loss is 0. That is the collapse seen with "pull only" in FIG 3, \(R\to1\). The uniformity term is largest at collapse (every \(\mathbf z^\top\mathbf z^-=1\)), so the negatives turn collapse from "optimal" into "worst". For a finite batch the loss at collapse equals the blind guess exactly: among SimCLR's \(2N\) views each anchor has \(2N-1\) candidates, so \(L=\log(2N-1)\).

    Collapse can also be prevented without negatives, through other mechanisms: BYOL and SimSiam use a predictor head plus a stop-gradient (BYOL also a momentum target encoder), DINO centres and sharpens the teacher's outputs, and VICReg directly penalizes dimensions whose variance is too small. These "non-contrastive" methods are left to Lesson 18.4.

    互信息下界The mutual-information bound

    取 \(N\) 对样本 \((x_i,y_i)\sim p(x,y)\),对任意打分函数 \(c(x,y)\),下式成立(van den Oord 等 2018 提出,Poole 等 2019 给出严格证明):

    Take \(N\) pairs \((x_i,y_i)\sim p(x,y)\). For any critic \(c(x,y)\) the following holds (proposed by van den Oord et al. 2018, proved rigorously by Poole et al. 2019):

    $$ I(X;Y)\;\ge\;\mathbb E\Bigg[\frac1N\sum_{i=1}^N\log\frac{e^{c(x_i,y_i)}}{\frac1N\sum_{j=1}^N e^{c(x_i,y_j)}}\Bigg]=\hl{logn}{\log N}-L_{\mathrm{NCE}},\qquad c^\star(x,y)=\log\frac{p(y\mid x)}{p(y)}+b(x) $$

    直觉:给定 \(x\),在 \(N\) 个候选 \(y\) 里猜哪个是它的搭档,贝叶斯最优的猜法就是按密度比 \(p(y\mid x)/p(y)\) 打分,这正是 \(c^\star\);只依赖 \(x\) 的项 \(b(x)\) 在 softmax 里抵消。FIG 4 用的就是这个 \(c^\star\):对相关高斯,\(\log p(y\mid x)-\log p(y)\) 是 \(\frac{\rho}{1-\rho^2}\mathbf x^\top\mathbf y\) 加上只依赖 \(\mathbf y\) 和只依赖 \(\mathbf x\) 的二次项。由于 \(L_{\mathrm{NCE}}\ge0\),右边不可能超过 \(\log N\):要“看见” \(k\) nats 的互信息,至少需要 \(N\approx e^k\) 个候选。

    Intuition: given \(x\), guess which of \(N\) candidates \(y\) is its partner; the Bayes-optimal guess scores each candidate by the density ratio \(p(y\mid x)/p(y)\), which is \(c^\star\), and any term \(b(x)\) that depends on \(x\) alone cancels in the softmax. FIG 4 uses exactly this \(c^\star\): for correlated Gaussians, \(\log p(y\mid x)-\log p(y)\) is \(\frac{\rho}{1-\rho^2}\mathbf x^\top\mathbf y\) plus quadratic terms in \(\mathbf y\) alone and in \(\mathbf x\) alone. Since \(L_{\mathrm{NCE}}\ge0\), the right side can never exceed \(\log N\): to "see" \(k\) nats of mutual information you need at least \(N\approx e^k\) candidates.

    SimCLR 与 CLIP 的完整损失The full SimCLR and CLIP losses

    $$ L_{\mathrm{SimCLR}}=\frac1{2N}\sum_{a=1}^{2N}-\log\frac{\exp(\mathbf z_a^\top\mathbf z_{a^+}/\tau)}{\sum_{k\ne a}\exp(\mathbf z_a^\top\mathbf z_k/\tau)},\qquad \mathbf z=\frac{g(\mathbf h)}{\|g(\mathbf h)\|},\quad\mathbf h=f_\theta(x) $$ $$ L_{\mathrm{CLIP}}=\frac12\Bigg[\hl{i2t}{\frac1N\sum_{i}-\log\frac{e^{\mathbf u_i^\top\mathbf t_i/\tau}}{\sum_{j}e^{\mathbf u_i^\top\mathbf t_j/\tau}}}+\hl{t2i}{\frac1N\sum_{i}-\log\frac{e^{\mathbf u_i^\top\mathbf t_i/\tau}}{\sum_{j}e^{\mathbf u_j^\top\mathbf t_i/\tau}}}\Bigg] $$

    SimCLR 的编码器 \(f_\theta\)(论文里是 ResNet)后面接一个小的 MLP 投影头 \(g\),损失作用在 \(\mathbf z\) 上,下游任务却用投影之前的 \(\mathbf h\):投影头会主动丢掉与增广有关的信息(比如颜色),而 \(\mathbf h\) 还保留着,所以 \(\mathbf h\) 上的线性分类效果更好。评价表示的标准做法是线性探测:冻结编码器,只在 \(\mathbf h\) 上训练一个线性分类器(21.1 节会把它和全量微调比较)。我们的小 MLP 没有单独的投影头,直接在 \(\mathbf z\) 上做近邻评估。CLIP 的式子里 \(\mathbf u_i\) 是第 \(i\) 张图的图像嵌入,\(\mathbf t_i\) 是第 \(i\) 句话的文本嵌入;第一项是“图找文”(相似度矩阵的每一行做一次 softmax),第二项是“文找图”(每一列)。\(1/\tau\) 用对数参数化来学,并截断在 100 以内;FIG 5 也这样做,从 \(1/\tau=5\) 开始,2000 步时升到约 13,之后在 14 左右。

    SimCLR's encoder \(f_\theta\) (a ResNet in the paper) is followed by a small MLP projection head \(g\). The loss acts on \(\mathbf z\), but downstream tasks use the pre-projection \(\mathbf h\): the head actively discards augmentation-related information (such as colour) that \(\mathbf h\) still keeps, so linear classifiers work better on \(\mathbf h\). The standard way to judge a representation is the linear probe: freeze the encoder and train only a linear classifier on \(\mathbf h\) (Lesson 21.1 compares it with full fine-tuning). Our small MLP has no separate head and is evaluated by nearest neighbours directly on \(\mathbf z\). In the CLIP formula \(\mathbf u_i\) is the image embedding of image \(i\) and \(\mathbf t_i\) the text embedding of sentence \(i\); the first term is "image finds text" (a softmax over each row of the similarity matrix), the second "text finds image" (over each column). \(1/\tau\) is learned through a log parametrization and clipped at 100. FIG 5 does the same, starting from \(1/\tau=5\), reaching about 13 by step 2000 and about 14 later.

    一句话总结In one sentence

    对比学习 = 用 softmax 交叉熵做“认搭档”的分类;正样本对的构造方式(增广、图文、时间、多视角)定义了表示要不变的东西,负样本提供均匀性、防止塌缩,温度决定梯度集中在哪些负样本上,批次大小决定能“看见”多少互信息。

    Contrastive learning = "spot your partner" classification with softmax cross-entropy: how positive pairs are built (augmentations, image and text, time, several viewpoints) defines what the representation must be invariant to, the negatives supply uniformity and prevent collapse, the temperature decides which negatives the gradient concentrates on, and the batch size decides how much mutual information can be "seen".

    6机器人中的它:从视频里学状态和奖励In robotics: states and rewards from video

    机器人的数据天然是视频,时间本身就提供了正样本。TCN(时间对比网络,Sermanet 等,2018)用多台相机同时拍同一个动作:同一时刻、不同相机的两帧是正样本,同一相机、不同时刻的帧是负样本。前者逼表示忽略视角和外观,后者逼它记住随时间变化的东西,也就是机器人和物体的状态。只用单台相机、把“相邻时刻”当正样本也行,但有个陷阱:同一段视频里每一帧都共享光照和背景,网络可以靠“这是哪段视频”配对,而不必在不同的视频之间对齐状态。

    下图是一个夹爪在 10×10 的俯视相机里从随机起点移到目标(右上方)的 20 段测试演示,每段视频有自己的光照梯度、增益和一个固定的干扰方块。训练时每步取 10 段新演示、每段 3 个时刻:选“多视角”时,正样本是同一时刻、另一台相机(光照与干扰物都不同)的画面;选“单视角时间”时,正样本是同一相机的下一帧。评估方法是跨演示检索:对每一帧,在其他演示里找表示最近的帧,看两帧的夹爪位置差多少像素。这正是“用别人的演示来判断我现在进行到哪一步”时需要的能力。

    Robot data is naturally video, and time itself supplies positives. TCN (Time-Contrastive Networks, Sermanet et al., 2018) films the same action with several cameras at once: two frames at the same instant from different cameras are positives, frames from the same camera at different times are negatives. The first forces the representation to ignore viewpoint and appearance; the second forces it to keep what changes over time, namely the state of the robot and the objects. A single camera with "neighbouring instants" as positives also works, but there is a trap: every frame of one video shares its lighting and background, so the network can pair frames by "which video is this" without aligning states across different videos.

    The figure shows 20 test demonstrations of a gripper moving, in a 10×10 top-down camera, from a random start to a goal (upper right). Each video has its own lighting gradient, gain and a fixed distractor box. Each training step takes 10 new demonstrations and 3 instants from each: with "multi-view", the positive is the frame at the same instant from another camera (different lighting and distractor); with "single-view time", the positive is the next frame from the same camera. The evaluation is cross-demonstration retrieval: for each frame, find the closest frame in representation space among the other demonstrations and measure how many pixels apart the two gripper positions are. That is exactly the ability needed to "tell how far along I am by looking at someone else's demonstration".

    FIG 6时间对比学习:表示里的距离成为进度与奖励Time-contrastive learning: distance in representation space becomes progress and reward
    左上:所选演示的 12 帧(青色越浓 = 越亮),带框的是所选帧。左下:所选帧在其他演示里的最近邻,按像素(紫色)和按学到的表示(绿色);右边的小地图是真实的夹爪位置:琥珀色是查询帧,紫色和绿色是两个最近邻,红叉是目标,虚线是这段演示的轨迹。右上:沿所选演示的“奖励” \(r_t=-\|\mathbf z_t-\mathbf z_g\|\)(\(\mathbf z_g\) 是目标图的表示,目标图来自另一台相机,各自归一化到 0 到 1),用表示(绿色)和用像素(紫色);随时间单调上升才是好的进度信号。 Top left: the 12 frames of the selected demonstration (more cyan = brighter), the boxed one being the selected frame. Bottom left: the selected frame's nearest neighbour in the other demonstrations, by pixels (purple) and by the learned representation (green); the small map on the right shows the true gripper positions: amber is the query frame, purple and green the two nearest neighbours, the red cross the goal, the dashed line this demonstration's path. Top right: the "reward" \(r_t=-\|\mathbf z_t-\mathbf z_g\|\) along the selected demonstration (\(\mathbf z_g\) is the representation of the goal image, which comes from a different camera; each curve normalized to 0 to 1), using the representation (green) and using pixels (purple); a good progress signal rises steadily over time.
    • 用“多视角”训练:跨演示检索的平均夹爪误差降到 0.9 像素以下,比像素最近邻(约 1.05 像素)更准。Train with "multi-view": the mean gripper error of cross-demonstration retrieval falls below 0.9 pixels, better than pixel nearest neighbours (about 1.05 pixels).
    • 切到“单视角时间”,重置并训练至少 1000 步:检索误差仍然比像素最近邻还差。网络学会了认“哪段视频”,而不是认“夹爪在哪”。Switch to "single-view time", reset and train for at least 1000 steps: the retrieval error is still worse than pixel nearest neighbours. The network learned to recognize "which video", not "where the gripper is".

    同一个思想在机器人学习里反复出现。R3M(Nair 等,2022)在人类第一视角视频数据集 Ego4D 上,用时间对比、视频与语言对齐和 L1 稀疏正则训练一个 ResNet,然后冻结它,供下游的行为克隆(22.1 节)在少量演示上学操作策略。VIP(Ma 等,2023)同样只用 Ego4D、不需要动作标签,把训练目标写成一个隐式的、以目标为条件的价值函数,得到的表示里“到目标图像的距离”可以直接当作奖励,正是 FIG 6 右上角那条曲线的思路。CLIP 则把语言带进了机器人:CLIPort(Shridhar 等,2021)用 CLIP 的特征把语言指令和相机画面对应起来,基于 CLIP 式训练的开放词汇检测器(如 OWL-ViT)让机器人按名字找物体。今天的视觉-语言-动作模型也沿用对比预训练的图像编码器:OpenVLA 把 SigLIP 和 DINOv2 的特征拼在一起,π0 建在 PaliGemma 上,其视觉编码器也是 SigLIP。SigLIP(Zhai 等,2023)把 CLIP 的 softmax 换成对每个图文对独立的 sigmoid 二分类,不再需要整批归一化。

    The same idea recurs throughout robot learning. R3M (Nair et al., 2022) trains a ResNet on the egocentric human video dataset Ego4D with time-contrastive learning, video–language alignment and an L1 sparsity penalty, then freezes it for downstream behaviour cloning (Lesson 22.1) of manipulation policies from a small number of demonstrations. VIP (Ma et al., 2023), also trained on Ego4D without action labels, casts the objective as an implicit goal-conditioned value function, so that "distance to the goal image" in its representation can be used directly as a reward: the idea behind the curve at the top right of FIG 6. CLIP brought language into robotics: CLIPort (Shridhar et al., 2021) uses CLIP features to ground language instructions in what the camera sees, and open-vocabulary detectors built on CLIP-style training (such as OWL-ViT) let a robot find objects by name. Today's vision-language-action models still use contrastively pre-trained image encoders: OpenVLA concatenates SigLIP and DINOv2 features, and π0 is built on PaliGemma, whose vision encoder is also SigLIP. SigLIP (Zhai et al., 2023) replaces CLIP's softmax by an independent sigmoid classification of each image–text pair, so no normalization over the whole batch is needed.

    真实系统里In real systems

    规模:CLIP 在约 4 亿个从网上收集的图文对上训练,批次 32768;SimCLR 在 ImageNet 上用上千的批次,一个加宽 4 倍的 ResNet-50 上的线性探测达到了有监督 ResNet-50 的水平。 预训练表示用于控制:常见做法是冻结 R3M、VIP、CLIP 或 DINOv2 等编码器,只在其特征上训练策略或价值函数,或者在少量机器人数据上微调(21.1 节)。 增广要配合任务:如果任务是“拿起红色的杯子”,颜色抖动会把颜色这一关键信息变成不变量;如果任务和左右有关(插销从哪边插入),水平翻转就不能用。 奖励:把“到目标嵌入的距离”当奖励很方便,但它只在表示真的对状态敏感、对干扰不敏感时才可靠:FIG 6 的单视角时间训练就是一个反例。

    Scale: CLIP was trained on about 400 million image–text pairs collected from the web, with batches of 32,768; SimCLR used batches in the thousands on ImageNet, and a linear probe on a 4× wider ResNet-50 matched a supervised ResNet-50. Pre-trained representations for control: a common recipe is to freeze an encoder such as R3M, VIP, CLIP or DINOv2 and train only a policy or value function on its features, or to fine-tune on a little robot data (Lesson 21.1). Augmentations must suit the task: if the task is "pick up the red cup", colour jitter turns the key information, colour, into an invariance; if the task depends on left and right (which side a peg goes in from), horizontal flips are off limits. Rewards: "distance to the goal embedding" is a convenient reward, but it is only reliable when the representation really is sensitive to the state and insensitive to nuisances: single-view time training in FIG 6 is a counterexample.

    7常见误区Common pitfalls

    误区 1:以为负样本一定“不同”Pitfall 1: assuming negatives are always "different"

    批次里的负样本只是“别的图”,很可能和锚点是同一类(FIG 3 里四类零件,批次里另外 31 张图中平均约有 7.75 张与锚点同类),甚至是同一个组合(FIG 5 的同一批次里常有重复的图文)。这些假负样本会被错误地推开,类越少、批次越大越严重。有标签时可以用监督对比学习(SupCon,Khosla 等 2020)把同类都当正样本;没有标签时,常见的缓解办法是去掉明显重复的样本、或者降低与锚点过于相似的负样本的权重。

    The negatives in a batch are merely "other images" and may well belong to the anchor's class (with four kinds of part in FIG 3, on average about 7.75 of the other 31 images in the batch share the anchor's class), or even be the same combination (FIG 5 batches often contain repeated image–text pairs). These false negatives are wrongly pushed away, worse with fewer classes and bigger batches. With labels, supervised contrastive learning (SupCon, Khosla et al. 2020) treats all same-class samples as positives; without labels, common mitigations are removing obvious duplicates or down-weighting negatives that are suspiciously similar to the anchor.

    误区 2:增广会自动“正确”Pitfall 2: expecting augmentations to be "right" by default

    增广定义了不变性,它是你写进模型的先验,不是中性的预处理。少了必要的增广,网络会走捷径(FIG 3 关掉光照抖动后,表示按光照分组);多了不该有的增广,任务需要的信息会被抹掉(颜色抖动之于“红杯子”,翻转之于左右)。在 ImageNet 上调好的增广组合,换到机器人腕部相机、深度图或触觉图像上未必合适。

    Augmentations define invariances: they are a prior you build into the model, not neutral preprocessing. Leave out a necessary one and the network takes a shortcut (with lighting jitter off in FIG 3, the representation groups by lighting); add an inappropriate one and information the task needs is erased (colour jitter for "the red cup", flips for left and right). An augmentation recipe tuned on ImageNet is not necessarily right for a wrist camera, depth images or tactile images.

    误区 3:用对比损失的数值评价表示Pitfall 3: judging a representation by its contrastive loss

    损失值依赖批次大小(瞎猜水平是 \(\log(2N-1)\)),也依赖增广的强度;FIG 3 里关掉光照抖动后损失更低,“只拉近”时损失接近 0,可这两种表示都没用。评价表示要看下游:冻结编码器后的线性探测、近邻分类、少量样本的微调,或者在机器人上的任务成功率。

    The loss value depends on the batch size (a blind guess gives \(\log(2N-1)\)) and on the augmentation strength; in FIG 3 the loss is lower with lighting jitter off and nearly 0 with "pull only", yet both representations are useless. Judge a representation downstream: a linear probe on the frozen encoder, nearest-neighbour classification, few-shot fine-tuning, or task success on the robot.

    误区 4:温度和批次随手一设Pitfall 4: setting the temperature and batch size casually

    \(\tau\) 太小,梯度几乎只来自最难的负样本,而最难的负样本往往是假负样本,训练会变得嘈杂、不稳定;\(\tau\) 太大,难负样本不再被重视,表示的区分度下降。批次太小,负样本少,互信息估计被 \(\log N\) 封顶(FIG 4)。如果显存放不下大批次,可以用 MoCo 式的负样本队列;CLIP 则干脆把 \(\tau\) 当参数来学。

    With \(\tau\) too small, the gradient comes almost entirely from the hardest negatives, which are often false negatives, so training becomes noisy and unstable; with \(\tau\) too large, hard negatives no longer get attention and the representation discriminates less. With too small a batch there are few negatives and the mutual-information estimate is capped by \(\log N\) (FIG 4). If memory does not allow big batches, use a MoCo-style queue of negatives; CLIP simply learns \(\tau\) as a parameter.

    误区 5:以为零样本就是“什么都认得”Pitfall 5: taking zero-shot to mean "recognizes anything"

    零样本只是不需要为新类别训练分类器,模型仍然只能组合它在训练中见过的概念。FIG 5 能认出“蓝色 L 形支架”,是因为它见过“蓝色”和“L 形支架”,而且颜色在 RGB 通道上有共享的结构;一个从未出现过的形状它就认不出来。真实的 CLIP 对计数、空间关系(“杯子在盘子左边”)和细粒度类别也明显较弱,提示措辞的小变化还会改变结果。在机器人上,用它做开放词汇的物体检索之前,应在自己的场景里先测一测。

    Zero-shot only means that no classifier has to be trained for the new classes; the model can still only combine concepts it saw during training. FIG 5 recognizes "blue L-bracket" because it saw "blue" and "L-bracket" and because colours share structure across the RGB channels; a shape that never appeared it cannot recognize. The real CLIP is also clearly weaker at counting, spatial relations ("the cup to the left of the plate") and fine-grained categories, and small changes in prompt wording change its answers. On a robot, test it in your own scenes before relying on it for open-vocabulary object retrieval.

    8小练习Check yourself

    1. SimCLR 一个批次有 \(N=32\) 张图(64 个视图)。如果编码器塌缩成常数,每个锚点的 InfoNCE 损失是多少?1. A SimCLR batch has \(N=32\) images (64 views). If the encoder collapses to a constant, what is each anchor's InfoNCE loss?
    塌缩时所有相似度都等于 1,softmax 在 \(2N-1=63\) 个候选(自己除外)上均匀分布,\(p_+=1/63\),\(L=\log 63\approx4.14\),正好是瞎猜的水平(FIG 3 的虚线)。选项 A 是“只拉近”损失在塌缩处的值:有了负样本,塌缩是最差的情形之一。At collapse every similarity is 1, so the softmax is uniform over the \(2N-1=63\) candidates (all views but the anchor itself): \(p_+=1/63\) and \(L=\log 63\approx4.14\), exactly the blind-guess level (the dashed line in FIG 3). Option A is the value of the "pull only" loss at collapse; with negatives, collapse is one of the worst cases.
    2. 把 InfoNCE 的温度 \(\tau\) 调得很小,梯度会怎样?2. What happens to the gradient when the InfoNCE temperature \(\tau\) is made very small?
    每个负样本的推力正比于 \(p_j\propto e^{s_j/\tau}\)。\(\tau\to0\) 时 softmax 趋于 one-hot,最大的 \(s_j\) 拿走几乎全部权重(FIG 1 的“最难负样本份额”),损失退化成只看最难负样本的铰链。选项 A 是 \(\tau\to\infty\) 的情形;logit 是 \(s/\tau\),\(\tau\) 小时变大而不是变成 0。Each negative's push is proportional to \(p_j\propto e^{s_j/\tau}\). As \(\tau\to0\) the softmax tends to one-hot and the largest \(s_j\) takes nearly all the weight (the "hardest-negative share" of FIG 1); the loss degenerates into a hinge on the hardest negative. Option A is the \(\tau\to\infty\) case; the logits are \(s/\tau\), which grow rather than vanish as \(\tau\) shrinks.
    3. 用 CLIP 做 \(K\) 类零样本分类时,“分类器的权重”是什么?3. When CLIP does \(K\)-way zero-shot classification, what are "the classifier's weights"?
    \(p(k\mid x)\propto\exp(\mathbf t_k^\top f(x)/\tau)\),权重矩阵的每一行就是一个提示词的文本嵌入 \(\mathbf t_k\),不需要任何带标签的图像。选项 A 是线性探测,选项 B 是“原型”分类器,两者都需要标签。\(p(k\mid x)\propto\exp(\mathbf t_k^\top f(x)/\tau)\): each row of the weight matrix is the text embedding \(\mathbf t_k\) of one prompt, and no labelled image is needed. Option A is a linear probe and option B a "prototype" classifier; both need labels.
    4. 用 \(N=256\) 个候选的 InfoNCE 去估计两个视图之间的互信息,真实值是 10 nats。估计值最多是多少?4. InfoNCE with \(N=256\) candidates is used to estimate the mutual information between two views, whose true value is 10 nats. What is the largest the estimate can be?
    估计值是 \(\log N-L\),而交叉熵 \(L\ge0\),所以无论打分函数多好,都不超过 \(\log N=\ln256\approx5.55\) nats(FIG 4 用最优打分函数验证过)。选项 D 混淆了单位:8 是以 2 为底的比特数,换成 nats 仍是 5.55。The estimate is \(\log N-L\) and the cross-entropy \(L\ge0\), so however good the critic, it cannot exceed \(\log N=\ln256\approx5.55\) nats (FIG 4 checks this with the optimal critic). Option D mixes units: 8 is the count in bits (base 2), which is still 5.55 in nats.
    5. TCN 用“同一时刻、不同相机”的两帧当正样本,“同一相机、不同时刻”的帧当负样本。这样设计主要是为了什么?5. TCN uses two frames "at the same instant from different cameras" as positives and frames "from the same camera at different times" as negatives. What is this design mainly for?
    正样本对共享状态而外观不同,所以外观必须被忽略;负样本共享外观(同一台相机)而状态不同,所以靠外观无法区分它们,只能靠状态。FIG 6 里单视角时间训练没有这层约束,网络靠光照和干扰物认出“哪段视频”,跨演示检索反而比像素还差。选项 B 正好相反。Positive pairs share the state but differ in appearance, so appearance must be ignored; negatives share the appearance (same camera) but differ in state, so they cannot be told apart by appearance, only by state. Single-view time training in FIG 6 lacks this constraint: the network recognizes "which video" by its lighting and distractor, and cross-demonstration retrieval ends up worse than pixels. Option B is the opposite.

    9延伸阅读Further reading

    • R. Hadsell, S. Chopra & Y. LeCun, Dimensionality Reduction by Learning an Invariant Mapping, CVPR 2006 — 早期的成对对比损失:拉近相似对、推开不相似对an early pairwise contrastive loss: pull similar pairs together, push dissimilar ones apart
    • A. van den Oord, Y. Li & O. Vinyals, Representation Learning with Contrastive Predictive Coding, arXiv:1807.03748, 2018 — 提出 InfoNCE 与它的互信息下界introduces InfoNCE and its mutual-information bound
    • B. Poole, S. Ozair, A. van den Oord, A. Alemi & G. Tucker, On Variational Bounds of Mutual Information, ICML 2019 — 互信息变分下界的统一视角,包括 InfoNCE 的 \(\log N\) 上限a unified view of variational mutual-information bounds, including InfoNCE's \(\log N\) ceiling
    • T. Chen, S. Kornblith, M. Norouzi & G. Hinton, A Simple Framework for Contrastive Learning of Visual Representations, ICML 2020 — SimCLR:增广组合、投影头、NT-Xent 与大批次SimCLR: augmentation composition, projection head, NT-Xent and large batches
    • K. He, H. Fan, Y. Wu, S. Xie & R. Girshick, Momentum Contrast for Unsupervised Visual Representation Learning, CVPR 2020 — MoCo:动量编码器加负样本队列MoCo: a momentum encoder plus a queue of negatives
    • T. Wang & P. Isola, Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere, ICML 2020 — 对齐与均匀两项分解the alignment and uniformity decomposition
    • M. Tschannen, J. Djolonga, P. K. Rubenstein, S. Gelly & M. Lucic, On Mutual Information Maximization for Representation Learning, ICLR 2020 — 为什么“最大化互信息”不足以解释对比学习的成功why "maximize mutual information" does not explain the success of contrastive learning
    • A. Radford et al., Learning Transferable Visual Models From Natural Language Supervision, ICML 2021 — CLIP:图文对比训练与零样本迁移CLIP: image–text contrastive training and zero-shot transfer
    • X. Zhai, B. Mustafa, A. Kolesnikov & L. Beyer, Sigmoid Loss for Language Image Pre-Training, ICCV 2023 — SigLIP:用逐对 sigmoid 代替批内 softmaxSigLIP: a pairwise sigmoid instead of an in-batch softmax
    • P. Sermanet, C. Lynch, Y. Chebotar, J. Hsu, E. Jang, S. Schaal & S. Levine, Time-Contrastive Networks: Self-Supervised Learning from Video, ICRA 2018 — 多视角时间对比与机器人模仿multi-view time contrast and robot imitation
    • S. Nair, A. Rajeswaran, V. Kumar, C. Finn & A. Gupta, R3M: A Universal Visual Representation for Robot Manipulation, CoRL 2022 — 从人类视频预训练、供操作策略使用的冻结表示a frozen representation for manipulation policies, pre-trained on human video
    • Y. J. Ma, S. Sodhani, D. Jayaraman, O. Bastani, V. Kumar & A. Zhang, VIP: Towards Universal Visual Reward and Representation via Value-Implicit Pre-Training, ICLR 2023 — 表示空间里到目标的距离作为奖励distance to the goal in representation space as a reward
    • M. Shridhar, L. Manuelli & D. Fox, CLIPort: What and Where Pathways for Robotic Manipulation, CoRL 2021 — 用 CLIP 理解语言指令的操作策略a manipulation policy that understands language instructions through CLIP