注意力

閱讀約需 45 分鐘 分鐘,10 節 中共有 8 個範例。

版次 2026.11.16 範例於 2026年11 月 19 通過測試 86 個範例中有 86 個通過 變更內容

由 AI 翻譯。經人工以英文驗證。 我們如何製作書籍

譯自英文書,版次 2026.11.16。 閱讀原文

讀完本章後,你可以用手算出注意力:為每個 token 的查詢(query)與每個較早 token 的鍵(key)之間的匹配程度打分,把分數轉成權重,再對這些權重所選出的值(value)取平均。你會加入因果遮罩(causal mask),避免語言模型看到未來;加入縮放,避免權重全部集中在單一 token 上;也會加入多個注意力頭,讓它們同時尋找不同的東西。接著,你會讀出訓練好的模型注意了什麼、測試它複製了什麼,並衡量它往回看多遠。

第 5 章的視窗模型,是根據前面恰好四個 token 預測商店名稱與描述的下一個 token,這四個 token 並排相接,每個位置各有自己的權重。這個設計有兩項限制。第一,無論往回數第五個 token 多麼重要,它都看不到;第二,它對第一個位置上的 token 與第三個位置上的同一個 token 是分開學習的。這家商店在線上販售家具與家居用品,其描述正好說明第一項限制為何有害:描述常在數十個 token 之後重複產品名稱中的字詞,例如 protect your outdoor patio furniture from harsh elements with this outdoor patio furniture cover。能回頭看名稱的模型,就知道下一個字是什麼。只看得到最後四個 token,也就是 this outdoor patio furniture,的模型,則必須在其他產品中接在這些字詞之後的所有內容裡猜測。

注意力(attention)讓每個位置都能查看所有較早的位置,並根據它們的內容決定各自的重要程度。它最初是為了讓翻譯模型能回頭查看正在翻譯的句子中的字詞而提出(Bahdanau et al., 2015)。它是 transformer(Vaswani et al., 2017)的核心,而 transformer 正是本書在第 10 章閱讀的開放模型所採用的設計。本章先單獨建構注意力,再到本書的小型 transformer 內部去閱讀它;本書稱這個 transformer 為商店的模型:它是以商店的文字訓練一次而成,由第 7 章逐部分組裝起來。

用加權平均回頭看

最近一次變動於第 2026.11.16 版

注意力機制以加權平均取代第 5 章的固定槽位。在每個位置上,模型把它能看到的各位置的向量取平均,算出一個新向量,而權重由模型依內容自行決定:對此處重要的位置給高權重,其餘給低權重。這些權重來自三個向量,每個詞元的嵌入向量經由三個學得的矩陣分別轉換成它們:

  • 一個查詢(query),代表這個位置在尋找什麼的向量,
  • 一個鍵(key),代表這個位置向看著它的位置提供什麼的向量,
  • 一個值(value),代表這個位置被看到時要傳遞出去什麼的向量。

位置 j 對位置 i 的分數,是 i 的查詢與 j 的鍵的內積,再除以 d 的平方根,其中 d 是每個查詢與鍵的大小,也就是它所含的數字個數。softmax 把每一列分數轉成皆為正數且總和為一的權重,位置 i 的輸出則是各個值的加權和。以矩陣形式一次處理所有位置,寫成:

Attention(Q, K, V) = softmax(QKᵀ / √d) V

其中 Q、K、V 分別以列的形式存放每個位置的查詢、鍵與值(Vaswani et al., 2017,第 3.2.1 節)。除以 √d 的原因,留待後面一節說明。

為了在很小的規模上觀察這些運算,取商店文字中的四個詞元:起始標記與 sled coffee table,這是一張底座形狀像雪橇滑板的桌子。為每個詞元指定一個由 8 個數字組成的隨機向量,如同尚未訓練的嵌入表,再用隨機的 8×4 查詢、鍵與值矩陣計算注意力:

attention-by-hand.py Python 3.12.15 · numpy 2.5.5 通過
"""Computes one attention layer by hand for four tokens, with random matrices. The prose's point rests on theprinted weight matrix: each row says which positions one position draws from, and how much."""import numpy as nptokens = ["<s>", "sled</w>", "coffee</w>", "table</w>"]rng = np.random.default_rng(2026)                            # a fixed seed, so the same numbers come out on every runx = rng.normal(0, 1, (4, 8))                        # one 8-number vector per token, as an embedding table givesw_query, w_key, w_value = (rng.normal(0, 0.5, (8, 4)) for _ in range(3))queries, keys, values = x @ w_query, x @ w_key, x @ w_value   # what each token looks for, offers, and passes onscores = queries @ keys.T / np.sqrt(4)                       # how well each query matches each key, scaledweights = np.exp(scores - scores.max(1, keepdims=True))      # subtracting each row's largest score keeps exp from overflowingweights /= weights.sum(1, keepdims=True)                     # softmax along each row: each row sums to 1output = weights @ values                                     # each token: a weighted average of all the valuesnp.set_printoptions(precision=2, suppress=True)print("attention weights (rows attend to columns):")for token, row in zip(tokens, weights):    print(f"  {token:<11}", row)assert np.allclose(weights.sum(1), 1)                        # each row sums to 1, which the prose relies onprint("output shape:", output.shape)
輸出python attention-by-hand.py
attention weights (rows attend to columns):
  <s>         [0.02 0.97 0.01 0.  ]
  sled</w>    [0.21 0.52 0.16 0.11]
  coffee</w>  [0.04 0.   0.03 0.94]
  table</w>   [0.16 0.   0.03 0.81]
