オープンモデルの内部
読了まで約40 分分、10 節 節の 7 例 例。
この章を終えると、本書がここまでに築いてきた道具を使って、オープンな言語モデルを読み解けるようになる。具体的には、パラメータがどこに使われているかを数え、動かすのに必要なコストを見積もり、トークナイザーの異なるモデルと公平に比較できる形でテキストをスコア付けし、第6章のアテンションパターンをそのヘッドの中に見いだし、モデルが何をコピーするかを検証し、モデルの規模がストアのテキストに対して何をもたらし、何をもたらさないかを知ることができる。
第9章は、ストア独自のモデルが生成した説明文で終わった。その説明文は、誰かが読む前に確認する必要がある。このモデルは、第6章から第9章で構築し、訓練し、1つの家具・家庭用品カタログに使った小さなトランスフォーマーである。Hugging Faceが Apache 2.0 ライセンスで公開したオープンモデルの SmolLM2-360M は、第7章で示したとおり、同じ部品から作られている。パラメータ数は200倍以上であり、Webテキスト、コード、数学、合成の教科書から成る4兆トークン(モデルカード、Allal et al., 2025の6節)で訓練された。この章が問うのは、これほど多くのテキストで訓練された、無料でダウンロードできるモデルが、ストア独自のモデルの仕事、すなわち検索ボックスでの次の単語の提案と、説明文の予測を担えるかどうかである。第2章ではSmolLM2のトークナイザーを読んだ。この章ではモデルそのものを読む。
SmolLM2の実行にはPyTorchと、約0.7GBのダウンロードが必要である。重みは16ビットの数値で保存されている。そのため、本書の他の記録済みの結果と同様に、一度だけ実行した。スクリプトrecordings/open_model.pyは、ストアのモデルと同じく次のトークンの予測だけを訓練されたベースモデルを、ピン留めしたリビジョン(リポジトリの固定されたバージョン)で読み込んだ。そしてストアのテキストでモデルを動かし、この章で読む内容を保存した。保存したのは、すべての重みの形状、ストアの検証用の名前と説明文に対するスコア、各ヘッドのアテンションの傾向、第6章のコピーのテスト、第8章の検索ボックスの接頭辞である。2つ目のスクリプトrecordings/open_model_family.pyは、SmolLM2の3つのサイズの設定ファイルだけを、やはりピン留めしたリビジョンでダウンロードした。例題は、examples/data/recorded/にある両方の記録を、lib.open_modelを通して読み込む。
この部分はまだ翻訳されていないため、英語で表示している。
Count the parameters at scale
The parts are familiar, so the first question is where the parameters sit. Chapter 7 counted the store's model by part: 1,334,144 parameters, 40% of them in the embedding table it shares with its output.
Run the same count on SmolLM2's recorded weights, and watch which part now holds the most:
1"""Counts SmolLM2-360M's recorded weights by part, with the embedding table shared with the output counted once.2The point that the feed-forward layers hold most of the parameters rests on the feed-forward line."""3import math45from lib import open_model67shapes = {name: shape for name, shape in open_model.read("parameters").items()8 if name != "lm_head.weight"} # the output layer is tied to the embeddings: the same weights, counted once9# A part is matched by name: a weight counts toward the part whose key appears in the weight's name.10parts = {"embedding (shared with the output)": ["embed_tokens"], "attention": ["q_proj", "k_proj", "v_proj", "o_proj"],11 "feed-forward": ["gate_proj", "up_proj", "down_proj"], "normalization": ["layernorm", "model.norm"]}12total = sum(math.prod(shape) for shape in shapes.values())13for part, keys in parts.items():14 count = sum(math.prod(shape) for name, shape in shapes.items() if any(key in name for key in keys))15 print(f"{part}:", f"{count:,}", f"({count / total:.0%})")16print("total:", f"{total:,}")17config = open_model.read("manifest")["config"] # the configuration recorded with the weights18print("layers:", config["num_hidden_layers"])19print("width:", config["hidden_size"])20print("query heads:", config["num_attention_heads"])21print("key and value heads:", config["num_key_value_heads"])22print("feed-forward width:", config["intermediate_size"])23print("vocabulary:", f"{config['vocab_size']:,}")24# Layer 0 stands for every layer: each layer's weights have the same shapes.25print("one layer's query weights:", shapes["model.layers.0.self_attn.q_proj.weight"])26print("one layer's key weights:", shapes["model.layers.0.self_attn.k_proj.weight"])
python open-model-parameters.pyembedding (shared with the output): 47,185,920 (13%)
attention: 78,643,200 (22%)
feed-forward: 235,929,600 (65%)
normalization: 62,400 (0%)
total: 361,821,120
layers: 32
width: 960
query heads: 15
key and value heads: 5
feed-forward width: 2560
vocabulary: 49,152
one layer's query weights: [960, 960]
one layer's key weights: [320, 960]
The balance has shifted from the store's model. The feed-forward layers hold 235,929,600 (65%) of SmolLM2's 361,821,120 parameters. The embedding table, still shared with the output, holds 47,185,920 (13%), attention 78,643,200 (22%), and the normalization gains almost nothing. The blocks grow with the number of layers times the square of the width, and the embedding table, for a fixed vocabulary, only with the width, so as a model grows, the blocks take over.
Attention holds fewer parameters than 15 full heads would, because of grouped-query attention, which shares each key and value head among several query heads. Each layer has 15 query heads but only 5 heads of keys and values, each shared by 3 query heads (Ainslie et al., 2023). The weights show it. One layer's query weights have the shape [960, 960], and its key weights [320, 960], a third as many numbers. Per layer, with the head size being the width divided by the number of query heads:
attention parameters = 2 × width² + 2 × width × key and value heads × head size
for the query and output weights, then the key and value weights. During generation, a model keeps every layer's keys and values for every earlier token, so sharing them shrinks that store, as a later section measures; Ainslie and colleagues found it costs little in quality.
Working rule: Count an open model's parameters by part from its weights before you use it, and read the shapes for its design choices: tied embeddings, grouped keys and values, a gated feed-forward layer. Expect the blocks, not the embeddings, to hold most of a large model's parameters.
モデルファミリーのサイズを比較する
SmolLM2 には3つのサイズがあり、いずれも同じ部品から作られている。それぞれの設定を比べると、開発者がパラメータをどこに多く割り当てるかが分かる。各設定ファイルには、層数、幅、ヘッド数、フィードフォワード層の幅が記されている。これらがあれば、第7章の計算と上の式を用いて、すべてのパラメータを部品ごとに数えられる。lib.open_model.parameters がその計算を行う。
3つのサイズすべてについて、記録された設定からパラメータ数を数え、360M の数を最初の記録が保存した重みと照合する。
1"""Counts all three SmolLM2 sizes from their recorded configurations, part by part, and checks the 360M model's count2against its recorded weights. The claim that the counts match the weights rests on the 360M parameters line and the last line."""3import math45from lib import open_model67for name in open_model.SIZES:8 config = open_model.config(name)9 parts = open_model.parameters(config) # the count by part, from the configuration alone, grouped keys and values included10 print(f"{name}, layers:", config["num_hidden_layers"])11 print(f"{name}, width:", f"{config['hidden_size']:,}")12 print(f"{name}, query heads:", config["num_attention_heads"])13 print(f"{name}, query heads per key and value head:", config["num_attention_heads"] // config["num_key_value_heads"]) # query heads sharing each key and value head14 print(f"{name}, feed-forward width:", f"{config['intermediate_size']:,}")15 print(f"{name}, RoPE base:", f"{config['rope_theta']:,}") # the rotary base: a larger base makes positions turn more slowly16 print(f"{name}, parameters:", f"{parts['total']:,}")17 print(f"{name}, embedding's share:", f"{parts['embedding'] / parts['total']:.0%}")18# The output layer is tied to the embeddings, so its weights are skipped: the shared weights are counted once.19recorded = sum(math.prod(shape) for key, shape in open_model.read("parameters").items() if key != "lm_head.weight")20print("SmolLM2-360M, parameters in the recorded weights:", f"{recorded:,}")
python open-model-family.pySmolLM2-135M, layers: 30
SmolLM2-135M, width: 576
SmolLM2-135M, query heads: 9
SmolLM2-135M, query heads per key and value head: 3
SmolLM2-135M, feed-forward width: 1,536
SmolLM2-135M, RoPE base: 100,000
SmolLM2-135M, parameters: 134,515,008
SmolLM2-135M, embedding's share: 21%
SmolLM2-360M, layers: 32
SmolLM2-360M, width: 960
SmolLM2-360M, query heads: 15
SmolLM2-360M, query heads per key and value head: 3
SmolLM2-360M, feed-forward width: 2,560
SmolLM2-360M, RoPE base: 100,000
SmolLM2-360M, parameters: 361,821,120
SmolLM2-360M, embedding's share: 13%
SmolLM2-1.7B, layers: 24
SmolLM2-1.7B, width: 2,048
SmolLM2-1.7B, query heads: 32
SmolLM2-1.7B, query heads per key and value head: 1
SmolLM2-1.7B, feed-forward width: 8,192
SmolLM2-1.7B, RoPE base: 130,000
SmolLM2-1.7B, parameters: 1,711,376,384
SmolLM2-1.7B, embedding's share: 6%
SmolLM2-360M, parameters in the recorded weights: 361,821,120
360M モデルの設定から数えた値は、記録された重みと完全に一致する。数えた値は 361,821,120、記録された値は 361,821,120 である。最大のモデルで増えたパラメータの大半は、深さではなく幅に使われている。SmolLM2-1.7B の層数は 24 であり、小さい2つのサイズの 30 と 32 より少ない。一方、幅は 2,048 であり、小さい2つの 576 と 960 よりはるかに広い。
埋め込みテーブルが占める割合は、モデルが大きくなるにつれて 21%、13%、6% と下がる。3つのモデルは語彙を共有しており、ブロックだけが大きくなるためである。また、最大のモデルはサイズ以外の点でも異なる。このモデルはキーと値をグループ化せず、キー・値ヘッド1つあたりのクエリヘッド数は 1 である。小さい2つのモデルでは、各キー・値ヘッドを 3 個のクエリヘッドで共有している。フィードフォワード層の幅は 8,192 で、モデルの幅の4倍である。360M モデルでは 2,560 で、幅の 8/3 である。さらに、回転位置埋め込みの回転はより遅く、基数は 130,000 である。もう一方の基数は 100,000 である。
実践ルール: モデルのパラメータ数は設定から数え、その数を重みと照合する。一致しなければ、何らかの詳細を読み誤っている。ファミリーのサイズを比較して、開発者が設計をどのように拡大したかを確かめる。大きなモデルが小さなモデルとサイズだけが違うと思い込んではならない。
実行にかかるコストを数える
パラメータ数はモデルが何を学習できるかを決めるが、同時に実行コストも決める。モデルの重みはメモリに載せておく必要があり、16ビット形式では1パラメータあたり2バイトを要する。SmolLM2の重みはこの形式で保存されている(モデルカード)。さらに生成の間は、第9章で述べたとおり、各層がそれ以前のすべてのトークンについてキーとバリューを保持する。新しいトークンを生成するたびに、先行するテキストの計算をやり直さずに済ませるためである。キーバリューキャッシュ、すなわち先行トークンに対する各層のキーとバリューは、テキストの長さに比例して増える。
トークンあたりのキャッシュ(バイト) = 層数 × 2 × キーとバリューのヘッド数 × ヘッドサイズ × 2
これは、各層についてキーとバリューを1つずつ数え、1つの数値を2バイトとして計算したものである。
メモリを見積もるには、各サイズについて、重み、トークンあたりのキャッシュ、そしてモデルが対応する最長のテキスト(8,192トークン)に対するキャッシュが必要になる。キーとバリューをグループ化する場合としない場合の両方を示す。
1"""Works out each size's weights and key and value cache, with and without grouped keys and values, in decimal gigabytes2and kilobytes. The point that grouping cuts the 360M model's cache to a third rests on its two cache lines for the longest text."""3from lib import open_model45longest = open_model.config("SmolLM2-360M")["max_position_embeddings"] # the longest text the models are set up for6print("longest text, in tokens:", f"{longest:,}")7for name in open_model.SIZES:8 config = open_model.config(name)9 head_size = config["hidden_size"] // config["num_attention_heads"] # the width shared out over the query heads, grouped or not10 weights = open_model.parameters(config)["total"] * 2 # 16-bit numbers: 2 bytes each11 cache = config["num_hidden_layers"] * 2 * config["num_key_value_heads"] * head_size * 2 # a key and a value per layer, 2 bytes each12 # The same cache with every query head keeping its own key and value.13 ungrouped = config["num_hidden_layers"] * 2 * config["num_attention_heads"] * head_size * 214 # Decimal units: a gigabyte is 1e9 bytes and a kilobyte 1e3 bytes.15 print(f"{name}, weights in 16-bit numbers, in GB:", f"{weights / 1e9:.1f}")16 print(f"{name}, key and value cache per token, in KB:", f"{cache / 1e3:.0f}")17 print(f"{name}, cache for the longest text, in GB:", f"{cache * longest / 1e9:.2f}")18 print(f"{name}, cache for the longest text without grouping, in GB:", f"{ungrouped * longest / 1e9:.2f}")
python open-model-memory.pylongest text, in tokens: 8,192
SmolLM2-135M, weights in 16-bit numbers, in GB: 0.3
SmolLM2-135M, key and value cache per token, in KB: 23
SmolLM2-135M, cache for the longest text, in GB: 0.19
SmolLM2-135M, cache for the longest text without grouping, in GB: 0.57
SmolLM2-360M, weights in 16-bit numbers, in GB: 0.7
SmolLM2-360M, key and value cache per token, in KB: 41
SmolLM2-360M, cache for the longest text, in GB: 0.34
SmolLM2-360M, cache for the longest text without grouping, in GB: 1.01
SmolLM2-1.7B, weights in 16-bit numbers, in GB: 3.4
SmolLM2-1.7B, key and value cache per token, in KB: 197
SmolLM2-1.7B, cache for the longest text, in GB: 1.61
SmolLM2-1.7B, cache for the longest text without grouping, in GB: 1.61
キーとバリューをグループ化すると、360Mモデルのキャッシュは小さく抑えられる。トークンあたり41キロバイトで済むため、最長のテキスト1本に必要な量は0.34ギガバイトとなり、グループ化しない場合の1.01の3分の1である。
多数の説明文を同時に書くサービスでは、テキストごとにキャッシュを1つ保持する。そのため長いテキストを扱うと、キャッシュが重みを上回ることがある。1.7Bモデルはキーとバリューをグループ化しておらず、トークンあたり197キロバイトを要し、長いテキスト1本で1.61ギガバイトとなる。これは重みの3.4ギガバイトの約半分にあたる。
実践ルール: モデルのメモリは、重みに、処理中のテキストごとのキャッシュ1つ分を加えたものとして、モデルの設定から計算して見積もる。長いテキストや多数のテキストを同時に扱うなら、キーとバリューをグループ化するモデルを選ぶ。許可するテキスト長は、見積もった範囲に収まるよう上限を設ける。
ストアのテキストを汎用モデルで採点する
パラメータ数が200倍あり、ストアのカタログが含むトークン数の100万倍以上のトークンで学習されたモデルであれば、ストア自前の小さなモデルよりもストアのテキストをうまく予測するだろうと期待されるかもしれない。しかし、これを検証するには注意が要る。二つのモデルはトークナイザーが異なるためである。SmolLM2 の語彙は 49,152 トークンであり、テキストの分割の仕方がストアのものとは異なるため、両者のトークンあたりのパープレキシティは別のものを数えている。両者に共通するのはテキストそのものである。単語あたりのパープレキシティは、モデルがテキストに与える対数確率の合計を、トークン数ではなく、そのテキストの単語数で割ったものである。式で表すと、W 語からなるテキストについて、モデルがそのトークンに与える確率を p₁ から pₙ とすると(トークン数がいくつであっても)次のようになる。
単語あたりのパープレキシティ = exp(−(log p₁ + … + log pₙ) / W)
各モデルの合計を同じ単語数で割ることで、各モデルが何トークンを費やしたかにかかわらず、両者を同じ尺度に載せることができる。
各モデルは同じ事象を採点する。名前については、ストアのモデルは <s> から、SmolLM2 は自身の開始トークン <|endoftext|> から始め、どちらも名前の単語とその終端を予測する。終端は、ストアのモデルでは <sep>、SmolLM2 では改行である。説明文については、どちらも名前が与えられ、説明文の単語とその終端を予測する。名前は検証用の名前の先頭から 500 件であり、説明文は第8章の 446 件の商品である。記録では、SmolLM2 に何を読んでいるのかを伝えることが助けになるかを調べるために、ラベル Product name: の後に置いた各名前の採点も行っている。
ストアの名前を単語あたりでより良く採点するのはどちらのモデルで、その差はどれほどか。先を読む前に予想してほしい。そのうえで、ストアのモデルのスコアを NumPy で計算し、SmolLM2 のスコアを記録から読み出して、トークンあたりと単語あたりで比較する。
1"""Scores the store's model and SmolLM2-360M on the same names and the same descriptions, per word, the unit the two share.2The point that the small model wins on both kinds of text rests on the per-word lines for names and for descriptions."""3import math45from lib import bpe, open_model, transformer6from lib.products import product_texts7from lib.store import load_products89_, vocabulary, _ = transformer.load() # load() returns the weights, the vocabulary and the manifest; only the vocabulary is used10index = {token: i for i, token in enumerate(vocabulary)}11scores, tokenizer = open_model.read("scores"), bpe.store_tokenizer()12per = lambda log_p, count: f"{math.exp(-log_p / count):,.1f}" # perplexity: e to the average negative log-probability per count1314# Names: each name's tokens and its end (<sep> for the store's model, a newline for SmolLM2), from the start token.15names = list(load_products("validation")["name"])[:len(scores["names"])] # as many names as SmolLM2 was scored on, from the top of the split16# The start marker, the name's tokens and <sep>: the model scores everything after the start marker.17encoded = [[index[transformer.START]] + [index[t] for t in tokenizer.encode(name)] + [index[transformer.SEP]] for name in names]18store = sum(transformer.total_log_probability(ids, 1) for ids in encoded) # scores ids[1:], every token after <s>19smollm2 = sum(row["log_p"] for row in scores["names"])20# Words are whitespace-separated, as the recording counted them; both models are divided by the same count.21words = sum(row["words"] for row in scores["names"])22print("validation names scored:", len(names))23print("names, per-token perplexity, the store's model:", per(store, sum(len(ids) - 1 for ids in encoded))) # all but <s>24print("names, per-token perplexity, SmolLM2-360M:", per(smollm2, sum(row["tokens"] for row in scores["names"]))) # SmolLM2's own count25print("names, per-word perplexity, the store's model:", per(store, words))26print("names, per-word perplexity, SmolLM2-360M:", per(smollm2, words))27# The label is context for the recording and is not scored; the same words count.28print("names after a label, per-word perplexity, SmolLM2-360M:", per(sum(r["log_p"] for r in scores["labelled names"]), words))2930# Descriptions: chapter 8's products, each description's tokens and its end, given the name.31end = index[transformer.END] # the end marker closes a description32# The first 500 validation products. Keeps those whose text ends rather than being cut at the length limit, and that have33# at least one description token after <sep>. Scores from sep + 1: the description and its end, given everything up to <sep>.34store = sum(transformer.total_log_probability(ids, sep + 1) for ids, sep in product_texts("validation", 500)35 if ids[-1] == end and sep < len(ids) - 2)36words = sum(row["words"] for row in scores["descriptions"])37print("descriptions scored:", len(scores["descriptions"]))38print("descriptions, per-word perplexity, the store's model:", per(store, words))39print("descriptions, per-word perplexity, SmolLM2-360M:", per(sum(r["log_p"] for r in scores["descriptions"]), words))
python open-model-on-the-store.pyvalidation names scored: 500
names, per-token perplexity, the store's model: 25.8
names, per-token perplexity, SmolLM2-360M: 564.8
names, per-word perplexity, the store's model: 199.3
names, per-word perplexity, SmolLM2-360M: 54,352.8
names after a label, per-word perplexity, SmolLM2-360M: 67,101.5
descriptions scored: 446
descriptions, per-word perplexity, the store's model: 37.0
descriptions, per-word perplexity, SmolLM2-360M: 61.2
小さなモデルが両方の種類のテキストで勝っており、名前では大差がついている。単語あたりでは、名前でストアのモデルが 199.3、SmolLM2 が 54,352.8 であり、説明文ではストアのモデルが 37.0、SmolLM2 が 61.2 である。これらの名前でトークンあたりにすると、ストアのモデルが 25.8、SmolLM2 が 564.8 である。トークンあたりでは差が隠れてしまう。SmolLM2 はストアの単語1語あたりにより多くのトークンを費やすからである。
商品名を読んでいることを SmolLM2 に伝えても、差は縮まらない。ラベルの後でも単語あたり 67,101.5 であり、ラベルなしの場合より良くなってはいない。したがって、差の原因は、SmolLM2 が名前が来ることを知らないからではなく、名前そのものにある。ここでは検証していない私たちの判断では、ストアのテキストの二つの特徴がその大部分を説明する。一つは、多くの名前が商品ラインの造語で始まることで、ストアのモデルはカタログ全体でこれを見ているという点である。もう一つは、ストアのテキストが小文字化され、句読点の前後に空白があるという点で、SmolLM2 が学習した大半のテキストとは異なる。
ここでの教訓は、小さなモデルのほうが優れているということではない。モデルは、自分が学習した種類のテキストを最もよく予測する。SmolLM2 はストアのモデルよりはるかに多くの英語を知っているが、ストアの流儀についてはほとんど知らない。その流儀を教えるにはストアのテキストでの追加学習が必要であり、それについては第11章で述べる。
実践ルール: トークナイザーの異なるモデルは、まったく同じテキストと事象について、単語あたり、または文字あたりで比較し、トークンあたりでは決して比較しない。自分のテキストで学習した小さなモデルよりも大きな汎用モデルを選ぶ前に、自分のテキストで両方を測定すること。モデルが学習したどのテキストとも似ていないテキストに対しては、大きさは埋め合わせにならない。
この部分はまだ翻訳されていないため、英語で表示している。
Find the same heads at scale
Chapter 6 measured the store's model's heads by their habits, against an even spread, which puts 1 / (i + 1) of a position's weight on each of the i + 1 tokens position i can see. The same measures work on any model, and SmolLM2 has 480 heads to measure.
Look at each head's recorded average weight on the previous token and on the first token, over the first 50 of the 446 products scored above, each text a name, a newline and its description. The even spread is averaged the same way, so the two can be set side by side:
1"""Reads SmolLM2's recorded head averages over the recorded texts, and compares them with an even spread averaged the same way.2The point that a few heads specialize and many put their weight on the first token rests on the head counts and the first-token averages."""3import numpy as np4from tokenizers import Tokenizer56from lib import open_model, transformer7from lib.products import product_texts8from lib.store import load_products910heads = open_model.read("heads")11previous, first = np.array(heads["previous"]), np.array(heads["first"]) # (layers, heads)12print("texts averaged:", heads["texts"])13print("heads in all:", previous.size)14print("heads with more than half their weight on the previous token:", int((previous > 0.5).sum())) # a position's weights sum to 1, so above 0.5 is most of it15print("the most weight a head puts on the previous token:", f"{previous.max():.2f}")16print("average weight on the first token, layers 1 to 4:", f"{first[:4].mean():.2f}") # rows count layers from 0: rows 0 to 317print("average weight on the first token, layers 5 to 32:", f"{first[4:].mean():.2f}") # rows from 4 on are layers 5 to 3218print("heads with more than half their weight on the first token:", int((first > 0.5).sum()))1920# An even spread, averaged the same way: each position i shares its weight equally among the i + 1 tokens it sees.21smollm2 = Tokenizer.from_file("data/smollm2-tokenizer/tokenizer.json")22end = transformer.load()[1].index(transformer.END) # [1] is the vocabulary: load() returns weights, vocabulary, manifest23rows = load_products("validation").head(500) # the first 500 validation products, the ones product_texts reads24# The same products as product_texts, with their names and descriptions, filtered the same way. Each text is a name, a newline25# and a description, as the recording wrote it.26texts = [f"{name}\n{description}\n" for (ids, sep), name, description in27 zip(product_texts("validation", 500), rows["name"], rows["description"]) if ids[-1] == end and sep < len(ids) - 2]28# Only the texts the recording averaged. The +1 is the start token the recording put before every text.29lengths = [len(smollm2.encode(text, add_special_tokens=False).ids) + 1 for text in texts[:heads["texts"]]]30# A position with k tokens to see gives an even spread 1 / k on each of them. k runs from 2 to the text's length.31print("an even spread's weight on the previous token, and on the first:",32 f"{np.mean([np.mean(1 / np.arange(2, n + 1)) for n in lengths]):.2f}")
python open-model-heads.pytexts averaged: 50
heads in all: 480
heads with more than half their weight on the previous token: 3
the most weight a head puts on the previous token: 0.79
average weight on the first token, layers 1 to 4: 0.13
average weight on the first token, layers 5 to 32: 0.61
heads with more than half their weight on the first token: 286
an even spread's weight on the previous token, and on the first: 0.05
A few heads specialize sharply. 3 heads put more than half their weight on the previous token, and the strongest puts 0.79 there, against an even spread's 0.05. The store's model's most previous-token head, measured the same way, put 0.35 on the previous token. With hundreds of heads, a model can afford to give a few of them one narrow job.
The first token's weight is the larger surprise. In the first four layers, heads put 0.13 of their weight on it on average; from layer 5 on, 0.61, against an even spread's 0.05, and 286 heads put more than half there. That's the attention sink that Xiao and colleagues found in large models (Xiao et al., 2024). They explain it by softmax: a head with nothing useful to attend to still has to put its weight somewhere, and the first token is always there. Chapter 6 found the pattern only weakly in the store's model, whose description tokens put 0.11 of their attention on its two markers, against an even spread's 0.05.
Working rule: Describe a large model's heads by the same measured averages you'd use on a small one, compared with an even spread. Expect a few specialized heads and many that put their weight on the first token, and keep that token when you cut a model's context to save memory.
この部分はまだ翻訳されていないため、英語で表示している。
Test copying at scale
Chapter 6 showed the store's model copying cover from a product's name into its description, by changing the name and watching the prediction follow. The same test asks whether SmolLM2 does it too. Whether its training text held this product's text can't be checked, and the test doesn't need it: if SmolLM2 predicted cover from memory of the product, taking cover out of the name wouldn't move it.
Check SmolLM2's recorded probabilities of cover and set at one point in the description of double chaise patio furniture cover, after this outdoor patio furniture, with the name as sold, without cover, and ending in set:
1"""Prints SmolLM2's recorded probabilities of cover and set after the same words of a description, under three versions of the name.2The point that each word follows its own name rests on the cover lines for the name as sold and without cover, and the set line for the name ending in set."""3from lib import open_model45copying = open_model.read("copying") # keyed by the version of the name, each with the probabilities of the tokens after the same words6for label, probabilities in copying.items():7 for token, p in probabilities.items():8 print(f"SmolLM2-360M, {label}, P({token.strip()}):", f"{p:.2f}") # the recorded tokens carry the space before them; strip removes it
python open-model-copying.pySmolLM2-360M, name as sold, P(cover): 0.75
SmolLM2-360M, name as sold, P(set): 0.00
SmolLM2-360M, name without cover, P(cover): 0.02
SmolLM2-360M, name without cover, P(set): 0.02
SmolLM2-360M, name ending in set, P(cover): 0.01
SmolLM2-360M, name ending in set, P(set): 0.77
Both models copy the next word of an earlier phrase when the phrase repeats. With the name as sold, SmolLM2 gives cover 0.75. Take cover out of the name and it falls to 0.02; end the name in set and set gets 0.77.
The store's model behaved the same way, with 0.97, 0.00 and 0.70 for the name ending in set. That copying is the behaviour of induction heads, heads that find an earlier copy of the current token and attend to what followed it. Olsson and colleagues found them in every model they studied with more than one layer (Olsson et al., 2022).
So copying isn't something scale adds; the store's 4-layer model learned it too. For a store like this one, the habit is useful and risky at once: a model that copies words from the product's name stays on the product, and one that copies from the wrong product's text spreads its mistake.
Working rule: Test a behaviour by changing the input and watching the output, and run the same test on every model you compare. When two models of very different sizes share a behaviour, it's a basic one; look for what differs elsewhere.
この部分はまだ翻訳されていないため、英語で表示している。
Suggest the next word at scale
The search box is where the store's text matters most. Chapter 8 found the store's model alone giving stool a probability of 0.50 after outdoor bar, and the mix of the store's model and its counts, the model the search box serves, 0.28.
Here are SmolLM2's three likeliest next tokens after the same five prefixes, each given with nothing before it, the way the store's model got them:
1"""Prints SmolLM2's three likeliest next tokens after five search-box prefixes, and its probability of stool after outdoor bar.2The point that its suggestions are the wrong text rests on the top token after each prefix, and on the stool line."""3from lib import open_model45for prefix, recorded in open_model.read("prefixes").items():6 shown = ", ".join(f"{token!r} {p:.2f}" for token, p in recorded["top"][:3]) # the three likeliest tokens, as recorded7 print(f"{prefix:<12} -> {shown}")8# The recorded key keeps the space before stool. Four places: at two, this probability would print as 0.00.9print("P(stool | outdoor bar), SmolLM2-360M:", f"{open_model.read('prefixes')['outdoor bar']['P( stool)']:.4f}")
python open-model-autocomplete.pybar -> 'ry' 0.05, 'ley' 0.05, 'b' 0.04
patio bar -> '\n' 0.21, 'be' 0.06, ',' 0.06
outdoor bar -> '\n' 0.28, ',' 0.06, '\n\n' 0.04
kitchen bar -> '\n' 0.37, '\n\n' 0.03, ',' 0.02
wine bar -> '\n' 0.20, ',' 0.09, '\n\n' 0.03
P(stool | outdoor bar), SmolLM2-360M: 0.0002
SmolLM2's suggestions read like general English, not like the store's search box. After outdoor bar, patio bar, kitchen bar and wine bar, its likeliest next token is a newline: it takes each prefix as a complete line, likely because short lines like these end in a newline in much of the text it learned from. Its probability of stool after outdoor bar is 0.0002. After bar alone, it suggests pieces of longer words, such as ry and ley, as in barry or barley. None of that is wrong English; it's the wrong text. A search box needs the store's habits, and the store's own models have them. A search box also has to answer within a keystroke, and the store's model runs a small fraction of SmolLM2's arithmetic per token.
Working rule: Don't put a general model in front of shoppers without measuring its suggestions on your own prefixes against what you have. Where a model trained on your text suggests better, keep it, and measure a general model on the jobs where its broader knowledge could matter.
二つのモデルを並べて比べる
すべての指標を測り終えたので、二つのモデルを一つの表で比較できる。店のモデルは本書独自のものであり、6章から8章で測定した。SmolLM2-360M については、本章でその記録から読み取った。
| 店のモデル | SmolLM2-360M | |
|---|---|---|
| パラメータ数 | 1,334,144 | 361,821,120 |
| 層数と幅 | 4 層、幅 128 | 32 層、幅 960 |
| 層ごとのクエリヘッド数、およびキーとバリューのヘッド数 | 4 と 4 | 15 と 5 |
| 語彙数 | 4,142 | 49,152 |
| テキスト量(トークン数):カタログ、または学習に用いたトークン数 | 2,843,222、店のカタログ | 4兆、大半は一般的なテキスト |
| 店の商品名に対する単語あたりパープレキシティ | 199.3 | 54,352.8 |
| 店の商品説明に対する単語あたりパープレキシティ | 37.0 | 61.2 |
説明文が商品名を繰り返すときの P(cover) |
0.97 | 0.75 |
| 一つのヘッドが直前のトークンに置く最大の重み | 0.35 | 0.79 |
各列を縦に読むと、本章の傾向が見えてくる。SmolLM2 は大きさのどの指標でもはるかに大きく、両モデルとも、コピーと直前のトークンへの注意という同じ基本的な振る舞いを学習している。一方、店自身のテキストに関することはすべて小さいモデルに有利である。小さいモデルが学習したのは、そのテキストだけだからである。店が選ぶべきなのは、小さいモデルか大きいモデルかではなく、それぞれにどの仕事を任せるかである。
実践ルール: 選択の候補とするモデルはすべて、自分の仕事にとって重要な指標で並べて比べる。その際、どの列でも同じテキストと同じテストを用いる。すべてを一つのモデルで済ませるのではなく、仕事ごとにモデルを選ぶ。
本番環境で何がうまくいかなくなるか
オープンモデルは、作り手の選択をそのまま持ち込む。しかも、その選択は自ら知らせてはくれない。
- モデルのテキストは、あなたのテキストではない。 SmolLM2 は、ストアの名称に対して、ストア独自の小さなモデルよりはるかに悪いスコアを出し、ラベルを付けても改善しなかった。どのモデルも、信頼する前に自分のテキストで測定すること。
- モデルのトークナイザは、あなたのものではない。 2 つのトークナイザによるトークン単位の数値は比較できない。同じイベントに対して、単語単位または文字単位でスコアを付けること。
- モデルの細部は、それを実行するコードと一致していなければならない。 グループ化されたキーと値、100,000 という RoPE base、重み共有された埋め込みは、いずれも SmolLM2-360M の設定に含まれている。第 7 章では、誤った RoPE base のコストを測定した。精度が少し落ちるだけで、エラーは出ない。モデルは、作り手が公開しているコードを、固定されたバージョンで使って読み込むか、すべての細部をそのコードと照合すること。
- リビジョンは変わる。 モデルのリポジトリは、同じ名前のまま更新されることがある。
recordings/open_model.pyと同様にリビジョンを固定し、すべての結果と一緒に記録すること。 - 最初のトークンは重要である。 SmolLM2 の後段のヘッドの多くは、最初のトークンに依存している。コンテキストを切り詰めるときは最初のトークンを残し、パイプラインがそれを黙って落とすことがないようにすること。
- サイズが速度を決める。 生成されるトークンはすべて全層を通過するため、数百倍大きいモデルでは、トークンあたりの演算量も数百倍になる。応答時間を約束する前に、実際に提供するマシンで、提供するテキスト長について、トークンあたりの時間を測定すること。
- ライセンスと利用条件はモデルとともに引き継がれる。 SmolLM2 は Apache 2.0 であるが、ほかのオープンモデルには別の条件が付いている。利用の基盤とする前に、そのモデルとリビジョンそのもののライセンスを確認すること。
この章で決めたこと
- 本書のオープンモデルは SmolLM2-360M であり、二つの記録から読み取る。 記録はいずれも固定したリビジョンのものであり、一つはストアのテキストに対する実行結果、もう一つは同モデルファミリーの設定である。すべての例は PyTorch もダウンロードも使わずに実行でき、結果は記録された内容と照合できる。
- tokenizers の異なるモデルどうしは、単語単位で比較する。 同じテキストと同じ事象を対象とし、各名前については、開始トークンから数えて名前の単語とその終端を、各説明については、名前が与えられた状態での説明の単語とその終端を評価する。
- ストアのテキストでは、ストアの小さなモデルが SmolLM2 を上回る。 単語あたりの値は、名前では 199.3 対 54,352.8、説明では 37.0 対 61.2 である。検索ボックスでは、第8章で選んだ、ストアのモデルとその頻度カウントの混合を引き続き用いる。
- ヘッドは、均等な分布を基準として、同じ尺度でモデル間を比較する。 SmolLM2 には、第6章の二つのパターンがどちらも、より鮮明に現れる。直前のトークンに特化した少数のヘッドと、重みを最初のトークンに置く多数のヘッドである。
- テキストの前方からのコピーは基本的な働きである。 4層のモデルにも 32層のモデルにも共通して見られ、両者で同じ方法で検証される。
- モデルのコストは、提供する前に設定から計算できる。 重みに加え、処理中のテキストごとに一組のキーと値のキャッシュが必要になる。SmolLM2 の各サイズのうち、グループ化したキーと値により、360M モデルのキャッシュは 3 分の 1 に減る。
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の7 例件のうち7件が合格
英語版の書籍(版2026.11.16)から翻訳した。