AIによる翻訳。英語版は人による検証済みである。 原文を読む

言語モデルをゼロから学ぶ

教材キット

2026.11.20版(書籍の現行版)より。書籍が更新されると変わる。出典を明記すれば、自由に利用および改変できる。

シラバス

読書時間は章の本文に基づく。学習者はLabまたは自分のマシンでコード例も実行する。

週ごとに一章: 11 週

5 週間後

学習目標と概要

各章の学習目標はその冒頭の一文である。各構成案は章の節に従い、定義される用語、例を実行する前に求められる予測、各節が締めくくる規則を含む。 主要な用語と確認すべき予測は、クイズバンクが出題するとおり英語版のものである。

1. 次の単語を予測する

読了まで約49分。9 例。

この章を終えるまでに、読者は、ある店舗の商品名から、カウントによって完全な言語モデルを構築できるようになる。

講義概要: 10 節
  1. ストアのテキストを読み込む
    • 実行 store-text.py
    • 実践ルール どのモデルにもテキストを見せる前に、テキストを学習用、検証用、テスト用に分割する。分割は文書単位(ここでは商品単位)で行い、同一の品目のほぼ重複したものが二つの部分にまたがらないようにする。作業中はモデルを検証用テキストで比較し、テスト用テキストは最終報告にだけ使う。手元にある最も短く最も規則的なテキストから先に学習する。この章は商品名から始め、説明文は本書の後の部分で扱う。
  2. どの単語がどの単語に続くかを数える
    • 重要用語 bigram
    • 実行 count-next-words.py
    • 実践ルール 組の数え上げは訓練用の分割だけで行い、すべてのテキストに開始マーカーと終了マーカーを付けて、テキストがどう始まりどう終わるかをモデルに学習させる。そこから導く確率だけでなく、生のカウントも保持しておくこと。カウントを見れば、各確率がどれだけの根拠に基づいているかが分かり、次の節でもカウントが必要になる。
  3. Turn counts into probabilities
    • 実行 next-word-probabilities.py
    • 実行 figure-next-word-distribution.py
    • 実践ルール Derive probabilities from counts by division, and check that each word's probabilities sum to one; a sum that doesn't is a bug in the counting. Treat a probability as only as good as the count under it: 0.9 from 1,000 pairs is evidence, while 1.0 from a single pair is an anecdote.
  4. Suggest the next word as a shopper types
    • 実行 autocomplete.py
    • 実践ルール For autocomplete, offer the top few next words by probability, and drop tokens that aren't words, such as punctuation. Expect a bigram model's suggestions to be good after words that are almost always followed by the same thing, such as coffee, and poor after words with many possible continuations, such as outdoor. When the earlier words matter, as they do in patio bar, a bigram model can't help, however much text it learns from.
  5. 名前を1語ずつ生成する
    • 実行 generate-names.py
    • 実践ルール モデルを変更するたびにサンプルを生成して読むこと。サンプルには、文章がある商品から別の商品へ流れていくような、スコアには隠れてしまう失敗が表れるからである。サンプルを再現できるように、シードは固定する。モデルの比較をサンプルで行ってはならない。検証用テキストでのパープレキシティで比較する。
  6. Score a model with perplexity
    • 重要用語 Perplexity
    • 実行 perplexity-by-hand.py
    • 実践ルール Score every language model by its perplexity on validation text, computed exactly as above, with natural logarithms and every predicted word counted, the end marker included. Compare perplexities only between models that use the same tokens and the same validation text, since splitting text differently changes N and what counts as a word. Report training perplexity only beside validation perplexity, to show how much the model memorized.
  7. Unseen word pairs break the model
    • 実行 perplexity-on-new-names.py
    • 実践ルール Never trust a language model that gives zero probability to anything; check for infinite or undefined perplexity on validation text before you compare models. When you see one, count the unseen pairs, as above, to know how much of the text the model can't handle.
  8. Give unseen pairs a little probability
    • 実行 add-one-smoothing.py
    • 実践ルール Never ship a counted model without smoothing, and never ship one with add-one smoothing: measure validation perplexity and expect add-one to lose to every method in chapter 3, which compares them on the same tokens. Use add-one only as this chapter does, to show that zero probabilities are fixable and that the fix needs care.
  9. 本番環境で起こる問題
  10. この章で決めたこと

2. トークン

読了まで約37分。8 例。

この章を終えるまでに、読者はバイトペア符号化(byte-pair encoding)のトークナイザをゼロから構築できるようになる。

