小さなモデルの訓練

読了まで約46 分分、10 節 節の 7 例 例。

第2026.11.16版 2026年11月19日時点で例が通過 86 例中 86 例が合格 変更点

AIによる翻訳。英語版は人による検証済みである。 当社の書籍の作り方

英語版の書籍(版2026.11.16)から翻訳した。 原文を読む

この章を終えると、小さなtransformerを最初から最後まで訓練し、その結果を評価できるようになる。テキストをバッチに変換し、AdamWで重みを更新し、ステップ幅のスケジュールを設定し、訓練曲線を読み、数え上げによるベースラインと比べてモデルを公平に測定する。さらに、この規模で幅を広げること、テキストを増やすこと、訓練を長くすることから何が得られるかを調べ、モデルが数え上げに勝つ場面と、数え上げを併用する必要がある場面を見極める。

第7章では、ストアのモデルを組み立て、訓練済みの重みを使って各部分を検証した。この章では、その重みがどこから来たのかを扱う。それは recordings/transformer.py に記録された1回の訓練の実行である。この実行によって、モデルはストアのカタログ、すなわちオンラインで販売している家具や家庭用品の名前と説明について、次の各トークンを予測することを学んだ。続いてこの章では、モデルが担う2つの仕事で性能を測定する。1つは検索ボックスで商品名の次の単語を提案すること、もう1つは、離れた文脈が意味を持つほどテキストが長くなる商品説明を予測することである。

第5章と同様に、訓練はPyTorchで1回だけ実行した。例では、その実行が保存した重み、曲線、設定を読み込む。設定は実行のマニフェストに記録されている。自分で訓練するには、専用の環境に recordings/requirements.txt をインストールする。これによりPyTorchのCPU版が追加される。そのうえで、本のフォルダーから python recordings/transformer.py を実行する。同じファイルが examples/data/recorded/transformer/ に書き出され、ノートパソコンのプロセッサーで動作する。

この部分はまだ翻訳されていないため、英語で表示している。

Turn products into batches

最終変更:版2026.11.16

Training starts by turning the store's catalog into numbers the model can learn from. Each product becomes one text: the start marker, the name, the separator <sep>, the description and the end marker, tokenized by the store's tokenizer. A text longer than the model's limit is cut. Each training step takes a batch of texts at once, so the arithmetic runs on whole matrices, and texts of different lengths are filled out to the longest in the batch with a padding token.

Each text then gives the model one prediction per position. The inputs are a text's tokens without the last, and the targets are the text's tokens without the first, so position i is trained to predict token i + 1. Thanks to the causal mask, one forward pass makes every one of those predictions at once. The loss is averaged over the targets that aren't padding: the padding costs computation but teaches nothing.

Padding is the cost to watch, so build one shuffled epoch's batches as the training script does, and count how much of each batch is padding:

training-batches.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Builds one shuffled epoch of batches the way the training script does, and measures the padding in them.The prose's point rests on the share of targets that are padding over that epoch."""import mathimport numpy as npfrom lib import transformerfrom lib.products import product_texts_, vocabulary, manifest = transformer.load()settings = manifest["settings"]pad, end = vocabulary.index(transformer.PAD), vocabulary.index(transformer.END)texts = [ids for ids, _ in product_texts("train")]size = settings["batch"]order = np.random.default_rng(settings["seed"]).permutation(len(texts))   # one shuffled epoch, from the run's seed, so it repeatspadding, targets_seen, shares = 0, 0, []for start in range(0, len(texts), size):    batch = [texts[i] for i in order[start:start + size]]                      # this step's texts: the next `size` in the shuffled order    longest = max(len(ids) for ids in batch)    padded = np.array([ids + [pad] * (longest - len(ids)) for ids in batch])   # short texts filled out with <pad>    inputs, targets = padded[:, :-1], padded[:, 1:]                            # each position predicts the next token    padding, targets_seen = padding + (targets == pad).sum(), targets_seen + targets.size    shares.append((targets == pad).mean())    if start == 0:        first_shape = (inputs.shape, targets.shape)print("training texts:", f"{len(texts):,}")print("tokens in them:", f"{sum(len(ids) for ids in texts):,}")print(f"texts cut at the length limit, {settings['longest']} tokens:", f"{np.mean([ids[-1] != end for ids in texts]):.1%}")   # a cut text lost its end markerprint("texts per batch:", size)print("one batch's inputs and targets:", *first_shape)print("share of targets that are padding, over one shuffled epoch:", f"{padding / targets_seen:.0%}")print("least and most padding in a batch:", f"{min(shares):.0%} and {max(shares):.0%}")print("steps per epoch:", f"{math.ceil(len(texts) / size):,}")   # the last, partly filled batch is a step tooprint("epochs in the recorded run:", settings["epochs"])print("steps in the recorded run:", f"{manifest['steps']:,}")
出力python training-batches.py
training texts: 34,252
tokens in them: 2,843,222
texts cut at the length limit, 160 tokens: 1.0%
texts per batch: 32
one batch's inputs and targets: (32, 151) (32, 151)
share of targets that are padding, over one shuffled epoch: 46%
least and most padding in a batch: 30% and 59%
steps per epoch: 1,071
epochs in the recorded run: 16
steps in the recorded run: 17,136

The training split holds 34,252 texts and 2,843,222 tokens. That count includes each text's start, separator and end markers, which chapter 4's count of 2,744,320 tokens leaves out, and excludes what the length limit cuts; only 1.0% of the texts are cut.

