작은 모델 학습하기
읽는 데 약 40분분 걸린다, 10절에 7개 예제이(가) 있음.
AI로 번역함. 영어 원문을 사람이 검증함. 우리가 책을 만드는 방식
영어판 2026.11.16판을 번역한 것이다. 원문 읽기
이 장을 마치면 작은 트랜스포머를 처음부터 끝까지 학습하고 그 결과를 평가할 수 있다. 텍스트를 배치로 만들고, AdamW로 가중치를 갱신하고, 스텝 크기의 스케줄을 정하고, 학습 곡선을 읽고, 횟수를 센 기준선과 비교해 모델을 공정하게 측정한다. 또한 이 규모에서 더 큰 너비, 더 많은 텍스트, 더 긴 학습이 무엇을 가져오는지 확인하고, 모델이 어디에서 횟수 세기보다 나은지, 어디에서 횟수 세기를 곁에 두어야 하는지 찾는다.
7장에서는 상점의 모델을 조립하고, 학습된 가중치로 각 부분을 검증했다. 이 장은 그 가중치가 어디에서 왔는지 묻는다. 그 출처는 recordings/transformer.py에 기록된 한 번의 학습 실행이다. 이 실행은 모델이 상점 카탈로그의 다음 토큰을 하나씩 예측하도록 가르쳤다. 카탈로그에는 상점이 온라인으로 판매하는 가구와 생활용품의 이름과 설명이 담겨 있다. 이어서 이 장은 모델이 맡을 두 가지 일에서 모델을 측정한다. 하나는 검색창에서 상품 이름의 다음 단어를 제안하는 일이고, 다른 하나는 먼 문맥이 중요해질 만큼 글이 길어지는 설명을 예측하는 일이다.
5장과 마찬가지로 학습은 PyTorch로 한 번만 실행했다. 예제는 그 실행이 저장한 가중치, 곡선, 설정을 읽으며, 설정은 실행의 매니페스트에 기록되어 있다. 직접 학습하려면 recordings/requirements.txt을 별도의 환경에 설치한다. 그러면 PyTorch의 CPU 빌드가 함께 설치된다. 그런 다음 책의 폴더에서 python recordings/transformer.py을 실행한다. 같은 파일이 examples/data/recorded/transformer/에 생성되며, 노트북의 프로세서에서 실행할 수 있다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Turn products into batches
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:
1"""Builds one shuffled epoch of batches the way the training script does, and measures the padding in them.2The prose's point rests on the share of targets that are padding over that epoch."""3import math45import numpy as np67from lib import transformer8from lib.products import product_texts910_, vocabulary, manifest = transformer.load()11settings = manifest["settings"]12pad, end = vocabulary.index(transformer.PAD), vocabulary.index(transformer.END)13texts = [ids for ids, _ in product_texts("train")]14size = settings["batch"]1516order = np.random.default_rng(settings["seed"]).permutation(len(texts)) # one shuffled epoch, from the run's seed, so it repeats17padding, targets_seen, shares = 0, 0, []18for start in range(0, len(texts), size):19 batch = [texts[i] for i in order[start:start + size]] # this step's texts: the next `size` in the shuffled order20 longest = max(len(ids) for ids in batch)21 padded = np.array([ids + [pad] * (longest - len(ids)) for ids in batch]) # short texts filled out with <pad>22 inputs, targets = padded[:, :-1], padded[:, 1:] # each position predicts the next token23 padding, targets_seen = padding + (targets == pad).sum(), targets_seen + targets.size24 shares.append((targets == pad).mean())25 if start == 0:26 first_shape = (inputs.shape, targets.shape)2728print("training texts:", f"{len(texts):,}")29print("tokens in them:", f"{sum(len(ids) for ids in texts):,}")30print(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 marker31print("texts per batch:", size)32print("one batch's inputs and targets:", *first_shape)33print("share of targets that are padding, over one shuffled epoch:", f"{padding / targets_seen:.0%}")34print("least and most padding in a batch:", f"{min(shares):.0%} and {max(shares):.0%}")35print("steps per epoch:", f"{math.ceil(len(texts) / size):,}") # the last, partly filled batch is a step too36print("epochs in the recorded run:", settings["epochs"])37print("steps in the recorded run:", f"{manifest['steps']:,}")
python training-batches.pytraining 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.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Update with AdamW and clipped gradients
With batches in hand, each step is the loop of chapter 5: forward pass, loss, gradients, update. These lines of recordings/transformer.py are the whole of it, run once per batch:
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()
The first three lines are the previous section: a padded batch, inputs without the last token, and a loss over the shifted targets that ignores padding. Two lines differ from chapter 5.
The optimizer is AdamW, the Adam of chapter 5 with weight decay applied apart from the gradient. Weight decay reduces each weight at every step by its value times the step size times a decay factor, here 0.1 (PyTorch's AdamW). Loshchilov and Hutter showed that applying the decay this way works better with Adam than adding it to the loss (Loshchilov and Hutter, 2019). Decay is a form of regularization, which chapter 5's window model lacked: it pulls every weight towards zero, so a weight stays large only while the training text keeps pushing it there.
The training script also clips the gradients: when their combined length, measured as if every gradient were one long vector, exceeds 1.0, it scales them all down to that length (PyTorch's clip_grad_norm_). One unusual batch then can't throw the weights far off. Pascanu and colleagues proposed clipping for exactly that: rare, very large gradients that would otherwise undo much of what training had learned (Pascanu et al., 2013).
Working rule: Use AdamW with a modest weight decay, and clip gradients by their combined length. Keep the training step short enough to read whole, so that every choice in it is visible: what the loss ignores, what the optimizer decays and what gets clipped.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Warm up, then decay the step size
The last line of the loop, scheduler.step(), changes the step size after every batch, following a schedule, which sets the step size for each step of the run. For the first 200 steps, the step size rises in a straight line from nearly zero to its peak, 0.003: a warm-up, as the transformer paper's schedule had (Vaswani et al., 2017, section 5.3). In Adam's first steps, its running average of squared gradients rests on only a few batches, so its step sizes vary widely; Liu and colleagues showed that warm-up works by reducing that variance (Liu et al., 2020). After the warm-up, the step size falls along half a cosine curve, to a tenth of the peak by the last step (Loshchilov and Hutter, 2017). Large steps early cover ground; small steps late let the weights settle into a low point instead of bouncing around it. In symbols, after the warm-up:
rate = peak × (0.1 + 0.9 × ½ (1 + cos(π × progress)))
where progress runs from 0 at the end of the warm-up to 1 at the last step.
Whether the schedule matches the run's is checkable: compute it by hand from the recorded settings, and set it against the step sizes the training script saved every tenth step:
1"""Computes the warm-up and cosine schedule by hand from the recorded settings, and checks it against the step sizes2the training script saved. The prose relies on the check: the assert fails the run if the two ever differ."""3import json4import math56from lib import transformer78_, _, manifest = transformer.load()9settings, total = manifest["settings"], manifest["steps"]10recorded_rates = json.loads((transformer.RECORDED / "curves.json").read_text())["rates"] # every 10th step's, after the scheduler's step111213def rate(step):14 """Warm up linearly to the peak, then follow half a cosine down to a tenth of it."""15 if step < settings["warmup_steps"]:16 return settings["peak_rate"] * (step + 1) / settings["warmup_steps"] # steps count from 0, so step 0 is already a share of the peak17 progress = (step - settings["warmup_steps"]) / (total - settings["warmup_steps"]) # 0 at the warm-up's end, 1 at the last step18 return settings["peak_rate"] * (0.1 + 0.9 * 0.5 * (1 + math.cos(math.pi * progress)))192021print("warm-up steps:", settings["warmup_steps"])22print("peak step size:", settings["peak_rate"])23print("weight decay:", settings["weight_decay"])24for step in [0, settings["warmup_steps"] // 2, settings["warmup_steps"], total // 2, total - 1]:25 print(f"step size at step {step:,}:", f"{rate(step):.2e}")26gap = 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 + 127assert gap < 1e-9 # every saved step size matches the hand calculation, to a billionth28print("same as the recorded step sizes:", "yes")
python learning-rate-schedule.pywarm-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
The hand calculation matches every saved step size. The step size starts at 1.50e-05, peaks at 3.00e-03 at the warm-up's end, and is 3.00e-04 at the last step, a tenth of that peak.
The decay matters. The comparison run trained for four epochs at the same width, with the same seed and the same batches, so its schedule finished its decay at step 4,284, and at that step it scored 27.6 on the validation names. The recorded run was still near its peak step size at that step, and scored 32.6. Same data, same steps: the difference is the decay.
Working rule: Warm the step size up over the first few hundred steps, then decay it, and match the schedule's length to the run's. Save the step size as training runs, as the training script does, and check it against the schedule you meant: a schedule bug looks like a training problem, and is far easier to find this way.
학습 곡선 읽기
배치, 업데이트, 스케줄을 정한 뒤 스토어의 모델은 16 에포크 동안 학습했고, 스크립트는 매 에포크가 끝날 때마다 검증 분할에서 이름과 설명을 따로 측정했다. 스크립트는 이름과 설명의 검증 손실을 더한 값이 가장 낮은 에포크의 가중치를 남겼는데, 5장에서 가장 좋은 에포크를 남긴 것과 같다.
기록된 곡선을 토큰당 퍼플렉서티로 읽으면 에포크별로 다음과 같다.
1"""Prints the recorded run's perplexity for each epoch, then the epoch kept and its validation perplexities.2The prose's point rests on the two validation columns and the epoch kept."""3import json4import math56from lib import transformer78_, _, manifest = transformer.load()9curves = json.loads((transformer.RECORDED / "curves.json").read_text())["epochs"]1011print("perplexity per token; training mixes names and descriptions, as the training text does")12print("epoch training validation names validation descriptions")13for curve in curves:14 print(f"{curve['epoch']:>5} {math.exp(curve['train_loss']):>8.1f} {math.exp(curve['validation_name_loss']):>16.1f}"15 f" {math.exp(curve['validation_description_loss']):>23.1f}")16kept = next(curve for curve in curves if curve["epoch"] == manifest["kept_epoch"]) # the epoch whose weights were kept17print("epoch kept, the lowest name and description losses added together:", manifest["kept_epoch"])18print("validation perplexity on names, kept epoch:", f"{math.exp(kept['validation_name_loss']):.1f}")19print("validation perplexity on descriptions, kept epoch:", f"{math.exp(kept['validation_description_loss']):.1f}")20print("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.pyperplexity 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 토큰을 학습했다. 또 이 모델은 스텝 크기가 감쇠하고, 가중치 감쇠가 있으며, 어텐션이 모든 위치에 같은 가중치를 적용한다. 이 실행만으로는 이러한 이유를 가려낼 수 없다. 실행이 보여 주는 것은 학습과 검증 사이의 격차이며, 이 격차는 에포크마다 커진다. 끝에 이르면 모델은 새 텍스트보다 학습 텍스트를 훨씬 잘 예측하므로 암기하기 시작한 것이다.
설명의 점수가 이름보다 낮지만, 이것이 모델이 설명을 더 잘 다룬다는 뜻은 아니다. 텍스트 종류마다 예측 가능한 정도가 다르다. 설명은 템플릿과 이름에서 가져온 구절을 되풀이하고, 이름은 새 제품을 몇 단어에 담는다. 퍼플렉서티는 같은 텍스트에서 모델끼리 비교하는 것이며, 서로 다른 텍스트끼리 비교하는 것이 아니다.
작업 규칙: 관심 있는 텍스트 종류마다 에포크별 검증 손실을 기록하고, 가장 좋은 에포크의 가중치를 남긴다. 학습 손실만이 아니라 학습과 검증 사이의 격차를 경고로 읽는다. 서로 다른 종류의 텍스트 사이에서는 퍼플렉서티를 절대 비교하지 않는다.
이름에서 기준선과 비교하기
학습 과정을 살펴보았으니 이제 결과를 측정할 수 있다. 이름에 대해 계수 기반 모델 중 가장 강력한 것은 학습용 이름으로 학습한 4-gram 기준선이다. 이 모델은 검증용 이름에서 23.1를 기록하는데, 검증용 이름은 이 책의 잣대이다. 3장 이후의 모든 모델이 이 이름들로 평가되었다. 이름과 설명을 모두 포함한 전체 텍스트로 학습한 같은 4-gram은 검증용 이름에서 27.7를 기록한다. 설명이 이름이 이어지는 방식에 대한 이 모델의 계수를 희석하기 때문이다.
비교는 같은 예측을 세어야 한다. 4-gram은 각 이름의 토큰을 예측한 다음 끝 표지를 예측한다. 트랜스포머는 각 이름의 토큰을 예측한 다음 <sep>를 예측하는데, 이것이 이름의 끝을 표시하므로 같은 역할을 한다. 이름 뒤에는 아무것도 필요하지 않으므로 트랜스포머는 이름만 읽는다. 두 모델은 같은 46,704개의 예측을 평가한다.
먼저 추측해 보자. 5장의 윈도 모델이 이기지 못했던 계수 기반 기준선을 트랜스포머만으로 이길 수 있을까? 그런 다음 5장에서 했던 방식대로 두 모델과 둘의 혼합을 평가한다.
1"""Scores every validation name, its end included, with the 4-gram baseline and with the transformer, then mixes them2at several shares. The prose's point rests on the share 0.5 line, the lowest of the five."""3import numpy as np45from lib import transformer6from lib.names import name_tokens7from lib.ngrams import KneserNey, ngrams, padded89_, vocabulary, _ = transformer.load()10index = {token: i for i, token in enumerate(vocabulary)} # each token's id in the vocabulary, which is its column in the model's output11counted = KneserNey(name_tokens("train"), 4) # chapter 3's baseline, trained on names12from_counts, from_transformer = [], []13for name in name_tokens("validation"):14 ids = [index[transformer.START]] + [index[token] for token in name] + [index[transformer.SEP]] # the name as the model reads it15 probabilities = transformer.softmax(transformer.forward(ids)[:-1]) # the last position predicts past <sep>, which a name never needs16 from_transformer += list(probabilities[np.arange(len(ids) - 1), ids[1:]]) # each position's probability for the token after it17 from_counts += [counted.probability(context, token) for context, token in ngrams(padded(name, 4), 4)] # then </s>18from_counts, from_transformer = np.array(from_counts), np.array(from_transformer)1920print("validation tokens scored, each name's end included:", f"{len(from_counts):,}")21for share in [0.0, 0.3, 0.5, 0.7, 1.0]:22 mixed = (1 - share) * from_counts + share * from_transformer23 print(f"validation perplexity on names, transformer share {share:.1f}:", f"{np.exp(-np.log(mixed).mean()):.1f}")
python transformer-on-names.pyvalidation 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
트랜스포머와 계수를 절반씩 섞으면 이름에서 18.4를 기록하며, 이는 이 책에서 이름에 대한 모든 모델 중 가장 좋다. 트랜스포머 단독으로는 24.0로, 기준선의 23.1보다 약간 나쁘다.
트랜스포머 단독은 36.4를 기록한 5장의 윈도 모델보다 훨씬 좋으며, 혼합은 5장의 최고 혼합인 21.9보다 좋다.
따라서 이름에서는 5장이 설명한 이유로 계수 기반 모델을 단독으로 이기기가 여전히 어렵다. 이름은 짧고 정형화되어 있어서 세 토큰의 문맥만으로도 이름이 담은 대부분을 볼 수 있기 때문이다. 그러나 트랜스포머는 계수와 다른 곳에서 틀리므로, 혼합은 양쪽에서 이득을 얻는다. 비율은 검증용 이름에서 골랐으므로 이득은 다소 낙관적이다. 시험용 이름은 책의 최종 비교를 위해 손대지 않은 채로 남겨 둔다.
작업 규칙: 새 모델은 만들 수 있는 가장 강력한 기준선과 정확히 같은 예측 위에서 비교하라. 각 모델이 텍스트의 끝을 표시하는 방식도 여기에 포함된다. 학습된 모델과 계수 기반 모델이 비슷하면 둘을 섞고, 비율은 따로 떼어 둔 텍스트에서 골라라.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Compare on descriptions
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:
1"""Scores the descriptions of the first 500 validation products with a 4-gram trained on whole texts, with the transformer,2and with their even mix, then splits the tokens by whether their context was seen in training. The prose's point rests on the34-gram baseline and transformer lines, the half-and-half line and the unseen-context lines."""4import numpy as np56from lib import transformer7from lib.names import name_tokens8from lib.ngrams import KneserNey, ngrams, padded9from lib.products import product_texts1011_, vocabulary, _ = transformer.load()12end = vocabulary.index(transformer.END)13as_tokens = lambda ids: [vocabulary[i] for i in ids[1:] if i != end] # padded() adds its own <s> and </s>14counted = KneserNey([as_tokens(ids) for ids, _ in product_texts("train")], 4) # whole texts: name, <sep>, description1516from_counts, from_transformer, seen, products = [], [], [], 017for ids, sep in product_texts("validation", 500):18 if ids[-1] != end or sep == len(ids) - 2:19 continue # cut at the length limit, or no description20 pairs = list(ngrams(padded(as_tokens(ids), 4), 4))[sep:] # from <sep> on: the description's tokens, then </s>21 from_counts += [counted.probability(context, token) for context, token in pairs]22 seen += [context in counted.totals[4] for context, _ in pairs] # was this 3-token context in the training texts?23 probabilities = transformer.softmax(transformer.forward(ids)[sep:-1]) # from <sep> on: each position predicts the next token24 from_transformer += list(probabilities[np.arange(len(probabilities)), ids[sep + 1:]]) # the description starts after <sep>, at sep + 125 products += 126from_counts, from_transformer, seen = np.array(from_counts), np.array(from_transformer), np.array(seen)27perplexity = lambda p: f"{np.exp(-np.log(p).mean()):.1f}"2829print("products scored:", products)30print("description tokens scored:", f"{len(from_counts):,}")31mixed = (from_counts + from_transformer) / 232for label, p in [("4-gram baseline", from_counts), ("transformer", from_transformer), ("half and half", mixed)]:33 print(f"{label}, validation perplexity on descriptions:", perplexity(p))34print("description tokens whose 3-token context is in the training texts:", f"{seen.mean():.0%}")35for part, where in [("seen", seen), ("unseen", ~seen)]:36 print(f"4-gram, {part} contexts:", perplexity(from_counts[where]))37 print(f"transformer, {part} contexts:", perplexity(from_transformer[where]))3839names = [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 of40on_names = [counted.probability(context, token) for pairs in names for context, token in pairs]41print("this 4-gram, trained on whole texts, validation perplexity on names:", perplexity(np.array(on_names)))
python transformer-on-descriptions.pyproducts 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.
너비, 데이터, 단계가 가져다주는 것
기록된 모델은 여러 선택지 중 하나다. 너비는 128개의 수이며, 전체 학습 텍스트로 16 에폭 동안 학습했다. 훨씬 큰 모델을 대상으로 한 연구들은 모델이 커지고, 더 많은 텍스트를 보고, 더 오래 학습할수록 손실이 매끄럽게 줄어든다는 것, 그리고 큰 모델일수록 보는 토큰 하나에서 더 많이 배운다는 것을 발견했다(Kaplan et al., 2020). 계산 예산이 고정되어 있을 때는 모델 크기와 학습 텍스트가 함께 늘어야 한다고 Hoffmann 등이 밝혔다(Hoffmann et al., 2022). 또한 Muennighoff 등은 같은 텍스트를 최대 약 네 에폭까지 반복하는 것이 새 텍스트를 쓰는 것과 거의 비슷하게 좋고, 그 이후에는 반복할 때마다 얻는 이득이 줄어든다고 보고했다(Muennighoff et al., 2023). 이런 결과가 이 작은 규모에서도 성립하는지는 가정할 것이 아니라 측정해야 할 문제다.
그래서 학습 스크립트는 주된 실행 옆에 더 저렴한 실행 일곱 개를 기록했다. 각 실행은 한 가지만 바꾼다.
- 세 가지 너비 64, 128, 256을 각각 네 에폭 동안 학습한다. 모든 헤드의 너비는 32개의 수로 유지한다.
- 학습 제품의 무작위 4분의 1과 2분의 1을 각각 네 에폭 동안 학습한다.
- 같은 4분의 1과 2분의 1을, 전체 데이터로 네 에폭 학습한 것과 같은 단계 수만큼 더 자주 반복해서 학습한다.
어떤 변화가 가장 많은 것을 가져다주는가? 여덟 실행을 나란히 읽어 보자. 각 실행의 크기, 단계 수, 그리고 최고 에폭과 마지막 에폭에서의 퍼플렉시티를 나타냈다.
1"""Reads eight recorded runs and prints each one's parameters, steps, best epoch, and validation perplexities at its best2and last epochs. The prose's point rests on the perplexity-on-names lines."""3import json4import math56from lib import transformer78runs = [("width 64, 4 epochs", "transformer-width-64"), ("width 128, 4 epochs", "transformer-width-128"),9 ("width 256, 4 epochs", "transformer-width-256"), ("width 128, 16 epochs", "transformer"),10 ("a quarter of the data, 4 epochs", "transformer-data-25"), ("half the data, 4 epochs", "transformer-data-50"),11 ("a quarter of the data, 16 epochs", "transformer-data-25-same-steps"),12 ("half the data, 8 epochs", "transformer-data-50-same-steps")]1314for label, folder in runs:15 run = transformer.RECORDED.parent / folder # every run sits in the folder beside the main run's16 manifest = json.loads((run / "manifest.json").read_text())17 curves = json.loads((run / "curves.json").read_text())["epochs"]18 best = min(curves, key=lambda curve: curve["validation_name_loss"] + curve["validation_description_loss"]) # the epoch the script kept19 print(f"{label}, parameters:", f"{manifest['parameters']:,}")20 print(f"{label}, steps:", f"{manifest['steps']:,}")21 print(f"{label}, best epoch:", best["epoch"])22 print(f"{label}, perplexity on names:", f"{math.exp(best['validation_name_loss']):.1f}")23 print(f"{label}, perplexity on descriptions:", f"{math.exp(best['validation_description_loss']):.1f}")24 print(f"{label}, perplexity on names, last epoch:", f"{math.exp(curves[-1]['validation_name_loss']):.1f}") # the last epoch trained, not the one kept25 print(f"{label}, perplexity on descriptions, last epoch:", f"{math.exp(curves[-1]['validation_description_loss']):.1f}")
python width-data-and-steps.pywidth 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으로 떨어진다. 이름에서는 네 에폭 학습한 가장 넓은 모델이 열여섯 에폭 학습한 기록된 모델의 24.0보다도 낫다. 그러나 너비 256의 매개변수는 4,273,920개로, 너비 128의 1,334,144개에 비해 많고, 단계마다 드는 비용도 그만큼 늘어난다.
새 텍스트는 단계당 추가 비용 없이 도움이 된다. 단계 수가 같을 때 제품의 무작위 4분의 1은 최고 시점에 이름에서 40.0, 2분의 1은 30.4, 전체는 27.6를 기록한다. 텍스트를 2분의 1에서 전체로 두 배 늘린 것은 너비를 128에서 256으로 두 배 늘린 것보다 이득이 작았지만 추가 계산이 들지 않았고, 4분의 1에서 2분의 1로 처음 두 배 늘린 것은 둘 중 어느 쪽보다도 이득이 컸다.
반복은 한동안 도움이 되다가 해가 된다. 텍스트의 4분의 1을 네 번 본 모델은 51.9를 기록한다. 더 자주 보면 11 에폭까지 나아지다가 나빠지며, 열여섯 번을 본 뒤에는 44.1로 끝난다. 모델이 너무 자주 본 것을 외워 버리기 때문이다. 같은 단계 수에서 반복된 텍스트는 새 텍스트를 따라잡지 못했다.
더 많은 단계는 도움이 가장 적다. 기록된 모델의 열여섯 에폭은 네 에폭보다 나아지지만, 이름에서 24.0 대 27.6에 그치며 단계 수는 네 배다.
이 실행들은 이 책이 다루는 규모의 한계도 보여 준다. 상점의 학습 텍스트는 카탈로그가 담고 있는 양으로 고정되어 있으며, 토큰 수는 2,843,222개다. 7장에서 상점의 모델과 설계를 비교한 SmolLM2-360M은 4조 개의 토큰으로 학습했다(모델 카드). 이는 백만 배가 넘는 양이며, 그 덕분에 너비 960, 깊이 32층의 모델이 오래된 텍스트를 외우는 대신 새 텍스트에서 계속 배울 수 있다.
작업 규칙: 가진 텍스트를 몇 번 넘게 반복하기 전에, 예측하려는 종류의 텍스트를 더 구하라. 단계당 비용이 들지 않는다. 계산에 여유가 있다면 좁은 모델을 더 오래 학습하기 전에 더 넓은 모델을 더 적은 에폭으로 학습해 보고, 둘 다 측정하라. 한 번의 실행에서는 한 가지만 바꾸고, 중요한 곳에서는 단계 수를 고정하라. 그렇지 않으면 비교가 두 가지를 한꺼번에 측정하게 된다.
이 부분은 아직 번역되지 않았으므로 영어로 표시된다.
Suggest the next word in the search box
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:
1"""Asks the transformer and its half-and-half mix with the 4-gram for their three likeliest next tokens after five prefixes,2treated as the start of a name, and prints the probability of stool after outdoor bar. The prose's point rests on the3stool lines and the control prefixes beside them."""4import numpy as np56from lib import bpe, transformer7from lib.names import name_tokens8from lib.ngrams import KneserNey910_, vocabulary, _ = transformer.load()11index = {token: i for i, token in enumerate(vocabulary)}12counted = KneserNey(name_tokens("train"), 4)13tokenizer = bpe.store_tokenizer()14as_counted = [{transformer.SEP: "</s>"}.get(token, token) for token in vocabulary] # <sep> ends a name, as </s> does15show = lambda token: token.replace("</w>", "")1617for prefix in ["bar", "patio bar", "outdoor bar", "kitchen bar", "wine bar"]:18 tokens = tokenizer.encode(prefix)19 ids = [index[transformer.START]] + [index[token] for token in tokens]20 from_transformer = transformer.softmax(transformer.forward(ids)[-1])21 context = tuple(["<s>"] * 3 + tokens)[-3:] # the 4-gram looks at the last three tokens, padded with start markers for a short prefix22 from_counts = np.array([counted.probability(context, token) for token in as_counted])23 mixed = (from_transformer + from_counts) / 224 for label, p in [("transformer", from_transformer), ("half and half", mixed)]:25 top = np.argsort(-p, kind="stable")[:3] # the three likeliest; a stable sort keeps tied tokens in vocabulary order26 print(f"{prefix:<12} {label:<13} -> " + ", ".join(f"{show(vocabulary[i])} {p[i]:.2f}" for i in top))27 if prefix == "outdoor bar":28 stool = index["stool</w>"] # </w> marks the end of a word in the tokenizer, so this is the whole word stool29 print("P(stool | outdoor bar), transformer:", f"{from_transformer[stool]:.2f}")30 print("P(stool | outdoor bar), 4-gram:", f"{from_counts[stool]:.2f}")31 print("P(stool | outdoor bar), half and half:", f"{mixed[stool]:.2f}")
python transformer-autocomplete.pybar 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.
운영 환경에서 잘못되는 것들
학습은 진행되는 동안에는 문제가 없어 보이지만 실제로는 잘못되는 경우가 있다.
- 패딩은 계산을 낭비한다. 여기서는 각 스텝의 예측 중 거의 절반이 패딩이었다. 계산 자원을 더 구입하기 전에 텍스트를 묶어 채우거나 길이별로 모은다.
- 스케줄 버그는 모델의 문제처럼 보인다. 경험칙으로, 끝나지 않는 워밍업이나 너무 일찍 시작되는 감쇠는 손실이 너무 느리게 줄어드는 모습으로 나타난다. 앞의 감쇠 비교는 스케줄이 결과를 얼마나 움직일 수 있는지 보여 준다. 스텝 크기를 저장하고, 의도한 스케줄과 대조하여 확인한다.
- 검증 데이터로 내린 선택은 결과를 실제보다 좋아 보이게 한다. 보관한 에폭과 혼합 비율은 모두 검증 분할로 선택했으므로, 그 수치는 약간 낙관적이다. 테스트 분할은 마지막까지 손대지 않고 둔다.
- 반복된 텍스트는 암기된다. 작은 데이터셋을 여러 번 보면 학습 손실은 좋아 보이지만 새로운 텍스트에서는 성능이 떨어진다. 학습이 각 텍스트를 몇 번 보는지 세고, 에폭을 늘리기보다 새 텍스트를 우선한다.
- 하나의 모델이 한 종류의 텍스트에서만 측정된다. 트랜스포머는 이름에서는 카운트 모델에 이어 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판을 번역한 것이다.