講義概要: 9 節
  1. 単語では語彙に穴が空く
    • 実行 unseen-words.py
    • 実践ルール 単語をトークンに選ぶ前に、保持したデータでテキストの語彙外率を測定する。経験則として、保持したデータの単語のうち未知のものが、ストアの名前のように1、2パーセントを超えるなら、単語をトークンに使わない。固定されたコマンド群のように語彙が閉じているテキストでは、単語トークンは引き続き妥当である。
  2. Characters cover everything
    • 実行 character-tokens.py
    • 実践ルール Use characters as tokens only for small experiments, or as a fallback inside a larger scheme, as the next sections do. Check how many characters per word your text has, since that factor multiplies every sequence length and every training step.
  3. 最も頻度の高いペアを繰り返し統合する
    • 実行 merge-pairs-by-hand.py
    • 実践ルール 統合の学習は、他のモデルと同じように訓練分割のみで行い、統合の順序を保持する。符号化がその順序に依存するためである。頻度が等しいペアの間の同順位は固定した規則で解消し、同じテキストからは常に同じトークナイザが得られるようにする。
  4. 店舗のトークナイザを訓練する
    • 実行 store-tokenizer.py
    • 実践ルール トークナイザは、モデルが学習するのと同じテキストで訓練する。ここでは商品名と説明文をあわせて用いる。そうすれば、そのテキストで頻出する単語が1つのトークンになる。トークナイザは一度だけ構築し、比較するすべてのモデルで使う。本書のモデルはいずれも、lib.bpe.store_tokenizer()を通して店舗のテキストを読む。
  5. マージ回数を選ぶ
    • 実行 vocabulary-size.py
    • 実行 figure-merges-trade-off.py
    • 実践ルール マージ回数は、学習テキストでの稀なトークン型の割合と、保持しておいたテキストでの1語あたりのトークン数を測って選ぶ。1語あたりのトークン数があまり下がらなくなり、稀な型が増え始める点で止める。語彙は学習テキストの量に合わせて調整する。経験則として、数百万語程度の小さなモデルには、数万ではなく数千回のマージが適している。
  6. オープンモデルのトークナイザを読む
    • 実行 smollm2-tokens.py
    • 実践ルール オープンモデルのトークナイザを使うときは、常に配布されたままの形で使うこと。モデルは、学習したトークンしか理解しない。コンテキスト長やコストの予算を見積もるときは、常に単語ではなくそのトークナイザでトークン数を数えること。限られた範囲のテキストで自分のモデルを学習するときは、そのテキストで自分のトークナイザも学習すること。
  7. SmolLM2 のマージを手作業で適用する
    • 実行 merges-by-hand.py
    • 実践ルール トークナイザはモデルの一部として扱う。モデルと一緒にバージョン管理し、モデル自身のファイルから読み込み、どちらかをアップグレードするたびに自分のテキストでテストする。同じテキストに対して二つのトークナイザがたとえ一つのトークンでも食い違う場合は、それらに基づくモデルの出力を信頼する前に、その原因を突き止める。
  8. 本番環境で何が問題になるか
  9. この章で決めたこと

3. Counting further back

読了まで約41分。8 例。

学習の終わりには、build an n-gram language model that looks several tokens back, smooth it with Kneser-Ney so it handles text it hasn't seen (smoothing gives some probability to what the counts never saw, as chapter 1 showed), measure the baseline that every neural model in this book is measured against, and see why counting, however clever, runs out of roadできるようになる。

講義概要: 9 節
  1. 文脈が長いほど訓練テキストによく適合する
    • 実行 ngram-memorizes.py
    • 実践ルール n-gramモデルであれ他の言語モデルであれ、自身の訓練テキストでのパープレキシティで評価してはならない。モデルが記憶するにつれて、その値は1に近づく。次数は、本章の以降の部分と同様に、取り置いたテキストでのパープレキシティで選ぶ。
  2. 文脈が長いほど根拠が尽きる
    • 実行 unseen-ngrams.py
    • 実践ルール n-gramの次数を選ぶ前に、学習テキストにまったく含まれない、ホールドアウトしたn-gramの割合を測定する。経験則として、この割合が3分の1に近づくとき(この店の商品名のトライグラムがそうである)、その次数のモデルは未出現の事象の扱い方に大きく左右される。そのため、次数よりもスムージングのほうが重要になる。
  3. 短い文脈と長い文脈を混ぜる
    • 実行 interpolate-orders.py
    • 実践ルール 単一のn-gram次数だけを使ってはならない。必ず低い次数と組み合わせ、すべてのトークンが何らかの確率を保つようにする。固定の重みよりも、後述のKneser-Neyのように、各文脈の重みをそのカウントから決める手法を選ぶ。固定の重みを使う場合は、カウントに用いたテキストではなく、保留したテキストで重みを選ぶ。
  4. トークンが後に続く文脈を数える
    • 実行 continuation-counts.py
    • 実践ルール 長い文脈から短い文脈へバックオフするときは常に、トークンの重みを出現頻度ではなく、そのトークンが後に続く異なる文脈の数で決めること。生のカウントを使うのは、文脈が実際に観測されている最高次の場合だけにする。
  5. Smooth with Kneser-Ney
    • 実行 kneser-ney-by-hand.py
    • 実行 kneser-ney-by-order.py
    • 実行 figure-perplexity-by-order.py
    • 実践ルール Smooth n-gram models with interpolated Kneser-Ney and a discount of 0.75 unless held-out text says otherwise. Raise the order only while validation perplexity keeps falling noticeably, and stop when a step barely helps or hurts, as the step from 4-gram to 5-gram does. A variant, modified Kneser-Ney, uses three discounts instead of one and is the one toolkits such as KenLM build; it would likely lower the baseline a little, and this book keeps the single discount because it's easier to follow by hand.
  6. 3トークンの文脈によるオートコンプリート
    • 実行 ngram-autocomplete.py
    • 実践ルール 候補の生成には、モデルが扱える最長の文脈を使うこと。outdoor bar のように学習データで稀な文脈の候補は、一般的な文脈とは別に確認すること。そこがカウントに基づくモデルが一般的な推測に戻る領域だからである。
  7. The baseline every later model is measured against
    • 実践ルール Before building a learned model, build the strongest counted model you can and record its held-out perplexity as the baseline. Report every later model against it, on the same text and with the same tokenizer, and treat a learned model that doesn't beat it as a result to explain, never as a success. Later chapters find exactly that, and earn the learned models their place another way.
  8. 本番環境で起こる問題
  9. この章で決めたこと

