アテンション
読了まで約42 分分、10 節 節の 8 例 例。
この章を終えるまでに、アテンションを手計算できるようになる。各トークンのクエリが、それ以前のすべてのトークンのキーとどれだけ合致するかをスコアにし、そのスコアを重みに変換し、その重みが選び出す値を平均する。言語モデルが未来を見ないようにする因果マスク、重みが1つのトークンに集中して崩れるのを防ぐスケーリング、異なるものを同時に探す複数のヘッドも加える。そのうえで、学習済みモデルが何にアテンションを向けているかを読み取り、何をコピーするかを検証し、どこまで遠くを見ているかを測定する。
第5章のウィンドウモデルは、店の商品名と商品説明の次のトークンを、直前のちょうど4トークンから予測した。4トークンは横に並べて結合され、各スロットがそれぞれ固有の重みを持っていた。この設計には2つの限界がある。1つ目は、どれほど重要であっても5つ前のトークンを見られないことである。2つ目は、最初のスロットにあるトークンと、3番目のスロットにある同じトークンを、別々に学習してしまうことである。この店は家具と家庭用品をオンラインで販売している。商品説明には、商品名の語が数十トークン後に繰り返されることがよくあり、ここから1つ目の限界の問題がわかる。例は protect your outdoor patio furniture from harsh elements with this outdoor patio furniture cover である。名前まで遡って見られるモデルは、次にどの語が来るかがわかる。直前の4トークン this outdoor patio furniture しか見えないモデルは、他の商品でその語句に続くあらゆる語のなかから推測するしかない。
アテンション(attention)は、すべての位置がそれ以前のすべての位置を見て、その内容から各位置がどれだけ重要かを判断できるようにする。もともとは、翻訳モデルが翻訳中の文の単語を振り返って参照できるようにするために導入された(Bahdanau et al., 2015)。アテンションはトランスフォーマー(Vaswani et al., 2017)の中核であり、本書が第10章で読むオープンモデルの設計でもある。この章ではまずアテンションを単独で構築し、次に本書の小さなトランスフォーマー(本書では店のモデルと呼ぶ)の内部で読み解く。店のテキストで一度学習させたトランスフォーマーであり、第7章で部品ごとに組み立てる。
重み付き平均で過去を振り返る
アテンションは、第5章の固定スロットを重み付き平均に置き換える。各位置で、モデルは自分が参照できる位置のベクトルの平均として新しいベクトルを計算する。その重みは各位置の内容に基づいてモデルが選ぶもので、ここで重要な位置には高く、それ以外には低く与えられる。重みは、各トークンの埋め込みを3つの学習済み行列で変換して得られる3つのベクトルから求められる。
- クエリ(query)は、この位置が何を探しているかを表すベクトルである。
- キー(key)は、この位置が、自分を参照する位置に対して何を提供するかを表すベクトルである。
- バリュー(value)は、この位置が参照されたときに何を受け渡すかを表すベクトルである。
位置 i から見た位置 j のスコアは、i のクエリと j のキーの内積を、d の平方根で割ったものである。ここで d は各クエリとキーの大きさ、つまりそれが保持する数値の個数を指す。ソフトマックスは、スコアの各行を、正の値で合計が1になる重みに変換し、位置 i の出力はバリューの重み付き和となる。全位置を一度に扱う行列の形では、次のように書ける。
Attention(Q, K, V) = softmax(QKᵀ / √d) V
ここで Q、K、V は、各位置のクエリ、キー、バリューを行として並べたものである(Vaswani et al., 2017、3.2.1節)。√d で割る理由は後の節で扱う。
小さな例で計算を追うために、ストアのテキストから4つのトークンを取る。開始マーカーとsled coffee tableである。これは、土台がそりの滑走部のような形をしたコーヒーテーブルを指す。それぞれに、未学習の埋め込みテーブルと同じように8個の数値からなるランダムなベクトルを与え、8×4のランダムなクエリ、キー、バリューの行列でアテンションを計算する。
1"""Computes one attention layer by hand for four tokens, with random matrices. The prose's point rests on the2printed weight matrix: each row says which positions one position draws from, and how much."""3import numpy as np45tokens = ["<s>", "sled</w>", "coffee</w>", "table</w>"]6rng = np.random.default_rng(2026) # a fixed seed, so the same numbers come out on every run7x = rng.normal(0, 1, (4, 8)) # one 8-number vector per token, as an embedding table gives8w_query, w_key, w_value = (rng.normal(0, 0.5, (8, 4)) for _ in range(3))910queries, keys, values = x @ w_query, x @ w_key, x @ w_value # what each token looks for, offers, and passes on11scores = queries @ keys.T / np.sqrt(4) # how well each query matches each key, scaled12weights = np.exp(scores - scores.max(1, keepdims=True)) # subtracting each row's largest score keeps exp from overflowing13weights /= weights.sum(1, keepdims=True) # softmax along each row: each row sums to 114output = weights @ values # each token: a weighted average of all the values1516np.set_printoptions(precision=2, suppress=True)17print("attention weights (rows attend to columns):")18for token, row in zip(tokens, weights):19 print(f" {token:<11}", row)20assert np.allclose(weights.sum(1), 1) # each row sums to 1, which the prose relies on21print("output shape:", output.shape)
python attention-by-hand.pyattention 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)
出力された重みの各行は、1つの位置の平均を表す。どの位置からどれだけ取り込むかを示している。どの行も合計は1になり、この例ではそれを assert で確認している。出力は、位置ごとに4個の数値からなるベクトルが1本ずつ並んだものである。行列がランダムなので重みもランダムだが、それでもアテンションの自由度はすでに表れている。coffeeは、自分より後ろのトークンであるtableに最も大きな重みを置き、開始マーカーはsledに最も大きな重みを置いている。計算上、ある位置が先を見ることを妨げるものは何もない。次のトークンを予測する場合、この自由度は欠陥となる。その理由は次の節で示す。
この計算の3つの性質は、以降のすべてにとって重要である。第1に、重みはクエリとキーを通じて内容に依存するため、同じトークンでもテキストが違えば異なる場所に注目できる。第2に、位置の数は問題にならない。同じ3つの行列が、4トークンの名前にも150トークンの説明文にも使えるので、モデルが学ぶのはスロットごとの見方ではなく、過去を振り返る1つの方法である。第3に、重み付き平均は平均する対象の順序を無視する。マスクがなければ、アテンションはbarに対して、bar stoolでもstool barでも同じ出力を与える。次の節の因果マスクは、少しだけ順序を取り戻す。各トークンが見られる過去のトークン数がそれぞれ異なるようになるからである。Haviv らは、言語モデルがそれだけから位置を推測できることを見出した(Haviv et al., 2022)。それでも、モデルは第7章で行うように、明示的な位置情報を加える。
実践ルール: この例のように、アテンションの4行の計算を一度は自分で書き下し、重み行列を出力して確かめること。その各行は、各位置がどこを見ているかを正確に示している。学習のあいだは、クエリ、キー、バリューを別々の行列として扱うこと。ライブラリでは、PyTorch のMultiheadAttentionがin_proj_weightでそうしているように、3つを1つの行列にまとめ、結果を分割することが多い(ソース)。これで計算される内容は同じである。
因果マスクで未来を隠す
最初の節では、coffeeは平均のほとんどを、後ろのトークンであるtableから取っていた。言語モデルにこれを許すことはできない。言語モデルは各トークンを、それより前のトークンから予測するからである。位置 i が位置 i + 1 に注目できるとすると、答えが見えてしまう。訓練では次のトークンを写すことが報われ、モデルは、次のトークンがまだ存在しないテキスト生成の場面で使えるものを何も学ばない。その対策が因果マスクである。softmax の前に、後ろの位置に対するスコアをすべて負の無限大にする。負の無限大の指数は 0 なので、それらの位置の重みは 0 になり、各位置は自分自身とそれより前の位置だけで平均を取る。
マスクは訓練も効率的にする。マスクがあれば、テキストを 1 回通すだけで、すべての位置をそれぞれの過去から同時に予測できる。第5章のウィンドウモデルでは、予測のたびに別々のウィンドウが必要だった。
最後のトークンへの変更がcoffeeに届くのは、coffeeが先を見ることを許されている場合に限られる。同じ 4 つのトークンのスコアにマスクを適用し、tableを別のベクトルに置き換えて、coffeeでの出力がどれだけ動くかを、マスクなしとマスクありで測る。
1"""Applies the causal mask to the same four tokens, then changes the last token and measures how far the output at2coffee moves, with and without the mask. The prose's point rests on the last printed line: with the mask, that change is zero."""3import numpy as np45tokens = ["<s>", "sled</w>", "coffee</w>", "table</w>"]6rng = np.random.default_rng(2026)7x = rng.normal(0, 1, (4, 8))8w_query, w_key, w_value = (rng.normal(0, 0.5, (8, 4)) for _ in range(3)) # the same draws as attention-by-hand9allowed = np.tril(np.ones((4, 4), dtype=bool)) # position i may look at positions 0 to i only101112def attend(x, mask):13 scores = (x @ w_query) @ (x @ w_key).T / np.sqrt(4)14 if mask:15 scores = np.where(allowed, scores, -np.inf) # a score of minus infinity becomes a weight of 016 weights = np.exp(scores - scores.max(1, keepdims=True))17 weights /= weights.sum(1, keepdims=True)18 return weights, weights @ (x @ w_value)192021weights, _ = attend(x, mask=True)22np.set_printoptions(precision=2, suppress=True)23print("weights with the causal mask:")24for token, row in zip(tokens, weights):25 print(f" {token:<11}", row)26print("weight on later tokens:", float(weights[~allowed].sum())) # ~allowed marks the positions above the diagonal2728changed = x.copy()29changed[3] = rng.normal(0, 1, 8) # a different last token in place of `table`30for mask in [False, True]:31 before, after = attend(x, mask)[1][2], attend(changed, mask)[1][2] # attend returns (weights, output); 2 is coffee32 change = float(np.abs(after - before).max())33 print(f"largest change in coffee's output, {'with' if mask else 'without'} the mask: {change:.2f}")34 assert (change == 0) == mask # the mask's job: with it, nothing after coffee reaches coffee, so the change is zero
python causal-mask.pyweights 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.0である。開始マーカーは自分自身にしか注目できないので、その行は 1 だけになる。sledは重みを開始マーカーと自分自身に分ける。coffeeは、マスクの前には後ろのtableにほぼ全部の重みを置いていたが、いまは許された位置に重みを分散する。softmax は残った位置の間でのみ割り算を行うからである。最後の行であるtableは変わらない。失う後ろの位置がもともとなかったためである。
最後の 2 行は、マスクが塞ぐ漏れを示している。マスクがなければ、最後のトークンを変えるとcoffeeの出力は4.69も動く。マスクがあれば、coffeeの出力は後ろに来るものに依存できず、この例は変化が 0 であることを assert で確かめている。マスクなしで訓練したモデルは、次の位置から答えを写すことを学べるため、訓練損失が 0 近くまで下がっても、テキスト生成に使えるものは何も学んでいない。その間に何もクラッシュしないので、誤ったマスクは気づきにくい。
実践ルール: マスクは softmax の後の重みではなく、softmax の前のスコアに適用する。そうすれば各行の合計は 1 のままになる。テストはこの例と同じ方法で行う。後ろの位置への重みがちょうど 0 であることと、後ろのトークンを変えても前の出力が変わらないことを確かめる。モデルの訓練損失が予想よりはるかに速く下がる場合は、まずマスクを確認する。
スコアのスケーリング
アテンションの式はすべてのスコアを √d で割る。その理由はドット積にある。2本のベクトルのドット積は、数値1つにつき1つの積を足し合わせたものである。クエリとキーの数値が互いに独立でランダムであり、平均が 0、分散が 1 であれば、スコアの分散は d になる。したがって、サイズの大きいクエリとキーほど大きなスコアを生む(Vaswani et al., 2017、3.2.1節、脚注4)。softmax はスコア間の大きな差を極端な重みに変える。1つの位置がほぼすべての重みを得て、残りはほとんど重みを得ない。Vaswani らは、そのような状態のモデルは学習が遅いのではないかと考えた。1つの重みが 1 に近いとき、softmax の勾配が極めて小さくなるためである。√d で割ると、サイズによらずスコアの分散は 1 に戻る。
ストアのモデルでこの点を具体的に確かめる。そのモデルのヘッドは、32個の数値からなるクエリとキーを扱う。4、32、256 の3つのサイズでランダムなクエリとキーを生成し、各クエリを16個のキーに対してスコア付けする。割り算をする場合としない場合の両方で、各行の最大の重みを求め、1,000個のクエリで平均を取る。先に予想してみよう。256個の数値で割り算をしない場合、1行の最大の重みは平均してどれほどの大きさになるだろうか。
1"""Measures the largest softmax weight in each row, at three sizes of query and key, with and without dividing by the2square root of the size. The prose's point rests on the unscaled averages growing with the size, and the scaled ones staying level."""3import numpy as np45rng = np.random.default_rng(2026) # a fixed seed, so the printed averages are the same on every run6for size in [4, 32, 256]:7 # numbers with mean 0 and variance 1, the case the scaling argument assumes; 1,000 queries against 16 keys8 queries, keys = rng.normal(0, 1, (1000, size)), rng.normal(0, 1, (16, size))9 for divide in [False, True]:10 scores = queries @ keys.T / (np.sqrt(size) if divide else 1)11 weights = np.exp(scores - scores.max(1, keepdims=True))12 weights /= weights.sum(1, keepdims=True)13 label = "scaled" if divide else "unscaled"14 print(f"size {size}, {label}, average largest weight in a row: {weights.max(1).mean():.2f}")
python scaling-matters.pysize 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 である。サイズが大きいと、学習が始まる前から、各クエリは主に1つのキーに注目している。割り算をする場合、最大の重みはどのサイズでも 0.25 にとどまる。重みは複数のキーに広がっているが、均等ではない。16個が等しければ、重みは1つあたり約 0.06 になるはずである。
学習はこの状態から始めるのが望ましい。どの位置も他の複数の位置に注目するので、勾配がそれらすべてに届き、学習は鋭い重みが有効な場所で重みを鋭くしていく。学習済みのヘッドが重みの大半を1つの位置に置くことはありうる。ストアのモデルのヘッドにもそうしたものがある。スケーリングが防ぐのは、ヘッドがその状態から出発することだけである。
実践ルール: トランスフォーマーの論文と同様に、アテンションスコアをクエリのサイズの平方根で割る。T5 のように、割り算を省き、その係数をクエリの重みの初期化に組み込むモデルも一部にある(出典)。重みを読み込む前に、モデルがどちらの方式かを確認すること。クエリとキーの計算方法や初期化を変更する場合は、未学習のモデルについて最大の重みの平均を出力し、1 を大きく下回ることを確かめる。
複数のヘッドが異なるものを探す
ここまでの各アテンション計算は、位置ごとに1組の重みを与える。この1組の重みが探せるものは1種類である。たとえば直前のトークンや、商品の名前などである。モデルには通常、複数の種類を同時に探すことが求められる。マルチヘッドアテンション(multi-head attention)は、ヘッド(head)と呼ばれる複数のアテンション計算を並列に実行する。各ヘッドは独自のクエリ行列、キー行列、バリュー行列を持ち、ベクトルの数値の一部を担当して計算する。たとえば数値が8個でヘッドが2つなら、各ヘッドは4個の数値で計算する。各ヘッドの出力は横に連結され、学習される行列をもう1つ通して混ぜ合わされる。この行列を出力射影(output projection)という(Vaswani et al., 2017、3.2.2節)。
数値を分割すると、全数値を使う1つのヘッドとほぼ同じ計算コストで済み、しかも各ヘッドが固有の重みのパターンを持てる。このストアのモデルは、各層に4個のヘッドを持ち、各ヘッドは32個の数値で計算する。
ランダムなベクトルの4つの位置に対し、因果マスクを使って2つのヘッドを実行する。最後の位置が、各ヘッドで同じ場所を見ているかどうかを確かめる。
1"""Runs two heads of causal attention over four positions, each head working in four of the eight numbers, then mixes2the heads with an output projection. The prose's point rests on the last position's weights differing between the heads,3and on the output keeping the input's shape."""4import numpy as np56rng = np.random.default_rng(2026) # a fixed seed, so the printed weights are the same on every run7positions, dims, heads = 4, 8, 28size = dims // heads # each head works in 4 of the 8 dimensions9x = rng.normal(0, 1, (positions, dims))10w_query, w_key, w_value, output_projection = (rng.normal(0, 0.5, (dims, dims)) for _ in range(4))111213def split(m): # (positions, dims) -> (heads, positions, size)14 return m.reshape(positions, heads, size).transpose(1, 0, 2) # head 1 takes the first four numbers of each vector151617queries, keys, values = split(x @ w_query), split(x @ w_key), split(x @ w_value)18scores = queries @ keys.transpose(0, 2, 1) / np.sqrt(size) # one score matrix per head19scores = np.where(np.tril(np.ones((positions, positions), dtype=bool)), scores, -np.inf) # the causal mask, for both heads20weights = np.exp(scores - scores.max(-1, keepdims=True))21weights /= weights.sum(-1, keepdims=True)22joined = (weights @ values).transpose(1, 0, 2).reshape(positions, dims) # the heads' outputs side by side23output = joined @ output_projection # mixed back together by one more matrix2425print("weights shape (heads, positions, positions):", weights.shape)26print("what the last token attends to, head 1:", np.round(weights[0, -1], 2)) # -1 is the last position, which sees all four27print("what the last token attends to, head 2:", np.round(weights[1, -1], 2))28print("output shape:", output.shape)
python attention-heads.pyweights 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)
重みはヘッドごとに1つの行列を持つようになり、形状は(2, 4, 4)である。両方のヘッドが同じ入力を読んでいるにもかかわらず、最後の位置の行はヘッドの間で異なる。ヘッド1は最大の重みを最初の位置に置き、ヘッド2は最後の位置、つまりその位置自身に置いている。行列がランダムなので、この違いにはまだ意味がない。しかし、これは学習が利用する余地である。各ヘッドは、それぞれ異なる振り返り方を学習でき、出力射影がそれらの見つけたものを組み合わせる。出力は再び入力と同じ形状(4, 8)になるので、第7章のように、アテンション層を積み重ねられる。
実践ルール: 経験則として、各ヘッドの幅は少なくとも32個の数値に保つ。Transformerの論文の実験では、幅32の16ヘッドは、幅64の8ヘッドと同等の性能を示した。一方、幅16の32ヘッドは性能が低く、キーのサイズを小さくすると性能が損なわれた(Vaswani et al., 2017、表3)。モデルを変更するたびに、重みテンソルの形状、すなわちヘッド数×位置数×位置数を確認すること。ヘッドの軸が誤った位置にあると、エラーが出ないままヘッドどうしが混ざってしまう。
この部分はまだ翻訳されていないため、英語で表示している。
Read what trained heads attend to
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:
1"""Runs the store's trained model on one validation product, up to the description's second furniture, and prints where2its heads attend there. The prose's point rests on the last layer's head with the most weight on the name's cover, and on3the probability it gives cover."""4import numpy as np56from lib import transformer7from lib.store import load_products89_, vocabulary, manifest = transformer.load() # forward reads the weights itself, so only the vocabulary and manifest are kept10settings = manifest["settings"]11index = {t: i for i, t in enumerate(vocabulary)}12product = load_products("validation").query("name == 'double chaise patio furniture cover'").iloc[0]13ids = transformer.product_ids(product["name"], product["description"], index, settings["longest"])14sep = ids.index(index[transformer.SEP])15position = ids.index(ids[sep - 1], sep) - 1 # just before the description first repeats the name's last token16logits, attention = transformer.forward(ids, keep=True)17probabilities = transformer.softmax(logits[position])181920def label(i):21 """Where a token sits: the current position, the name, the description, or a marker."""22 if i == position:23 return f"current:{vocabulary[ids[i]]}"24 if i == 0 or i == sep:25 return vocabulary[ids[i]]26 return f"{'name' if i < sep else 'description'}:{vocabulary[ids[i]]}"272829print("layers:", settings["layers"])30print("heads per layer:", settings["heads"])31print("dimensions per head:", settings["dimensions"] // settings["heads"])32print("name:", " ".join(vocabulary[i] for i in ids[1:sep]))33# after <sep>, up to and including the current position34print("description so far:", " ".join(vocabulary[i] for i in ids[sep + 1:position + 1]))35# position + 1 is the token that really comes next in the text36print(f"P(next token is {vocabulary[ids[position + 1]]}): {probabilities[ids[position + 1]]:.2f}")37for layer in [0, len(attention) - 1]:38 for head, weights in enumerate(attention[layer]):39 top = np.argsort(-weights[position], kind="stable")[:3]40 print(f"layer {layer + 1}, head {head + 1}: " + ", ".join(f"{label(i)} {weights[position, i]:.2f}" for i in top))4142name_cover = sep - 1 # the name's last token, `cover`43earlier = ids.index(ids[position], sep + 1) # the description's earlier `furniture`44last = attention[-1][:, position] # the last layer's heads, at the current position45head = int(last[:, name_cover].argmax())46print("last-layer head with the most weight on the name's cover:", f"head {head + 1}")47print("its weight on the name's cover:", f"{last[head, name_cover]:.2f}")48print(f"its weight on {vocabulary[ids[earlier + 1]].removesuffix('</w>')}, after the description's earlier furniture:", # earlier + 1: the token after the first furniture49 f"{last[head, earlier + 1]:.2f}")
python trained-attention.pylayers: 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.
モデルがコピーするものを検証する
モデルが cover を名前からコピーして予測しているのであれば、名前を変えれば予測も変わるはずである。これに対し、この種の説明文はしばしばそのように続くという理由で cover を予測しているのであれば、名前はそれほど影響しないはずである。入力を変えて出力を観察する検証は、アテンションの重みでは答えられないこの問いに答えられる。
説明文はそのままにして、名前だけを変える。販売時のままの名前、cover を除いた名前、set で終わる名前の三つである。ある一つの位置における cover と set の確率から、予測が名前に従っているかどうかが分かる。次に、訓練データの説明文で this outdoor patio furniture の後に何が続くかを数える。これは、ウィンドウ型モデルが見ることになる4トークンである。
1"""Changes the name of one validation product and reads the model's probabilities for cover and set at the same position,2then counts what follows this outdoor patio furniture in the training descriptions. The prose's point rests on P(cover)3falling when cover leaves the name, and on how rarely this outdoor patio furniture is followed by cover in the training4descriptions, which is all the four tokens alone give."""5from lib import transformer6from lib.store import load_products78_, vocabulary, manifest = transformer.load() # forward reads the weights itself, so only the vocabulary and manifest are kept9index = {t: i for i, t in enumerate(vocabulary)}10product = load_products("validation").query("name == 'double chaise patio furniture cover'").iloc[0]11cover, other = index["cover</w>"], index["set</w>"]1213for name, label in [("double chaise patio furniture cover", "name as sold"),14 ("double chaise patio furniture", "name without cover"),15 ("double chaise patio furniture set", "name ending in set")]:16 ids = transformer.product_ids(name, product["description"], index, manifest["settings"]["longest"])17 sep = ids.index(index[transformer.SEP])18 furniture = [i for i in range(sep + 1, len(ids)) if ids[i] == index["furniture</w>"]]19 p = transformer.softmax(transformer.forward(ids)[furniture[1]]) # at the description's second `furniture`20 print(f"{label}, P(cover): {p[cover]:.2f}")21 print(f"{label}, P(set): {p[other]:.2f}")2223phrase = "this outdoor patio furniture " # the trailing space makes the phrase end at a word boundary24# the word after the phrase, in each description that has one; a phrase at the very end has no next word and is skipped25after = [d.split(phrase, 1)[1].split()[0] for d in load_products("train")["description"]26 if isinstance(d, str) and phrase in d and d.split(phrase, 1)[1].split()]27print("training descriptions with 'this outdoor patio furniture':", len(after))28print("followed by cover:", after.count("cover"))
python copy-from-the-name.pyname 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 を与える。
この4トークンだけでは、cover を弱くしか示さない。this outdoor patio furniture を含む訓練用の説明文 6 件のうち、cover へ続くのは 2 件である。
これは前の節の重みが示唆していた挙動を、その効果によって示したものである。モデルは商品名にある単語を、何トークンも前からコピーしている。4トークンのウィンドウに限られたモデルには、これはできない。ただし、1つの商品だけでは、モデルがどれほどの頻度でこれを行うかの尺度にはならない。次の2つの節では、多数の商品にわたってヘッドを測定する。
実践ルール: モデルが何を使っているかについての主張は、その入力を変えて出力を測定することで検証する。その際、出力を変えないはずの変更も含める。アテンションの重みは仮説を立てるために読み、結論を出すにはこのような検証を用いる。
直前のトークンに注目するヘッド
1 つのテキストだけでは誤解を招くことがある。多数のテキストにわたる平均を取ると、ヘッドの習性が見えてくる。測定する価値のある習性の 1 つが、直前のトークンへの注目である。これを行うヘッドは、各トークンの直前のトークンを自分の位置へ運ぶので、後続の層は第 1 章のバイグラム数と同じようにトークンの対を見ることができる。また、前の節で見たコピーもこれに依存している。以前に furniture の次に来たものを見つけるには、ヘッドが、先行する各位置にその直前のトークンを知らせておく必要がある。
最初の 300 件の検証用製品について、各ヘッドが直前のトークンに置く重みを平均し、直前のトークンへの重みが最も大きいヘッドを、均等な分布と比較する。均等な分布では、位置 i から見える i + 1 個のトークンのそれぞれに 1 / (i + 1) を置く。
1"""Averages each head's weight on the previous token over 300 validation products, and sets the largest average beside2an 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."""3import numpy as np45from lib import transformer6from lib.products import product_texts78texts = product_texts("validation", 300) # the first 300 validation products, which the model never trained on9# with keep=True, forward's second value is every layer's weights; the head count is in the manifest's settings10layers, heads = len(transformer.forward(texts[0][0], keep=True)[1]), transformer.load()[2]["settings"]["heads"]11on_previous = np.zeros((layers, heads))12for ids, _ in texts:13 _, attention = transformer.forward(ids, keep=True)14 for layer, weights in enumerate(attention): # weights: (heads, positions, positions)15 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 start16on_previous /= len(texts)17even = 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) each1819print("average weight on the previous token (rows: layers, columns: heads):")20for layer, row in enumerate(on_previous, start=1):21 print(f" layer {layer}: " + " ".join(f"{w:.2f}" for w in row))22layer, head = np.unravel_index(on_previous.argmax(), on_previous.shape)23print("head with the most weight on the previous token:", f"layer {layer + 1}, head {head + 1}")24print("its weight on the previous token:", f"{on_previous.max():.2f}")25print("an even spread's weight on the previous token:", f"{even:.2f}")
python previous-token-heads.pyaverage 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 となる。したがって、このヘッドは直前のトークンをおよそ 5 倍重視していることになる。後ろの層のいくつかのヘッドは、重みの 4 分の 1 以上をそこに置いている。一方、最初の層のヘッドが置く重みはずっと小さい。訓練済みアテンションの例では、そのうちの 1 つが主に現在のトークンに注目していた。
純粋に直前のトークンだけを担うヘッドは存在しない。どのヘッドも、この習性を他の習性と混ぜ合わせている。ヘッドの平均が示すのは、そのヘッドが最も多く行うことであって、行うことのすべてではない。したがって、ヘッドに 1 つの役割があると述べるのは単純化しすぎである。
実践ルール: 訓練済みのヘッドは、数百件のテキストにわたる測定平均、たとえば直前のトークン、現在のトークン、開始マーカーへの重みによって記述する。それぞれを、同じ方法で平均した均等な分布の値と比較する。そうすれば、0.3 のような数値が大きいのか小さいのかを判断できる。
ウィンドウの先へ届く
アテンションの約束は、現在のトークンとその前の3トークンから予測する第5章の4トークンのウィンドウを超えて見ることであった。ストアのモデルが実際にそうしているかどうかは、測定によって確かめられる。ウィンドウの外にどれだけの重みが置かれているのか。最初の300件の検証用商品について、終端マーカーを除くすべての説明文トークンを対象に、各ヘッドが4トークン以上前のトークンに置く重みを合計する。4トークンのウィンドウが見ることのできない最も近い位置がここである。これとは別に、2つのマーカー <s> と <sep> に置く重みも合計する。これをトークン、ヘッド、層にわたって平均し、各トークンが見ることのできる位置に均等に重みを配分した場合と比較する。
1"""Measures how much attention a description token puts on tokens four or more positions back, and on the two markers,2against an even spread, over 300 validation products. The prose's point rests on the all-layers share four or more back,3and on the count of descriptions that repeat a token of the name."""4import numpy as np56from lib import transformer7from lib.products import product_texts89_, vocabulary, manifest = transformer.load()10end = vocabulary.index(transformer.END)11texts = product_texts("validation", 300) # the first 300 validation products, which the model never trained on12layers = manifest["settings"]["layers"]13far, markers, even_far, even_markers, counted = np.zeros(layers), np.zeros(layers), 0.0, 0.0, 014for ids, sep in texts:15 # the description's tokens: after <sep>, so not the name, and without the end marker16 queries = np.array([i for i in range(sep + 1, len(ids)) if ids[i] != end])17 if len(queries) == 0:18 continue # a product with no description19 _, attention = transformer.forward(ids, keep=True)20 stacked = np.stack(attention)[:, :, queries] # (layers, heads, description tokens, positions)21 positions = np.arange(len(ids))22 is_marker = np.isin(positions, [0, sep]) # <s> and <sep>23 beyond = (queries[:, None] - positions[None, :] >= 4) & ~is_marker # 4 positions back is the nearest a four-token window can't see24 far += (stacked * beyond).sum(-1).mean(1).sum(-1)25 markers += (stacked * is_marker).sum(-1).mean(1).sum(-1)26 even_far += (beyond.sum(1) / (queries + 1)).sum() # an even spread over the positions each token can see27 even_markers += (2 / (queries + 1)).sum() # two markers among the query's i + 1 visible positions28 counted += len(queries)2930print("description tokens measured:", f"{counted:,}")31print("average attention weight of a description token, by layer:")32for layer in range(layers):33 print(f" layer {layer + 1}: 4 or more tokens back {far[layer] / counted:.2f}, on <s> and <sep> {markers[layer] / counted:.2f}")34print("all layers, weight 4 or more tokens back:", f"{far.mean() / counted:.2f}")35print("an even spread's weight 4 or more tokens back:", f"{even_far / counted:.2f}")36print("all layers, weight on <s> and <sep>:", f"{markers.mean() / counted:.2f}")37print("an even spread's weight on <s> and <sep>:", f"{even_markers / counted:.2f}")38# the name without <s>, and what follows <sep>; a product counts as described if anything but the end marker follows39described = [(ids[1:sep], ids[sep + 1:]) for ids, sep in texts if any(i != end for i in ids[sep + 1:])]40print("products with a description:", len(described))41print("descriptions that repeat a token of the name:", sum(bool(set(n) & set(d)) for n, d in described))
python attention-reaches-back.pydescription 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
ヘッドは、次の単語を予測する以上は当然だが、近くのトークンを好む。それでも注意の大きな割合をウィンドウの先に向けており、この本のこれまでのどのモデルにも使えなかった情報にアクセスしている。全層を通じて、説明文トークンは4トークン以上前のトークンに注意の 0.46 を置いている。均等な配分であれば 0.85 となる。これは、説明文トークンが見ることのできるもののほとんどが遠くにあるためである。
このことは、このテキストでは重要である。説明文のある 262 件の商品のうち、244 件の説明文には、名前のトークンを少なくとも1つ繰り返すものがある。
マーカーには注意の 0.11 が集まる。均等な配分では 0.05 であるから、偶然の約2倍である。マーカー自体はどの単語も予測しないにもかかわらずである。考えられる理由の1つは、より大きなモデルで見つかっているパターンである。ソフトマックスは重みの各行の合計を1にするため、ある位置で有用なものを何も見つけられないヘッドも、重みをどこかに置かなければならない。Xiaoらは、言語モデルがテキストの最初のトークンに、それが何であってもよく、大きな重みを置くことを見いだし、これをアテンションシンク(attention sink)と呼んだ(Xiao et al., 2024)。ストアのモデルでは、<s> は常に先頭に来て、<sep> はどのテキストにも含まれるため、どちらもシンクとして働きうる。<sep> は説明文の開始位置も示しており、それ自体にも役立つ。この例では、両者を区別することはできない。
実践ルール: 文脈の長さをどれだけにするかを決める前に、学習済みモデルがどれだけ遠くまで注意を向けているかを測定する。数値に意味を持たせるため、均等な配分と比較する。マーカーの重みが長距離のアテンションに見えないよう、マーカーへの重みは別に報告する。また、容量を節約するためにモデルの文脈を切り詰めるときは、先頭のトークンを残す。
本番環境で何が問題になるか
アテンションは、言語モデルの中でテキスト長に応じてコストが最も速く増える部分であり、最も誤解されやすい部分でもある。次のような問題がある。
- コストは長さの2乗で増える。 すべての位置がそれ以前のすべての位置にスコアを付けるため、2倍の長さのテキストではアテンションのコストが4倍になる。店舗のモデルが 160 トークンとしているように、最大長を設定し、その上限で切り詰められるテキストがどれだけあるかを確認すること。
- 誤ったマスクは気づかれないまま失敗する。 未来を参照できるモデルは、学習損失を低く抑えられても、テキスト生成には使い物にならないことがある。学習コードと生成コードの両方で、後続の位置にかかる重みがゼロであること、および後ろのトークンを変更しても前の出力が変わらないことをテストすること。
- アテンション重みは説明ではない。 重みが大きいことは、ヘッドがどこから平均を取ったかを示すだけで、モデルがなぜその予測をしたかを示すものではない。同じモデルでも、大きく異なるアテンション重みが同じ予測を導くことがある(再帰型および畳み込み型の分類器を扱った Jain and Wallace, 2019)。重みは仮説を立てるために使い、その仮説は、この章で製品名を使って行ったように、入力を変更して検証すること。
- マーカーへの重みは重要度に見える。 先頭のトークンや区切りトークンに重みが集中しているのは、そのヘッドがそこで行うべきことがないだけかもしれない。これらのトークンを取り除いてはならず、その重みに意味を読み取ってもならない。
- 注意しないとソフトマックスはオーバーフローする。 指数を取る前に、
lib.transformer.softmaxが行っているように、各行の最大スコアを引くこと。また、すべての行に少なくとも1つはマスクされない位置が残るようにすること。そうでなければその行は NaN になる。因果マスクは各位置自身を必ず残すが、パディングを隠すマスクは行全体を隠してしまうことがある。
この部分はまだ翻訳されていないため、英語で表示している。
What this chapter decided
- The book's models use causal, scaled, multi-head attention, as Vaswani et al. defined it: scores divided by the square root of the size of each head's queries and keys, minus infinity on every later position before softmax, and heads that each work in a share of the numbers, mixed by an output projection.
- The store's model has 4 layers of 4 heads, each head 32 numbers wide, trained once in
recordings/transformer.pyon names and descriptions joined by a<sep>marker, and recomputed in NumPy bylib.transformer. - Claims about what a model uses are tested by changing its input. Attention weights suggest hypotheses; changing the product's name showed that the model copies
coverfrom it. - Trained heads are described by measured averages over many texts, compared with an even spread: the weight on the previous token, the weight on tokens 4 or more back, and the weight on markers, counted separately.
- On the store's descriptions, attention reaches well past chapter 5's window. Description tokens put 0.46 of their attention on tokens 4 or more back, and the model copies from the name, which a fixed window can't.
- Attention needs explicit position information. A weighted average ignores order, and the causal mask restores only a little of it, so chapter 7 adds rotary positions, as the store's model does inside every head.
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格
英語版の書籍(版2026.11.16)から翻訳した。