← PyTorch From First Principles

特征空间:线性模型实际看到了什么?

弄清特征空间里向量表示什么:分开张量秩与表示维度,推导点积、余弦相似度、距离与线性分数,测试不变性,用简单线性模型恢复埋下的可分方向。

这里有个序列分类器。八个样本,每样本 128 位置,每位置 768 特征,线性 head 产出一个分数。

x = torch.randn(8, 128, 768)
classifier = nn.Linear(768, 1)

scores = classifier(x)
input           (8, 128, 768)
Linear(768,1)  -> (8, 128, 1)

期待八个分数,得到一千零二十四个。没抛,非有限没有,知道规则后形状完全可预测。层精确做了张量让它做的:nn.Linear 变换末轴并保留之前每轴,所以为每个(样本,位置)对产出一分——每样本 128 分,独立算。

层没错。张量没错。缺的是没人大声问的问题:

我在分类哪个对象?

程序员想要每序列一分。张量里每序列 128 向量,线性 head 无从知道那 128 向量本该是一东西。每序列一分先决定 128 向量如何变一:

[B, T, D]
     ↓   aggregate or select — an architectural decision
[B, D]
     ↓   linear classifier
[B, 1]
x.mean(dim=1)       (8, 128, 768) -> (8, 768)
classifier(pooled) -> (8, 1)

x[:, 0]             (8, 128, 768) -> (8, 768)
classifier(x[:,0]) -> (8, 1)

mean-pool == first-token scores: False

都给出 [8, 1]。都合法。不同模型,没有默认正确答案——平均池化、取指定位置、注意力池化、最大池化都是真选择,行为不同。形状不替你选。

本章讲这个错误底下的推理层。

我们在哪

第 8 章末尾看网格消失。卷积 body 把

[B, C, H, W]

变成

[B, D]

轴的含义跟着变。H、W 有相邻:像素 (h, w) 挨着 (h, w+1),卷积完全围着这个事实建。池化展平后剩下的是坐标列表:

image   (16, 3, 64, 64)     grid axes have adjacency
body    (16, 32, 1, 1)
flatten (16, 32)            D=32 coordinates, no adjacency

特征 17 挨着特征 18 毫无意义。它们是对同一对象的两 learned 测量,全网一致重排它们除了名字什么都不变。

所以读者到这里手里的张量,第 8 章的几何描述不了。第 8 章的问题是空间格发生什么。本章的问题是格没了之后发生什么:

一个对象用几百上千坐标表示时,方向、分数、距离、决策边界是什么意思,没法画空间怎么推理?

诚实的答案是可视化从没干活。要紧的每量都是能算能打印的数。技能是知道哪个数回答哪个问题,本章建这个。

环境

本章每个数、形状、训练结果都来自跑出的代码,种子固定。

PyTorch      2.13.0
TorchVision  0.28.0
Python       3.12.3
OS           Linux, CPU only

张量秩不是表示维度

维度一词干两份活,开篇失败住两者的 gap 里。

shape (768,)             ndim=1   D=768   one object
shape (32, 768)          ndim=2   D=768   32 objects
shape (8, 128, 768)      ndim=3   D=768   8 x 128 objects

三不同张量秩。同一表示空间。torch.randn(768) 是秩一张量,768 个数描述一对象,该对象是 768 维特征空间的点。两句话都对,因为回答不同问题:

TENSOR AXES
    how representations are organized

FEATURE DIMENSION D
    how many coordinates describe one represented object

这给出拿到任何形状的阅读流程。轴分成结构与坐标:

[32, 768]        32 objects,  768 coordinates each
[8, 128, 768]    8 sequences, 128 positions each, 768 coordinates per position
[16, 32]         16 images,   32 coordinates each

前导轴说表示怎么组织。末轴在本书面约定里装一被表示对象的坐标;周围模型与数据契约告诉你该对象到底是什么。做线性代数前大声说出来,开篇失败写不出:[8, 128, 768] 装着 1024 个被表示向量,逐向量分类器返回 1024 分数。

nn.Linear 变换末轴

开篇背后的规则值得精确说,因为它让 Transformer 代码可读。

lin = nn.Linear(768, 16)
(768,)               -> (16,)
(32, 768)            -> (32, 16)
(8, 128, 768)        -> (8, 128, 16)
(4, 7, 9, 768)       -> (4, 7, 9, 16)

一般:

[..., D_in]  ->  [..., D_out]

每前导轴保留,什么意思都保留。层握形状 [D_out, D_in] 的 weight 与 [D_out] 的 bias,对每 D_in 向量独立施加。在开篇张量的一位置上确认:

one = x[3, 17]                                    # (768,)
manual = one @ classifier.weight[0] + classifier.bias[0]
manual  : 0.047477103769779205
observed: 0.047477103769779205
close   : True

所以 [8, 128, 1] 输出是 1024 个独立点积,层对 128 向量该不该一起从没意见。