4. Words as vectors

読了まで約46分。9 例。

学習の終わりには、turn every token of the store's text into a short vector of numbers, so that tokens used in similar ways get similar vectors, by two methodsできるようになる:

  • compressing counts of which tokens appear together, training a small model to predict each token's neighbours
講義概要: 10 節
  1. ワンホットベクトルは何も知らない
    • 実行 one-hot-vectors.py
    • 実践ルール トークン同士を関連づける必要があるモデルに、ワンホットベクトルを入力として与えてはならない。次の節で行うように、各トークンの学習済みベクトルを引くための添字としてのみ使うこと。
  2. トークンを周囲のトークンで記述する
    • 実行 cooccurrence-counts.py
    • 実践ルール 共起は、モデルが学習するテキストの中で、2〜5トークンの小さなウィンドウ内で数え、文書の境界をまたいでは数えない。生の頻度をそのままベクトルに用いてはならない。次の節で行うように重み付けし直し、頻出する隣接語が支配しないようにする。
  3. 共起を意外性で重み付けする
    • 実行 ppmi-neighbours.py
    • 実践ルール 共起カウントをベクトルとして使う前に、正の PMI で重み付けし直す。PMI は、まれなトークンのペアを過大評価しがちであると考えておく。そうしたペアでは、わずかな共起でも偶然をはるかに上回るように見えるからである。本章のように頻出するトークンだけを残す理由の一つはここにあり、最小カウントを要求することもその一つである。
  4. カウントを密なベクトルに圧縮する
    • 実行 svd-neighbours.py
    • 実行 figure-token-map.py
    • 実践ルール PPMIをSVDで50〜300次元に圧縮し、この節と同じ方法で結果を確認する。つまり、いくつかのトークンの最近傍語を一覧にして読む。近傍語の大半が頻出の機能語であれば、再重み付けに誤りがある。無関係な語であれば、ウィンドウか語彙が小さすぎる。
  5. Learn vectors by predicting neighbours
    • 実行 skipgram-step.py
    • 実践ルール When you train embeddings, start the second set of vectors at zero and the first at small random values, as lib.skipgram.train does, and draw noise tokens in proportion to their frequency raised to the power 0.75, which Mikolov et al. found works better than plain frequency. Check one update by hand before running millions: a probability moving the wrong way means the gradient's sign is wrong.
  6. Compare learned vectors with counted ones
    • 実行 skipgram-neighbours.py
    • 実践ルール Treat counted embeddings (PPMI and SVD) and learned ones (skip-gram) as close alternatives: on a few million tokens they give similar neighbours, and counted ones are deterministic and fast. Prefer learned embeddings when they're part of a larger model you're training anyway, as in every later chapter of this book. Never read a high similarity as synonymy without checking for opposites.
  7. Analogies, and where they fail
    • 実行 analogies.py
    • 実践ルール Don't judge embeddings by analogies; judge them by how much they help the task they're for, as the next section and every later chapter do. When an analogy fails, check whether the answer is in the vocabulary and whether the words mean what you assume in your text.
  8. Find similar names with vectors
    • 実行 name-vectors.py
    • 実践ルール Average token embeddings when you need a quick, order-free representation of short texts, and expect it to find related items but rank them loosely. For real semantic retrieval, use a model trained for it, as the Primer does. For language modeling, give the model the embeddings themselves and let it learn how to combine them, which chapter 5 starts doing.
  9. 本番環境で問題となること
  10. この章で決めたこと