Each batch holds 32 texts, so one pass over the training texts, an epoch, takes 1,071 steps, and the recorded run took 17,136 steps over 16 epochs.

Over one shuffled epoch, 46% of the targets are padding, between 30% and 59% depending on the batch, because one long description sets the width of every shorter text beside it. Each batch is a rectangle: one row per text, one column per position.

Padding on that scale is waste: nearly half of each forward pass computes predictions the loss then ignores. It doesn't change what the model learns, since padding never counts, but it nearly doubles the cost of each step. Krell and colleagues found padding up to half of all tokens in common datasets, and proposed packing, several texts end to end in each row, with the attention kept from crossing between them (Krell et al., 2021). Putting texts of similar length in the same batch reduces padding too.

Working rule: 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.

AdamWとクリッピングした勾配による更新

最終変更:版2026.11.16

バッチが用意できれば、各ステップは第5章のループそのものである。順伝播、損失、勾配、更新の順に進む。recordings/transformer.pyの以下の数行がその全体であり、バッチごとに一度実行される。

        ids = pad([train[i] for i in order[start:start + SETTINGS["batch"]]])
        logits = model(ids[:, :-1])
        loss = torch.nn.functional.cross_entropy(logits.transpose(1, 2), ids[:, 1:], ignore_index=index[PAD])
        optimizer.zero_grad()
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        optimizer.step()
        scheduler.step()

最初の3行は前節の内容である。パディングされたバッチ、末尾のトークンを除いた入力、そしてパディングを無視してずらしたターゲットに対して計算する損失である。第5章と異なる行は2つある。

最適化器はAdamWである。これは第5章のAdamに、勾配とは別に適用される重み減衰を加えたものである。重み減衰は、各ステップですべての重みを、その値にステップ幅と減衰係数を掛けた分だけ減らす。ここでの減衰係数は0.1である(PyTorchのAdamW)。LoshchilovとHutterは、減衰をこのように適用する方が、損失に加える方法よりもAdamでうまく機能することを示した(Loshchilov and Hutter, 2019)。減衰は正則化の一種であり、第5章のウィンドウモデルにはこれがなかった。減衰はすべての重みをゼロへ引き寄せるので、重みが大きいままでいられるのは、訓練テキストがそれを押し上げ続ける間だけである。

訓練スクリプトは勾配のクリッピングも行う。すべての勾配を1本の長いベクトルとみなして測った合成の長さが1.0を超えるとき、その長さになるようにすべての勾配を縮小する(PyTorchのclip_grad_norm_)。これにより、1つの異常なバッチが重みを大きく狂わせることはない。Pascanuらはまさにこの目的でクリッピングを提案した。まれに現れる非常に大きな勾配は、それまでの訓練で学習した内容の多くを台無しにしかねないからである(Pascanu et al., 2013)。

実践ルール: 控えめな重み減衰を持つAdamWを使い、勾配は合成の長さでクリッピングする。訓練ステップは全体を通して読めるほど短く保ち、その中のあらゆる選択が見えるようにする。損失が何を無視するのか、最適化器が何を減衰させるのか、何がクリッピングされるのかである。

ウォームアップしてから、ステップサイズを減衰させる

最終変更:版2026.11.16

ループの最後の行であるscheduler.step()は、バッチごとにステップサイズを変更する。その変更はスケジュールに従う。スケジュールとは、学習の各ステップにおけるステップサイズを定めるものである。最初の200ステップでは、ステップサイズがほぼ0からピークの0.003まで直線的に上昇する。これがウォームアップであり、トランスフォーマーの論文のスケジュールにも含まれていた(Vaswani et al., 2017、5.3節)。Adamの最初の数ステップでは、勾配の二乗の移動平均がわずかなバッチにしか基づいていないため、ステップサイズのばらつきが大きい。Liuらは、ウォームアップがこの分散を抑えることで効くことを示した(Liu et al., 2020)。ウォームアップの後、ステップサイズはコサイン曲線の半周に沿って下がり、最後のステップではピークの10分の1になる(Loshchilov and Hutter, 2017)。序盤の大きなステップは広い範囲を進み、終盤の小さなステップは、重みが低い点の周りで跳ね回らず、そこに落ち着くようにする。ウォームアップ後の式は次のとおりである。

rate = peak × (0.1 + 0.9 × ½ (1 + cos(π × progress)))

ここで progress は、ウォームアップの終了時点で0、最後のステップで1となるように変化する。

このスケジュールが学習の実際のスケジュールと一致しているかどうかは確認できる。記録された設定から手計算でスケジュールを求め、学習スクリプトが10ステップごとに保存したステップサイズと突き合わせればよい。