output shape: (4, 4)

印出的權重中,每一列就是一個位置的平均:它從哪些位置取值,各取多少。每一列的總和都是一,範例以斷言確認了這點;輸出則是每個位置一個由 4 個數字組成的向量。這些權重是隨機的,因為矩陣是隨機的,但它們已經顯示出注意力的自由度:coffee 把大部分權重放在它後面的詞元 table 上,而起始標記則把大部分權重放在 sled 上。運算本身並沒有任何限制,阻止某個位置往前看。對於預測下一個詞元而言,這種自由是個缺陷,下一節會說明。

這套運算有三項性質,對後面的一切都很重要。第一,權重透過查詢與鍵取決於內容,所以同一個詞元在不同的文字中可以注意到不同的地方。第二,位置的數量無關緊要:同樣的三個矩陣,處理 4 個詞元的名稱或 150 個詞元的描述都行,所以模型學到的是一種回頭看的方式,而不是每個槽位各一種。第三,加權平均不理會被平均對象的順序。沒有遮罩時,注意力讓 bar 在 bar stool 與在 stool bar 中得到相同的輸出。下一節的因果遮罩讓一點順序資訊重新進來,因為每個詞元此時看到的先前詞元數量各不相同,而 Haviv 等人發現,語言模型僅憑這一點就能推斷位置(Haviv et al., 2022)。模型仍會加入明確的位置資訊,第 7 章就是這樣做的。

實用原則: 像這個範例一樣,把注意力的四行運算親手寫一遍,並印出權重矩陣:它的每一列,精確地說明了每個位置往哪裡看。學習階段,請讓查詢、鍵與值保持為各自獨立的矩陣。函式庫常把它們合併在同一個矩陣中,例如 PyTorch 的 MultiheadAttention 就用 in_proj_weight 這樣做(原始碼),再把結果切開,兩者算出的是同樣的東西。

用因果遮罩隱藏未來

最近一次變動於第 2026.11.11 版

在第一節中,coffee的平均值大部分來自較後面的詞元 table。語言模型不能允許這種情形,因為它是根據前面的詞元來預測每個詞元。如果位置 i 可以注意到位置 i + 1,它就會看到答案:訓練會獎勵複製下一個詞元的行為,而模型在生成文字時什麼也學不到,因為生成時下一個詞元尚不存在。解決方法是因果遮罩(causal mask):在 softmax 之前,把所有指向較後面位置的分數設為負無限大。負無限大的指數為零,因此這些位置的權重為零,每個位置只會對自己以及前面的位置取平均。

遮罩也讓訓練更有效率。有了它,對一段文字做一次前向傳遞就能同時預測每個位置,且每個位置只根據自己的過去;第 5 章的視窗模型則必須為每次預測準備各自的視窗。

只有在coffee被允許往後看時,最後一個詞元的變動才可能影響到coffee。對相同四個詞元的分數套用遮罩,把table換成另一個向量,然後分別在沒有遮罩與有遮罩的情況下,測量coffee的輸出移動了多少:

causal-mask.py Python 3.12.15 · numpy 2.5.5 通過
"""Applies the causal mask to the same four tokens, then changes the last token and measures how far the output atcoffee moves, with and without the mask. The prose's point rests on the last printed line: with the mask, that change is zero."""import numpy as nptokens = ["<s>", "sled</w>", "coffee</w>", "table</w>"]rng = np.random.default_rng(2026)x = rng.normal(0, 1, (4, 8))w_query, w_key, w_value = (rng.normal(0, 0.5, (8, 4)) for _ in range(3))   # the same draws as attention-by-handallowed = np.tril(np.ones((4, 4), dtype=bool))               # position i may look at positions 0 to i onlydef attend(x, mask):    scores = (x @ w_query) @ (x @ w_key).T / np.sqrt(4)    if mask:        scores = np.where(allowed, scores, -np.inf)          # a score of minus infinity becomes a weight of 0    weights = np.exp(scores - scores.max(1, keepdims=True))    weights /= weights.sum(1, keepdims=True)    return weights, weights @ (x @ w_value)weights, _ = attend(x, mask=True)np.set_printoptions(precision=2, suppress=True)print("weights with the causal mask:")for token, row in zip(tokens, weights):    print(f"  {token:<11}", row)print("weight on later tokens:", float(weights[~allowed].sum()))   # ~allowed marks the positions above the diagonalchanged = x.copy()changed[3] = rng.normal(0, 1, 8)                             # a different last token in place of `table`for mask in [False, True]:    before, after = attend(x, mask)[1][2], attend(changed, mask)[1][2]   # attend returns (weights, output); 2 is coffee    change = float(np.abs(after - before).max())    print(f"largest change in coffee's output, {'with' if mask else 'without'} the mask: {change:.2f}")    assert (change == 0) == mask      # the mask's job: with it, nothing after coffee reaches coffee, so the change is zero
輸出python causal-mask.py
weights with the causal mask:
  <s>         [1. 0. 0. 0.]
  sled</w>    [0.29 0.71 0.   0.  ]
  coffee</w>  [0.58 0.01 0.41 0.  ]
  table</w>   [0.16 0.   0.03 0.81]
weight on later tokens: 0.0
largest change in coffee's output, without the mask: 4.69
largest change in coffee's output, with the mask: 0.00