5. ニューラル言語モデル

読了まで約41分。11 例。

この章を終えるまでに、読者は、それ以前のトークンの窓から次のトークンを予測するニューラル言語モデルを構築し、その勾配を手で計算して検証し、PyTorch で学習させ、計数にもとづくベースラインと公平に比較できるようになる。

講義概要: 11 節
  1. 埋め込みのウィンドウから予測する
    • 実行 window-model-by-hand.py
    • 実践ルール 自分で学習させるモデルは、少なくとも一度は順伝播を手で組み立て、この例のように中間配列すべての形状を出力すること。形状の誤りはニューラルネットワークのコードでよくあるバグであり、形状を見ればモデルが何を計算しているかが正確に分かる。語彙が大きいときは、出力層がパラメータの大部分を占めると見込んでおくこと。
  2. 逆伝播による勾配の計算
    • 実行 gradients-by-hand.py
    • 実践ルール 手書きの勾配は、信頼する前に、小さいモデルで微小変化による推定値と照合する。PyTorch の節のように、勾配を計算してくれるライブラリを使う場合は、代わりにライブラリの順伝播を自分のものと照合する。
  3. 勾配降下法のステップを実行する
    • 実行 gradient-descent-by-hand.py
    • 実践ルール 新しいモデルは、まず少数の例で数ステップ実行し、損失が下がることを確認してから始める。3 つの例で損失が下がらないなら、問題が難しいのではなくバグがあるということである。ステップ幅はいくつか試して選ぶ。小さすぎると損失はのろのろとしか下がらず、大きすぎると損失は跳ね回るか増加する。
  4. Train with PyTorch
    • 実行 same-as-pytorch.py
    • 実践ルール Train with a library that computes gradients for you, and keep a short, independent forward pass of your own to check its outputs, as lib.neural does here. Record the library's outputs for a few inputs whenever you save weights, so the check can run anywhere, long after training.
  5. Stop when validation loss turns up
    • 実行 training-curve.py
    • 実践ルール Always record validation loss per epoch and keep the best epoch's weights, never the last. When the curves part early, as they do here after a few epochs, the model has more capacity than its training text supports: regularize it, use a smaller model, or get more text of the same kind.
  6. ベースラインとの比較
    • 実行 neural-vs-baseline.py
    • 実行 seen-and-unseen-contexts.py
    • 実践ルール 学習したモデルが有効だと主張する前に、必ず同じテキストと同じトークンで、強力なカウントベースのベースラインと比較すること。さらに、比較を既知の文脈と未知の文脈に分け、各モデルがどこで勝つかを確かめること。小さな一つのデータセットから、ニューラルモデルは機能しないとも、常に機能するとも結論してはならない。
  7. ネットワークとカウントを混合する
    • 実行 mix-neural-and-counts.py
    • 実行 figure-mixing-curve.py
    • 実践ルール 学習したモデルとカウントによるモデルが拮抗しているときは、どちらかを選ぶ前に両者の確率の混合を試し、割合は保持したテキストで選ぶ。一方のモデルがはるかに強い場合は割合を小さくとどめ、結果に頼る前に別のテストセットで改善を確認する。
  8. 追加するテキストは同じ種類のものでなければ役に立たない
    • 実行 more-text-of-another-kind.py
    • 実践ルール 学習用テキストを追加する前に、それが予測対象のテキストに似ているかを確認する。多いほどよいと決めてかからず、両方で学習させて対象のテキストで測定する。追加するテキストが大きく異なる場合は、対象のテキストだけで学習させるか、モデルが種類を区別できるように各テキストの配置を工夫する。第8章では、商品の名前と説明の間に区切りを置くことでこれを行っている。
  9. Suggest from similar contexts
    • 実行 neural-autocomplete.py
    • 実践ルール Look at a learned model's predictions on contexts the training text lacks, with control prefixes beside them, but judge it by measurements over many contexts, not by examples. For autocomplete in production, use the mix, and test it on rare prefixes as well as common ones.
  10. 本番環境で起こる問題
  11. この章で決めたこと

6. アテンション

読了まで約46分。10 例。

この章を終えるころには、アテンションを手計算で求められるようになる。