learning-rate-schedule.py Python 3.12.15 · numpy 2.5.5 合格
"""Computes the warm-up and cosine schedule by hand from the recorded settings, and checks it against the step sizesthe training script saved. The prose relies on the check: the assert fails the run if the two ever differ."""import jsonimport mathfrom lib import transformer_, _, manifest = transformer.load()settings, total = manifest["settings"], manifest["steps"]recorded_rates = json.loads((transformer.RECORDED / "curves.json").read_text())["rates"]   # every 10th step's, after the scheduler's stepdef rate(step):    """Warm up linearly to the peak, then follow half a cosine down to a tenth of it."""    if step < settings["warmup_steps"]:        return settings["peak_rate"] * (step + 1) / settings["warmup_steps"]   # steps count from 0, so step 0 is already a share of the peak    progress = (step - settings["warmup_steps"]) / (total - settings["warmup_steps"])   # 0 at the warm-up's end, 1 at the last step    return settings["peak_rate"] * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress)))print("warm-up steps:", settings["warmup_steps"])print("peak step size:", settings["peak_rate"])print("weight decay:", settings["weight_decay"])for step in [0, settings["warmup_steps"] // 2, settings["warmup_steps"], total // 2, total - 1]:    print(f"step size at step {step:,}:", f"{rate(step):.2e}")gap = max(abs(recorded - rate(10 * i + 1)) for i, recorded in enumerate(recorded_rates))   # recorded_rates[i] was saved after step 10 * i, so it is the size used at step 10 * i + 1assert gap < 1e-9                   # every saved step size matches the hand calculation, to a billionthprint("same as the recorded step sizes:", "yes")
出力python learning-rate-schedule.py
warm-up steps: 200
peak step size: 0.003
weight decay: 0.1
step size at step 0: 1.50e-05
step size at step 100: 1.51e-03
step size at step 200: 3.00e-03
step size at step 8,568: 1.68e-03
step size at step 17,135: 3.00e-04
same as the recorded step sizes: yes

手計算の結果は、保存されたすべてのステップサイズと一致する。ステップサイズは1.50e-05から始まり、ウォームアップの終わりで3.00e-03のピークに達し、最後のステップでは3.00e-04となる。これはピークの10分の1である。

減衰は重要である。比較用の学習は、同じ幅、同じシード、同じバッチで4エポック学習したため、そのスケジュールは減衰をステップ4,284で終えた。そのステップでの検証用の名前に対するスコアは27.6であった。記録された学習は、そのステップではまだピークに近いステップサイズのままであり、スコアは32.6であった。データもステップ数も同じであり、差は減衰によるものである。

実践ルール: ステップサイズは最初の数百ステップでウォームアップし、その後に減衰させる。スケジュールの長さは学習の長さに合わせる。学習スクリプトと同様に、学習中のステップサイズを保存し、意図したスケジュールと照合する。スケジュールのバグは学習の問題のように見えるが、この方法ならはるかに見つけやすい。

学習曲線を読む

最終変更:版2026.11.11

バッチ、更新、スケジュールを設定したうえで、ストアのモデルは 16 エポック学習した。スクリプトは各エポックの後に、検証分割に対してモデルを名前と説明文に分けて測定した。第5章が最良のエポックを残したのと同様に、名前と説明文の検証損失を足し合わせた値が最も低いエポックの重みを残した。

記録された曲線をトークンあたりのパープレキシティとして読むと、エポックごとに次のようになる。

transformer-training-curve.py Python 3.12.15 · numpy 2.5.5 合格
"""Prints the recorded run's perplexity for each epoch, then the epoch kept and its validation perplexities.The prose's point rests on the two validation columns and the epoch kept."""import jsonimport mathfrom lib import transformer_, _, manifest = transformer.load()curves = json.loads((transformer.RECORDED / "curves.json").read_text())["epochs"]print("perplexity per token; training mixes names and descriptions, as the training text does")print("epoch  training  validation names  validation descriptions")for curve in curves:    print(f"{curve['epoch']:>5}  {math.exp(curve['train_loss']):>8.1f}  {math.exp(curve['validation_name_loss']):>16.1f}"          f"  {math.exp(curve['validation_description_loss']):>23.1f}")kept = next(curve for curve in curves if curve["epoch"] == manifest["kept_epoch"])   # the epoch whose weights were keptprint("epoch kept, the lowest name and description losses added together:", manifest["kept_epoch"])print("validation perplexity on names, kept epoch:", f"{math.exp(kept['validation_name_loss']):.1f}")print("validation perplexity on descriptions, kept epoch:", f"{math.exp(kept['validation_description_loss']):.1f}")print("validation perplexity on names, epoch 4:", f"{math.exp(curves[3]['validation_name_loss']):.1f}")   # the list starts at epoch 1, so index 3 is epoch 4
出力python transformer-training-curve.py
perplexity per token; training mixes names and descriptions, as the training text does
epoch  training  validation names  validation descriptions
    1     131.4              50.5                     50.4
    2      41.4              38.8                     36.2
    3      32.8              34.5                     31.5
    4      29.0              32.6                     29.3
    5      26.6              30.9                     27.8
    6      24.8              30.2                     26.4
    7      23.3              28.9                     25.0
    8      21.8              28.1                     23.9
    9      20.5              27.1                     22.9
   10      19.2              26.5                     22.2
   11      17.9              25.8                     21.6
   12      16.8              25.1                     20.8
   13      15.8              24.6                     20.4
   14      14.9              24.2                     20.0
   15      14.2              24.0                     19.9
   16      13.8              24.1                     19.9
epoch kept, the lowest name and description losses added together: 15
validation perplexity on names, kept epoch: 24.0
validation perplexity on descriptions, kept epoch: 19.9
validation perplexity on names, epoch 4: 32.6

検証パープレキシティはエポック 15 まで下がる。このエポックが残されたエポックであり、その後は横ばいになる。最後のエポックはそれより良くない。残されたエポックでは、名前で 24.0、説明文で 19.9 である。第5章と同様に、エポック1の学習パープレキシティは検証より高い。これは、モデルが何も知らなかったそのエポックの最初のバッチにわたって平均を取るためである。学習の列は、学習テキストと同じく名前と説明文を混ぜているため、傾向を示すにとどまり、どちらの検証の列とも並べて比べられる数値ではない。