顺便说命名陷阱。第 8 章 H 指图像高;这里 D_in、D_out 是特征维。[B, C, H, W] 的章节旁边用 H 表隐尺寸是 confusion 进来的路,本章说 D 指坐标。

另个伸手就拿的 temptation 值得点名:

x.flatten(1)
x.flatten(1): (8, 128, 768) -> (8, 98304)   128*768 = 98304
classifier(flat): mat1 and mat2 shapes cannot be multiplied (8x98304 and 768x1)

那是不同表示,不是修复。它把 128 位置向量 concat 成一 98304 坐标向量,哪个位置与哪个坐标的区分擦了。第 8 章对展平空间格说过同样的话:算子便宜,表示契约变了。塌缩正是想要的才对。

技术:说出对象,找到特征轴

本书每章加一种调查法。第 2 章要第一个错的张量而不是第一个不合法的。第 3 章问梯度通路第一次消失处。第 5 章问四套结构哪套对归属不一致。第 7 章问样本在哪不再满足契约。第 8 章问推导与观测几何第一次分歧处。

第 9 章加:

说出一向量表示的对象。找到装其坐标的轴。推导算子对该轴做什么。到那时再解释出来的数。

四步,开篇失败死在第一步。剩下是第四步认真做会怎样——因为特征空间算子的数比形状容易误读得多。

点积是沿方向的分数

二维开始,答案对着图可查,再拿走图。

给定方向 w 与偏移 b,点的分数是

s(x) = x · w + b = x₁w₁ + x₂w₂ + ... + x_D w_D + b

w = [0.8, 1.3]、b = -0.2:

point               x@w+b    side
[2.0, -1.0]         0.100       +
[3.0, 2.0]          4.800       +
[-2.0, -1.0]       -3.100       -
[0.0, 0.0]         -0.200       -
[1.5, 0.0]          1.000       +

expanded for [2,-1]: 2.0*0.8 + (-1.0)*1.3 + (-0.2) = 0.10000000000000003

符号说点在边界哪边。边界本身是分数零的集合:

w · x + b = 0

二维这个方程描述直线;三维平面;D 维超平面。名字变方程不变,本章最有用的一事实。

w 与边界垂直。证明两行不要图。x₁、x₂ 都在边界上,则 w·x₁ + b = 0 且 w·x₂ + b = 0,相减得 w·(x₁ - x₂) = 0。沿边界的每位移都与 w 正交。验证过:

boundary point p1: [1.0, -0.4615]   score: -0.0
boundary point p2: [4.0, -2.3077]   score:  0.0
w . (p1 - p2) = -0.0

现在拿走图别的不变:

D=2     X (32, 2)      w (2,)     -> scores (32,)   positive: 21/32
D=100   X (32, 100)    w (100,)   -> scores (32,)   positive: 18/32
D=768   X (32, 768)    w (768,)   -> scores (32,)   positive: 12/32

同样表达式,同样输出形状,符号同样解释。图没了。计算没没,几何也没没——w 在 D=768 仍是边界的法线,用的正是上面两行论证,它从没提坐标多少。

这里熟悉的层也变几何了。nn.Linear(D, C) 握形状 [C, D] 的 weight:同一特征空间的 C 个方向,外加 C 个偏移。每输出是一点沿其中一方向的分数。第 4 章的 x @ W.T + b 与第 8 章的分类 head 一直在做这个;新的只有词汇。

点积不是相似度、余弦、距离

解释从这里开始错,错得 quiet。两非零向量的点积精确分解:

x · y = ||x|| ||y|| cos(θ)
x = [3.0, 4.0]  ||x|| = 5.0
y = [1.0, 0.0]  ||y|| = 1.0
x @ y            = 3.0
||x|| ||y|| cos  = 3.0
cos              = 0.6000000238418579
angle (degrees)  = 53.130104064941406

三因子,只有一个关于方向。所以缩放一向量改点积而不动夹角:

  scale         x@y      cosine     ||x||
    0.5      1.5000    0.600000     2.500
    1.0      3.0000    0.600000     5.000
    2.0      6.0000    0.600000    10.000
   10.0     30.0000    0.600000    50.000
  100.0    300.0000    0.600000   500.000

两向量相对方向始终一样的“相似度”变一百倍。排名、检索、阈值用 raw 点积而向量范数在数据集上变,排名部分在度量大小。

两向量都归一化两量重合,这就是余弦相似度存在的全部原因:

||x_hat|| = 1.0   ||y_hat|| = 1.0
x_hat @ y_hat = 0.6000000238418579   cosine = 0.6000000238418579   equal: True

欧氏距离回答第三个问题。一个例子让三者分歧:

a = [1.0, 1.0]

b1 = same direction, far          b2 = near, different direction
   dot          20.0000              dot           2.2000
   cosine        1.0000              cosine        0.9959
   euclidean    12.7279              euclidean     0.2000