權重矩陣現在是下三角矩陣,對角線以上全為零,因此落在較後面詞元上的總權重為 0.0。起始標記只能注意到自己,所以它那一列只有一個 1。sled把權重分給起始標記與自己。coffee在遮罩之前幾乎把全部權重放在較後面的table上,現在則把權重分散到它被允許的位置上,因為 softmax 只在剩下的位置之間做除法。最後一列table沒有改變,因為它本來就沒有較後面的位置可以失去。

最後兩行顯示遮罩所堵住的洩漏。沒有遮罩時,改變最後一個詞元會使coffee的輸出移動多達 4.69。有遮罩時,coffee的輸出不可能取決於後面出現的內容,範例也斷言這個變動為零。沒有遮罩訓練出來的模型,可以學會從下一個位置複製每個答案,因此訓練損失可能降到接近零,卻學不到任何能用於生成文字的東西。過程中不會有任何當機,這正是錯誤的遮罩難以察覺的原因。

**實用原則:**遮罩要在 softmax 之前套用在分數上,而不是在 softmax 之後套用在權重上,這樣每一列的總和仍然為一。測試時採用本範例的做法:檢查較後面位置的權重恰好為零,並檢查改變較後面的詞元後,前面的輸出維持不變。如果模型的訓練損失下降得遠比預期快,應先檢查遮罩。

縮放分數

最近一次變動於第 2026.11.16 版

注意力的公式會把每個分數除以 √d,原因就在點積之中。兩個向量的點積會把每個數值各自對應的乘積加總起來。若查詢與鍵中的數值彼此獨立且隨機,平均為 0、變異數為 1,則分數的變異數為 d,因此查詢與鍵的維度愈大,分數就愈大(Vaswani et al., 2017,第 3.2.1 節,註腳 4)。softmax 會把分數之間的大幅差距轉成極端的權重:某一個位置取得幾乎全部的權重,其餘位置則幾乎得不到。Vaswani 等人推測,處於這種狀態的模型學習緩慢,因為當某個權重接近 1 時,softmax 的梯度會非常小。除以 √d 可以把分數的變異數拉回 1,不論維度為何。

商店模型的例子可以讓這件事更具體:它的注意力頭使用 32 個數值的查詢與鍵。我們抽取三種維度(4、32 與 256)的隨機查詢與鍵,把每個查詢對 16 個鍵評分,分別在有除法與沒有除法的情況下,記錄每一列中最大的權重,並對 1,000 個查詢取平均。先猜猜看:維度為 256 且不做除法時,一列中最大的權重平均會有多大?

scaling-matters.py Python 3.12.15 · numpy 2.5.5 通過
"""Measures the largest softmax weight in each row, at three sizes of query and key, with and without dividing by thesquare root of the size. The prose's point rests on the unscaled averages growing with the size, and the scaled ones staying level."""import numpy as nprng = np.random.default_rng(2026)                            # a fixed seed, so the printed averages are the same on every runfor size in [4, 32, 256]:    # numbers with mean 0 and variance 1, the case the scaling argument assumes; 1,000 queries against 16 keys    queries, keys = rng.normal(0, 1, (1000, size)), rng.normal(0, 1, (16, size))    for divide in [False, True]:        scores = queries @ keys.T / (np.sqrt(size) if divide else 1)        weights = np.exp(scores - scores.max(1, keepdims=True))        weights /= weights.sum(1, keepdims=True)        label = "scaled" if divide else "unscaled"        print(f"size {size}, {label}, average largest weight in a row: {weights.max(1).mean():.2f}")
輸出python scaling-matters.py
size 4, unscaled, average largest weight in a row: 0.45
size 4, scaled, average largest weight in a row: 0.25
size 32, unscaled, average largest weight in a row: 0.78
size 32, scaled, average largest weight in a row: 0.24
size 256, unscaled, average largest weight in a row: 0.92
size 256, scaled, average largest weight in a row: 0.25

不做除法時,最大權重會隨維度增加:維度 4 時為 0.45,維度 32(商店模型各注意力頭的維度)時為 0.78,維度 256 時為 0.92。在較大的維度下,尚未經過任何訓練,每個查詢就已經主要只注意某一個鍵。做了除法之後,不論維度為何,最大權重都維持在 0.25:分散在數個鍵上,但並不均勻,因為 16 個相等的權重各約為 0.06。

訓練應該從這樣的狀態開始。每個位置都會看向其他數個位置,因此梯度能傳到所有這些位置,訓練再於銳利權重有幫助之處讓權重變得銳利。訓練完成的注意力頭仍然可以把大部分權重放在單一位置,商店模型的部分注意力頭就是如此;縮放只是避免各注意力頭一開始就處於那種狀態。

實用原則: 如同 transformer 論文的做法,把注意力分數除以查詢維度的平方根。少數模型(例如 T5)省略這個除法,改把這個係數併入查詢權重的初始化方式(出處),因此在載入模型權重之前,請先確認該模型採用哪一種做法。如果你改變了查詢與鍵的計算或初始化方式,請印出未訓練模型的平均最大權重,並預期它遠低於 1。

多個注意力頭會尋找不同的東西

最近一次變動於第 2026.11.11 版

到目前為止,每一次注意力計算都只為每個位置產生一組權重,而這組權重只能尋找一種東西,例如前一個詞元,或是商品的名稱。模型通常需要同時尋找好幾種。多頭注意力(multi-head attention)會並行執行數個注意力計算,這些計算稱為注意力頭(head),每個注意力頭各有自己的查詢、鍵與值矩陣,並且各自在向量數值的一部分上運作:若向量有 8 個數值、共 2 個注意力頭,則每個注意力頭處理 4 個數值。各注意力頭的輸出會並排接合,再由另一個學得的矩陣混合起來,這個矩陣稱為輸出投影(output projection)(Vaswani et al., 2017,第 3.2.2 節)。