第5章のウィンドウモデルはエポック 5 の後に改善が止まったが、このモデルははるかに長く改善し続けた。この二つの実行には、それを説明しうる違いがいくつかある。このモデルは名前と説明文、合わせて 2,843,222 トークンから学習したのに対し、ウィンドウモデルは名前だけの 337,071 トークンから学習した。また、このモデルはステップサイズが減衰し、重み減衰を持ち、アテンションがすべての位置で同じ重みを適用する。この実行は、それらの理由を切り分けない。示しているのは学習と検証の差であり、それは毎エポック広がる。終わりの時点では、モデルは新しいテキストよりも学習テキストをはるかによく予測しており、記憶し始めている。

説明文のスコアは名前より低いが、それはモデルが説明文のほうが得意であることを意味しない。テキストの種類ごとに予測しやすさは異なる。説明文はテンプレートや名前からの語句を繰り返し、名前は新しい製品を数語に詰め込む。パープレキシティは同じテキストに対するモデル同士を比べるものであり、テキスト同士を比べるものではない。

実践ルール: 関心のあるテキストの種類ごとに、エポックごとの検証損失を記録し、最良のエポックの重みを残す。学習損失だけでなく、学習と検証の差を警告として読む。異なる種類のテキストの間でパープレキシティを比較してはならない。

この部分はまだ翻訳されていないため、英語で表示している。

Compare with the baseline on names

最終変更:版2026.11.11

With the training read, the result can be measured. The strongest counted model for names is the 4-gram baseline trained on the training names. It scores 23.1 on the validation names, the book's yardstick: every model since chapter 3 has been scored on them. The same 4-gram trained on whole texts, names and descriptions, scores 27.7 on them, because descriptions dilute its counts of how names run.

The comparison has to count the same predictions. The 4-gram predicts each name's tokens and then its end marker; the transformer predicts each name's tokens and then <sep>, which plays the same part, since it marks where the name ends. A name needs nothing after it, so the transformer reads the name alone. Both models score the same 46,704 predictions.

Make a guess first: can the transformer alone beat the counted baseline that chapter 5's window model couldn't? Then score both models, and mixtures of the two, the way chapter 5 did:

transformer-on-names.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Scores every validation name, its end included, with the 4-gram baseline and with the transformer, then mixes themat several shares. The prose's point rests on the share 0.5 line, the lowest of the five."""import numpy as npfrom lib import transformerfrom lib.names import name_tokensfrom lib.ngrams import KneserNey, ngrams, padded_, vocabulary, _ = transformer.load()index = {token: i for i, token in enumerate(vocabulary)}   # each token's id in the vocabulary, which is its column in the model's outputcounted = KneserNey(name_tokens("train"), 4)                     # chapter 3's baseline, trained on namesfrom_counts, from_transformer = [], []for name in name_tokens("validation"):    ids = [index[transformer.START]] + [index[token] for token in name] + [index[transformer.SEP]]   # the name as the model reads it    probabilities = transformer.softmax(transformer.forward(ids)[:-1])   # the last position predicts past <sep>, which a name never needs    from_transformer += list(probabilities[np.arange(len(ids) - 1), ids[1:]])   # each position's probability for the token after it    from_counts += [counted.probability(context, token) for context, token in ngrams(padded(name, 4), 4)]   # then </s>from_counts, from_transformer = np.array(from_counts), np.array(from_transformer)print("validation tokens scored, each name's end included:", f"{len(from_counts):,}")for share in [0.0, 0.3, 0.5, 0.7, 1.0]:    mixed = (1 - share) * from_counts + share * from_transformer    print(f"validation perplexity on names, transformer share {share:.1f}:", f"{np.exp(-np.log(mixed).mean()):.1f}")
出力python transformer-on-names.py
validation tokens scored, each name's end included: 46,704
validation perplexity on names, transformer share 0.0: 23.1
validation perplexity on names, transformer share 0.3: 18.7
validation perplexity on names, transformer share 0.5: 18.4
validation perplexity on names, transformer share 0.7: 18.8
validation perplexity on names, transformer share 1.0: 24.0

Mixed half and half, the transformer and the counts score 18.4 on names, the best of any model in this book on names. Alone, the transformer scores 24.0, slightly worse than the baseline's 23.1.

The transformer alone is far better than chapter 5's window model, which scored 36.4, and the mix beats chapter 5's best mix, 21.9.

So on names, counting is still hard to beat alone, for the reason chapter 5 gave: names are short and formulaic, and three tokens of context see most of what a name holds. But the transformer is wrong in different places from the counts, and the mix gains from both. The share was chosen on the validation names, so the gain is slightly optimistic; the test names stay untouched for the book's final comparison.

Working rule: 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.

この部分はまだ翻訳されていないため、英語で表示している。

Compare on descriptions

最終変更:版2026.11.11

The names comparison favours counting, because names are short. Descriptions run many times longer, and chapter 6 showed the model copying from the name many tokens back, so this is where its longer reach should pay. A fair baseline here is a 4-gram trained on the same texts the transformer learned from, the name, <sep> and description joined, and scored on the same tokens: each description's tokens and its end, with the same text before them.

Put the longer reach to the test on descriptions: fit the 4-gram on every training text, then score it, the transformer and an even mix on the descriptions of the first 500 validation products, leaving out texts cut at the length limit and products with no description. It also splits the tokens, as chapter 5 did, by whether their three-token context occurs in the training texts:

