ニューラル言語モデル
読了まで約40 分分、11 節 節の 10 例 例。
この章を終えると、先行するトークンの窓から次のトークンを予測するニューラル言語モデルを構築できるようになる。さらに、その勾配を手計算で求めて検証し、PyTorch で学習させ、カウントに基づくベースラインと公平に比較して評価できるようになる。また、学習されたモデルは、学習されたというだけでは優位に立てないことも確認する。このモデルは単独ではカウントに負けるが、両者を混ぜ合わせると役に立つ。
第3章では、本書のベースラインとして 4-gram Kneser-Ney モデルを構築した。これは、店の商品名の各トークンを、直前の3トークンからカウントによって予測するものである。このモデルの限界は、ある文脈と別の文脈を関連づけられないことにあった。家具と家庭用品を扱う店の商品名には、patio bar のカウントはあっても outdoor bar のカウントはなく、両者を結びつけるものは何もない。第4章では、ベクトルがトークン同士を関連づけられることを示した。店のテキストから学習すると、patio と outdoor は近いベクトルを持つからである。本章では、ベクトルをモデルの内部に組み込む。ニューラル言語モデルは、直前のトークンをベクトルとして読み取り、学習された演算でそれらを組み合わせ、語彙内のすべてのトークンに対する確率を出力する。ベクトルと演算は、次のトークンを予測するように学習されることで、同時に獲得される。この設計は Bengio らが導入したものである(Bengio et al., 2003)。
テキストは店から供給される。評価は、第3章以降のすべてのモデルが受けるものと同じで、店のトークナイザを通した検証用の商品名に対するトークンあたりのパープレキシティである。値は低いほど良く、ベースラインのスコアは 23.1 である。
埋め込みのウィンドウから予測する
この章のモデルは、直前のトークンの固定長のウィンドウを参照する。ここでは4トークンであり、5-gramが数える文脈と同じである。各トークンは埋め込みテーブルから引かれる。これは語彙内のトークンごとに1行の数値を持つ行列であり、第4章と同じ形をしているが、このテーブルは数え上げから計算されるのではなく、次のトークンを予測するために学習される。4つの行は横に連結され、1本の長いベクトル x になる。隠れ層は入力 x から h = tanh(xW + b) を計算する。x に重みの行列 W を掛け、バイアスのベクトル b を加え、各結果を tanh に通す。tanh は任意の数を −1 から 1 の範囲に押し込む関数であり、これによって隠れ層は、和だけではできない仕方で入力を組み合わせられる。続いて出力層が、隠れ層の出力 h から z = hU + c を計算する。語彙内のトークンごとに1つのスコアが得られ、これをロジットと呼ぶ。
最後の段階では、スコアを確率に変換する。ソフトマックスはすべてのロジットを指数関数に通し、その総和で割る。結果はすべて正で総和が1となり、スコアが高いほど確率も高くなる。
P(token i) = exp(zᵢ) / Σⱼ exp(zⱼ)
学習済みの重みを使って1つの予測を最後まで追うと、モデルが4つのトークンから確率を作り出す過程が分かる。ここで扱うのは、patio bar で始まる名前の次のトークンである。例の各行は上記の式のいずれかに対応しており、出力される形状から各段階の働きが読み取れる。
1"""One prediction of the trained window model, computed by hand from its saved weights: the embeddings, the tanh layer,2the output scores and the softmax. The prose's point rests on the shapes, the parameter counts and the three likeliest3tokens after `patio bar`."""4import numpy as np56from lib import bpe, neural7from lib.ngrams import START89weights, vocabulary, manifest = neural.load()10index, width = {t: i for i, t in enumerate(vocabulary)}, manifest["settings"]["context"] # token -> row; the window's width, from the saved settings11context = ([START] * width + bpe.store_tokenizer().encode("patio bar"))[-width:] # pad with start markers, keep the last width tokens12ids = np.array([[index[t] for t in context]])1314vectors = weights["embedding"][ids] # one 64-number vector per token15joined = vectors.reshape(1, -1) # -1 lets numpy work out the length: 4 vectors of 64 make 25616hidden = np.tanh(joined @ weights["hidden_w"] + weights["hidden_b"]) # one layer, squashed into -1 to 117logits = hidden @ weights["output_w"] + weights["output_b"] # one score for every token18probabilities = np.exp(logits - logits.max()) # subtract the largest score first: same probabilities, and exp can't overflow19probabilities /= probabilities.sum() # softmax: scores into probabilities2021print("context:", " ".join(context))22for name, array in [("embeddings", vectors), ("joined", joined), ("hidden", hidden), ("logits", logits)]:23 print(f"{name} shape:", array.shape)24print("vocabulary size:", f"{len(vocabulary):,}")25print("parameters:", f"{sum(w.size for w in weights.values()):,}")26for part in ["embedding", "hidden_w", "output_w"]:27 print(f"parameters in {part}:", f"{weights[part].size:,}")28for i in np.argsort(-probabilities[0], kind="stable")[:3]: # the three likeliest; a stable sort keeps ties in vocabulary order29 print(f"P({vocabulary[i]} | patio bar): {probabilities[0, i]:.2f}")
python window-model-by-hand.pycontext: <s> <s> patio</w> bar</w>
embeddings shape: (1, 4, 64)
joined shape: (1, 256)
hidden shape: (1, 256)
logits shape: (1, 4140)
vocabulary size: 4,140
parameters: 1,394,732
parameters in embedding: 264,960
parameters in hidden_w: 65,536
parameters in output_w: 1,059,840
P(stool</w> | patio bar): 0.63
P(with</w> | patio bar): 0.23
P(&</w> | patio bar): 0.05
この名前にはまだ2トークンしかないため、ウィンドウは開始マーカーで埋められている。4つのトークンはそれぞれ64個の数値のベクトルになり、連結されて256個の数値からなる1本のベクトルになる。隠れ層はそれをさらに256個の数値に変換し、出力層はモデルが知っている 4,140 個のトークンのそれぞれに1つずつスコアを与える。この語彙は、ストアのトークナイザの語彙に開始マーカーと終了マーカーを加えたものである。ウィンドウモデルのパラメータ、すなわちモデルが学習する数値は 1,394,732 個である。その約4分の3は出力層の重み 1,059,840 にある。出力層にはトークンごとに1列が必要だからである。残りの大半は埋め込みテーブルにある。予測は妥当なものである。stool が確率 0.63 で最も高く、with と & が続く。これらは patio bar with stools のような名前を続けるトークンである。
実践ルール: 自分で学習させるモデルは、少なくとも一度は順伝播を手で組み立て、この例のようにすべての中間配列の形状を出力すること。形状の誤りはニューラルネットワークのコードで多いバグであり、形状を見ればモデルが何を計算しているかが正確に分かる。語彙が大きい場合は、出力層がパラメータの大半を占めると考えてよい。
逆伝播によって勾配を計算する
ランダムな重みを持つモデルの予測は悪い。訓練とは、予測が良くなるように重みを調整することである。モデルの予測がどれほど悪いかを測るには、損失を用いる。損失は L = −log P(next token) で定義され、実際に次に来たトークンにモデルが与えた確率の負の対数である。これは第1章で平均して perplexity にした、あの驚きと同じ量である。訓練は平均損失を下げ、損失が下がれば perplexity も下がる。損失を下げるには、各重みに勾配が必要になる。勾配とは、その重みを少し変えたときに損失がどれだけ変わるかを表す量であり、∂L/∂w と書く。
逆伝播(backpropagation)は、順伝播に対して微積分の連鎖律を逆向きに適用することで、すべての勾配を一度に計算する。計算は損失からロジットへ、ロジットから出力層を通って隠れ層へ、tanh を通って、使われた埋め込みへと戻っていく(Rumelhart et al., 1986)。このうち2つのステップは暗記しておく価値がある。1つ目は、ロジットに関する損失の勾配が、softmax の確率から、真のトークンの位置で 1 を引いたものになることである。2つ目は、tanh を通る勾配に 1 − h² が掛かることであり、この値は h が ±1 に近いところで小さくなる。本書の共有モジュール lib.tinynet は、この全体を1行ずつ書き下している。対象は、店のモデルを小さくしたもので、トークン数は5、埋め込みは2つの数、ウィンドウは2、隠れユニットは3つである。
逆伝播のコードは気づきにくい形で誤りを含みやすい。そのため、誤りを含みえない、より遅い方法と照合して確かめる。1つの重みをごくわずかに増減させ、損失がどう動くかを測り、その結果を比べるのである。店のモデルでは100万回を超える増減が必要になる(パラメータ1つにつき上下2回の増減を含めた数ではなく、パラメータ数が100万を超える)が、小さいモデルなら全パラメータを検査できる。
1"""Backpropagation's gradients for the tiny model, checked against nudging every one of its parameters up and down.2The assert is the check the prose relies on: the two agree to six decimal places, for every parameter."""3import numpy as np45from lib.tinynet import backprop, forward, parameters67p = parameters() # the tiny model: 5 tokens, a window of 2, 3 hidden units; seeded, so the same every run8context, target = np.array([1, 3]), 4 # the window: token ids 1 and 3; the token that came next is id 4910worst, step = 0.0, 1e-6 # the nudge: small enough that the loss is nearly a straight line over it11gradients = backprop(p, context, target)12for name, value in p.items(): # nudge each parameter both ways, and see how the loss moves13 for i in np.ndindex(value.shape):14 value[i] += step15 up = forward(p, context, target)[3] # forward returns (joined, hidden, logits, loss): index 3 is the loss16 value[i] -= 2 * step # from up to down is two steps, so the estimate is centred on the value17 down = forward(p, context, target)[3]18 value[i] += step # back where it started19 worst = max(worst, abs((up - down) / (2 * step) - gradients[name][i]))20agrees = worst < 1e-6 # the largest disagreement over all parameters, against six decimal places21assert agrees22print("loss:", round(float(forward(p, context, target)[3]), 4))23print("parameters checked:", sum(v.size for v in p.values()))24print("backprop agrees with nudging to 6 decimal places:", "yes" if agrees else "no")
python gradients-by-hand.pyloss: 1.5293
parameters checked: 45
backprop agrees with nudging to 6 decimal places: yes
逆伝播で得た 45 個の勾配はすべて、増減による推定値と小数点以下6桁まで一致する。この例ではそれを assert で確認している。増減による方法はパラメータ1つにつき順伝播を2回必要とするため、これで訓練する人はいないが、小さなモデルでは逆伝播が正しいことを示す基準になる。
実践ルール: 手で書いた勾配は、信頼する前に、小さなモデルで増減による推定値と照合する。勾配を代わりに計算してくれるライブラリを使う場合は、PyTorch の節で行うように、ライブラリの順伝播を自分で書いた順伝播と照合する。
勾配降下法のステップを実行する
勾配が得られれば、訓練はループになる。勾配降下法(gradient descent)は、すべての重みを勾配と逆向きに少しずつ動かす。更新式は w ← w − η · ∂L/∂w であり、η はステップ幅(step size)、または学習率(learning rate)とも呼ばれ、1回の更新でどれだけ動かすかを決める。各ステップは、勾配の計算に使った例に対する損失を少し小さくする。これを多くの例について繰り返すと、重みはモデルが良い予測を行える値に落ち着く。
前の節で扱った店の小さなモデルについて、3つの例を使い、lib.tinynetの勾配を用いて、ステップ幅0.5で勾配降下法を20ステップ実行すると、損失が下がっていく様子が分かる。
1"""Twenty steps of gradient descent on three examples of the tiny model, printing the average loss before training and2after one, five and twenty steps. The prose's point rests on the average loss at those four points."""3import numpy as np45from lib.tinynet import backprop, forward, parameters67p = parameters() # seeded, so every run starts from the same weights8examples = [(np.array([1, 3]), 4), (np.array([0, 1]), 3), (np.array([3, 4]), 2)] # three (window, next token) pairs: each window is two token ids, then the id of the token after it9rate = 0.5 # the step size101112def average_loss():13 return np.mean([forward(p, c, t)[3] for c, t in examples])141516print("average loss before:", f"{average_loss():.3f}")17for step in range(1, 21): # twenty steps, each one a pass over all three examples18 for c, t in examples:19 for name, gradient in backprop(p, c, t).items():20 p[name] -= rate * gradient / len(examples) # w <- w - rate * dL/dw, with each gradient averaged over the examples21 if step in (1, 5, 20):22 print(f"average loss after {step} steps:", f"{average_loss():.3f}")
python gradient-descent-by-hand.pyaverage loss before: 1.568
average loss after 1 steps: 1.346
average loss after 5 steps: 0.646
average loss after 20 steps: 0.109
平均損失は、この例が出力する各ステップで減少し、訓練前の1.568から20ステップ後の0.109まで下がる。学習する例が3つしかないため、この小さなモデルは損失をほぼ0にまで下げられるが、これは暗記である。店のモデルは数十万の例から学習するので、同じループが、それらの例にわたって成り立つパターンを見つけなければならない。
実際の訓練では、このループに2つの違いがある。1つ目は、各ステップをすべての例ではなく、一度に数百件程度の例からなるバッチ(batch)で計算することである。そのため各ステップの計算は軽く、ステップごとの結果には少しばらつきが出る。2つ目は、固定のステップ幅ではなく、改良された更新式を用いることであり、これは次の節で述べる。
実践ルール: 新しいモデルは、まず少数の例で数ステップ実行し、損失が下がることを確認してから始める。3つの例で損失が下がらないなら、それは難しい問題ではなくバグである。ステップ幅はいくつか試して選ぶ。小さすぎると損失はなかなか下がらず、大きすぎると損失は跳ね回るか増加する。
この部分はまだ翻訳されていないため、英語で表示している。
Train with PyTorch
Writing backpropagation by hand for every model would be slow and error-prone. PyTorch, a widely used library for training neural networks, computes gradients automatically from the forward pass, and runs the arithmetic fast. The book trains its model with it, in recordings/neural_lm.py, which builds the same window model as the first section: an embedding table, one tanh layer and an output layer, trained on the store's training names. The heart of the script is the loop of the previous section, on batches of 512 predictions:
loss = loss_of(model(train_x[pick]), train_y[pick]) # forward pass and average loss on one batch
optimizer.zero_grad() # clear the previous batch's gradients
loss.backward() # backpropagation: a gradient for every weight
optimizer.step() # move every weight against its gradient
The training script's optimizer is Adam, a refinement of gradient descent (Kingma and Ba, 2015). It keeps, for every weight, a running average of its gradients and a running average of their squares, and steps by the first divided by the square root of the second. A weight whose gradients are consistently large gets steps of about the same size as one whose gradients are small, so one step size works for all of them.
Training depends on the machine's floating-point arithmetic, which chapter 4 explains, so it runs once and the book's examples read the weights it saved, as they read every such result. The examples never import PyTorch: lib.neural recomputes the model's forward pass in NumPy, from those weights. That only works if the NumPy version computes what PyTorch computed, so the training script saved PyTorch's own logits for 64 validation contexts, and the next example compares:
1"""The trained model's logits, recomputed in NumPy from its saved weights and compared with the logits PyTorch computed2for the same saved validation contexts. The prose's point rests on the agreement, which the last line prints."""3import numpy as np45from lib import neural67weights, _, manifest = neural.load()8check = np.load("data/recorded/neural-lm/check.npz") # saved by the training script, so this runs without PyTorch: contexts, and PyTorch's logits for them910ours = neural.forward(weights, check["contexts"])11print("PyTorch version:", manifest["torch"])12print("contexts compared:", len(check["contexts"]))13print("logits compared:", f"{ours.size:,}") # every logit: one per context and per token in the vocabulary14print("same as PyTorch to 4 decimal places:", bool(np.abs(ours - check["logits"]).max() < 1e-4)) # 1e-4: four decimal places
python same-as-pytorch.pyPyTorch version: 2.14.1+cpu
contexts compared: 64
logits compared: 264,960
same as PyTorch to 4 decimal places: True
The NumPy forward pass reproduces all 264,960 of PyTorch's logits to four decimal places, for the model trained with PyTorch 2.14.1+cpu. Every number this chapter reports about the trained model comes from that NumPy code, except the training curve, which the script recorded as it trained.
Working rule: 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.
この部分はまだ翻訳されていないため、英語で表示している。
Stop when validation loss turns up
A model with 1.4 million parameters, trained on a few hundred thousand tokens, can memorize its training text, as chapter 3's 5-gram did. Training perplexity keeps falling as it does. Validation perplexity falls at first, while the model learns patterns that hold for new names, then rises, once it starts fitting quirks of the training names. A validation perplexity that turns up while training perplexity keeps falling is overfitting, and the simplest defence is early stopping: measure validation loss after every epoch, one full pass over the training text, and keep the weights from the best epoch.
The training script recorded both perplexities after each of its twelve epochs. Read them for where validation stops improving:
1"""The training script's record of training and validation perplexity after each epoch, and the epoch whose weights were2kept. The prose's point rests on the validation column, and on the two validation figures printed after the table."""3import json4import math56curves = json.load(open("data/recorded/neural-lm/curves.json", encoding="utf-8"))7manifest = json.load(open("data/recorded/neural-lm/manifest.json", encoding="utf-8"))89print(f"{'epoch':>5} {'training perplexity':>19} {'validation perplexity':>21}")10for c in curves: # losses are averages of log probabilities: exp turns them into perplexities11 print(f"{c['epoch']:>5} {math.exp(c['train_loss']):>19.1f} {math.exp(c['validation_loss']):>21.1f}")12best = min(curves, key=lambda c: c["validation_loss"]) # the epoch with the lowest validation loss, which the kept epoch should match13print("epoch kept:", manifest["kept_epoch"])14print("validation perplexity at the kept epoch:", f"{math.exp(best['validation_loss']):.1f}")15print("validation perplexity at the last epoch:", f"{math.exp(curves[-1]['validation_loss']):.1f}") # curves[-1]: the final epoch's record, whatever was kept
python training-curve.pyepoch training perplexity validation perplexity
1 109.3 51.4
2 37.6 39.9
3 27.3 37.3
4 22.4 36.6
5 19.3 36.4
6 17.2 36.9
7 15.6 37.8
8 14.4 38.6
9 13.5 39.7
10 12.7 40.9
11 12.0 42.1
12 11.5 43.7
epoch kept: 5
validation perplexity at the kept epoch: 36.4
validation perplexity at the last epoch: 43.7
In epoch 1, training perplexity is higher than validation, because the training figure averages over the whole epoch, including its first batches, when the model was still untrained, while validation is measured at the epoch's end. Validation perplexity bottoms out at 36.4 in epoch 5 and climbs from there, to 43.7 by the last epoch, while training perplexity falls at every epoch after the first. The training script kept the weights from the best epoch, and every result in the rest of this chapter uses them.
The gap between the two curves is the model memorizing. It grows every epoch, because the training names repeat their product lines and phrasing, and this model has no regularization, which is anything in training that discourages memorizing, so early stopping is its only defence.
Working rule: 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.
ベースラインとの比較
本書のすべてのモデルが受ける本当の試験は、検証用の名前に対するトークンあたりのパープレキシティを、4-gram ベースラインと比べることである。これらの名前では、似た文脈を関連づけることと、正確な頻度を数えることのどちらが重要だろうか。ニューラルモデルは 4-gram にはできない、似た文脈の関連づけができる。一方、4-gram は、見たことのあるすべての文脈について正確な頻度を持っている。
1"""The window model and the 4-gram baseline, each scored by perplexity per token on the same validation names. The2prose's point rests on the two printed perplexities."""3from lib import neural4from lib.names import name_tokens5from lib.ngrams import KneserNey, perplexity67train, validation = name_tokens("train"), name_tokens("validation") # both models are scored on the same tokens of the same names8print("window model validation perplexity:", f"{neural.perplexity(validation):.1f}") # the window model, from its saved weights9print("4-gram baseline validation perplexity:", f"{perplexity(KneserNey(train, 4), validation):.1f}") # a 4-gram: each token is predicted from the three before it
python neural-vs-baseline.pywindow model validation perplexity: 36.4
4-gram baseline validation perplexity: 23.1
勝つのは頻度を数えるモデルであり、その差は大きい。ウィンドウモデルの検証パープレキシティは 36.4 であり、ベースラインは 23.1 である。
どこで差がつくかを調べるために、検証トークンを、3 トークンの文脈が訓練用の名前に現れるかどうかで二つに分け、それぞれの部分で両モデルを採点する。
1"""Splits the validation tokens by whether their three-token context occurs in the training names, and scores both models2on each part. The prose's point rests on the four perplexities printed for the two parts."""3import math45import numpy as np67from lib import neural8from lib.names import name_tokens9from lib.ngrams import KneserNey, ngrams, padded1011train, validation = name_tokens("train"), name_tokens("validation")12counted = KneserNey(train, 4)13pairs = [(c, t) for text in validation for c, t in ngrams(padded(text, 4), 4)] # padding gives each name's first tokens a context14seen = np.array([c in counted.totals[4] for c, _ in pairs]) # was this 3-token context in the training names?15from_counts = np.array([counted.probability(c, t) for c, t in pairs])16from_network = neural.token_probabilities(validation) # in the same order as pairs, so each entry is for the same token1718print("validation tokens with a context seen in training:", f"{seen.mean():.0%}")19for part, where in [("seen", seen), ("unseen", ~seen)]: # ~seen: the complement, the contexts the training names lack20 for model, p in [("4-gram", from_counts), ("network", from_network)]:21 print(f"{model} perplexity, {part} contexts: {math.exp(-np.log(p[where]).mean()):.1f}") # exp of the average surprise, over this part
python seen-and-unseen-contexts.pyvalidation tokens with a context seen in training: 70%
4-gram perplexity, seen contexts: 17.9
network perplexity, seen contexts: 26.1
4-gram perplexity, unseen contexts: 41.2
network perplexity, unseen contexts: 78.5
ネットワークはどちらの部分でも劣っており、文脈どうしを関連づける能力が最も役立つはずの未知の文脈で、差はより大きい。そこでは 4-gram が 41.2、ネットワークが 78.5 である。既知の文脈は検証トークンの 70% を占めており、そこでは 4-gram が 17.9、ネットワークが 26.1 である。
したがって、このネットワークは、頻度が正確な場面で負けるだけではない。うまく汎化することも学習できていない。このモデルとこのテキストの二つの特徴が、最も有力な理由である。第一に、ネットワークには正則化がなく、訓練曲線が示したように、数エポックのあとで過学習する。第二に、店の名前は短く定型的である。3 トークンの文脈で名前の内容の大半が賄えるため、Kneser-Ney の頻度が最も強く働く状況になっている。Bengio らは、より大きく多様なテキストでは逆の結果を得た。約 80 万語の訓練データを持つ Brown コーパスでは、最良のネットワーク単独でテストパープレキシティが 268、トライグラムモデルと混合すると 252 であり、最良の n-gram モデルは 312 であった(Bengio et al., 2003、4.2 節および表 1)。学習したモデルは、学習したからといって優れているわけではない。測定しなければならない。
実践ルール: 学習したモデルが役に立つと主張する前に、必ず同じテキストと同じトークンで、強力な頻度ベースのベースラインと比較すること。そして、比較を既知の文脈と未知の文脈に分けて、各モデルがどこで勝つかを調べること。一つの小さなデータセットから、ニューラルモデルは機能しないとも、常に機能するとも結論してはならない。
ネットワークとカウントを混合する
平均では劣るモデルでも、その誤りがより良いモデルの誤りと異なっていれば、役に立つことがある。二つのモデルが異なる誤りを犯すとき、両者の確率を混合すれば、どちらのモデルよりも良い結果が得られる場合がある。Bengio らは、自らのネットワークと平滑化したトライグラムモデルの混合でこれを実現した(Bengio et al., 2003、4節)。混合は、各トークンについて二つのモデルの確率を重み付き平均したものであり、3章の補間と同じである。
混合は両端のモデルより優れているだろうか。ネットワークの混合比率を 0、0.2、0.3、0.5、1 として検証用の名前を採点する。0 はカウントに基づくモデルのみ、1 はネットワークのみを表す。
1"""Mixes the network's and the 4-gram's probability of every validation token, at five shares for the network, and prints2the validation perplexity of each mix. The prose's point rests on the printed perplexity at share 0.2, and at the two ends."""3import math45import numpy as np67from lib import neural8from lib.names import name_tokens9from lib.ngrams import KneserNey, ngrams, padded1011train, validation = name_tokens("train"), name_tokens("validation")12from_network = neural.token_probabilities(validation) # the network's probability of each actual next token, in order13counted = KneserNey(train, 4)14# the 4-gram's probability for the same tokens, in the same order: each name padded with three start markers first15from_counts = np.array([counted.probability(c, t) for text in validation for c, t in ngrams(padded(text, 4), 4)])1617for share in [0.0, 0.2, 0.3, 0.5, 1.0]: # the network's share of the mix; the counts get the rest18 mixed = share * from_network + (1 - share) * from_counts19 print(f"validation perplexity, network share {share:.1f}: {math.exp(-np.log(mixed).mean()):.1f}")
python mix-neural-and-counts.pyvalidation perplexity, network share 0.0: 23.1
validation perplexity, network share 0.2: 21.9
validation perplexity, network share 0.3: 22.1
validation perplexity, network share 0.5: 22.9
validation perplexity, network share 1.0: 36.4
混合は両方のモデルを上回る。ネットワークの比率を 0.2 としたとき、検証パープレキシティは 21.9 であり、ベースラインの 23.1 より良く、ネットワーク単独の 36.4 よりはるかに良い。ネットワークは平均では劣るが、カウントがあるトークンにごくわずかな確率しか与えない場合でも、ネットワークの寄与によってその確率が極端に小さくなることが避けられ、平均的な驚きが小さくなる。
採用したエポックと混合比率はいずれも検証用の名前を見て選んだため、この改善はやや楽観的な値である。本書の最終比較では、テスト用の名前でこれを確認する。また、混合が役に立つのは二つのモデルの誤りが異なるからにすぎない。同じ誤りを犯すのであれば、平均しても何も得られない。
実践ルール: 学習したモデルとカウントに基づくモデルが拮抗しているときは、どちらかを選ぶ前に両者の確率の混合を試し、比率は取り置いた(ホールドアウトの)テキストで選ぶ。一方のモデルがはるかに強い場合は比率を小さく保ち、改善に頼る前に別のテストセットでその効果を確認する。
追加するテキストは同じ種類である場合に限って役に立つ
ネットワークが過学習するのが学習したテキストの少なさによるのであれば、当然の対策はテキストを増やすことである。ストアには商品説明という十分な量のテキストがある。学習スクリプトは、同じモデルを名前と説明の両方で学習させることができ、本書はこの版も記録して、同じ検証用の名前で評価した。
記録された二つのモデル、すなわち名前だけで学習したモデルと、名前と説明で学習したモデルを、検証用の名前で比較する。
1"""Scores the window model trained on names alone against the one trained on names and descriptions, counts the training2tokens of each kind of text, and prints the second model's validation perplexity after each of its epochs. The prose's3point rests on the two validation perplexities, and on the training token counts printed beside them."""4import json5import math67from lib import neural8from lib.names import name_tokens910validation = name_tokens("validation")11for name in ["neural-lm", "neural-lm-all-text"]: # the recorded runs: names alone, then names and descriptions12 manifest = json.load(open(f"data/recorded/{name}/manifest.json", encoding="utf-8"))13 print(f"learned from {manifest['settings']['text']}:", f"{neural.perplexity(validation, name):.1f}")1415from lib import bpe16from lib.store import load_products1718tokenizer = bpe.store_tokenizer()19names_tokens = sum(len(t) for t in name_tokens("train")) # counted in the store's tokens, the ones the model reads20description_tokens = sum(len(tokenizer.encode(d)) for d in load_products("train")["description"]) # the training split only, as for names21print("training tokens, names:", f"{names_tokens:,}")22print("training tokens, names and descriptions:", f"{names_tokens + description_tokens:,}")23curve = json.load(open("data/recorded/neural-lm-all-text/curves.json", encoding="utf-8"))24print("all-text model, validation perplexity by epoch:", ", ".join(f"{math.exp(c['validation_loss']):.1f}" for c in curve)) # one per epoch, in order
python more-text-of-another-kind.pylearned from names: 36.4
learned from all: 59.0
training tokens, names: 337,071
training tokens, names and descriptions: 2,744,320
all-text model, validation perplexity by epoch: 73.6, 64.0, 60.8, 59.0
説明を加えると、モデルは名前の予測が下手になる。学習用の名前には 337,071 個のトークンがあり、名前と説明を合わせると 2,744,320 個で、約8倍になる。名前だけで学習したモデルのスコアは 36.4 であり、名前と説明で学習したモデルのスコアは 59.0 である。後者のモデルは4エポック学習し、停止した時点でも検証パープレキシティは下がり続けていたが、その幅はエポックごとに小さくなっていた。その推移は 73.6, 64.0, 60.8, 59.0 のとおりである。エポック数を増やしても、名前だけのモデルに近づくことはないというのが我々の判断である。
説明は種類の異なるテキストである。説明は完全な文で書かれ、your、this、perfect のように、名前にはほとんど含まれない語を使う。説明から主に学習したモデルは、名前を説明であるかのように予測する。追加したテキストは、このタスクにとって誤った分布をモデルに教えたのである。モデルは与えられたテキストを学習し、パープレキシティはそのようなテキストをどれだけうまく予測できるかを測る。別の種類のデータはモデルを悪化させることがあり、重みを調整するか、分けて扱う必要がある。
実践ルール: 学習用のテキストを追加する前に、それが予測対象のテキストに似ているかを確認する。多いほど良いと決めてかからず、両方で学習して対象のテキストで測定する。追加するテキストが大きく異なる場合は、対象のテキストだけで学習するか、モデルが種類を区別できるように各テキストの配置を工夫する。第8章が、商品の名前と説明の間に区切りを置いているのはその一例である。
この部分はまだ翻訳されていないため、英語で表示している。
Suggest from similar contexts
The network lost on average, including on contexts the training names lack, but averages hide single cases. Chapter 3's autocomplete showed the 4-gram's worst case, outdoor bar, a context no training name contains, where it fell back to generic continuations.
Next, the network's three likeliest tokens after five name prefixes, and a few embeddings, tell whether outdoor bar gets the stool suggestion that patio bar does:
1"""The network's three likeliest next tokens after five typed prefixes, its probability of `stool` after `outdoor bar`,2and the cosine similarity of `patio` with three other tokens in its embedding table. The prose's point rests on the3suggestions after each prefix, and on the three cosines printed last."""4import numpy as np56from lib import bpe, neural7from lib.ngrams import START89weights, vocabulary, manifest = neural.load()10index, width = {t: i for i, t in enumerate(vocabulary)}, manifest["settings"]["context"]11tokenizer = bpe.store_tokenizer()1213for typed in ["bar", "patio bar", "outdoor bar", "kitchen bar", "wine bar"]: # each typed prefix is read as the start of a name14 context = ([START] * width + tokenizer.encode(typed))[-width:] # pad with start markers, keep the last width tokens15 logits = neural.forward(weights, np.array([[index[t] for t in context]]))[0] # forward takes a batch: one row, so take row 016 probabilities = np.exp(neural.log_softmax(logits[None])[0]) # log_softmax wants a batch too: add an axis, then take it off17 best = np.argsort(-probabilities, kind="stable")[:3] # the three likeliest; a stable sort keeps ties in vocabulary order18 # the end-of-word marker </w> is shown as nothing, so the tokens read as the words they came from19 print(f"{typed:<12} -> " + ", ".join(f"{vocabulary[i].replace('</w>', '')} {probabilities[i]:.2f}" for i in best))2021outdoor_bar = ([START] * width + tokenizer.encode("outdoor bar"))[-width:] # the same padding as above22p_stool = np.exp(neural.log_softmax(neural.forward(weights, np.array([[index[t] for t in outdoor_bar]])))[0, index["stool</w>"]])23print("P(stool | outdoor bar):", f"{p_stool:.2f}")24table = weights["embedding"] / np.linalg.norm(weights["embedding"], axis=1, keepdims=True) # unit-length rows, so a dot product is a cosine25for a, b in [("patio</w>", "outdoor</w>"), ("patio</w>", "kitchen</w>"), ("patio</w>", "wine</w>")]:26 print(f"cosine({a.replace('</w>', '')}, {b.replace('</w>', '')}) in the model's embeddings:", f"{float(table[index[a]] @ table[index[b]]):.2f}")
python neural-autocomplete.pybar -> with 0.22, cabinet 0.14, cart 0.13
patio bar -> stool 0.63, with 0.23, & 0.05
outdoor bar -> stool 0.40, with 0.13, & 0.12
kitchen bar -> & 0.53, with 0.17, cart 0.09
wine bar -> with 0.23, cabinet 0.16, </s> 0.14
P(stool | outdoor bar): 0.40
cosine(patio, outdoor) in the model's embeddings: 0.16
cosine(patio, kitchen) in the model's embeddings: 0.07
cosine(patio, wine) in the model's embeddings: 0.10
After outdoor bar, the network suggests stool first, with probability 0.40, where the 4-gram put & and with ahead of it. The control prefixes show that stool isn't automatic after bar: after bar alone, kitchen bar and wine bar, it isn't among the network's three suggestions. And in the network's own embedding table, patio is a little closer to outdoor, with a cosine similarity of 0.16, than to kitchen or wine. That's consistent with the network having carried something from patio bar over to outdoor bar, though the similarity is weak, and one prefix proves little.
This is one case, not an average: the seen and unseen split showed the network worse on unseen contexts overall. It shows what a learned model can do that counting can't, and that this one does it only sometimes.
Working rule: 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.
本番環境で起こる問題
ニューラル言語モデルは、新たな強みとともに新たな故障モードをもたらす。
- 過学習は気づかれないまま進行する。 訓練損失は常に良好に見える。検証曲線がなければ、長く訓練しすぎたモデルは、訓練量を抑えたモデルより性能の劣る状態で出荷されることになる。最良のエポックを保存し、両者の差を監視すること。
- 出荷する重みを保存する。 別のプロセッサで再訓練すると、重みはわずかに異なる。そのため、重みを作ったコードと設定、およびいくつかの入力に対するライブラリの出力を、ここでの訓練スクリプトのように保存しておく。
- 出力層が支配的になる。 各ステップで語彙内のすべてのトークンにスコアを付ける処理が、計算量の大半とパラメータの大半を占める。語彙を大きくすると、まずここでコストが増える。
- 訓練テキストが合っていないと性能が下がる。 名前に対する説明文のように、対象と異なるテキストを加えると、訓練損失は問題なく見えても予測は悪化する。訓練データを変更するたびに、対象のテキストで測定すること。
- 平均は稀な文脈を隠す。 モデルは全体として高いスコアを示しながら、買い物客が新しいものを探すときに入力する珍しい接頭辞では失敗することがある。この章で行ったように、既知の文脈と未知の文脈を別々に採点し、未知のほうを注視すること。
- 混合には提供時に両方のモデルが必要である。 ネットワークとカウントを混合すると、読み込んで最新に保つべきものが2倍になる。ネットワークを再訓練するたびにカウントも再構築し、両者が同じテキストを表すようにすること。
この章で決めたこと
- 本書のニューラルモデルは、PyTorch で
recordings/に一度だけ学習する。 各例は、保存された重みから NumPy でモデルを再計算する。NumPy の順伝播は PyTorch のロジットを小数第4位まで再現するので、例の実行に PyTorch は不要である。 - モデルは、検証データでの成績が最良だったエポックの重みを保持する。 ウィンドウモデルの検証パープレキシティは、エポック 5 の後で最も低く、それ以降は毎エポック上昇した。一方、訓練パープレキシティは下がり続けた。モデルは訓練用の名前を記憶していたのである。
- 店の名前に対しては、ウィンドウモデルは単独では 4-gram のベースラインに、既出の文脈でも未出の文脈でも負けるが、混合すると上回る。 ネットワークの比率を 0.2 にすると 21.9 となり、本書のこれまでのモデルの中で最良である。
- 学習済みモデルは、平均だけでなく、既出の文脈と未出の文脈に分けてベースラインと比較する。 二つの部分が異なる結果を示すことがあるからである。ここでは、ネットワークは両方で負け、未出の文脈ではその差がより大きかった。
- 訓練テキストは、対象とするテキストに似ていなければならない。 説明文を加えるとモデルは名前に対して悪化した。名前と説明文を合わせたトークン数は、名前だけの約8倍であったにもかかわらずである。したがって、どのモデルの訓練テキストも、評価に使うテキストに合わせて選ぶ。
- 名前は短いので、第8章からは、本書は店の説明文でもモデルを評価する。
この版における本章
第2026.11.16版2026年11月19日時点で例が通過この章の10 例件のうち10件が合格
英語版の書籍(版2026.11.16)から翻訳した。