講義概要: 10 節
  1. Look back with a weighted average
    • 実行 attention-by-hand.py
    • 実践ルール Write out attention's four lines once, as this example does, and print the weight matrix: its rows say exactly where each position looks. Keep queries, keys and values as separate matrices while you're learning. Libraries often keep them in one matrix, as PyTorch's MultiheadAttention does with its in_proj_weight (source), and split the result, which computes the same thing.
  2. 因果マスクで未来を隠す
    • 実行 causal-mask.py
    • 実践ルール マスクは softmax の後の重みではなく、softmax の前のスコアに適用する。そうすれば各行の合計は 1 のままである。この例と同じ方法でテストする。後ろの位置への重みがちょうど 0 であること、後ろのトークンを変えても前の出力が変わらないことを確認する。モデルの訓練損失が予想よりはるかに速く下がる場合は、まずマスクを確認する。
  3. スコアのスケーリング
    • 実行 scaling-matters.py
    • 実行 figure-scaling-keeps-spread.py
    • 実践ルール トランスフォーマーの論文と同様に、アテンションスコアをクエリのサイズの平方根で割る。T5 のように、割り算を行わず、その係数をクエリの重みの初期化に組み込むモデルもある(出典)。そのため、重みを読み込む前に、モデルがどちらの方式かを確認すること。クエリとキーの計算方法や初期化方法を変更する場合は、未学習のモデルの最大の重みの平均を出力し、それが 1 を大きく下回ることを確認する。
  4. 複数のヘッドが異なるものを探す
    • 実行 attention-heads.py
    • 実践ルール 経験則として、各ヘッドの幅は少なくとも 32 個の数値に保つ。Transformer の論文の実験では、幅 32 のヘッド 16 個は幅 64 のヘッド 8 個と同等の性能を示した。一方、幅 16 のヘッド 32 個は性能が劣り、キーのサイズを小さくすると性能が悪化した(Vaswani et al., 2017、表 3)。モデルを変更するたびに、重みテンソルの形状、すなわちヘッド数×位置数×位置数を確認すること。ヘッドの軸が誤った位置にあると、エラーなしにヘッドが混ざってしまう。
  5. Read what trained heads attend to
    • 実行 trained-attention.py
    • 実践ルール 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.
  6. モデルがコピーするものを検証する
    • 実行 copy-from-the-name.py
    • 実践ルール モデルが何を使っているかについての主張は、その入力を変えて出力を測ることで検証する。その際、出力を変えないはずの変更も含める。アテンション重みは仮説を立てるために読み、結論を得るにはこのような検証を用いる。
  7. 一部のヘッドは直前のトークンに注意を向ける
    • 実行 previous-token-heads.py
    • 実行 figure-previous-token-pattern.py
    • 実践ルール 学習済みのヘッドは、数百件のテキストにわたる測定済みの平均で記述する。たとえば、直前のトークン、現在のトークン、開始マーカーへの重みである。それぞれを、同じ方法で平均した均等な分布の値と比較する。そうすれば、0.3 のような数値が大きいのか小さいのかを判断できる。
  8. ウィンドウの先に届く
    • 実行 attention-reaches-back.py
    • 実践ルール 文脈をどれだけの長さにするかを決める前に、訓練済みのモデルがどれだけ前まで注意を向けているかを測定する。数値に意味を持たせるため、均等な配分とも比較する。マーカーの重みが長距離の注意に見えてしまわないよう、マーカーへの重みは別に報告する。また、スペースを節約するためにモデルの文脈を切り詰めるときは、最初のトークンを残す。
  9. 本番環境で何が問題になるか
  10. この章で決めたこと

7. トランスフォーマーブロック

読了まで約49分。9 例。

この章を読み終えると、トランスフォーマーブロックを、その部品である注意機構、正規化、ゲート付きフィードフォワード層、位置情報から、残差接続でつなぎ合わせて組み立てられるようになる。