transformer-on-descriptions.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Scores the descriptions of the first 500 validation products with a 4-gram trained on whole texts, with the transformer,and with their even mix, then splits the tokens by whether their context was seen in training. The prose's point rests on the4-gram baseline and transformer lines, the half-and-half line and the unseen-context lines."""import numpy as npfrom lib import transformerfrom lib.names import name_tokensfrom lib.ngrams import KneserNey, ngrams, paddedfrom lib.products import product_texts_, vocabulary, _ = transformer.load()end = vocabulary.index(transformer.END)as_tokens = lambda ids: [vocabulary[i] for i in ids[1:] if i != end]          # padded() adds its own <s> and </s>counted = KneserNey([as_tokens(ids) for ids, _ in product_texts("train")], 4)   # whole texts: name, <sep>, descriptionfrom_counts, from_transformer, seen, products = [], [], [], 0for ids, sep in product_texts("validation", 500):    if ids[-1] != end or sep == len(ids) - 2:        continue                                          # cut at the length limit, or no description    pairs = list(ngrams(padded(as_tokens(ids), 4), 4))[sep:]    # from <sep> on: the description's tokens, then </s>    from_counts += [counted.probability(context, token) for context, token in pairs]    seen += [context in counted.totals[4] for context, _ in pairs]   # was this 3-token context in the training texts?    probabilities = transformer.softmax(transformer.forward(ids)[sep:-1])   # from <sep> on: each position predicts the next token    from_transformer += list(probabilities[np.arange(len(probabilities)), ids[sep + 1:]])   # the description starts after <sep>, at sep + 1    products += 1from_counts, from_transformer, seen = np.array(from_counts), np.array(from_transformer), np.array(seen)perplexity = lambda p: f"{np.exp(-np.log(p).mean()):.1f}"print("products scored:", products)print("description tokens scored:", f"{len(from_counts):,}")mixed = (from_counts + from_transformer) / 2for label, p in [("4-gram baseline", from_counts), ("transformer", from_transformer), ("half and half", mixed)]:    print(f"{label}, validation perplexity on descriptions:", perplexity(p))print("description tokens whose 3-token context is in the training texts:", f"{seen.mean():.0%}")for part, where in [("seen", seen), ("unseen", ~seen)]:    print(f"4-gram, {part} contexts:", perplexity(from_counts[where]))    print(f"transformer, {part} contexts:", perplexity(from_transformer[where]))names = [list(ngrams(padded(name + [transformer.SEP], 4), 4))[:-1] for name in name_tokens("validation")]   # to <sep>: the last pair predicts </s>, which a name stops short ofon_names = [counted.probability(context, token) for pairs in names for context, token in pairs]print("this 4-gram, trained on whole texts, validation perplexity on names:", perplexity(np.array(on_names)))
出力python transformer-on-descriptions.py
products scored: 446
description tokens scored: 35,651
4-gram baseline, validation perplexity on descriptions: 22.5
transformer, validation perplexity on descriptions: 20.1
half and half, validation perplexity on descriptions: 14.7
description tokens whose 3-token context is in the training texts: 74%
4-gram, seen contexts: 16.3
transformer, seen contexts: 16.6
4-gram, unseen contexts: 57.6
transformer, unseen contexts: 35.0
this 4-gram, trained on whole texts, validation perplexity on names: 27.7

On descriptions, the transformer beats counting alone: it scores 20.1 on the 35,651 description tokens of 446 products, against the 4-gram's 22.5. It is the first learned model in this book to beat a counted model of the same text on its own.

The split shows where they differ. 74% of the tokens have a context the training texts contain, and on those the two models tie: 16.3 for the 4-gram, 16.6 for the transformer. On the rest, the transformer scores 35.0 where the 4-gram scores 57.6. Descriptions are formulaic enough that counts do as well as the transformer wherever they have seen the context; where they haven't, the transformer reads further back and relates what it sees to what it learned, and the counts can only back off.

That's also why the mix works so well. Half and half, the two score 14.7, far below either alone: on any one token, at least one of the two is often confident and right, and the even mix keeps half of that probability, enough to avoid the worst surprises of each.

Working rule: 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.

幅・データ・ステップ数で得られるもの

最終変更:版2026.11.11

記録されたモデルは、数多くある選択肢の一つである。幅は 128 個の数であり、訓練テキスト全体を使って 16 エポック訓練されている。はるかに大きなモデルを調べた研究では、モデルが大きくなり、より多くのテキストを見て、より長く訓練するほど損失が滑らかに下がること、そして大きなモデルほど見たトークン一つあたりから多くを学ぶことが明らかになった(Kaplan et al., 2020)。計算量の予算が固定されている場合には、モデルのサイズと訓練テキストを共に増やすべきであることを Hoffmann らが見いだした(Hoffmann et al., 2022)。さらに Muennighoff らは、同じテキストを最大で約 4 エポックまで繰り返しても新しいテキストとほぼ同等の効果があり、それ以上の繰り返しで得られる効果は小さくなることを見いだした(Muennighoff et al., 2023)。これらがこの小規模なモデルでも成り立つかどうかは、仮定せずに測定して確かめるべきことである。

そこで訓練スクリプトは、本番の実行に加えて、より安価な 7 回の実行を記録した。いずれも一つだけを変更している。

  • 幅を 64、128、256 の三通りとし、それぞれ 4 エポック訓練する。どのヘッドも 32 個の数の幅に保つ。
  • 訓練用の商品からランダムに選んだ 4 分の 1 と 2 分の 1 を使い、それぞれ 4 エポック訓練する。
  • 同じ 4 分の 1 と 2 分の 1 を、全データの 4 エポック分と同じステップ数になるまで、より多く繰り返して訓練する。

