上一课我们能让整个 Token 序列跑过 Linear Layer 了。
但 Linear Layer 和 MLP 都是逐 Token 计算的,不同 Token 之间仍然无法交换信息。
这一课只解决一件事:让一个 Token 读到其他 Token 的信息。暂时不引入 Q、K、V。
第十一课:Self-Attention 自注意力机制
11.1 重新定义 Layer
之前的接口是:
public interface Layer {
Vector forward(Vector input);
}输入一个向量,输出一个向量。
现在定义一个新接口:
public record HiddenSequence(List<Vector> states) {
public HiddenSequence {
states = List.copyOf(states);
}
}
public interface SequenceLayer {
HiddenSequence forward(HiddenSequence input);
}这两个接口存在根本区别。
Layer 只能变换单个向量,而 SequenceLayer 能访问整个序列。
我们的目标是让每个 Token 的输出向量,不仅包含自身信息,还包含上下文的信息。
这种表示叫 Contextual Representation(上下文相关表示)。
11.2 最简单的信息交换:平均值
假设输入为:
猫 喜欢 吃Embedding 返回以下人为构造的向量:
Vector cat = new Vector(new double[]{2, 0});
Vector like = new Vector(new double[]{0, 1});
Vector eat = new Vector(new double[]{1, 0});我们希望「吃」能获得前面两个 Token 的信息。
最简单的办法就是取平均值:
Vector contextualEat = divide(add(cat, like, eat), 3.0);
// Vector(1.0, 0.3333)如果把「猫」换成「牛」:
Vector cow = new Vector(new double[]{0, 2});
Vector contextualEat = divide(add(cow, like, eat), 3.0);
// Vector(0.3333, 1.0)最后一个 Token 都是「吃」,但最终的向量已经不同了。
最基础的上下文信息交换,成立。
不过代价也明显:位置在最后,就默认能「看到全部」,而且看得一样清楚。真实语言里不是这样。
11.3 从平均值到加权平均
简单平均有个问题:所有 Token 的重要程度完全相同。
例如:
猫 今天 很开心 地 吃在预测接下来吃什么的时候,「猫」可能比「今天」更重要。
因此需要给每个 Token 分配不同的权重。先定义一个专用类型:
public record AttentionWeights(double[] values) {
public AttentionWeights {
values = values.clone();
double sum = 0.0;
for (double w : values) {
if (w < 0.0) {
throw new IllegalArgumentException("权重不能为负:" + w);
}
sum += w;
}
if (Math.abs(sum - 1.0) > 1e-9) {
throw new IllegalArgumentException("权重之和必须是 1,实际为 " + sum);
}
}
}这个类型带着两条约束:所有权重非负,总和约等于 1。
把它写进构造器,而不是写在注释里——第三课那句话在这里第一次真正兑现:约束应该由类型守着,而不是靠调用方自觉。
然后定义加权聚合:
static Vector aggregate(List<Vector> vectors, AttentionWeights weights) {
if (vectors.size() != weights.values().length) {
throw new IllegalArgumentException(
"向量个数与权重个数不一致:"
+ vectors.size() + " vs " + weights.values().length);
}
int dim = vectors.getFirst().dimension();
double[] output = new double[dim];
for (int i = 0; i < vectors.size(); i++) {
Vector vector = vectors.get(i);
double weight = weights.values()[i];
for (int j = 0; j < dim; j++) {
output[j] += vector.values()[j] * weight;
}
}
return new Vector(output);
}这个函数假设输入非空、向量维度相同,并且权重已经通过校验——后一条现在由类型保证了。
输入
- 猫
- [2, 0]
- 权重 0.6
- 喜欢
- [0, 1]
- 权重 0.1
- 吃
- [1, 0]
- 权重 0.3
输出
- aggregate()
- [1.5000, 0.1000]
- 0.6×2 + 0.3×1
权重和为 1,所以输出一定落在三个输入张成的范围内。
Attention 的最终操作,其实就是这样的加权聚合。
真正困难的部分是:权重从哪里来?
11.4 动态计算权重
显然不能让程序员为每个句子手写权重。
因此需要定义一个函数,衡量两个向量之间的匹配程度。
回忆第三课的点积:
double dot(Vector a, Vector b);暂时用点积当评分函数:
public interface AttentionScorer {
double score(Vector reader, Vector source);
}实现:
public final class DotProductScorer implements AttentionScorer {
@Override
public double score(Vector reader, Vector source) {
return Geometry.dot(reader, source);
}
}其中 reader 是想读取信息的 Token,source 是提供信息的 Token。
例如,让「吃」读取整个序列:
double scoreA = dot(eat, cat); // 2.0
double scoreB = dot(eat, like); // 0.0
double scoreC = dot(eat, eat); // 1.0现在拿到三个分数:
public record AttentionScores(double[] values) {
public AttentionScores {
values = values.clone();
}
}AttentionScores scores = new AttentionScores(new double[]{2.0, 0.0, 1.0});注意 AttentionScores 和 AttentionWeights 是不同的类型。
Score 可以是任意实数,Weight 必须非负且总和为 1。
这里还缺一个类型转换函数。
(顺带一提:这两个 record 里装的是 double[],所以 equals 是引用比较。它们在这里只当数据容器用,不参与相等判断;真要比较,得用 Arrays.equals。第九课那个 List<Integer> 的选择,换到这里就换不动了——这也是数组和列表的取舍一直存在的原因。)
11.5 Softmax
Softmax 的类型签名:
AttentionWeights softmax(AttentionScores scores);它把任意有限实数构成的非空向量,转成一个归一化的权重向量。
static AttentionWeights softmax(AttentionScores scores) {
double[] input = scores.values();
double max = Arrays.stream(input).max().orElseThrow();
double[] output = new double[input.length];
double sum = 0.0;
for (int i = 0; i < input.length; i++) {
output[i] = Math.exp(input[i] - max);
sum += output[i];
}
for (int i = 0; i < output.length; i++) {
output[i] /= sum;
}
return new AttentionWeights(output);
}减去 max 是为了避免指数运算浮点溢出,不改变数学上的结果。
| Token | Score | exp(s − max) | 权重 |
|---|---|---|---|
| 猫 | 2.0 | 1.0000 | |
| 喜欢 | 0.0 | 0.1353 | |
| 吃 | 1.0 | 0.3679 |
这里 max = 2.0。减去 max 之后最大项恒为 1,其余都小于 1,指数溢出于是不可能发生。
Softmax 保留分数的大小顺序,并通过指数运算放大分数差异。
现在我们已经能把评分转换成聚合权重。
11.6 实现第一个 Self-Attention
把所有组件组合起来:
public final class SimpleSelfAttention {
private final AttentionScorer scorer = new DotProductScorer();
Vector forward(HiddenSequence sequence, int position) {
List<Vector> states = sequence.states();
Vector reader = states.get(position);
// 只允许读取当前位置及之前的 Token
List<Vector> sources = states.subList(0, position + 1);
double[] scores = new double[sources.size()];
for (int i = 0; i < sources.size(); i++) {
scores[i] = scorer.score(reader, sources.get(i));
}
AttentionWeights weights = softmax(new AttentionScores(scores));
return aggregate(sources, weights);
}
}这已经是一个简化的、带因果约束的 Self-Attention。
flowchart LR
A["HiddenSequence"] --> B["scorer.score() 计算匹配程度"]
B --> C["AttentionScores 任意实数"]
C --> D["softmax() 归一化"]
D --> E["AttentionWeights 非负且和为 1"]
E --> F["aggregate() 加权求和"]
F --> G["Vector 上下文相关表示"]每一步都是上一课写过的类型;这整条链里目前没有任何可训练参数。
注意 subList(0, position + 1) 那一行:它保证第 i 个位置只看得见 0..i。
这是因果掩码的最朴素形态——不靠加一个负无穷大的 mask 矩阵,而是干脆不把未来的 Token 放进 sources。
11.7 当前实现的缺陷
这个实现有一个架构上的问题。
double score = dot(reader, source);随后又直接使用:
output += source * weight;同一个 source 向量,同时承担了两个职责:
- 决定自己是否值得被读取。
- 提供被读取的实际信息。
reader 也只能用原始向量去寻找信息。
这就是下一课要拆开的东西:不是加功能,是分职责。
这使模型难以灵活地学习不同的信息检索与提取规则。当前实现本身甚至没有独立的可训练参数,也没有显式的位置编码。
从软件工程的角度看,应该把三个职责拆开:
public record Query(Vector vector) {
}
public record Key(Vector vector) {
}
public record Value(Vector vector) {
}Query:我需要什么信息?
Key:我拥有什么类型的信息?
Value:如果你选择读取我,我实际提供什么信息?
下一课,我们从职责分离的角度推导 Q、K、V,以及为什么三个独立的 LinearLayer 能赋予 Attention 可学习的信息检索能力。