トランスフォーマーブロック
読了まで約48 分分、11 節 節の 8 例 例。
この章を終えると、トランスフォーマーブロックをその部品から組み立てられるようになる。部品とは、アテンション、正規化、ゲート付きフィードフォワード層、位置情報であり、これらを残差接続でつなぐ。さらに、ブロックを積み重ねて完全な言語モデルを構成できる。各部品をストアの学習済みモデルで検証し、モデル全体をPyTorch自身の実装と照合し、各ブロックと各細部が何に寄与するかを測定し、パラメータがどこに使われているかを数える。
第6章ではアテンションを構築した。各位置は先行する位置を振り返り、見つけた情報の加重平均をとる。アテンションだけでは言語モデルにならず、オンラインの家具・生活雑貨店であるストアが必要とするのもアテンションだけではない。アテンションは位置間で情報を運ぶが、その情報をほとんど変換せず、語順の感覚もほぼ持たない。アテンションだけを直接積み重ねると劣化も起こる。ブロックの他の部品がなければ、純粋なアテンションの出力は全位置で同じベクトルに近づき、その速さは層を重ねるごとに増す(Dong et al., 2021)。トランスフォーマーブロックは、アテンションの周囲に、各位置を変換し、語順を与え、深い積み重ねの劣化を防ぐ部品を加えたものである(Vaswani et al., 2017)。
この章では、LLaMAモデルが広めた形でブロックを構築する。すなわち、各部品の入力をRMSNormで正規化し、ゲート付きフィードフォワード層を用い、すべての層で回転位置埋め込みを使う(Touvron et al., 2023、2.2節)。第2章でトークナイザーを読んだSmolLM2も同じ構成である。その3.6億パラメータのモデルは960次元、32層、15ヘッドを持ち、ストアのモデルとは以下で扱う2つの細部で異なる。ヘッドがキーと値を共有する点と、回転位置の回転がより緩やかである点である(設定)。
ストアの商品テキストで学習したストアのモデルは、埋め込みテーブルと出力層の間に置かれた4個のこのブロックからなり、第6章ではそのヘッドを読んだ。本書では各ブロックをモデルの層と呼ぶ。各ブロックは、すべての位置で次の2つの処理を順に行う。
- ベクトルを正規化し、アテンションを実行して、その結果をベクトルに加え戻す。
- 再び正規化し、フィードフォワード層を実行して、その結果もやはり加え戻す。
各部分の出力を残差ストリームに加える
第5章のウィンドウモデルでは、各層が入力を置き換えていた。出力層が見るのは隠れ層の出力のみであった。これに対し、Transformer ブロックは入力に加算する。各部分は現在のベクトルから何かを計算し、その出力をベクトルに加える。x ← x + attention(x) の後に、x ← x + feed-forward(x) が続く。入力を置き換えずに、部分の出力を入力に加えるこの仕組みを残差接続(residual connection)と呼ぶ。残差接続は画像モデルに由来する。非常に深い層の積み重ねは、各層が入力を置き換えずに入力へ加算するようになって初めて、うまく学習できるようになった(He et al., 2016)。
ここから2つの帰結が生じる。第一に、加算があることで、信号は「あるブロックから他の任意のブロックへ直接」伝わる。これは順方向でも、勾配としての逆方向でも成り立つ。そのため、深い積み重ねは、加算がない場合よりもはるかに確実に学習できる(He et al., 2016b)。第二に、各位置のベクトルは、各部分が読み出し、書き込む共有の作業領域になる。トークンの埋め込みが最下部から入り、各部分が計算結果を加え、出力層が最上部で総和を読み取る。Elhage らは、この累積和、すなわち各部分の出力が加えられた各位置のベクトルを残差ストリーム(residual stream)と呼んでいる(Elhage et al., 2021)。
この店のモデルを検証用の商品1件に対して実行し、各層で、注意機構が加えるものの長さ、フィードフォワード層が加えるものの長さ、および両方の加算後のベクトルの長さを、位置について平均して測定する。ここでベクトルの長さとは、各成分の二乗和の平方根である。
1"""Runs the store's model on one validation product, one block at a time, and prints how much attention and the2feed-forward layer add to the residual stream at each layer. The prose's point rests on the two lengths printed3first and last: the vectors entering layer 1 and leaving the last layer."""4import numpy as np56from lib import transformer7from lib.products import product_texts89weights, _, manifest = transformer.load()10ids, sep = product_texts("validation", 1)[0] # the first validation product; sep, its <sep> position, isn't needed here11x = weights["embedding"][np.array(ids)] # the stream entering block 1: each token's embedding12print("length of the vectors entering layer 1:", f"{np.linalg.norm(x, axis=1).mean():.2f}")13for layer in range(manifest["settings"]["layers"]):14 layer_weights = transformer.layer_weights(layer)15 added_by_attention, _ = transformer.attention(transformer.rms_norm(x, layer_weights["norm1"]), layer_weights, manifest["settings"]["heads"])16 x = x + added_by_attention17 normalized = transformer.rms_norm(x, layer_weights["norm2"])18 added_by_feed_forward = (transformer.silu(normalized @ layer_weights["gate"]) * (normalized @ layer_weights["up"])) @ layer_weights["down"]19 x = x + added_by_feed_forward20 print(f"layer {layer + 1}: attention adds {np.linalg.norm(added_by_attention, axis=1).mean():.2f}, "21 f"feed-forward adds {np.linalg.norm(added_by_feed_forward, axis=1).mean():.2f}, "22 f"vectors now {np.linalg.norm(x, axis=1).mean():.2f}")23print("length of the vectors leaving the last layer:", f"{np.linalg.norm(x, axis=1).mean():.2f}")24print("largest number in the stream:", f"{np.abs(x).max():.1f}")
python residual-stream.pylength of the vectors entering layer 1: 1.17
layer 1: attention adds 2.90, feed-forward adds 3.00, vectors now 4.65
layer 2: attention adds 2.05, feed-forward adds 2.90, vectors now 6.14
layer 3: attention adds 2.26, feed-forward adds 4.12, vectors now 8.46
layer 4: attention adds 4.08, feed-forward adds 6.33, vectors now 13.16
length of the vectors leaving the last layer: 13.16
largest number in the stream: 50.6
ストリームは層を経るにつれて大きくなる。各加算が直前の値の上に積み重なるからである。平均の長さは、第1層に入るときの1.17から、最終層を出るときの13.16へと増える。どの層も加算を行っており、注意機構が加えるものの大きさは、フィードフォワード層が加えるものと同程度である。ただし、フィードフォワード層はどの層でもより多く加え、後ろの層ほどその差は大きい。どちらの部分も、すべての層で実質的な働きをしている。上部付近の長いベクトルを読む層は、下部の短いベクトルを読む層とは大きく異なる尺度の重みを必要とする。各層が読むものを再スケールする仕組みがなければ、そうなる。次の節がそれを扱う。
実践ルール: すべてのブロックを、置き換えではなく、残差ストリームへの加算として書くこと。加算がそろうよう、モデル全体でストリームの幅を同じに保つこと。深いモデルをデバッグするときは、各部分が加えるものを測定すること。ほとんど何も加えない部分は、ほとんど何もしていない。
各部分の前で正規化する
残差ストリームは、前の節で測定したとおり層を重ねるごとに大きくなる。そのため、各部分はストリームを再スケールしたコピーを読むべきである。正規化(normalization)は、部分がベクトルを読む前にそのベクトルを標準的な大きさに再スケールする操作であり、ストリームが短くても長くても、その部分の重みが同じように働くようにする。元のトランスフォーマーは、各加算の後に層正規化(layer normalization)を行っていた。層正規化は、各ベクトルから平均を引き、標準偏差で割る操作である(Ba et al., 2016)。Xiongらは、代わりに各部分の前で正規化すると学習がより安定することを示した。再スケールされるのは各部分が読むコピーだけであり、ストリーム自体は再スケールされないためである(Xiong et al., 2020)。そして RMSNorm は平均を落とす。各ベクトルを二乗平均平方根、すなわち各数値の二乗の平均の平方根で割り、各次元に学習されたゲインを掛ける(Zhang and Sennrich, 2019)。
RMSNorm(x) = x / √(mean(x²) + ε) · g
ここで ε は除算を安全にするための微小な数であり、本書では 10⁻⁵ とする。g はゲインであり、初期値は 1 である。Zhang と Sennrich は、RMSNorm が層正規化とほぼ同程度の精度で、しかも高速であることを見いだした。この店のモデルは、アテンションの前、フィードフォワード層の前、そして出力層の前でもう一度、RMSNorm を用いる。
同じ検証用商品のストリームを、モデルの両端、すなわち最初のブロックへの入口と最後のブロックの出口で、ゲインを 1 のままにして手計算で正規化する。そして、すべての位置のベクトルを lib.transformer.rms_norm の結果と比較する。
1"""Normalizes one validation product's residual stream by hand, entering the first block and leaving the last, and2asserts that the result matches the shared module's rms_norm. The prose's point rests on the root mean square before3and after normalizing, and on the largest mean of a position's numbers, which RMSNorm does not remove."""4import numpy as np56from lib import transformer7from lib.products import product_texts89ids, _ = product_texts("validation", 1)[0] # the first validation product; its <sep> position isn't needed10streams, _ = transformer.run(ids) # the residual stream entering block 1 and leaving each block11gain = np.ones(streams[0].shape[1]) # the learned gain set to 1, to show the normalization alone12for label, x in [("entering block 1", streams[0]), ("leaving the last block", streams[-1])]:13 root_mean_square = np.sqrt((x ** 2).mean(1, keepdims=True) + 1e-5) # one per position; 1e-5 is the ε14 by_hand = x / root_mean_square * gain15 print(f"root mean square {label}, before:", f"{root_mean_square.mean():.2f}")16 print(f"root mean square {label}, after:", f"{np.sqrt((by_hand ** 2).mean(1)).mean():.2f}")17 assert np.allclose(by_hand, transformer.rms_norm(x, gain), atol=1e-4) # the library's function, to 4 decimal places18 print(f"same as lib.transformer.rms_norm, {label}:", "yes")19 # layer normalization would subtract the mean first; RMSNorm doesn't, so this mean need not be zero20 print(f"largest mean of a position's numbers after, {label}:", f"{np.abs(by_hand.mean(1)).max():.2f}")
python rms-norm-by-hand.pyroot mean square entering block 1, before: 0.10
root mean square entering block 1, after: 1.00
same as lib.transformer.rms_norm, entering block 1: yes
largest mean of a position's numbers after, entering block 1: 0.23
root mean square leaving the last block, before: 1.16
root mean square leaving the last block, after: 1.00
same as lib.transformer.rms_norm, leaving the last block: yes
largest mean of a position's numbers after, leaving the last block: 0.26
正規化によって、両端は同じスケールになる。二乗平均平方根の平均は、最初のブロックへの入口で 0.10、最後のブロックの出口で 1.16 であったが、正規化後はどちらも 1.00 になる。手計算の結果は、両端ともライブラリの結果と一致する。RMSNorm は再スケールするが中心化はしない。したがって、正規化後も位置ごとの数値の平均はゼロからずれることがあり、ここでは最大で 0.26 である。これが、層正規化に対して RMSNorm が省く手順である。
このように、ストリームは層を重ねるうちに何倍もの長さに成長したが、すべてのアテンション層とフィードフォワード層は、同じスケールのベクトルに、学習されたゲインを掛けたものを読んだことになる。
実践ルール: 正規化はブロックの各部分の後ではなく前で行い、出力層の前でもストリームをもう一度正規化する。層正規化を使うモデルに合わせる場合を除き、RMSNorm を用いる。他のモデルの重みを読み込むときは、何よりもまず、そのモデルがどの正規化を、どこで、どの ε で使っているかを確認する。わずかな不一致が何をもたらすかは、不一致の細部の例が示している。
この部分はまだ翻訳されていないため、英語で表示している。
Transform each position with a gated feed-forward layer
Attention moves information between positions; the feed-forward layer transforms it, at each position separately. It's the same idea as chapter 5's hidden layer: widen the vector, apply a function that isn't a straight line, and narrow the result back to the stream's width. The store's model widens 128 numbers to 352.
The form the LLaMA models use is gated. A gated feed-forward layer computes two widened vectors from the input, passes one through a function called SiLU, and multiplies the two number by number, so the first decides how much of the second gets through (Shazeer, 2020):
FFN(x) = (SiLU(x W_gate) ⊙ (x W_up)) W_down
where ⊙ multiplies number by number, and SiLU(z) = z · σ(z), with σ the logistic function from chapter 4. SiLU passes large positive numbers almost unchanged and turns large negative ones to nearly zero, smoothly. Shazeer compared several gated forms with the plain one, at the same number of parameters, and found the gated ones predicted better; this form is called SwiGLU.
What does the gate shut? Compute SiLU at three points, then run the first block's real feed-forward layer on the same validation product and count, at each position, how many of its hidden units the gate nearly shuts:
1"""Computes SiLU at three points, then runs block 1's feed-forward layer on one validation product and counts the hidden2units its gate nearly shuts at each position. The prose's point rests on the three SiLU values and on that count."""3import numpy as np45from lib import transformer6from lib.products import product_texts78print("silu(-3), silu(0), silu(3):", ", ".join(f"{v:.2f}" for v in transformer.silu(np.array([-3.0, 0.0, 3.0]))))910ids, _ = product_texts("validation", 1)[0] # the first validation product; its <sep> position isn't needed11heads = transformer.load()[2]["settings"]["heads"] # load returns (weights, vocabulary, manifest): index 2 is the manifest12first = transformer.layer_weights(0) # block 1's weights13x = transformer.load()[0]["embedding"][np.array(ids)] # index 0 is the weights: the embeddings, the stream entering block 114attended, _ = transformer.attention(transformer.rms_norm(x, first["norm1"]), first, heads)15normalized = transformer.rms_norm(x + attended, first["norm2"]) # what block 1's feed-forward layer reads16gate = transformer.silu(normalized @ first["gate"]) # how much of each hidden unit to let through17up = normalized @ first["up"] # what each hidden unit carries18output = (gate * up) @ first["down"] # gated, then projected back to the stream's width19shut = (np.abs(gate) < 0.05).sum(1) # per position; 0.05 is the threshold for "nearly shut"20print("hidden units:", gate.shape[1])21print("hidden units nearly shut at a position (gate under 0.05 in size), on average:", f"{shut.mean():.0f}")22print("fewest and most nearly shut at a position:", f"{shut.min()} and {shut.max()}")23print("positions:", len(ids))24print("output shape:", output.shape)
python gated-feed-forward.pysilu(-3), silu(0), silu(3): -0.14, 0.00, 2.86
hidden units: 352
hidden units nearly shut at a position (gate under 0.05 in size), on average: 49
fewest and most nearly shut at a position: 33 and 67
positions: 133
output shape: (133, 128)
SiLU of −3, 0 and 3 gives -0.14, 0.00, 2.86: nearly zero for the negative number, nearly unchanged for the positive one.
Which units the gate shuts depends on the input. At a typical position it nearly shuts 49 of the first block's 352 hidden units, and the count ranges between 33 and 67 over the positions. So each position uses its own mix of them. The output has one vector per position at the stream's width again, (133, 128), ready to add.
The feed-forward layers hold most of a block's parameters: in the store's model, three matrices of 128 by 352, against attention's four of 128 by 128. Geva and colleagues found that in trained models these layers work like stores of patterns: each hidden unit responds to particular patterns in the text, and pushes the prediction towards particular next tokens (Geva et al., 2021).
Working rule: Use a gated feed-forward layer with SiLU. Set its width so its three matrices hold as many parameters as a plain layer four times the stream's width, the original transformer's ratio, 2,048 for 512 (Vaswani et al., 2017, section 3.3): that's about 8/3 times the width. SmolLM2-360M uses exactly 8/3, 2,560 for 960. The store's model rounds 8/3 of its width up to a multiple of 32, a rule of thumb that keeps matrix sizes convenient for hardware. When you load another model, check whether its feed-forward layer is gated, since a gated layer has three matrices where a plain one has two.
この部分はまだ翻訳されていないため、英語で表示している。
Give attention positions with rotations
A weighted average ignores the order of what it averages, as chapter 6 showed, so attention gets at most a weak sense of position from the causal mask alone. The original transformer added a vector for each position to each token's embedding (Vaswani et al., 2017, section 3.5). The LLaMA models instead use rotary position embeddings, RoPE, which work inside attention, at each layer (Su et al., 2021; Touvron et al., 2023, section 2.2). Before scoring, RoPE rotates each query and key by angles that grow with its position. The vector's d numbers are taken in pairs, number i with number i + d/2 in the store's model, and each pair (a, b) is treated as a point on a plane and turned around the origin. At position p, pair i turns by the angle p·θᵢ, where θᵢ = 10000^(−i/(d/2)):
(a, b) → (a cos pθᵢ − b sin pθᵢ, a sin pθᵢ + b cos pθᵢ)
So the first pairs turn fast, a full radian per position, and the last pairs slowly. The line angles = ... in lib.transformer.rope computes p·θᵢ for every position and pair, and the line after it applies the rotation.
Rotation has two properties that suit attention. It doesn't change a vector's length, so it adds position without distorting content. And if a query at position m is turned by mθᵢ and a key at position n by nθᵢ, their dot product depends only on the difference, (m − n)θᵢ: the score depends on how far apart they are, not on where they sit in the text. A head can learn to look 3 tokens back, and it works the same at the start of a name and deep in a description.
Rotate a random query and key of 32 numbers, the size of the store's heads, for positions 0 to 19, and compare scaled scores, as chapter 6 defines them, at three pairs, which tests that:
1"""Rotates one random query and key for each of 20 positions, checks that the rotation keeps their lengths, and scores2three pairs of positions. The prose's point rests on the two scores for pairs 3 apart, which match, and the score for3the pair 6 apart, which doesn't."""4import numpy as np56from lib.transformer import rope78rng = np.random.default_rng(2026) # a fixed seed: the same random query and key on every run9size = 32 # 32 numbers: the store's width of 128 split across 4 heads10query, key = rng.normal(0, 1, size), rng.normal(0, 1, size)11positions = 2012rotated_q = rope(np.tile(query, (positions, 1))) # the same query, rotated for each position 0 to 1913rotated_k = rope(np.tile(key, (positions, 1)))14kept = np.allclose(np.linalg.norm(rotated_q, axis=1), np.linalg.norm(query)) and \15 np.allclose(np.linalg.norm(rotated_k, axis=1), np.linalg.norm(key)) # rotation turns a vector, never changes its length16assert kept17print("length kept by the rotation, for the query and the key:", "yes")18for i, j in [(2, 5), (12, 15), (2, 8)]: # (key position, query position): the first two are 3 apart, the third 619 print(f"score with the key at {i} and the query at {j}:", f"{rotated_q[j] @ rotated_k[i] / np.sqrt(size):.3f}") # scaled, as chapter 6 defines it
python rope-by-hand.pylength kept by the rotation, for the query and the key: yes
score with the key at 2 and the query at 5: 0.217
score with the key at 12 and the query at 15: 0.217
score with the key at 2 and the query at 8: -0.765
Pairs the same distance apart score the same, wherever they sit. The key at position 2 and the query at 5 score 0.217, and the key at 12 and the query at 15 score 0.217, the same, because both pairs are 3 apart. The key at 2 and the query at 8, 6 apart, score -0.765: the same query and key, scored differently because they're further apart. The rotation keeps both vectors' lengths, which the example asserts.
RoPE has no learned parameters: the angles are fixed, and the model learns queries and keys that use them. The store's model applies it to the queries and keys of every head in every layer, which gives chapter 6's previous-token heads a direct way to find the previous token, alongside the weak signal the mask provides.
Working rule: Use rotary position embeddings, applied to queries and keys, never values. When you load another model's weights, check how its RoPE pairs the numbers and what base it uses. Some implementations pair neighbouring numbers; others pair the first half with the second, as lib.transformer.rope does and as SmolLM2's configuration states with "rope_interleaved": false. SmolLM2 uses a base of 100,000 where the store's model uses 10,000.
出力層を埋め込みに結びつける
部品がすべてそろったので、モデル全体は一続きで読めるほど短い。lib.transformer.blockは、本章でこれまで説明してきたとおりの1つのブロックである。
def block(x: np.ndarray, layer_weights: dict[str, np.ndarray], heads: int, positions=rope):
"""One transformer block: attention, then the gated feed-forward layer, each added to the residual stream."""
attended, weights = attention(rms_norm(x, layer_weights["norm1"]), layer_weights, heads, positions)
x = x + attended
normalized = rms_norm(x, layer_weights["norm2"])
x = x + (silu(normalized @ layer_weights["gate"]) * (normalized @ layer_weights["up"])) @ layer_weights["down"]
return x, weights
lib.transformer.runは、各トークンの埋め込みをブロックに順に通す。lib.transformer.forwardのこれらの行は、最終的なストリームを語彙の各トークンに対する1つのロジットに変換する。ロジットとは、第5章のソフトマックスが確率に変換するスコアである。
streams, kept = run(ids, name, positions, skip)
weights, _, _ = load(name)
logits = rms_norm(streams[-1], weights["final_norm"]) @ weights["embedding"].T
最後の行には、もう1つの考え方である重み共有(weight tying)が含まれている。出力層は、独自の行列を学習する代わりに、埋め込みテーブルを転置して再利用する。あるトークンのロジットは、最終ベクトルとそのトークンの埋め込みとの内積である。PressとWolfは、重み共有が出力層のパラメータを節約するだけでなく、パープレキシティも下げることを見いだした(Press and Wolf, 2017)。SmolLM2も両者を共有している(設定の"tie_word_embeddings": true)。このくらいの規模のモデルでは、独立した出力層が全体のかなりの割合を占めてしまうからである。パラメータ数を見ると、重み共有によってストアのモデルでどれだけ節約できるかがわかる。
実践ルール: 小さなモデルでは出力層を埋め込みに結びつける。また、読み込んだモデルが両者を結びつけているかどうかは、独立した出力行列を探す前に確認する。自作のフォワードパスは、lib.transformerのように全体を通して読める短さに保つ。そうすれば、次の節で検証する細部がすべて見えるようになる。
この部分はまだ翻訳されていないため、英語で表示している。
Check the model against PyTorch
PyTorch trained the store's model once, in recordings/transformer.py, as it trained chapter 5's (see Train with PyTorch), and the script saved PyTorch's own logits for every position of one validation product. The training script uses PyTorch's own RMSNorm, causal attention and SiLU, so comparing them with lib.transformer checks the NumPy code against a library's, not against a second copy of itself. RoPE is the exception: PyTorch has no built-in version, so both programs write it out, and the check confirms only that they agree. The rope-by-hand example checks its properties instead.
To test the whole forward pass, recompute the saved product's logits in NumPy and compare every position with PyTorch's:
1"""Recomputes the store's model's logits in NumPy for the validation product the training script saved, and checks every2one against PyTorch's to four decimal places. The prose's point rests on the count of logits compared, and on the3assertion that they all match."""4import numpy as np56from lib import transformer78_, _, manifest = transformer.load()9check = np.load("data/recorded/transformer/check.npz") # one validation product's ids, and PyTorch's logits1011ours = transformer.forward(list(check["ids"])) # forward takes a list of token ids, not an array12print("PyTorch version:", manifest["torch"])13print("positions compared:", len(check["ids"]))14print("logits compared:", f"{ours.size:,}")15assert np.abs(ours - check["logits"]).max() < 1e-4 # 1e-4 is four decimal places16print("same as PyTorch to 4 decimal places:", "yes")
python transformer-same-as-pytorch.pyPyTorch version: 2.14.1+cpu
positions compared: 133
logits compared: 550,886
same as PyTorch to 4 decimal places: yes
The NumPy model reproduces all 550,886 of PyTorch's logits, for 133 positions, to four decimal places, with PyTorch 2.14.1+cpu. Because the check covers a whole text, it covers the parts that depend on position, the mask and the rotations, as well as the norms, gates and tied output.
Working rule: Check your own forward pass against the training library's outputs on a full text, not a single position. Where the library has its own implementation of a part, train with it, so the check compares two independent implementations; where it doesn't, as with RoPE here, test the part's properties by hand.
ブロックを取り除いて、その働きを調べる
モデルの検証は済んだ。次に、各ブロックが何を担っているかを測定する。どのブロックも残差ストリームに加算を行うため、ブロックを1つ取り除いてもモデルは動作する。ストリームはそのブロックを変更されないまま通過し、次のブロックはこれまでと同じようにそれを読む。部品を取り除くと簡単な実験ができ、これをアブレーション(ablation)と呼ぶ。部品を1つ取り除き、モデルが何を失うかを測る。これにより、各ブロックが訓練済みモデルの予測にどれだけ寄与しているかがわかる。重みを読むだけでは、これはわからない。
どのブロックを取り除くと最も大きな損失が出るだろうか。まず1つ予測してから、検証用商品の先頭100件について名前と説明を採点する。予測数は全部で7,624個であり、完全なモデルと、ブロックを1つずつ取り除いたモデルの両方で採点する。
1"""Scores the names and descriptions of the first 100 validation products with the full model, and with each block left2out in turn, reporting perplexity and the top token's average probability. The prose's point rests on the perplexity3with each block left out, set against the full model's."""4import numpy as np56from lib import transformer7from lib.products import product_texts89layers = transformer.load()[2]["settings"]["layers"] # load returns (weights, vocabulary, manifest): index 2 is the manifest10texts = [ids for ids, _ in product_texts("validation", 100)] # the <sep> positions aren't needed: each text is scored whole111213def measure(skip=None):14 """Perplexity per token, and the average probability of the top token, with one block left out."""15 surprise, top, count = 0.0, 0.0, 016 for ids in texts:17 p = transformer.softmax(transformer.forward(ids, skip=skip)[:-1]) # [:-1] drops the last position: nothing follows it18 surprise -= np.log(p[np.arange(len(ids) - 1), ids[1:]]).sum() # position i predicts token i + 119 top += p.max(1).sum()20 count += len(ids) - 121 return np.exp(surprise / count), top / count # perplexity: exp of the average surprise per token222324print("tokens scored, names and descriptions:", f"{sum(len(ids) - 1 for ids in texts):,}")25for skip in [None] + list(range(layers)): # None keeps all four blocks: the full model26 label = "all blocks" if skip is None else f"without block {skip + 1}" # skip counts blocks from 0, so block skip + 1 is left out27 perplexity, top = measure(skip)28 print(f"{label}:", f"{perplexity:,.1f}")29 print(f"{label}, average probability of the top token:", f"{top:.2f}")
python skip-a-block.pytokens scored, names and descriptions: 7,624
all blocks: 24.3
all blocks, average probability of the top token: 0.42
without block 1: 17,896.9
without block 1, average probability of the top token: 0.21
without block 2: 77.8
without block 2, average probability of the top token: 0.29
without block 3: 64.3
without block 3, average probability of the top token: 0.34
without block 4: 77.3
without block 4, average probability of the top token: 0.37
ブロック2、3、4のいずれを取り除いても、トークンあたりのパープレキシティは2倍を超えて増加する。4つのブロックがすべて揃っている場合の24.3から、それぞれ77.8、64.3、77.3になる。後段の各ブロックがモデルの能力の一部を担っており、不要なブロックは1つもない。このパープレキシティは名前と説明の両方を対象としているため、検証用の名前だけで採点した第3章のベースラインや第5章のウィンドウモデルと並べて比べることはできない。この比較は第8章で行う。
ブロック1を取り除いた場合は、失敗の様相が異なる。パープレキシティは17,896.9に上昇し、全4,142トークンから一様に選ぶ当て推量よりも悪くなる。その当て推量のスコアは4,142である。
理由は、後段のブロックが何を前提にしているかにある。後段のブロックは、ブロック1がすでに書き込んだストリームで訓練されている。ブロック1がないと、訓練中に一度も見たことのないベクトルを読むことになる。その結果、予測の確信度は下がり、最上位トークンの平均確率は0.42から0.21に低下する。しかも、その確率は誤ったトークンに割り当てられる。ブロック1は、生の埋め込みを、以降のすべてが依拠する形式に変換する。その一部は、これまでのテキストから文脈を集めることで行われる。第6章の第1層のヘッドのうち3つがそうしていた。訓練済みモデルのブロックは、互いに独立したモジュールではない。各ブロックは、前のブロックが書き込んだものに依存している。
実践ルール: モデルの部品が何をしているかを知るには、重みから推測するのではなく、その部品を取り除いて測定する。最初のブロックは、以降のすべてがその上に築かれるため、最も重要になると予想してよい。それ以外については、測定して確かめる必要がある。ここでは、2番目のブロックと最後のブロックの重要度がほぼ同程度で、3番目のブロックより大きかった。部品を取り除いたときの損失が小さくても、それを読み取る際には注意する。残りの部品はその部品と並行して訓練されているため、この測定からわかるのは、訓練済みモデルが何に頼っているかであって、その部品が単独で何をできるかではない。
食い違った細部が何を損なうかを測る
ブロックのすべての細部は、そのブロックが使う重みと一致していなければならない。食い違いは自らそれを知らせることがなく、モデルは確率を出力し続ける。他のモデルの重みを読み込むときに誤りやすい細部は RoPE にある。数値の対の作り方と基数が実装ごとに異なるためであり、SmolLM2 の実装も、このストアのモデルのものとは異なっている。
RoPE の細部を一度に一つだけ誤らせると、それぞれの代償が分かる。同じ 100 件の検証用商品を、学習済みの重みで採点する。比較する設定は三つである。数値を前半と後半で対にする代わりに隣り合う数値同士を対にした場合、基数をストアのモデルの 10,000 ではなく SmolLM2 の 100,000 にした場合、RoPE をまったく使わない場合である。
1"""Scores the same 100 validation products with the trained weights, changing one detail of RoPE at a time: how it pairs2numbers, its base, and whether it is applied at all. The prose's point rests on each variant's perplexity, printed3beside the trained model's."""4import numpy as np56from lib import transformer7from lib.products import product_texts89texts = [ids for ids, _ in product_texts("validation", 100)] # the <sep> positions aren't needed: each text is scored whole101112def neighbours(x, base=10000.0):13 """RoPE that pairs neighbouring numbers, (0, 1), (2, 3) and so on, instead of the first half with the second."""14 half = x.shape[-1] // 215 rotated = transformer.rope(np.concatenate([x[..., 0::2], x[..., 1::2]], axis=-1), base) # even numbers, then odd: rope pairs halves, so these are neighbours16 out = np.empty_like(x)17 out[..., 0::2], out[..., 1::2] = rotated[..., :half], rotated[..., half:] # each rotated number back where its dimension was18 return out192021for label, positions in [("as trained", transformer.rope),22 ("RoPE pairing neighbouring numbers", neighbours),23 ("RoPE with base 100,000", lambda x: transformer.rope(x, base=100000.0)), # 100,000 is SmolLM2's base24 ("no RoPE", lambda x: x)]: # no RoPE: the queries and keys pass through unrotated25 print(f"perplexity, {label}:", f"{transformer.perplexity(texts, positions=positions):,.1f}")
python mismatched-details.pyperplexity, as trained: 24.3
perplexity, RoPE pairing neighbouring numbers: 112.2
perplexity, RoPE with base 100,000: 26.4
perplexity, no RoPE: 182.0
二つの食い違いは、生成したテキストの最初のサンプルで見つかるだろう。前半と後半ではなく隣り合う数値同士を組み合わせると、パープレキシティは 24.3 から 112.2 に上がり、RoPE を省くと 182.0 に上がる。
危険なのは基数である。100,000 のときのパープレキシティは 26.4 で、24.3 よりわずかに悪いだけである。エラーは出ず、出力も流暢に見えるため、そのまま出荷されかねない誤りとなる。
SmolLM2 とのもう一つの違いはグループ化クエリアテンションである。クエリヘッド 15 個がキーと値の 5 組を共有するため、キー行列と値行列の大きさはクエリ行列の 3 分の 1 になる(Ainslie et al., 2023)。このような重みを、ヘッドごとにキーと値を要求するモデルに読み込むと、形状のエラーで失敗する。これは、こうあってほしい種類の食い違いである。
実践ルール: 他のモデルの重みを読み込むときは、そのモデルの設定を自分のコードと一行ずつ照合する。照合する項目は、正規化とその ε、RoPE の組み合わせ方と基数、フィードフォワード層のゲート、出力の重み共有、キーと値を共有するヘッドの数である。そのうえで、内容の分かっているテキストを採点し、元の実装の出力と比べる。恐れるべきなのは、エラーを伴わずに損失がわずかに大きくなる場合である。
この部分はまだ翻訳されていないため、英語で表示している。
Count where the parameters go
With every part built, count what the model learns, and where. A model's parameters are its capacity to learn, and where they sit says what it spends that capacity on. The trained model's count, by part:
1"""Counts the store's model's parameters by part from its saved weights, and prints its settings. The prose's point2rests on the total, the feed-forward count and the embedding's share of it."""3from lib import transformer45weights, vocabulary, manifest = transformer.load()6settings = manifest["settings"]7# one table serves as input and output, so the embedding is counted once; a weight's group is the last part of its name8groups = {"embedding (shared with the output)": ["embedding"], "attention": ["q", "k", "v", "o"],9 "feed-forward": ["gate", "up", "down"], "normalization": ["norm1", "norm2", "final_norm"]}10for group, parts in groups.items():11 count = sum(v.size for k, v in weights.items() if k.split(".")[-1] in parts) # a weight's name ends in its part: layer3.q is attention's q12 print(f"{group}:", f"{count:,}")13print("total:", f"{sum(v.size for v in weights.values()):,}")14print("embedding's share of the total:", f"{weights['embedding'].size / sum(v.size for v in weights.values()):.0%}")15print("layers:", settings["layers"])16print("width:", settings["dimensions"]) # the width of the residual stream, which the manifest calls dimensions17print("heads:", settings["heads"])18print("feed-forward width:", settings["feed_forward"])19print("longest text, in tokens:", settings["longest"]) # longer texts were cut to this many tokens20print("vocabulary:", f"{len(vocabulary):,}") # the store tokenizer's tokens, plus the four markers
python transformer-parameters.pyembedding (shared with the output): 530,176
attention: 262,144
feed-forward: 540,672
normalization: 1,152
total: 1,334,144
embedding's share of the total: 40%
layers: 4
width: 128
heads: 4
feed-forward width: 352
longest text, in tokens: 160
vocabulary: 4,142
The model has 1,334,144 parameters, slightly fewer than the 1,394,732 of chapter 5's window model. The two are about the same size but spend their parameters differently. The window model put about three quarters of its parameters in its output layer, and could see four tokens back. The transformer puts most of its parameters in its blocks, 540,672 of them in feed-forward layers alone. It shares its embeddings with its output, and can see every earlier token in a text of up to 160 tokens.
The embedding table, shared with the output layer, holds 530,176 parameters, 40% of the total, because it has a row of 128 numbers for each of the 4,142 tokens. Those are the store tokenizer's vocabulary plus four markers: start, separator, end, and padding, which fills out short texts in a training batch. Chapter 8 explains how the model was trained, and measures it against the baseline.
Working rule: Count parameters by part whenever you design or load a model. At small sizes, the embedding table is a large share of the total, so tie it to the output layer, and choose the vocabulary size with that cost in mind, as chapter 2's choice of merges did.
本番環境で起こる問題
Transformer の各部品は正確に噛み合う必要があり、問題の大半は、ほぼ合っているだけの部品から生じる。
- 細部の不一致は気づかれないまま失敗することがある。 正規化層の位置、RoPE が数値をどう組にするかとその基底、フィードフォワード層にゲートがあるか、出力が重み共有されているかは、いずれも学習済みの重みと一致していなければならない。不一致のなかには、すぐに無意味な出力を生むものがある。一方、ここで測定した RoPE の基底のように、エラーなしにわずかな精度の低下を招くものもある。参照出力と照合して確認すること。
- 学習時を超える長さは検証されていない。 RoPE はどの位置にも角度を与えるが、最大 160 トークンのテキストで学習したモデルは、それを超える角度の使い方を学習していない。学習時の長さを超えて測定するまでは、その長さをモデルの限界とみなすこと。
- 精度を下げると大きな値がオーバーフローすることがある。 ビット数の少ない形式は、通常の大きさであればどの桁でも同じ相対精度を保つ。しかし float16 は 65,504 を超える値を保持できない。また 8 ビット形式では、少数の大きな外れ値が、ほかのすべての値の精度を損なう (Dettmers et al., 2022)。ストアのモデルのストリームは、ここで測定した積では最大 50.6 に達するが、これは float16 の上限からは遠い。モデルを低い精度で提供する前に、自分のモデルのストリームにおける最大値を確認すること。
- 参照出力は重みとともに保管する。 第4章で説明したとおり、結果は計算機に依存する。そのため、重み、参照出力、正確な学習スクリプトをまとめて保管し、コードやライブラリを変更するたびに照合をやり直すこと。
- すべての部品がすべての位置で動作する。 フィードフォワード層のコストはどの位置でも同じであり、第6章で示したとおり、アテンションのコストは長さの2乗に比例して増える。どちらかを最適化する前に、自分のテキストでどちらが支配的かを測定すること。
この章で決めたこと
- ストアのトランスフォーマーは LLaMA 型のブロックを使う。 大きさは玩具のような小規模なものである。各部の前に RMSNorm を置き、アテンションには回転位置埋め込みを用い、フィードフォワード層はゲート付き SiLU とし、出力層は埋め込みと重みを共有する。層数は 4、幅は 128、ヘッド数は 4、フィードフォワード幅は 352 である。SmolLM2-360M も同じ種類の部品を備えており、規模がより大きく、グループ化クエリアテンションを持ち、RoPE の基数は 100,000 である。
lib.transformerの NumPy による順伝播が、本書の基準実装である。 検証用の商品の全位置について、PyTorch 自身の RMSNorm、アテンション、SiLU と照合し、小数点以下4桁まで一致することを確かめている。以後このモデルを使う例はすべて、この実装を実行する。- すべてのブロックは残差ストリームに加算し、すべての部品はその正規化したコピーを読む。 このため、ストリームは層を重ねるにつれて成長できる一方、各部品は一定のスケールのベクトルを受け取る。
- 部品の良し悪しは、それを除いたモデル、または変更を加えたモデルを測定して判断する。 ブロックを1つ除くだけでも、ストアのモデルは大きく悪化し、最初のブロックを除くと使い物にならなくなる。そのため本書は、学習済みモデルのブロックを1つの系として扱う。RoPE の基数が誤っていると、性能はわずかに落ちるがエラーは出ない。したがって、読み込んだ重みは必ず基準となる出力と照合する。
- このモデルの大きさは、第5章のウィンドウモデルとほぼ同じであり、パラメータは出力層ではなくブロックに使われている。 出力と共有している埋め込み表は、それでも全体の 40% を占めるため、語彙サイズは本書が引き続き注視するコストである。
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の8 例件のうち8件が合格
英語版の書籍(版2026.11.16)から翻訳した。