どの変更が最も効果的だろうか。8 回の実行を並べて、それぞれのサイズ、ステップ数、最良エポックと最終エポックでのパープレキシティを読み取ってみよう。

width-data-and-steps.py Python 3.12.15 · numpy 2.5.5 合格
"""Reads eight recorded runs and prints each one's parameters, steps, best epoch, and validation perplexities at its bestand last epochs. The prose's point rests on the perplexity-on-names lines."""import jsonimport mathfrom lib import transformerruns = [("width 64, 4 epochs", "transformer-width-64"), ("width 128, 4 epochs", "transformer-width-128"),        ("width 256, 4 epochs", "transformer-width-256"), ("width 128, 16 epochs", "transformer"),        ("a quarter of the data, 4 epochs", "transformer-data-25"), ("half the data, 4 epochs", "transformer-data-50"),        ("a quarter of the data, 16 epochs", "transformer-data-25-same-steps"),        ("half the data, 8 epochs", "transformer-data-50-same-steps")]for label, folder in runs:    run = transformer.RECORDED.parent / folder   # every run sits in the folder beside the main run's    manifest = json.loads((run / "manifest.json").read_text())    curves = json.loads((run / "curves.json").read_text())["epochs"]    best = min(curves, key=lambda curve: curve["validation_name_loss"] + curve["validation_description_loss"])   # the epoch the script kept    print(f"{label}, parameters:", f"{manifest['parameters']:,}")    print(f"{label}, steps:", f"{manifest['steps']:,}")    print(f"{label}, best epoch:", best["epoch"])    print(f"{label}, perplexity on names:", f"{math.exp(best['validation_name_loss']):.1f}")    print(f"{label}, perplexity on descriptions:", f"{math.exp(best['validation_description_loss']):.1f}")    print(f"{label}, perplexity on names, last epoch:", f"{math.exp(curves[-1]['validation_name_loss']):.1f}")   # the last epoch trained, not the one kept    print(f"{label}, perplexity on descriptions, last epoch:", f"{math.exp(curves[-1]['validation_description_loss']):.1f}")
出力python width-data-and-steps.py
width 64, 4 epochs, parameters: 478,656
width 64, 4 epochs, steps: 4,284
width 64, 4 epochs, best epoch: 4
width 64, 4 epochs, perplexity on names: 36.9
width 64, 4 epochs, perplexity on descriptions: 35.9
width 64, 4 epochs, perplexity on names, last epoch: 36.9
width 64, 4 epochs, perplexity on descriptions, last epoch: 35.9
width 128, 4 epochs, parameters: 1,334,144
width 128, 4 epochs, steps: 4,284
width 128, 4 epochs, best epoch: 4
width 128, 4 epochs, perplexity on names: 27.6
width 128, 4 epochs, perplexity on descriptions: 24.7
width 128, 4 epochs, perplexity on names, last epoch: 27.6
width 128, 4 epochs, perplexity on descriptions, last epoch: 24.7
width 256, 4 epochs, parameters: 4,273,920
width 256, 4 epochs, steps: 4,284
width 256, 4 epochs, best epoch: 4
width 256, 4 epochs, perplexity on names: 23.5
width 256, 4 epochs, perplexity on descriptions: 19.5
width 256, 4 epochs, perplexity on names, last epoch: 23.5
width 256, 4 epochs, perplexity on descriptions, last epoch: 19.5
width 128, 16 epochs, parameters: 1,334,144
width 128, 16 epochs, steps: 17,136
width 128, 16 epochs, best epoch: 15
width 128, 16 epochs, perplexity on names: 24.0
width 128, 16 epochs, perplexity on descriptions: 19.9
width 128, 16 epochs, perplexity on names, last epoch: 24.1
width 128, 16 epochs, perplexity on descriptions, last epoch: 19.9
a quarter of the data, 4 epochs, parameters: 1,334,144
a quarter of the data, 4 epochs, steps: 1,072
a quarter of the data, 4 epochs, best epoch: 4
a quarter of the data, 4 epochs, perplexity on names: 51.9
a quarter of the data, 4 epochs, perplexity on descriptions: 54.1
a quarter of the data, 4 epochs, perplexity on names, last epoch: 51.9
a quarter of the data, 4 epochs, perplexity on descriptions, last epoch: 54.1
half the data, 4 epochs, parameters: 1,334,144
half the data, 4 epochs, steps: 2,144
half the data, 4 epochs, best epoch: 4
half the data, 4 epochs, perplexity on names: 35.2
half the data, 4 epochs, perplexity on descriptions: 34.8
half the data, 4 epochs, perplexity on names, last epoch: 35.2
half the data, 4 epochs, perplexity on descriptions, last epoch: 34.8
a quarter of the data, 16 epochs, parameters: 1,334,144
a quarter of the data, 16 epochs, steps: 4,288
a quarter of the data, 16 epochs, best epoch: 11
a quarter of the data, 16 epochs, perplexity on names: 40.0
a quarter of the data, 16 epochs, perplexity on descriptions: 39.6
a quarter of the data, 16 epochs, perplexity on names, last epoch: 44.1
a quarter of the data, 16 epochs, perplexity on descriptions, last epoch: 45.9
half the data, 8 epochs, parameters: 1,334,144
half the data, 8 epochs, steps: 4,288
half the data, 8 epochs, best epoch: 8
half the data, 8 epochs, perplexity on names: 30.4
half the data, 8 epochs, perplexity on descriptions: 28.6
half the data, 8 epochs, perplexity on names, last epoch: 30.4
half the data, 8 epochs, perplexity on descriptions, last epoch: 28.6