切分數值後,運算成本與單一注意力頭處理全部數值大致相同,而且每個注意力頭都有自己的權重模式。這家商店的模型每一層有 4 個注意力頭,每個注意力頭處理 32 個數值。

以因果遮罩對四個位置的隨機向量執行兩個注意力頭,並觀察最後一個位置在每個注意力頭中是否看向相同的地方:

attention-heads.py Python 3.12.15 · numpy 2.5.5 通過
"""Runs two heads of causal attention over four positions, each head working in four of the eight numbers, then mixesthe heads with an output projection. The prose's point rests on the last position's weights differing between the heads,and on the output keeping the input's shape."""import numpy as nprng = np.random.default_rng(2026)                            # a fixed seed, so the printed weights are the same on every runpositions, dims, heads = 4, 8, 2size = dims // heads                                          # each head works in 4 of the 8 dimensionsx = rng.normal(0, 1, (positions, dims))w_query, w_key, w_value, output_projection = (rng.normal(0, 0.5, (dims, dims)) for _ in range(4))def split(m):                                                 # (positions, dims) -> (heads, positions, size)    return m.reshape(positions, heads, size).transpose(1, 0, 2)   # head 1 takes the first four numbers of each vectorqueries, keys, values = split(x @ w_query), split(x @ w_key), split(x @ w_value)scores = queries @ keys.transpose(0, 2, 1) / np.sqrt(size)             # one score matrix per headscores = np.where(np.tril(np.ones((positions, positions), dtype=bool)), scores, -np.inf)   # the causal mask, for both headsweights = np.exp(scores - scores.max(-1, keepdims=True))weights /= weights.sum(-1, keepdims=True)joined = (weights @ values).transpose(1, 0, 2).reshape(positions, dims)   # the heads' outputs side by sideoutput = joined @ output_projection                                       # mixed back together by one more matrixprint("weights shape (heads, positions, positions):", weights.shape)print("what the last token attends to, head 1:", np.round(weights[0, -1], 2))   # -1 is the last position, which sees all fourprint("what the last token attends to, head 2:", np.round(weights[1, -1], 2))print("output shape:", output.shape)
輸出python attention-heads.py
weights shape (heads, positions, positions): (2, 4, 4)
what the last token attends to, head 1: [0.41 0.18 0.29 0.11]
what the last token attends to, head 2: [0.04 0.32 0.14 0.5 ]
output shape: (4, 8)

權重現在每個注意力頭各有一個矩陣,形狀為 (2, 4, 4)。雖然兩個注意力頭讀取相同的輸入,最後一個位置的各列在兩者之間卻不相同:第 1 個注意力頭把最大的權重放在第一個位置,第 2 個注意力頭則放在最後一個位置,也就是它自己。使用隨機矩陣時,這個差異尚無意義,但這正是訓練所利用的空間:每個注意力頭都可以學會不同的回看方式,再由輸出投影把它們的發現結合起來。輸出又回到與輸入相同的形狀 (4, 8),因此注意力層可以堆疊,如第 7 章所做的那樣。

實用原則: 經驗法則是讓每個注意力頭至少有 32 個數值寬。在 Transformer 論文的實驗中,16 個各為 32 的注意力頭與 8 個各為 64 的注意力頭表現相當,而 32 個各為 16 的注意力頭表現較差,縮小鍵的大小也會造成損害(Vaswani et al., 2017,表 3)。每當修改模型時,都要檢查權重張量的形狀,即注意力頭數乘以位置數乘以位置數:注意力頭的軸放錯位置,會把各注意力頭混在一起,而且不會出現任何錯誤。

此部分尚未翻譯,因此以英文呈現。

Read what trained heads attend to

最近一次變動於第 2026.11.11 版

Random matrices show the arithmetic; a trained model shows what attention is for. The store's model has 4 layers, each with 4 heads of attention. It was trained once, in recordings/transformer.py, on the store's training names and descriptions, each product as one text: the start marker, the name, a separator token <sep>, the description and the end marker. Each layer's attention reads the output of the layer before, so later layers can attend on the basis of what earlier ones found. As in chapter 5, the examples read the saved weights and recompute the model in NumPy, with lib.transformer, which also returns every head's weights.

The question is where the model looks for cover in a validation product it never trained on, double chaise patio furniture cover, whose description repeats the end of its name. Stop at the description's second furniture, where the next token is cover, and print the model's probability for cover, and each head's three largest weights in the first and last layers. current: marks the position being predicted from, name: a token in the name, and description: an earlier token in the description:

trained-attention.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通過
"""Runs the store's trained model on one validation product, up to the description's second furniture, and prints whereits heads attend there. The prose's point rests on the last layer's head with the most weight on the name's cover, and onthe probability it gives cover."""import numpy as npfrom lib import transformerfrom lib.store import load_products_, vocabulary, manifest = transformer.load()   # forward reads the weights itself, so only the vocabulary and manifest are keptsettings = manifest["settings"]index = {t: i for i, t in enumerate(vocabulary)}product = load_products("validation").query("name == 'double chaise patio furniture cover'").iloc[0]ids = transformer.product_ids(product["name"], product["description"], index, settings["longest"])sep = ids.index(index[transformer.SEP])position = ids.index(ids[sep - 1], sep) - 1           # just before the description first repeats the name's last tokenlogits, attention = transformer.forward(ids, keep=True)probabilities = transformer.softmax(logits[position])def label(i):    """Where a token sits: the current position, the name, the description, or a marker."""    if i == position:        return f"current:{vocabulary[ids[i]]}"    if i == 0 or i == sep:        return vocabulary[ids[i]]    return f"{'name' if i < sep else 'description'}:{vocabulary[ids[i]]}"print("layers:", settings["layers"])print("heads per layer:", settings["heads"])print("dimensions per head:", settings["dimensions"] // settings["heads"])print("name:", " ".join(vocabulary[i] for i in ids[1:sep]))# after <sep>, up to and including the current positionprint("description so far:", " ".join(vocabulary[i] for i in ids[sep + 1:position + 1]))# position + 1 is the token that really comes next in the textprint(f"P(next token is {vocabulary[ids[position + 1]]}): {probabilities[ids[position + 1]]:.2f}")for layer in [0, len(attention) - 1]:    for head, weights in enumerate(attention[layer]):        top = np.argsort(-weights[position], kind="stable")[:3]        print(f"layer {layer + 1}, head {head + 1}: " + ", ".join(f"{label(i)} {weights[position, i]:.2f}" for i in top))name_cover = sep - 1                                     # the name's last token, `cover`earlier = ids.index(ids[position], sep + 1)              # the description's earlier `furniture`last = attention[-1][:, position]                        # the last layer's heads, at the current positionhead = int(last[:, name_cover].argmax())print("last-layer head with the most weight on the name's cover:", f"head {head + 1}")print("its weight on the name's cover:", f"{last[head, name_cover]:.2f}")print(f"its weight on {vocabulary[ids[earlier + 1]].removesuffix('</w>')}, after the description's earlier furniture:",  # earlier + 1: the token after the first furniture      f"{last[head, earlier + 1]:.2f}")
輸出python trained-attention.py
layers: 4
heads per layer: 4
dimensions per head: 32
name: double</w> chaise</w> patio</w> furniture</w> cover</w>
description so far: protect</w> your</w> outdoor</w> patio</w> furniture</w> from</w> har sh</w> elements</w> with</w> this</w> outdoor</w> patio</w> furniture</w>
P(next token is cover</w>): 0.97
layer 1, head 1: current:furniture</w> 0.80, description:furniture</w> 0.11, description:elements</w> 0.03
layer 1, head 2: current:furniture</w> 0.31, name:furniture</w> 0.13, description:furniture</w> 0.11
layer 1, head 3: current:furniture</w> 0.18, description:patio</w> 0.18, <sep> 0.12
layer 1, head 4: description:protect</w> 0.17, current:furniture</w> 0.14, description:patio</w> 0.11
layer 4, head 1: name:cover</w> 0.48, name:double</w> 0.18, name:furniture</w> 0.13
layer 4, head 2: name:cover</w> 0.37, <s> 0.13, name:chaise</w> 0.11
layer 4, head 3: description:patio</w> 0.27, current:furniture</w> 0.25, description:outdoor</w> 0.21
layer 4, head 4: description:with</w> 0.38, description:from</w> 0.21, description:elements</w> 0.06
last-layer head with the most weight on the name's cover: head 1
its weight on the name's cover: 0.48
its weight on from, after the description's earlier furniture: 0.00

The model gives cover a probability of 0.97, and the heads show where it may have looked. In the first layer, one head attends mostly to the current token, furniture, and the other three spread their weight over the description and the name so far. In the last layer, head 1 puts 0.48 of its weight on cover in the name, many tokens back: the token that followed furniture in the name. The description's own earlier furniture was followed by from, and that head gives from only 0.00. A second last-layer head also puts its largest weight on the name's cover.

That pattern has a name. Olsson and colleagues found pairs of heads that work this way in small models made only of attention layers, and heads with the same behaviour in large models. They call the later head of each pair an induction head: a head in an earlier layer copies each token's predecessor into its position, and the induction head uses that to find earlier positions that followed the current token, and attends to them (Olsson et al., 2022). The weights above are consistent with that behaviour, but weights show where a head drew its average from, not what the model used, so the next section tests it.

Working rule: Inspect a trained model by starting with specific tokens in texts you understand, where you know what the model should look at. Treat what the weights suggest as a hypothesis, and test it by changing the input, as the next section does.

測試模型複製了什麼

最近一次變動於第 2026.11.11 版

如果模型是從名稱中複製 cover 來預測它,那麼更改名稱就應該改變預測。如果模型預測 cover 是因為這類描述經常這樣接續,那麼名稱就不太重要。改變輸入並觀察輸出的測試可以回答這個問題,而注意力權重做不到。

保留描述,改變名稱:維持原本的銷售名稱、去掉 cover,或以 set 結尾。在同一個位置比較 cover 與 set 的機率,就能看出預測是否隨名稱而變。接著計算訓練描述中接在 this outdoor patio furniture 之後的內容,也就是視窗模型會看到的那四個詞元:

copy-from-the-name.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通過
"""Changes the name of one validation product and reads the model's probabilities for cover and set at the same position,then counts what follows this outdoor patio furniture in the training descriptions. The prose's point rests on P(cover)falling when cover leaves the name, and on how rarely this outdoor patio furniture is followed by cover in the trainingdescriptions, which is all the four tokens alone give."""from lib import transformerfrom lib.store import load_products_, vocabulary, manifest = transformer.load()   # forward reads the weights itself, so only the vocabulary and manifest are keptindex = {t: i for i, t in enumerate(vocabulary)}product = load_products("validation").query("name == 'double chaise patio furniture cover'").iloc[0]cover, other = index["cover</w>"], index["set</w>"]for name, label in [("double chaise patio furniture cover", "name as sold"),                    ("double chaise patio furniture", "name without cover"),                    ("double chaise patio furniture set", "name ending in set")]:    ids = transformer.product_ids(name, product["description"], index, manifest["settings"]["longest"])    sep = ids.index(index[transformer.SEP])    furniture = [i for i in range(sep + 1, len(ids)) if ids[i] == index["furniture</w>"]]    p = transformer.softmax(transformer.forward(ids)[furniture[1]])   # at the description's second `furniture`    print(f"{label}, P(cover): {p[cover]:.2f}")    print(f"{label}, P(set): {p[other]:.2f}")phrase = "this outdoor patio furniture "                    # the trailing space makes the phrase end at a word boundary# the word after the phrase, in each description that has one; a phrase at the very end has no next word and is skippedafter = [d.split(phrase, 1)[1].split()[0] for d in load_products("train")["description"]         if isinstance(d, str) and phrase in d and d.split(phrase, 1)[1].split()]print("training descriptions with 'this outdoor patio furniture':", len(after))print("followed by cover:", after.count("cover"))
輸出python copy-from-the-name.py
name as sold, P(cover): 0.97
name as sold, P(set): 0.02
name without cover, P(cover): 0.00
name without cover, P(set): 0.29
name ending in set, P(cover): 0.00
name ending in set, P(set): 0.70
training descriptions with 'this outdoor patio furniture': 6
followed by cover: 2

名稱決定了預測。名稱維持原樣時,模型給 cover 的機率是 0.97;名稱中沒有 cover 時,機率降到 0.00。若改以 set 作為名稱結尾,模型給 set 的機率是 0.70,給 cover 的機率是 0.00。

單憑這四個詞元,只能微弱地指向 cover:在包含 this outdoor patio furniture 的 6 筆訓練描述中,有 2 筆接著出現 cover。

這正是上一節的權重所暗示的行為,現在由其效果證實:模型從商品名稱中複製了一個相隔許多詞元的字詞,而受限於四個詞元視窗的模型做不到這一點。單一商品無法衡量模型這麼做的頻率;接下來兩節會在許多商品上衡量它的注意力頭。

實用原則: 要驗證關於模型使用了什麼的說法,就改變該輸入並測量輸出,同時加入一項應該不影響輸出的改變。注意力權重用來提出假設,像這樣的測試才用來下結論。

有些注意力頭會關注前一個詞元

最近一次變動於第 2026.11.11 版

單一文本可能產生誤導;對大量文本取平均,才能看出注意力頭的習慣。一個值得測量的習慣是關注前一個詞元。做到這一點的注意力頭,會把每個詞元的前一個詞元帶入該詞元所在的位置,因此後面的層看到的是成對的詞元,就像第 1 章的二元組計數一樣。前幾節的複製行為也仰賴這一點:若要找出先前接在 furniture 後面的是什麼,注意力頭需要每個較早的位置都知道它的前一個詞元。

我們對前 300 筆驗證集商品,計算每個注意力頭放在前一個詞元上的平均權重,並將放在前一個詞元上權重最多的注意力頭與均勻分布相比。均勻分布會在位置 i 能看到的 i + 1 個詞元上,各放 1 / (i + 1) 的權重:

previous-token-heads.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通過
"""Averages each head's weight on the previous token over 300 validation products, and sets the largest average besidean even spread. The prose's point rests on the head with the most weight on the previous token, and on the even spread beside it."""import numpy as npfrom lib import transformerfrom lib.products import product_textstexts = product_texts("validation", 300)                    # the first 300 validation products, which the model never trained on# with keep=True, forward's second value is every layer's weights; the head count is in the manifest's settingslayers, heads = len(transformer.forward(texts[0][0], keep=True)[1]), transformer.load()[2]["settings"]["heads"]on_previous = np.zeros((layers, heads))for ids, _ in texts:    _, attention = transformer.forward(ids, keep=True)    for layer, weights in enumerate(attention):        # weights: (heads, positions, positions)        on_previous[layer] += weights[:, np.arange(1, len(ids)), np.arange(len(ids) - 1)].mean(1)   # position i's weight on i - 1, for i after the starton_previous /= len(texts)even = np.mean([np.mean(1 / np.arange(2, len(ids) + 1)) for ids, _ in texts])   # position i sees i + 1 tokens, so 1 / (i + 1) eachprint("average weight on the previous token (rows: layers, columns: heads):")for layer, row in enumerate(on_previous, start=1):    print(f"  layer {layer}: " + "  ".join(f"{w:.2f}" for w in row))layer, head = np.unravel_index(on_previous.argmax(), on_previous.shape)print("head with the most weight on the previous token:", f"layer {layer + 1}, head {head + 1}")print("its weight on the previous token:", f"{on_previous.max():.2f}")print("an even spread's weight on the previous token:", f"{even:.2f}")
輸出python previous-token-heads.py
average weight on the previous token (rows: layers, columns: heads):
  layer 1: 0.03  0.06  0.13  0.10
  layer 2: 0.32  0.13  0.27  0.24
  layer 3: 0.13  0.33  0.09  0.07
  layer 4: 0.11  0.07  0.35  0.27