講義概要: 11 節
  1. 各部分の出力を残差ストリームに加える
    • 実行 residual-stream.py
    • 実践ルール すべてのブロックを、置き換えではなく残差ストリームへの加算として書く。加算が揃うように、ストリームの幅はモデル全体で同じに保つ。深いモデルをデバッグするときは、各部分が加えるものを測定する。ほとんど何も加えない部分は、ほとんど何もしていないのである。
  2. 各部分の前で正規化する
    • 実行 rms-norm-by-hand.py
    • 実践ルール 正規化はブロックの各部分の後ではなく前で行い、出力層の前でもストリームをもう一度正規化する。層正規化を用いるモデルに合わせる場合を除き、RMSNorm を使う。他のモデルの重みを読み込むときは、何よりも先に、そのモデルがどの正規化を、どこで、どの ε で用いているかを確認する。わずかな不一致がどれだけの代償を生むかは、不一致の詳細の例が示している。
  3. Transform each position with a gated feed-forward layer
    • 実行 gated-feed-forward.py
    • 実践ルール 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.
  4. Give attention positions with rotations
    • 実行 rope-by-hand.py
    • 実行 figure-rope-depends-on-offset.py
    • 実践ルール 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.
  5. 出力層を埋め込みに結びつける
    • 実践ルール 小さなモデルでは出力層を埋め込みに結びつける。読み込んだモデルについては、別個の出力行列を探す前に、それらが結びつけられているかどうかを確認する。自分で書く順伝播は、lib.transformer のように全体を読める短さに保つ。そうすれば、以降の節で検証するすべての詳細が見えるようになる。
  6. Check the model against PyTorch
    • 実行 transformer-same-as-pytorch.py
    • 実践ルール 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.
  7. ブロックを外して働きを見る
    • 先に確認する Predict one, then score the names and descriptions of the first 100 validation products, 7,624 predictions in all, with the full model and with each block left out in turn:
    • 実行 skip-a-block.py
    • 実践ルール モデルの部品が何をしているかを知るには、重みから推測するのではなく、取り除いて測定する。最初のブロックは、以降のすべてがその上に作られるため、最も重要だと予想してよい。それ以外は測定で確かめる。ここでは、2番目のブロックと最後のブロックの重要度がほぼ等しく、3番目のブロックより大きかったためである。部品を取り除いたときの損失が小さい場合は、解釈に注意する。残りの部品はその部品と並んで学習されたので、測定からわかるのは学習済みモデルが何に頼っているかであり、その部品が単独で何をできるかではない。
  8. 不一致した細部のコストを測る
    • 実行 mismatched-details.py
    • 実践ルール 他のモデルの重みを読み込むときは、そのモデルの設定を自分のコードと一行ずつ照合する。照合する項目は、正規化とその ε、RoPE の組み合わせ方と基底、フィードフォワード層のゲート、出力の重み共有、そして何個のヘッドがキーと値を共有するかである。そのうえで、内容が分かっているテキストを採点し、元の実装の出力と比べる。恐れるべきなのは、エラーを伴わない小さな損失の場合である。
  9. Count where the parameters go
    • 実行 transformer-parameters.py
    • 実践ルール 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.
  10. 本番環境で起こる問題
  11. この章で決めたこと

8. 小さなモデルの訓練

読了まで約47分。8 例。

この章を終えると、小さなtransformerを最初から最後まで訓練し、その結果を評価できるようになる。

講義概要: 10 節
  1. Turn products into batches
    • 重要用語 inputs, targets
    • 実行 training-batches.py
    • 実践ルール Build batches as inputs and shifted targets, mask padding out of the loss, and shuffle the texts each epoch with a fixed seed, so the run can be repeated. Measure the share of padding in your batches; if it's large, pack texts or group them by length before you buy a bigger machine.
  2. AdamW とクリッピングした勾配による更新
    • 実践ルール 控えめな重み減衰を付けた AdamW を使い、勾配は全体の長さでクリッピングする。訓練ステップは全体を通して読める短さに保ち、そこでの選択をすべて見えるようにする。損失が何を無視し、オプティマイザが何を減衰させ、何がクリッピングされるかである。
  3. ウォームアップしてからステップサイズを減衰させる
    • 実行 learning-rate-schedule.py
    • 実行 figure-learning-rate-schedule.py
    • 実践ルール 最初の数百ステップでステップサイズをウォームアップさせ、その後に減衰させる。スケジュールの長さは実行の長さに合わせる。学習スクリプトと同様に、学習の進行中にステップサイズを保存し、意図したスケジュールと照らし合わせて確認する。スケジュールのバグは学習の問題のように見えるが、この方法ならはるかに見つけやすい。
  4. 学習曲線を読む
    • 実行 transformer-training-curve.py
    • 実践ルール 関心のある種類のテキストごとに、エポックごとに検証損失を記録し、最良のエポックの重みを残すこと。学習損失だけでなく、学習と検証の差を警告として読むこと。異なる種類のテキストの間でパープレキシティを比較してはならない。
  5. Compare with the baseline on names
    • 実行 transformer-on-names.py
    • 実践ルール Compare a new model with the strongest baseline you can build on exactly the same predictions, including how each marks the end of a text. When a learned model and a counted one are close, mix them, and choose the share on held-out text.
  6. Compare on descriptions
    • 実行 transformer-on-descriptions.py
    • 実践ルール Measure a model on the kind of text it will predict, against a baseline that sees the same text, and expect the ranking to change from one kind of text to another. Split the comparison by seen and unseen contexts to see where each model wins. Try a mix before concluding that either model is enough: the mix gained more than any change to either model that this chapter measured.
  7. 幅・データ・ステップ数で得られるもの
    • 実行 width-data-and-steps.py
    • 実践ルール 予測したい種類のテキストは、手持ちのものを数回より多く繰り返す前に、まず増やすこと。1 ステップあたりの費用はかからない。計算量に余裕があるなら、幅の狭いモデルを長く学習させる前に、幅の広いモデルを少ないエポックで試し、両方を測定すること。1 回の実行で変更するのは一点だけにし、重要な場面ではステップ数を固定すること。そうしないと、比較は二つのものを同時に測ってしまう。
  8. Suggest the next word in the search box
    • 実行 transformer-autocomplete.py
    • 実践ルール Serve the mix for autocomplete, and test it on rare prefixes as well as common ones, with control prefixes beside each. Treat a single striking suggestion as an illustration of a measured gain, never as the evidence for it.
  9. 本番環境で何がうまくいかなくなるか
  10. What this chapter decided