幅は大きな効果があるが、代償を伴う。ステップ数が同じなら、名前に対するパープレキシティは、幅 64 の 36.9 から、幅 128 の 27.6、幅 256 の 23.5 へと下がる。名前に関しては、4 エポック訓練した最も幅の広いモデルが、16 エポック訓練した記録モデルの 24.0 をも上回る。しかし幅 256 のパラメータ数は 4,273,920 であり、幅 128 の 1,334,144 に比べて多く、1 ステップあたりの計算量もほぼその分だけ増える。

新しいテキストは、1 ステップあたりの追加コストなしに効果をもたらす。ステップ数が同じなら、商品のランダムな 4 分の 1 は最良時に名前で 40.0、2 分の 1 は 30.4、全体は 27.6 となる。テキストを 2 分の 1 から全体へ倍増して得られた改善は、幅を 128 から 256 へ倍増して得られた改善より小さいが、追加の計算量はかからない。また、4 分の 1 から 2 分の 1 への最初の倍増は、どちらよりも大きな改善をもたらした。

繰り返しは、しばらくは効果があるが、やがて逆効果になる。4 分の 1 のテキストを 4 回見た場合は 51.9 である。それ以上繰り返すとエポック 11 まで改善し、その後は悪化して、16 周後には 44.1 で終わる。何度も見たものをモデルが記憶してしまうのである。繰り返したテキストは、同じステップ数での新しいテキストに追いつくことはなかった。

ステップ数の増加は最も効果が小さい。記録モデルの 16 エポックは 4 エポックより改善しており、名前では 24.0 対 27.6 であるが、そのためにステップ数は 4 倍になる。

これらの実行は、本書の規模の限界も示している。ストアの訓練テキストは、カタログが持つ量に固定されており、トークン数は 2,843,222 である。第 7 章でストアのモデルと設計を比較した SmolLM2-360M は、4 兆トークンで訓練されており(モデルカード)、その量はストアの訓練テキストの 100 万倍を超える。そのため、幅 960、深さ 32 層のモデルが、古いテキストを記憶するのではなく、新しいテキストから学び続けることができる。

実践ルール: 手元のテキストを数回より多く繰り返す前に、予測の対象となる種類のテキストをもっと集めること。それには 1 ステップあたりのコストがかからない。計算量に余裕があるなら、幅の狭いモデルをより長く訓練する前に、幅の広いモデルを少ないエポックで試し、両方を測定すること。1 回の実行で変更するのは一つだけにし、重要な場面ではステップ数を固定すること。そうしないと、比較が二つのことを同時に測ってしまう。

この部分はまだ翻訳されていないため、英語で表示している。

最終変更:版2026.11.11

Averages say how good a model is; the search box shows what that means to a shopper. Chapter 3's 4-gram suggested & and with after outdoor bar, a context no training name contains, and chapter 5's window model suggested stool. A few training descriptions do contain outdoor bar, and the transformer learned from them as well as from the names, while the 4-gram learned from names alone.

A shopper would see the transformer's three likeliest next tokens, and those of the half-and-half mix that the names comparison favoured, after the same five prefixes, each treated as the start of a name. A suggestion of <sep> means the model expects the name to end there:

transformer-autocomplete.py Python 3.12.15 · numpy 2.5.5 · pandas 3.1.1 合格
"""Asks the transformer and its half-and-half mix with the 4-gram for their three likeliest next tokens after five prefixes,treated as the start of a name, and prints the probability of stool after outdoor bar. The prose's point rests on thestool lines and the control prefixes beside them."""import numpy as npfrom lib import bpe, transformerfrom lib.names import name_tokensfrom lib.ngrams import KneserNey_, vocabulary, _ = transformer.load()index = {token: i for i, token in enumerate(vocabulary)}counted = KneserNey(name_tokens("train"), 4)tokenizer = bpe.store_tokenizer()as_counted = [{transformer.SEP: "</s>"}.get(token, token) for token in vocabulary]   # <sep> ends a name, as </s> doesshow = lambda token: token.replace("</w>", "")for prefix in ["bar", "patio bar", "outdoor bar", "kitchen bar", "wine bar"]:    tokens = tokenizer.encode(prefix)    ids = [index[transformer.START]] + [index[token] for token in tokens]    from_transformer = transformer.softmax(transformer.forward(ids)[-1])    context = tuple(["<s>"] * 3 + tokens)[-3:]   # the 4-gram looks at the last three tokens, padded with start markers for a short prefix    from_counts = np.array([counted.probability(context, token) for token in as_counted])    mixed = (from_transformer + from_counts) / 2    for label, p in [("transformer", from_transformer), ("half and half", mixed)]:        top = np.argsort(-p, kind="stable")[:3]   # the three likeliest; a stable sort keeps tied tokens in vocabulary order        print(f"{prefix:<12} {label:<13} -> " + ", ".join(f"{show(vocabulary[i])} {p[i]:.2f}" for i in top))    if prefix == "outdoor bar":        stool = index["stool</w>"]   # </w> marks the end of a word in the tokenizer, so this is the whole word stool        print("P(stool | outdoor bar), transformer:", f"{from_transformer[stool]:.2f}")        print("P(stool | outdoor bar), 4-gram:", f"{from_counts[stool]:.2f}")        print("P(stool | outdoor bar), half and half:", f"{mixed[stool]:.2f}")
出力python transformer-autocomplete.py
bar          transformer   -> with 0.17, & 0.14, and 0.09
bar          half and half -> & 0.19, with 0.14, unit 0.07
patio bar    transformer   -> stool 0.51, table 0.25, set 0.02
patio bar    half and half -> stool 0.69, table 0.13, & 0.01
outdoor bar  transformer   -> stool 0.50, with 0.05, table 0.04
outdoor bar  half and half -> stool 0.28, & 0.12, with 0.12
P(stool | outdoor bar), transformer: 0.50
P(stool | outdoor bar), 4-gram: 0.06
P(stool | outdoor bar), half and half: 0.28
kitchen bar  transformer   -> room 0.14, with 0.08, cabinet 0.08
kitchen bar  half and half -> with 0.14, & 0.12, room 0.07
wine bar     transformer   -> with 0.43, <sep> 0.22, cabinet 0.08
wine bar     half and half -> with 0.30, <sep> 0.21, cabinet 0.13