head with the most weight on the previous token: layer 4, head 3
its weight on the previous token: 0.35
an even spread's weight on the previous token: 0.07

在前一個詞元上放最多權重的注意力頭是 layer 4, head 3,平均權重為 0.35。以同樣方式平均,均勻分布在該處只會放 0.07,所以該注意力頭偏好前一個詞元的程度約為均勻分布的五倍。後面幾層中有數個注意力頭在這裡放了四分之一以上的權重,而第一層的注意力頭放得少得多:在訓練後注意力範例中,其中一個注意力頭主要關注當前的詞元。

沒有任何一個注意力頭純粹只是前一個詞元頭;每個注意力頭都把這項習慣與其他習慣混合在一起。注意力頭的平均值說明的是它最常做的事,而不是它做的全部,因此把一個注意力頭描述為只有單一工作,是過度簡化。

**實用原則:**以測得的平均值來描述訓練後的注意力頭,例如它在前一個詞元、當前詞元或起始標記上的權重,並對數百個文本取平均。將每一項與以同樣方式平均的均勻分布結果相比,這樣 0.3 之類的數字才能判讀為大或小。

越過視窗

最近一次變動於第 2026.11.11 版

注意力的承諾,是能看見超出第 5 章四個詞元視窗的範圍;該視窗是以目前的詞元和前面三個詞元來預測。商店的模型是否做到這一點,是可以量測的。視窗之外落下了多少權重?針對前 300 筆驗證商品中的每個描述詞元(不含結尾標記),我們把每個注意力頭放在往前 4 個或更多位置的詞元上的權重加總,這是四個詞元的視窗最近看不到的範圍;另外也單獨加總放在兩個標記 <s> 與 <sep> 上的權重。接著對詞元、注意力頭和層取平均,並與在每個詞元可見位置上平均分配的情況相比:

attention-reaches-back.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 通過
"""Measures how much attention a description token puts on tokens four or more positions back, and on the two markers,against an even spread, over 300 validation products. The prose's point rests on the all-layers share four or more back,and on the count of descriptions that repeat a token of the name."""import numpy as npfrom lib import transformerfrom lib.products import product_texts_, vocabulary, manifest = transformer.load()end = vocabulary.index(transformer.END)texts = product_texts("validation", 300)                    # the first 300 validation products, which the model never trained onlayers = manifest["settings"]["layers"]far, markers, even_far, even_markers, counted = np.zeros(layers), np.zeros(layers), 0.0, 0.0, 0for ids, sep in texts:    # the description's tokens: after <sep>, so not the name, and without the end marker    queries = np.array([i for i in range(sep + 1, len(ids)) if ids[i] != end])    if len(queries) == 0:        continue                                          # a product with no description    _, attention = transformer.forward(ids, keep=True)    stacked = np.stack(attention)[:, :, queries]          # (layers, heads, description tokens, positions)    positions = np.arange(len(ids))    is_marker = np.isin(positions, [0, sep])              # <s> and <sep>    beyond = (queries[:, None] - positions[None, :] >= 4) & ~is_marker   # 4 positions back is the nearest a four-token window can't see    far += (stacked * beyond).sum(-1).mean(1).sum(-1)    markers += (stacked * is_marker).sum(-1).mean(1).sum(-1)    even_far += (beyond.sum(1) / (queries + 1)).sum()     # an even spread over the positions each token can see    even_markers += (2 / (queries + 1)).sum()             # two markers among the query's i + 1 visible positions    counted += len(queries)print("description tokens measured:", f"{counted:,}")print("average attention weight of a description token, by layer:")for layer in range(layers):    print(f"  layer {layer + 1}: 4 or more tokens back {far[layer] / counted:.2f}, on <s> and <sep> {markers[layer] / counted:.2f}")print("all layers, weight 4 or more tokens back:", f"{far.mean() / counted:.2f}")print("an even spread's weight 4 or more tokens back:", f"{even_far / counted:.2f}")print("all layers, weight on <s> and <sep>:", f"{markers.mean() / counted:.2f}")print("an even spread's weight on <s> and <sep>:", f"{even_markers / counted:.2f}")# the name without <s>, and what follows <sep>; a product counts as described if anything but the end marker followsdescribed = [(ids[1:sep], ids[sep + 1:]) for ids, sep in texts if any(i != end for i in ids[sep + 1:])]print("products with a description:", len(described))print("descriptions that repeat a token of the name:", sum(bool(set(n) & set(d)) for n, d in described))
輸出python attention-reaches-back.py
description tokens measured: 20,571
average attention weight of a description token, by layer:
  layer 1: 4 or more tokens back 0.42, on <s> and <sep> 0.12
  layer 2: 4 or more tokens back 0.39, on <s> and <sep> 0.04
  layer 3: 4 or more tokens back 0.58, on <s> and <sep> 0.13
  layer 4: 4 or more tokens back 0.47, on <s> and <sep> 0.13
all layers, weight 4 or more tokens back: 0.46
an even spread's weight 4 or more tokens back: 0.85
all layers, weight on <s> and <sep>: 0.11
an even spread's weight on <s> and <sep>: 0.05
products with a description: 262
descriptions that repeat a token of the name: 244