9. Choosing the next token

読了まで約37分。8 例。

学習の終わりには、turn a language model's probabilities into text, and choose howできるようになる:

  • always the likeliest token
  • the likeliest whole text by beam search
  • a sample shaped by a temperature
  • a top-k or top-p cut
  • a repetition penalty and a minimum length
講義概要: 9 節
  1. 最も尤度の高いトークンを選ぶ
    • 実行 greedy-description.py
    • 実践ルール 毎回同じ出力が欲しい場合や、検索ボックスの候補のように、最も尤度の高い次の語こそが目的である短いテキストの場合には、貪欲法を使う。句より長いものでは、繰り返しが起こると予想し、以降の節の手法のいずれかを選ぶ。
  2. 最も確からしいテキストを探索する
    • 実行 beam-search.py
    • 実践ルール ビームサーチは、検索クエリのように最も確からしい句が目的となる短い補完に用い、総確率で順位付けする。より長いテキストでは、総確率が最も短いテキストを有利にするため、完成したテキストをトークンあたりで順位付けする。ただしその場合でも、人間が書く文章により近いテキストを生成する次の節のサンプリング手法を優先する。
  3. 温度を用いてサンプリングする
    • 実行 temperature-by-hand.py
    • 実行 figure-temperature-flattens.py
    • 実践ルール 温度は、予測しやすいテキストと変化に富むテキストとの間のダイヤルとして扱う。商品説明のように、学習テキストが通常述べる内容に近いままであるべきテキストでは、温度を1か、1より少し低い値に保つ。温度を下げるとテキストはより予測しやすくなるが、より正確になるわけではない。
  4. サンプリングと裾の切り捨て
    • 実行 sample-descriptions.py
    • 実践ルール 多様な文章が必要なときは、top-p を 0.9 前後、または top-k を 20 前後にして裾を切り、温度は 1 かそれより少し低くする。結果を再現する必要があるときは乱数シードを固定する。どの設定でも文章が真になるとは期待しない。デコーディングはモデルがもっともらしいと見なすものの中から選ぶだけであり、事実の確認は別の作業である。
  5. 各設定が書くものを測定する
    • 実行 measure-decoding.py
    • 実践ルール サンプルを読む前に、このような指標で、同種の実際のテキストと比べて、デコーディングの設定を比較する。その作業にとって最も重要な指標を決める。商品の説明文では、商品に即していることと繰り返さないことが先に来る。そのうえで、どの指標でも捉えられないものを見つけるために、出力の一部を必ず読み、事実に関する主張はすべて商品のデータと照合する。
  6. Penalize repetition
    • 実行 repetition-penalty-by-hand.py
    • 実践ルール Add a repetition penalty around 1.2 to 1.3 when you decode greedily or at a low temperature, and check what it does to length, since it shortens text. As a rule of thumb, if descriptions come out clipped, leave common function words and punctuation out of the penalty.
  7. 空の説明文を禁止する
    • 実行 minimum-length.py
    • 実践ルール 生成対象について、訓練テキストに空の例や非常に短い例が含まれる場合は、必ず最小長を設定すること。最小長は、本章の他の設定の代わりにではなく、それらと組み合わせて用いること。また、最小長によって強制的に出力されたテキストも、他のテキストと同様の確認が必要になると考えておくこと。
  8. 本番環境で起こる問題
  9. この章で決めたこと

10. オープンモデルの内部

読了まで約42分。9 例。

この章を読み終えると、本書がここまでに築いてきた道具を使って、オープンな言語モデルを読み解けるようになる。