After outdoor bar, the transformer gives stool 0.50, where the 4-gram gives it 0.06; the mix, at 0.28, still puts it first. The control prefixes show the models aren't suggesting stool after every bar: after kitchen bar and wine bar they suggest other continuations, and after wine bar both expect, with good reason, that the name may already be complete. After patio bar, a context the names contain often, the mix is more confident in stool than the transformer alone.

One prefix is an example, not a measure. The measure is the names comparison, and there the mix won. For the search box, that's the model to serve.

Working rule: 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.

本番環境で起こりうる問題

学習は、進行中には問題がないように見えるまま、うまくいかなくなることがある。

  • パディングは計算を無駄にする。 ここでは、各ステップの予測のうち半分近くがパディングであった。計算資源を増やす前に、テキストをパッキングするか、長さでグループ化するとよい。
  • スケジュールのバグはモデルの問題に見える。 経験則として、終わらないウォームアップや早すぎる減衰の開始は、損失の低下が遅すぎるという形で現れる。先の減衰の比較は、スケジュールが結果をどれだけ動かしうるかを示している。ステップサイズを保存し、意図したスケジュールと照合すること。
  • 検証データで下した選択は結果を良く見せる。 採用したエポックと混合の割合は、どちらも検証用の分割で選んだため、その数値はわずかに楽観的である。テスト用の分割は最後まで手を付けずに保持すること。
  • 繰り返されたテキストは記憶される。 小さなデータセットを何度も見せると、訓練損失は良好に見えるが、新しいテキストでは成績が悪くなる。学習が各テキストを何回見るかを数え、エポックを増やすよりも新しいテキストを優先すること。
  • 一つのモデルは一種類のテキストで測定される。 Transformer は、名前では計数に次ぐ2位、説明文では1位であった。配備するモデルを選ぶ前に、各モデルが扱うすべての種類のテキストで採点すること。
  • 結果は計算機に依存する。 PyTorch は、リリース間やプラットフォーム間で同一の結果を保証しない(再現性)。recordings/transformer.py がスクリプトのハッシュで行っているように、重み、曲線、正確なスクリプトを記録し、まとめて保管すること。

この部分はまだ翻訳されていないため、英語で表示している。

What this chapter decided

  • The store's model is trained in one recorded run: batches of 32 product texts, AdamW with weight decay 0.1, gradients clipped, a warm-up of 200 steps to a peak step size of 0.003, cosine decay to a tenth, and the weights kept from epoch 15 of 16.
  • Every comparison counts the same predictions. On names, both models predict each name's tokens and its end, against chapter 3's names-only baseline, the stronger one for names. On descriptions, a 4-gram trained on the same texts scores the same tokens, with the same text before them.
  • On the validation names, the transformer alone roughly ties the 4-gram baseline, and mixed half and half with it scores 18.4, the best on names in this book so far. The mix is the model the book uses for autocomplete, replacing chapter 5's mix of the window model and the counts.
  • From this chapter on, models are also measured on the validation descriptions. There the transformer beats the baseline alone, 20.1 against 22.5, by winning where the counts haven't seen the context, and the mix scores 14.7.
  • At this scale, new text is the cheapest gain, width the largest at a price, and repetition helps only for a few passes. The recorded model stays at width 128, because every example from chapter 6 on reads it and the examples have to run in seconds on a laptop; a wider one would score better.

この版における本章

第2026.11.16版2026年11月19日時点で例が通過この章の7 例件のうち7件が合格

英語版の書籍(版2026.11.16)から翻訳した。

この節を引用する

形式

いずれの形式も、本訳書が従う英語版の書籍を出典として示す。

いずれの形式もこの版を明示している。そのリンクは現行版を開き、節の見出しには本文が最後に変更された日付が示される。アクセス日と取得日は、これを開いた日である。

このページの内容

全11章中の第8章: 小さなモデルの訓練

  1. Turn products into batches
  2. AdamWとクリッピングした勾配による更新
  3. ウォームアップしてから、ステップサイズを減衰させる
  4. 学習曲線を読む
  5. Compare with the baseline on names
  6. Compare on descriptions
  7. 幅・データ・ステップ数で得られるもの
  8. Suggest the next word in the search box
  9. 本番環境で起こりうる問題
  10. What this chapter decided

ページの先頭に戻るすべての章