如預測下一個詞時所預期的,各注意力頭偏好鄰近的詞元,但仍有相當大比例的注意力落在視窗之外,這是本書先前任何模型都無法利用的。在所有層中,描述詞元把 0.46 的注意力放在往前 4 個或更多位置的詞元上,而平均分配時會是 0.85,因為描述詞元可見的內容大多位於遠處。

這對此類文字很重要:在 262 個有描述的商品中,有 244 個的描述至少重複了名稱中的一個詞元。

標記獲得 0.11 的注意力,平均分配則是 0.05:約為隨機情況的兩倍,儘管它們本身不預測任何詞。一個可能的原因是較大型模型中發現的一種模式。Softmax 使每一列權重的總和為一,因此若某個注意力頭在某個位置找不到有用的內容,仍必須把權重放在某處;Xiao 等人發現,語言模型會把很大的權重放在文本最前面的詞元上,不論那些詞元是什麼,並稱之為注意力匯聚點(attention sinks,Xiao et al., 2024)。在商店的模型中,<s> 一定在最前面,<sep> 則出現在每段文字中,所以兩者都可能扮演這個角色;<sep> 同時標示描述從何處開始,這本身就有用。本範例無法區分這兩者。

實用原則: 在決定模型的上下文需要多長之前,先量測已訓練模型向前注意多遠,並與平均分配相比,讓這個數字有意義。把標記上的權重另外回報,以免標記權重被誤認為長距離注意力;為節省空間而截短模型的上下文時,則要保留最前面的詞元。

正式環境中會出什麼問題

最近一次變動於第 2026.11.16 版

注意力是語言模型中成本隨文本長度成長最快的部分,也是最常被誤解的部分:

  • 成本隨長度的平方成長。 每個位置都要對之前的每個位置計算分數,因此長度加倍的文本,注意力的成本會變成四倍。請設定最大長度,如同商店的模型將其設為 160 個 token,並檢查有多少文本被這個上限截斷。
  • 錯誤的遮罩會悄悄失效。 一個看得到未來的模型,可能達到很低的訓練損失,卻仍然無法用來生成文本。請在訓練程式碼與生成程式碼中測試:後面位置的權重為零,且更動後面的 token 不會改變前面位置的輸出。
  • 注意力權重不是解釋。 高權重只說明某個注意力頭從哪裡取得平均,並不說明模型為何做出那樣的預測。在同一個模型中,差異極大的注意力權重也可能得出相同的預測(Jain and Wallace, 2019,針對循環式與卷積式分類器)。請用權重來提出假說,再以更動輸入的方式加以檢驗,如同本章對產品名稱所做的那樣。
  • 標記符號上的權重看起來像重要性。 第一個 token 或分隔符號上的大量權重,可能只表示某個注意力頭在那裡無事可做。不要移除這些 token,也不要把它們的權重解讀為有意義。
  • softmax 若不小心處理會溢位。 在取指數之前,先減去每一列的最大分數,如同 lib.transformer.softmax 所做的那樣。並確認每一列至少保留一個未被遮蔽的位置,否則該列會變成 NaN:因果遮罩一定會讓每個位置保留它自己,但遮蔽填充(padding)的遮罩可能把整列都遮住。

本章的決定

  • **本書的模型採用因果、縮放的多頭注意力(causal, scaled, multi-head attention),**定義依 Vaswani 等人:分數除以每個注意力頭的查詢(query)與鍵(key)大小的平方根,在 softmax 之前,將所有後面位置的分數設為負無限大,各個注意力頭分別處理其中一部分數值,再由輸出投影(output projection)將結果混合。
  • **商店的模型有 4 層,每層 4 個注意力頭,每個頭寬 32 個數值,**由 recordings/transformer.py 以名稱與描述訓練一次,兩者以 <sep> 標記相連,並由 lib.transformer 以 NumPy 重新計算。
  • **關於模型使用了什麼的說法,要靠改變輸入來檢驗。**注意力權重只能提出假設;更改商品名稱後,結果顯示模型會從名稱中複製 cover。
  • **訓練後的注意力頭,以大量文本上的測量平均值來描述,**並與均勻分布相比較:放在前一個詞元上的權重、放在往前 4 個以上詞元上的權重,以及放在標記上的權重,三者分開計算。
  • **在商店的描述文字上,注意力遠遠超出第 5 章的視窗。**描述中的詞元將 0.46 的注意力放在往前 4 個以上的詞元上,而且模型會從名稱複製內容,這是固定視窗做不到的。
  • **注意力需要明確的位置資訊。**加權平均不考慮順序,因果遮罩(causal mask)只能恢復一小部分順序,因此第 7 章加入旋轉位置編碼,商店的模型在每個注意力頭內部也是這樣做。

本章,於本版次中

版次 2026.11.16範例於 2026年11 月 19 通過測試本章 8 個範例 個範例中有 8 個通過

譯自英文書,版次 2026.11.16。

引用本節

格式

各種格式皆引用英文原書,本譯本即依循該原書。

每種格式都會標示本版。其連結會開啟目前版次,節標題會說明該節內文最後一次變動的時間。存取日期與擷取日期即為你開啟此頁的當日。

本頁內容

第 6 章,共 11 章: 注意力

  1. 用加權平均回頭看
  2. 用因果遮罩隱藏未來
  3. 縮放分數
  4. 多個注意力頭會尋找不同的東西
  5. Read what trained heads attend to
  6. 測試模型複製了什麼
  7. 有些注意力頭會關注前一個詞元
  8. 越過視窗
  9. 正式環境中會出什麼問題
  10. 本章的決定

返回頂端所有章節