按余弦 b1 完美匹配。按欧氏距离 b1 比 b2 远六十倍。都是对不同问题的正确答案:

dot product          direction and both magnitudes together
cosine similarity    direction only, after normalizing
Euclidean distance   displacement magnitude

算之前说出要哪个。“相似度”不是量,是量的类别,代码得选一个。

归一化错轴

选对量也保不住算子作用到错轴。这个失败有第 7 章的 exact 签名——同样形状、同样 dtype、合法算子、错几何——好写。

x = torch.arange(1., 25.).reshape(2, 4, 3)     # B=2 sequences, T=4 positions, D=3

n_last = F.normalize(x, dim=-1)
n_one  = F.normalize(x, dim=1)
F.normalize(x, dim=-1).shape: (2, 4, 3)
F.normalize(x, dim=1).shape : (2, 4, 3)
same shape: True    same values: False

两调,形状相同,张量不同。分开它们的问题是之后哪些向量单位长:

norms of each D-vector (over dim=-1):
   after dim=-1: [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
   after dim=1 : [0.2409, 0.5887, 0.9456, 1.3043, 0.6445, 0.7829, 0.9213, 1.0597]

norms over dim=1 (across positions):
   after dim=1 : [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]

dim=-1 让每 D 维表示成单位向量,这就是这个例子意图的契约。dim=1 让每坐标跨位置单位范数——不同、coherent 的算子,不归一化表示向量本身。

后果在这些向量比较时现形。前两轴展平让八位置向量变成 [8, 3] 矩阵,每向量与自己比:

特征空间算子施加前,说出装坐标的轴是哪个,几何本想改谁。F.normalize、vector_norm、cosine_similarity、softmax 都要 dim,都会接受错的那个。

诊断便宜,值得进任何嵌入流水线:归一化后断言 torch.linalg.vector_norm(x, dim=-1) 是一。

raw 分数不是几何距离

第三个误读关于分类器自己的输出,最可能上 dashboard。

分数 s(x) = w·x + b。x 到边界的有符号欧氏距离是

distance = (w·x + b) / ||w||

w ≠ 0 时。区别重要因为边界对分数不 invariant 的重缩放 invariant。w、b 同乘 100,集合 {x : w·x + b = 0} 完全不变:

w, b
   ||w||     1.5264
   scores    [0.1, 4.8, -3.1, -0.2]
   distances [0.0655, 3.1446, -2.0309, -0.131]
   predicted [1, 1, -1, -1]

100w, 100b
   ||w||     152.6434
   scores    [10.0, 480.0, -310.0, -20.0]
   distances [0.0655, 3.1446, -2.0309, -0.131]
   predicted [1, 1, -1, -1]

predictions identical: True
scores ratio         : [99.99993, 99.99999, 99.99999, 100.0]
distances identical  : True

同样边界,同样预测,每分数大一百倍。所以按 abs(score) 排名自称“离边界距离”的常见动作,度的量依赖任意参数缩放:

max abs 'distance' claimed  : 4.8 then 480.0
true max geometric distance : 3.1446 then 3.1446

排序在这里活下来,正是 bug 活下来的原因——单固定模型按 abs(score) 排名与按距离排名一致,看起来没坏。数跨模型、跨训练跑、跨固定置信阈值、跨另一参数尺度拟合的校准曲线比,马上不 harmless。决策边界相同的两模型报告的分数能差任意倍。

distance = scores / torch.linalg.vector_norm(model.w)

解释数之前,问它对不该有影响的东西 invariant 吗。模型分数不是;几何距离是。

坐标与权重只有一起才有意思

还有一重不变性,它处理一个很流行的断言。

训好的线性模型,一特征乘 100,对应权重除 100:

Xs = X.clone();  Xs[:, 3] *= 100
ws = w.clone();  ws[3] /= 100
original w[3]        : 0.387591
adjusted w[3]        : 0.00387591
max abs score change : 2.384185791015625e-07
scores identical     : True
x[0,3] * w[3]        : -0.659439  ->  -0.659439

每分数保留,因为模型用的是乘积 x_j · w_j,变的只是两因子之 split。同样模型换坐标系表达。所以:

|w| original: [0.7121, 0.2718, 0.7974, 0.3876, 1.1464, ...]
|w| rescaled: [0.7121, 0.2718, 0.7974, 0.0039, 1.1464, ...]

坐标 3 从第四大系数变最小,模型一点没变。

系数大小不是模型的属性。是模型与其坐标单位的属性。

这是第 7 章值尺度契约的特征空间 analogue。那里 float32 张量不记录值住 [0,1] 还是 [0,255],Normalize 检查不了。这里权重向量不记录坐标什么单位,断言恢复不了。

坏缩放坐标对真模型做什么

上面不变性精确,看起来 harmless。其实不,因为训练不 invariant:正则化在你交的坐标系里罚 ||w||。

两相同数据集,除了坐标 99——纯噪声、与标签无关——乘 1000。同样种子、同样结构、同样目标:

unit scale
   held-out accuracy    : 0.9337
   w[99]                : -0.025984
   mean |x_j * w_j| j=99: 0.0210
   mean |x_j * w_j| j=7 : 0.4685
   largest contributor  : coord 7 at 0.4685

feature 99 x1000
   held-out accuracy    : 0.6862
   w[99]                : 0.001156
   mean |x_j * w_j| j=99: 0.9328
   mean |x_j * w_j| j=7 : 0.4572
   largest contributor  : coord 99 at 0.9328

精度 0.934 到 0.686。看怎么发生的。模型把 w[99] 缩了,从 -0.026 到 0.0012——二十多倍。远远不够。贡献 |x₉₉ · w₉₉| 涨到 0.93,噪声坐标成分数里最大单项,超过真 informative 的坐标 7。

机制更直接。坐标 99 大 1000 倍后,模型用小得多的 w₉₉ 得到同样的分数贡献 x₉₉w₉₉。L2 罚 w₉₉²,不罚贡献 x₉₉w₉₉,大尺度坐标在正则化下变便宜用。优化动态也变。特征单位改了目标的 trade-off,特征信息一点没多。

训练 split 的统计标准化坐标恢复它:

held-out accuracy   : 0.9312
cosine(w, true_w)   : 0.9750
top-|w| coordinates : [7, 42, 81, 97]

统计在训练数据上拟合——第 7 章的规则,原样适用于从数据估计的任何预处理 state。

解释距离、间隔、系数前,看坐标尺度。特征空间与其单位一样有意义。

间隔:选哪个分离超平面?

到此描述线性分类器。没说选哪个。

类别可分,分离超平面很多。有的贴着最近样本过,有的留宽走廊。哪个 separator 的问题挣出支持向量机,答案是最大化间隔(margin):边界周围空走廊的宽度。

两约定让它 tractable。第一标签 y ∈ {-1, +1} 而不是 {0, 1},一次乘积同时捕获正确与置信:

y · s(x)

分数符号与标签一致时正,大小说点在正确区多深。

第二,SVM 典范参数化把两间隔面放在 w·x + b = ±1,hinge 损失罚 y·(w·x+b) < 1 的样本。这把分数否则任意的尺度与数据绑住:单纯缩 w、b 几何上加宽 ±1 面,但把更多样本推进间隔,hinge 项涨。这个缩放下走廊几何宽 2/||w||,减 ||w|| 利于宽间隔,hinge 项强制竞争的数据约束。

三区域:

表达它的损失是 max(0, 1 - y·s),表胜段落:

hinge = torch.relu(1 - y * scores)
   y    score   y*score   hinge   region
   1      2.0       2.0     0.0   beyond margin
      1      1.0       1.0     0.0   on margin
   1      0.4       0.4     0.6   inside margin
   1     -0.5      -0.5     1.5   wrong side
   -1     -2.0       2.0     0.0   beyond margin
   -1     -0.3       0.3     0.7   inside margin
   -1      1.1      -1.1     2.1   wrong side

两性质值得点名。损失在典范间隔上及外零——y·s >= 1 后点再远 hinge 不再降。交叉熵行为不同:正确样本正确类 logit 间隔大了它继续降,虽然逼零。hinge 对违反间隔约束的量线性涨。

本章用的完整目标:

loss = 0.5 * model.w.square().sum() + C * torch.relu(1 - y * scores).mean()

C 权衡两项:C 大重数据拟合,C 小重间隔。说清约定再跨库信——hinge 项 sum 还是 mean、正则怎么缩放实现各异,数值 C 跨库含义不同。

本章从该目标推导能跑的线性 SVM 到此为止。核方法是 SVM 故事著名另一半,故意 out of scope:核让特征空间隐式,本章全部目的让显式高维表示可检查。

建模

class LinearSVM(nn.Module):
    def __init__(self, features):
        super().__init__()
        self.w = nn.Parameter(torch.zeros(features))
        self.b = nn.Parameter(torch.zeros(()))

    def forward(self, x):
        return x @ self.w + self.b
named parameters: [('w', (100,)), ('b', ())]
[32,100] -> (32,)
[100]    -> ()

这里没新机器。nn.Parameter 是第 5 章的声明:这些张量属于模型、该到优化器。x @ self.w 是第 2 章的矩阵向量乘,[B, D] @ [D] -> [B]。标量偏置跨 batch 广播。autograd 按第 3 章记录整个。

训练循环是第 1 章的循环换损失:

Chapter 1:   parameter → prediction → loss → backward → update
Chapter 9:   w, b      → projection score → hinge objective → backward → update

同样类 serve 任意特征维:

LinearSVM(2   ) params=3     [32,2]   -> (32,)
LinearSVM(100 ) params=101   [32,100] -> (32,)
LinearSVM(768 ) params=769   [32,768] -> (32,)

在答案看得见处验证

二维两高斯云,400 点,学到的边界对着几何查而不是信。

neg = torch.randn(200, 2) * 0.7 + torch.tensor([-2.0, -1.5])
pos = torch.randn(200, 2) * 0.7 + torch.tensor([ 2.0,  1.5])
X = torch.cat([neg, pos])
y = torch.cat([-torch.ones(200), torch.ones(200)])
step=0000 loss=1.0000 hinge=1.0000 |w|=0.0505 acc=0.500
step=0250 loss=0.1643 hinge=0.0532 |w|=0.4713 acc=1.000
step=0500 loss=0.1643 hinge=0.0533 |w|=0.4711 acc=1.000
step=0999 loss=0.1643 hinge=0.0533 |w|=0.4711 acc=1.000

learned w: [0.373, 0.2878]   b: 0.0108
||w||: 0.4711
accuracy: 1.0
margin width 2/||w||: 4.2451

再查几何而不是精度。构造在边界上的两点分数该零,差与 w 正交:

boundary points score: -0.0  -0.0
w . (xa - xb): -0.0

前面推导对学到的参数成立。也注意损失干了什么:精度已 1.000,损失停在 0.1643、hinge 非零 0.053。完美分类不是零 hinge 损失,因为典范间隔内的点仍贡献。目标在每点站对边后仍在间隔与违反间 trade。

在画不出的空间恢复方向

现在让本章断言可测的实验。构造标签真依赖 100 维空间已知方向的数据,训时从不给模型看方向,测它逼近多少。

X = torch.randn(4000, 100)
true_w = torch.zeros(100)
true_w[7] = 2.0;  true_w[42] = -1.5;  true_w[81] = 0.8
y = torch.where(X @ true_w + 0.15 * torch.randn(4000) >= 0, 1.0, -1.0)

一百坐标里九十七纯噪声。三带信号。3000/1000 切,结果在模型没优化过的数据上度:

train (3000, 100)  test (1000, 100)
class balance train: 0.491

step=0000 loss=2.0000 hinge=1.0000 |w|=0.5000 acc=0.491
step=0300 loss=1.2008 hinge=0.4267 |w|=0.8334 acc=0.948
step=0900 loss=1.2012 hinge=0.4266 |w|=0.8358 acc=0.947
step=1499 loss=1.2012 hinge=0.4275 |w|=0.8314 acc=0.948

单精度是弱结果——说模型分类好,没说找到对的方向。所以直接比几何:

train accuracy      : 0.9473
held-out accuracy   : 0.9490
||w_learned||       : 0.8314
||w_true||          : 2.6249
cosine(w, true_w)   : 0.9833
angle (degrees)     : 10.50
cosine(random, true): -0.0649   (baseline)

top-|w| coordinates : [7, 42, 81, 5, 10, 93]
their values        : [0.6208, -0.4514, 0.2837, -0.0365, 0.0324, -0.0318]
true nonzero coords : [7, 42, 81] values [2.0, -1.5, 0.8]

两块仔细读,说的不同事。

方向恢复了:余弦 0.983,夹角约十度,seeded 随机方向余弦 -0.065。大小没对上:||w|| 出来 0.83,真范数 2.62。这里 mismatch 期待。二值标签主要认出样本在 latent 边界哪边,SVM 目标经 hinge/正则 trade 自己选参数尺度。余弦相似度才是这里有用的恢复度量:要学到的 separator 与埋的方向对齐,不是复现 raw 系数尺度。

系数 top 三正好是埋的三坐标,顺序对,符号对,比值大致跟 2.0 : -1.5 : 0.8。结果 satisfying,说清什么让它可能:这里坐标独立、同缩放、只三个有用。上一节已展示一坐标重缩放后排名会怎样,相关坐标再 blur 它。系数排名是关于哪些坐标重要的假设,可信程度正比于对坐标系的理解。

间隔分析

学到的边界用前面定义的三区域,在留出数据上盘问:

misclassified   (y*s < 0)  :    51 (0.051)
inside margin   (0<=y*s<1) :   728 (0.728)
beyond margin   (y*s >= 1) :   221 (0.221)
signed distance  min/mean/max: -3.205 -0.095 3.345
closest to canonical margin, y*score: [0.999, 1.0035, 1.0038, 1.0041, 1.0054]

这个 C 下留出点近四分之三在典范间隔里。这是选的 trade-off 的事实,不是缺陷:C 小 favor 宽间隔、容忍更多违反。

词汇注一句,因为常被 abuse。y·s ≈ 1 的点是坐在典范间隔面上的,叫 margin-constraining 候选 fair。严格意义叫支持向量是对 SVM 优化问题解的断言,这个模型是固定步数梯度下降拟合的 soft-margin 目标。描述测到的。

特征空间检查器

第 7 章有阶段报告。第 8 章有形状台账。本章的等价物让 [B, D] 表示的几何可观测,因为上面失败没有一个进形状。

def inspect(X, name="X", model=None, y=None):
    assert X.ndim == 2, f"{name}: expected [B, D], got {tuple(X.shape)}"
    X = X.detach()
    B, D = X.shape
    norms = torch.linalg.vector_norm(X, dim=1)
    std = X.std(dim=0, correction=0)

    print(f"  {name}: shape={tuple(X.shape)} dtype={X.dtype} D={D}")
    print(f"    finite                 : {bool(torch.isfinite(X).all())}"
          f"  (non-finite {int((~torch.isfinite(X)).sum())})")
    print(f"    row norm  min/mean/max : {norms.min():.4g} {norms.mean():.4g} {norms.max():.4g}")
    print(f"    feature std min/med/max: {std.min():.4g} {std.median():.4g} {std.max():.4g}")
    print(f"    widest coord {int(std.argmax()):<4} scale ratio "
          f"{(std.max()/std.min().clamp_min(1e-30)):.4g}x")

    s = F.normalize(X[:64], dim=1)
    cos = s @ s.T
    mask = ~torch.eye(len(s), dtype=torch.bool, device=cos.device)
    off = cos[mask]
    if off.numel():
        print(f"    pairwise cosine (64)   : mean {off.mean():.4f}  max {off.max():.4f}")

    if model is not None:
        with torch.no_grad():
            sc = model(X)
            wn = model.w.norm()
            print(f"    ||w|| {wn.item():.4f}  b {model.b.item():.4f}")
            print(f"    score    min/mean/max : {sc.min():.4f} {sc.mean():.4f} {sc.max():.4f}")
            if wn.item() == 0.0:
                print("    distance              : undefined (||w|| = 0)")
            else:
                d = sc / wn
                print(f"    distance min/mean/max : {d.min():.4f} {d.mean():.4f} {d.max():.4f}")
            if y is not None:
                sg = y * sc
                print(f"    wrong side {(sg<0).float().mean():.3f}"
                      f"  inside margin {((sg>=0)&(sg<1)).float().mean():.3f}"
                      f"  at/beyond {(sg>=1).float().mean():.3f}")

健康表示与坏缩放的并排:

healthy: shape=(2200, 100) dtype=torch.float32 D=100
  finite                 : True  (non-finite 0)
  row norm  min/mean/max : 7.863 9.989 12.66
  feature std min/med/max: 0.9674 1.002 1.034
  widest coord 60   scale ratio 1.069x
  pairwise cosine (64)   : mean -0.0021  max 0.2931

one coordinate x1000: shape=(2200, 100) dtype=torch.float32 D=100
  finite                 : True  (non-finite 0)
  row norm  min/mean/max : 9.129 807.4 3385
  feature std min/med/max: 0.9674 1.002 1014
  widest coord 99   scale ratio 1048x
  pairwise cosine (64)   : mean 0.0086  max 1.0000

三行点名问题。尺度比 1048×。最宽坐标认出 99。最大两两余弦到 1.0000——两向量方向看起来相同,因为一巨大共享坐标主导集合里每向量的几何。

它抓住另两种产出完全合法张量的表示失败:

collapsed to near-zero norm: shape=(200, 64) D=64
  row norm  min/mean/max : 5.707e-08 8.005e-08 9.949e-08
  pairwise cosine (64)   : mean 0.0014  max 0.4460

collapsed to one direction: shape=(200, 64) D=64
  row norm  min/mean/max : 7.576 7.579 7.582
  pairwise cosine (64)   : mean 1.0000  max 1.0000

第一种数值噪声里消失了;行范数说的。第二种范数健康、每对余弦 1.0000——200 向量 effectively 同一向量。下游分类器喂任一种都训、损失有限、什么都学不到,形状 dtype 里都看不见。

挂分类器:

held-out with classifier: shape=(800, 100) D=100
  ||w|| 0.8238  b -0.0233
  score    min/mean/max : -2.4186 -0.0246 2.2989
  distance min/mean/max : -2.9358 -0.0299 2.7904
  wrong side 0.066  inside margin 0.716  beyond 0.218

分数与距离分开 deliberate 报告,因为前面确立它们是不同量。

这个报告回答的问题,特征空间行为奇怪时值得问的:

Is D what the model expects?
Are the vector norms exploding, or collapsed to zero?
Is one coordinate scaled a thousand times larger than the rest?
Has the representation collapsed so that every vector points the same way?
Are the classifier's scores saturated on one side?
How much of the data sits inside the margin?

坐标多不是表达力强

大 D 让问题容易的结论很诱人。不对,最干净的反例最小。

原始两坐标的异或:

raw 2 coordinates:
   w = [0.0, 0.0]   b = 0.0
   scores   : [0.0, 0.0, 0.0, 0.0]
   accuracy : 0.5

模型收敛到零向量,这是诚实的答案:四点没超平面分开,正则赢。不可能两行代数,不用训练:

need  s(0,0) < 0,  s(0,1) > 0,  s(1,0) > 0,  s(1,1) < 0

s(0,1) + s(1,0) = w₁ + w₂ + 2b
s(0,0) + s(1,1) = w₁ + w₂ + 2b

the two sums are identical, so they cannot have opposite signs

现在加坐标。先 998 随机:

XOR padded with 998 random coordinates (D=1000):
   train accuracy on those 4 rows      : 1.0
   accuracy on same 4 inputs, new noise: 0.485

D=1000 训练精度完美。几百独立连续噪声坐标,这四个采样行几乎 surely 一般位置,超平面好分。这不是“高维数据集每四个标号点都可分”的定理——冲突标签的重复是 obvious 反例。同样四个逻辑输入换新噪声坐标,精度掉回瞎猜。模型分开四个采样行,不是异或函数。维度买了这个训练集好记的分离,别无其他。

再加一个是别的函数坐标,x₁·x₂:

with one extra coordinate x1*x2 (D=3):
   features : [[0,0,0], [0,1,0], [1,0,0], [1,1,1]]
   scores   : [-0.9958, 1.0034, 1.0034, -0.9942]
   accuracy : 1.0

三坐标,完美分离,泛化,因为加的坐标编码了关于问题的真东西。D=1000 与 D=3 的区别不是大小。是一个表示含任务依赖的交互,一个含噪声。

线性模型学一个超平面,D 多大都一样。改变难度的表示是超平面作用的表示。

这正是前面章节网在做的。CNN body 是学到的变换,进单 nn.Linear 够用的表示——这就是第 8 章分类器能 nn.Linear(32, 10) 的原因。卷积堆干了让决策线性的活。

嵌入与线性探针确立什么

同样推理适用于没训过的模型产出的表示。文本、音频、图像 routinely 映成向量:

raw input  →  encoder  →  [B, 768]  →  linear classifier  →  score

分类器不知道也不在乎 768 个数从哪来。两 caution 适用,都是关于 overread。

坐标通常不是概念。 维度 0 是清晰度、维度 1 是幽默的图几乎从不是 learned 表示的 work 方式。属性可能对应方向、子空间、非线性区而不是一轴,这正是本章强调 learned 方向 w 而不是单个系数的原因。100 维实验余弦 0.983 恢复方向——那还是构造了三有意义轴的合成问题。

成功的探针是有界证据。 冻结嵌入上训线性分类器,留出精度高,确立真东西:该线性决策要的信息在该表示里线性可及,在该训练 setup 下。它不确立上游模型以人类方式表示概念,不确立单坐标编码它,不确立上游模型干自己活时因果用它,不确立表示解耦。报告第一个断言;其余要不同实验,是研究领域不是 corollary。

每样本多向量

回到开篇形状,现在有词汇读它。

[8, 128, 768]

8     sequences
128   positions per sequence
768   coordinates describing the representation at each position

这个张量握着一 768 维空间的 1024 个点,按哪个序列、哪个位置产出组织。x[0, 17] 是其中一点,形状 [768],本章确立的一切都适用于它:有范数,与别的向量有夹角,线性层沿方向给它打分。

算子行为对应。nn.Linear(768, 16) 映 [8, 128, 768] -> [8, 128, 16],1024 表示独立变换。F.normalize(x, dim=-1) 让 1024 单位长。其中两向量的点积问方向多大程度一致,按两范数缩放——本章前面的分解,后面后果最大的算子。

在特征空间代码上用 AI

助手读特征空间代码看到形状与算子,本章覆盖的失败里两者通常都对。它看不见的是一向量表示什么,因为那不在代码里。所以 prompt 得先强制 labeling 再解释。

Here is a PyTorch tensor and the code that operates on it.
Do not rewrite the code and do not propose fixes yet.

1. Label every tensor axis semantically. Say which axes are structure
   (how representations are organized) and which axis holds the coordinates
   of one represented object.
2. State plainly what ONE represented object is in this tensor.
3. For every Linear, matmul, dot product or norm:
     - write the input shapes;
     - write the mathematical operation;
     - derive the output shape;
     - state which leading axes are preserved and what that means here.
4. For every call taking a `dim` argument (normalize, softmax, vector_norm,
   cosine_similarity, mean), state which objects that dim makes the operation
   act on, and which vectors become unit norm if it is a normalization.
5. For every number the code eventually reports, classify it as one of:
     raw dot product / cosine similarity / classifier score /
     signed geometric distance / Euclidean distance
   and say what it is invariant to and what it is not.
6. Identify the FIRST place where an operation acts on a different object or
   a different axis than the surrounding code appears to intend.

Only after identifying that divergence should you propose a repair.

步骤 5 赚回位置。助手会 happily 把 x @ y 叫相似度分数,学的大多代码也这么叫。问数对什么 invariant 是有可检查答案的问题,正是分数与距离分开的问题。

系数解释摆上台时第二个问题值得问:

Here are the per-feature standard deviations of my training data and the
learned weight vector. Tell me what I can and cannot conclude about which
features matter, given these scales. Do not rank the features yet.

让 AI 先认出被表示对象与特征轴,再让它解释数。

特征空间调试序列

1.  Print the shape and name every axis. Which are structure, which holds
    the coordinates of one object?

2.  Say out loud what ONE vector represents: a token, a position, an image,
    a whole sequence, a user, a document.

3.  Count the represented objects. If a per-object operation returns more
    numbers than you expected, this is where it went wrong.

4.  Identify D and confirm it matches what the layer was built for.

5.  Run the inspector: norms, per-coordinate scales, non-finite values,
    pairwise cosine. Look for collapse and for one dominant coordinate.

6.  For every `dim=` argument, state which objects that operation acts on.
    Assert the invariant afterwards: unit norms along dim=-1, and so on.

7.  Name the quantity you are about to interpret:
      dot product          not invariant to either norm
      cosine similarity    invariant to both norms, direction only
      Euclidean distance   displacement magnitude
      classifier score     not invariant to parameter rescaling
      signed distance      score / ||w||, invariant to parameter rescaling

8.  If a classifier is involved, report ||w||, scores and distances
    separately, and the fractions wrong-side / inside-margin / beyond.

9.  Before ranking features by coefficient, check the coordinate scales.

10. Change one representation assumption at a time and re-measure.

步骤 1 到 3 抓住开篇失败。步骤 5 到 7 抓住本章其余一切。

别试图可视化空间。盘问定义其几何的量。

练习

这些是用来跑的,对应本章配套 notebook。

  1. 开篇失败。 复现 [8, 128, 768] -> [8, 128, 1],再从 weight[0] 与 bias[0] 手验证一输出值。三种方式产出 [8, 1] 并证明三组分数不同。
  2. 末轴规则。 秩 1、2、3、4 张量过一 nn.Linear,跑前预测每输出形状。再解释 [B, T, D] 上 flatten(1) 为什么不是到逐序列分数的替代路。
  3. 三量。 构造两向量并报告点积、余弦相似度、欧氏距离。再找按余弦最近、按欧氏最远的第三向量,反过来排名的各一。
  4. 尺度与夹角。 固定两向量夹角,一向量四量级缩放。列表点积与余弦。两都归一化并证明点积等于余弦。
  5. 错轴。 建小确定性 [B, T, D] 张量,dim=1 与 dim=-1 各归一化一遍。每种报告哪些向量单位范数。再写抓住错误的断言。
  6. 分数 vs 距离。 训任意线性分类器,w、b 乘 100。验证预测相同、分数大 100、几何距离不动。找分数下游用法里这个重要的一处与不重要的一处。
  7. 坐标系。 一特征乘 100 对应权重除 100。确认分数不变、系数排名变。再缩放与没缩放数据上各训模型比留出精度。
  8. 手算 hinge。 至少八 (y, score) 对算 hinge 表,每对分三间隔区。再训到完美精度并解释 hinge 损失为何仍非零。
  9. 恢复方向。 D=100 埋已知方向,proper split 训练,报告留出精度、与真方向余弦、夹角、随机向量基线。再加噪声、缩训练集、变 C,记每者影响余弦而不是精度。
  10. 建检查器。 写出来,在四表示上跑:健康、一坐标大 1000、塌到近零范数、塌到单方向。每种说出认出问题的行。
  11. 表示,不是维度。 经验与代数都证明异或在两 raw 坐标不可分。再加一派生坐标分开,再 padding 到 D=1000 噪声分开。解释只有一种泛化。

下一步:互相比较向量

格没了,特征空间不再抽象。一对象是坐标列表;方向是同样长度的另一列表;两者点积是分数,符号说对象落超平面哪边。除以 ||w|| 分数变几何距离。两向量都归一化点积变余弦。这些都没要图,全用打印的数可查。

本章三误读值得一起带走,因为结构相同。点积叫相似度,其实还在度量大小。分数叫距离,对参数缩放不 invariant。系数叫重要性,单位没说。三种情形代码都跑,形状都对,数的意思不是名字的意思。

说出被表示对象。找到特征轴。推导算子。再解释分数——并说出分数对什么 invariant。

注意本章反复回来的是哪个算子。线性分类器拿一向量与一 learned 方向比。但 w 从不特殊:它是与 x 同一空间的向量,点积不在乎两者从哪来。batch 里一向量与同样 batch 里另一向量打分,没什么拦着。

那正是手头的形状:

[B, T, D]     B sequences, T positions, D coordinates per position

每序列 T 向量,全住同一 D 维空间,任一能与任一用本章刚 concrete 的算子比。每位置对做一遍产出 T × T 分数格。大小依赖向量范数,成分尺度大致固定时 D 变大还能系统变大。下一章把缩放问题显式化。

下一章认真对待。它问每位置产出的向量与别位置的向量比时发生什么——那些比较如何成形、缩放、掩盖、组合,张量 bookkeeping 哪错。

进注意力。