講義概要: 10 節
  1. Count the parameters at scale
    • 実行 open-model-parameters.py
    • 実践ルール 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.
  2. モデルファミリーのサイズを比較する
    • 実行 open-model-family.py
    • 実践ルール モデルのパラメータは設定から数え、その数を重みと照合すること。一致しなければ、どこかの細部を読み誤っている。ファミリーのサイズを比較して、作り手が設計をどのように拡大したかを確かめること。大きいモデルが小さいモデルと大きさだけが違うと思い込んではならない。
  3. 実行にかかるコストを数える
    • 実行 open-model-memory.py
    • 実行 figure-kv-cache-grows.py
    • 実践ルール モデルのメモリは、重みに、処理中のテキストごとに1つのキャッシュを加えたものとして、モデルの設定から計算して見積もる。長いテキストや多数のテキストを扱う場合は、キーとバリューをグループ化するモデルを選ぶ。許可するテキストの長さには、見積もった予算の範囲内で上限を設ける。
  4. 汎用モデルでストアのテキストを採点する
    • 実行 open-model-on-the-store.py
    • 実践ルール トークナイザの異なるモデルは、トークン単位ではなく、単語単位または文字単位で、まったく同じテキストと事象について比較する。自分のテキストで学習した小さなモデルではなく大きな汎用モデルを選ぶ前に、自分のテキストで両方を測定する。モデルが学習したものと似ていないテキストに対しては、規模の大きさは埋め合わせにならない。
  5. Find the same heads at scale
    • 実行 open-model-heads.py
    • 実行 figure-first-token-sinks.py
    • 実践ルール 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.
  6. Test copying at scale
    • 実行 open-model-copying.py
    • 実践ルール 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.
  7. Suggest the next word at scale
    • 実行 open-model-autocomplete.py
    • 実践ルール 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.
  8. 二つのモデルを並べる
    • 実践ルール 選択の対象となるすべてのモデルを、自分の仕事にとって重要な指標で並べて比較する。その際、どの列でも同じテキストと同じテストを用いる。モデルは、すべてに一つのモデルを使うのではなく、仕事ごとに選ぶ。
  9. 本番環境で何が問題になるか
  10. この章で決めたこと

11. 予測から指示への追従へ

読了まで約41分。11 例。

この章を終えると、次のトークンを予測するモデルがどのようにして要求に従うモデルになるのかを説明できるようになる。

講義概要: 10 節
  1. Build the two training losses by hand
  2. ベースモデルとチューニング済みモデルに尋ねる
    • 実行 base-and-tuned.py
    • 実践ルール 依頼に従わせたいときはチューニング済みモデルを使い、直前の文章の文体で続きを書かせたいときはベースモデルを使う。流暢さを知識と取り違えてはならない。チューニング済みモデルは、事実が乏しいままでも、形の整った説明文を書く。
  3. モデルがチューニングされた形式でリクエストを整える
    • 重要用語 chat template
    • 実行 chat-template.py
    • 実践ルール チューニング済みモデルへのリクエストは、必ずそのモデル自身のチャットテンプレートで整える。テンプレートはモデルのトークナイザーファイルからライブラリに適用させ、手作業で組み立ててはならない。モデルはリクエストのたびに既定のシステムメッセージを読むので、テンプレートの既定のシステムメッセージを確認する。保存する回答には、整形済みの完全なプロンプトを必ず記録する。
  4. 作り話の商品情報を測定する
    • 実行 made-up-materials.py
    • 実践ルール モデルは、入力から答えられる質問だけでなく、答えられない質問でも検証し、作り話の答えは別に数えること。モデルが商品について述べる事実上の主張は、可能な限り自動的に、商品のデータと照合すること。lib.claims が素材に対して行っているのがその例である。
  5. 確信度が警告になるかを確かめる
    • 実行 answer-confidence.py
    • 実行 figure-confidence-overlap.py
    • 実践ルール モデルの確信度だけで、回答を信頼するかどうかを決めてはならない。自分の質問で、確信度と正しさがどう関係するかを測定すること。しきい値を使う場合は、その測定結果から選び、何が通り抜けるかを数えること。
  6. 長いコンテキストで失われるものを調べる
    • 実行 answer-position.py
    • 実践ルール モデルが最も必要とする詳細は、コンテキストの中間ではなく先頭か末尾に置き、無関係なテキストはタスクが許す限り少なくする。多数の情報の中からモデルが詳細を見つけられると信頼する前に、長いコンテキストからの検索を各位置でテストする。
  7. モデルを自店のテキストに適応させる
    • 実行 lora-parameters.py
    • 実践ルール 汎用モデルに自店のテキストを教えるには、そのテキストでファインチューニングする。メモリや保存容量に余裕がないときはLoRAを用い、結果は同種のホールドアウトしたテキストで測定する。モデルが学習したことのない知識を、指示チューニングや巧妙なプロンプトが補ってくれると期待してはならない。
  8. 物差しを振り返る
    • 実行 test-names.py
    • 実践ルール モデルを比較する物差しは、本書が行ったように、毎回同じ文章、同じトークナイザー、同じ指標で固定する。そのうえで、モデルを選んで運用する前に、その仕事向けに作ったテストで仕事そのものを測る。パープレキシティが低いことは、モデルをテストする理由にはなるが、出荷する理由にはならない。
  9. 本番環境で起こる問題
  10. この章で決めたこと

問題バンク

全章の設問と解答を、認証済み教育者向けに提供する。各解答は該当する節に紐づいている。 入手方法