Boil down what an LLM does to one sentence and you get “look at the previous tokens and output a probability distribution over the next token”. Conversation, writing code, reasoning and tool calls all come from repeating this one operation. Post-training (SFT, RLHF, RLVR) is, in the end, also a story about how to change this conditional distribution. So the starting point is what exactly this distribution is, and how to measure how well it predicts.
The probability of a sentence as a product of next-token probabilities
The probability of a token sequence factors exactly using nothing but the chain rule of probability.
There is no assumption here. Any joint distribution can be written this way. A model that follows this factorisation is called an autoregressive language model, and the model only needs to learn one function: “prefix → distribution over the next token”. With a vocabulary of size , the output is numbers (logits), turned into probabilities by a softmax.
The factorisation brings two gifts.
- Generation is easy. Sample , append it and sample , and so on, and you get an exact sample from the joint distribution (ancestral sampling). The decoding lesson twists this step in several ways.
- The training signal is dense. One document of length becomes “guess the next token” problems. Thanks to the causal mask, a Transformer computes all of them in a single forward pass (GPT lesson).
The loss: per-token negative log-likelihood
Maximum likelihood estimation (MLE), finding the that makes the data most likely, is — after taking logs so the product becomes a sum — the same as minimising the following loss.
This is the per-token negative log-likelihood (NLL). It is a sample estimate of the cross-entropy between the data distribution and the model, which can be rewritten as
The first term is why the loss never reaches 0. Language has inherent uncertainty (“today I ate ___” has more than one right answer). All the model can reduce is the KL, which is why pre-training loss curves converge towards some floor. The constant term in the scaling-laws lesson is exactly an estimate of this floor.
During training, the prefix fed to the model is not something the model generated but the real prefix from the data. This is called teacher forcing. It lets us train all positions in parallel, but it creates a mismatch (exposure bias): at generation time the model has to continue from its own (possibly wrong) prefix. RL-based post-training, which trains on the model’s own outputs (on-policy), is also a way of tackling this mismatch directly.
Perplexity: the effective number of choices
NLL is in nats, which is hard to get a feel for. Exponentiating it gives perplexity (PPL).
The right-hand side gives the interpretation: PPL is the geometric mean of “one over the probability given to the right answer”. If the model always bets evenly on candidates and the answer is always among them, NLL and PPL . So PPL reads as how many options the model is effectively choosing among at each step — the effective branching factor. A uniform model that knows nothing has PPL equal to the vocabulary size ; a perfect model has 1.
Keep two things in mind.
- PPL becomes infinite if the model gives to a single correct token. Log loss punishes “confident wrong answers” without bound. You can see it in the figure below.
- PPL is per token, so models with different tokenizers cannot be compared on it. A model averaging 4 bytes per token and one averaging 2 split the same text into different numbers of problems.
A tokenizer-independent measure is bits-per-byte (BPB): convert the total NLL to bits and divide by the number of bytes in the original text.
This is literally a compression rate. With arithmetic coding, a model can store text in almost bits, so building a good language model and compressing text well are the same problem. Shannon (1951), by having people guess the next letter, estimated the entropy of English given long context at roughly 0.6–1.3 bits per character — a ballpark for the BPB a human-level “language model” could achieve.
The simplest model: n-grams
What if we just counted in a table? Using the entire prefix as the key, the same prefix almost never occurs twice, so we assume the model looks only at the last tokens (the Markov assumption).
With this is a bigram model. Let be the probability that follows the previous character , and maximise the log-likelihood of the training data (where is the bigram count). Attaching a Lagrange multiplier to each constraint and differentiating gives
The MLE is just count and divide. The problem is that a bigram never seen in training gets . A single such pair in the evaluation text makes PPL infinite. The simplest fix is add-k smoothing.
Add a pseudo-count to every cell. With this is Laplace smoothing; in Bayesian terms it is the posterior mean under a symmetric Dirichlet() prior. A large pulls the distribution towards uniform and worsens the training PPL; a small one gives too little probability to unseen pairs. Somewhere in between lies the with the lowest held-out PPL.
LLM이 하는 일을 한 문장으로 줄이면 “앞의 토큰들을 보고 다음 토큰의 확률분포를 낸다”이다. 대화, 코드 작성, 추론, tool 호출이 모두 이 한 가지 연산을 반복해서 나온다. 사후학습(SFT, RLHF, RLVR)도 결국 이 조건부 분포를 어떻게 바꿀지에 대한 이야기다. 그러니 출발점은 이 분포가 정확히 무엇이고, 얼마나 잘 맞혔는지를 어떻게 재는지다.
문장의 확률을 다음 토큰의 곱으로
토큰열 의 확률은 확률의 연쇄법칙(chain rule)만으로 정확히 쪼개진다.
여기에는 아무 가정도 없다. 어떤 결합분포든 이렇게 쓸 수 있다. 이 분해를 따르는 모델을 자기회귀(autoregressive) 언어 모델이라 부르고, 모델 는 “접두사(prefix) → 다음 토큰 분포”라는 함수 하나만 배우면 된다. 어휘(vocabulary) 크기가 이면 출력은 개 숫자(logit)이고 softmax로 확률이 된다.
이 분해가 주는 선물은 두 가지다.
- 생성이 쉽다. 을 뽑고, 그걸 붙여서 를 뽑고, … 를 반복하면 결합분포 에서 정확한 표본이 나온다(ancestral sampling). 디코딩 레슨에서 이 단계를 여러 방식으로 비튼다.
- 학습 신호가 촘촘하다. 길이 인 문서 하나가 개의 “다음 토큰 맞히기” 문제가 된다. Transformer는 causal mask 덕분에 이 개를 한 번의 forward로 동시에 계산한다(GPT 레슨).
손실: 토큰당 음의 로그 가능도
데이터 를 가장 그럴듯하게 만드는 를 찾는 최대가능도 추정(MLE)은, 로그를 씌우면 곱이 합이 되어 다음 손실을 최소화하는 것과 같다.
토큰당 음의 로그 가능도(negative log-likelihood, NLL) 이다. 이것은 데이터 분포 와 모델 사이의 cross-entropy를 표본으로 추정한 값이고, 다시 쓰면
이다. 손실이 0까지 내려가지 않는 이유가 첫째 항이다. 언어에는 본질적인 불확실성이 있다(“나는 오늘 ___을 먹었다”의 정답은 하나가 아니다). 모델이 줄일 수 있는 것은 KL뿐이고, 그래서 사전학습 손실 곡선은 어떤 바닥을 향해 수렴한다. 스케일링 법칙 레슨의 상수항 가 바로 이 바닥의 추정치다.
학습할 때 모델에 넣는 접두사 는 모델이 생성한 것이 아니라 데이터의 진짜 접두사다. 이를 teacher forcing이라 한다. 덕분에 개 위치를 병렬로 학습하지만, 생성할 때는 자기가 만든 (틀릴 수 있는) 접두사 위에서 이어 가야 한다는 불일치(exposure bias)가 생긴다. RL 기반 사후학습이 모델 자신의 출력 위에서 학습하는 것(on-policy)은 이 불일치를 직접 다루는 방법이기도 하다.
Perplexity: 실효 선택지 수
NLL은 nat 단위라 감이 잘 안 온다. 지수를 씌운 것이 perplexity(PPL) 다.
오른쪽 식이 해석을 준다. PPL은 “정답에 준 확률의 역수”의 기하평균이다. 모델이 매번 개 후보에 똑같이 씩 걸고 정답이 늘 그 안에 있다면 NLL , PPL 다. 그래서 PPL은 모델이 매 걸음 실질적으로 몇 개 중에서 고르는 것만큼 헷갈리는가, 즉 실효 분기 계수(effective branching factor)로 읽는다. 아무것도 모르는 균등 모델의 PPL은 어휘 크기 이고, 완벽한 모델은 1이다.
두 가지를 기억해 두자.
- PPL은 정답 하나에 을 주면 무한대가 된다. 로그 손실은 “확신에 찬 오답”을 무한히 벌한다. 아래 그림에서 직접 볼 수 있다.
- PPL은 토큰 단위라서, 토크나이저가 다른 모델끼리는 비교할 수 없다. 한 토큰이 평균 4바이트인 모델과 2바이트인 모델은 같은 글을 다른 개수의 문제로 쪼갠다.
토크나이저에 독립적인 척도가 bits-per-byte(BPB) 다. 전체 NLL을 비트로 바꿔 원문 바이트 수로 나눈다.
이것은 그대로 압축률이다. 산술 부호화(arithmetic coding)를 쓰면 모델 로 글을 거의 비트에 담을 수 있으므로, 언어 모델을 잘 만드는 것과 글을 잘 압축하는 것은 같은 문제다. Shannon(1951)은 사람에게 다음 글자를 맞히게 하는 실험으로, 긴 문맥이 주어졌을 때 영어의 엔트로피를 글자당 대략 0.6–1.3비트로 추정했다. 사람 수준의 “언어 모델”이 낼 수 있는 BPB의 어림값인 셈이다.
가장 단순한 모델: n-gram
를 표로 직접 세면 어떨까? 접두사 전체를 키로 쓰면 같은 접두사가 두 번 나오는 일이 거의 없으니, 최근 개만 본다고 가정한다(Markov 가정).
이면 bigram이다. 직전 글자 다음에 가 올 확률을 로 두고 학습 데이터의 로그 가능도 를 최대화하자(는 bigram 빈도). 각 마다 제약에 Lagrange 승수 를 붙여 미분하면
MLE는 그냥 세어서 나누기다. 문제는 학습 데이터에 한 번도 안 나온 bigram이 을 받는다는 것이다. 평가 글에 그런 쌍이 하나만 있어도 PPL은 무한대다. 이를 막는 가장 단순한 방법이 add-k 평활(smoothing) 이다.
모든 칸에 가짜 빈도 를 더한다. 이면 Laplace 평활이고, 베이즈적으로는 대칭 Dirichlet() prior를 둔 posterior 평균이다. 가 크면 분포가 균등 쪽으로 끌려가 학습 PPL이 나빠지고, 작으면 처음 보는 쌍에 너무 적은 확률을 준다. 그 사이 어딘가에 held-out PPL이 가장 낮은 가 있다.
Things to check in the figure:
- Lower k to 0 and the training PPL is minimised, but the held-out PPL is ∞. “The model that best explains the training data” and “the model that best predicts new text” are different. This is overfitting in its most blatant form.
- On the English corpus the bigram PPL is far below the uniform PPL (). Knowing just the previous character greatly narrows the candidates for the next one — after ‘q’ almost always comes ‘u’.
- Switch to the Korean corpus and the syllable-level vocabulary grows to several hundred. A table of cells has to be filled from a text of the same length, so most cells are empty and unseen pairs pour in on held-out text. The next lesson shows how byte-level tokenizers avoid this problem.
- Press sample and you get word-like fragments but not sentences. A bigram cannot see past the single previous character.
What happens as n grows
Raising lengthens the context, but the table size explodes as and the data to fill each cell becomes correspondingly sparse. This is the curse of dimensionality that Bengio et al. (2003) talked about. The classical remedy was more elaborate smoothing: interpolation, which mixes in the short-context estimate when the long-context estimate is uncertain; backoff, which drops to a shorter context when the count is 0; and Kneser–Ney smoothing, which uses “how many different contexts a word appears after” (Chen & Goodman, 1999).
Bengio et al. (2003)‘s remedy was to throw the table away. Map each word to an -dimensional vector (an embedding), concatenate the vectors of the previous words, feed them through a small neural network, and output a next-word distribution with a softmax. The parameter count grows not as but roughly as , and learning “the cat sat on the mat” spreads probability to “the dog sat on the mat” as well, because similar words get similar vectors. Replace the fixed-length context of this architecture with attention and stack it deep, and you get GPT (GPT lesson).
Implementing it
First we count a character bigram model with NumPy into a probability table, compute NLL and PPL, and draw a sample. It is the same computation as the figure above.
import numpy as np
text = (
"the cat sat on the mat. the dog sat on the log. a cat and a dog met on the mat "
"and the cat ran to the log. the dog ran after the cat. then the cat sat on the dog "
"and the dog sat on the log. that is the tale of the cat and the dog. the end. "
"a model of language gives a probability to every string. it predicts the next letter "
"from the letters before it. the better it predicts, the lower its loss and the lower "
"its perplexity. a good model puts high probability on the text that actually comes next. "
"a bad model spreads its bets thin, and pays for it in nats. "
) * 3
chars = sorted(set(text))
V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
cut = int(len(ids) * 0.85)
train, test = ids[:cut], ids[cut - 1:]
def fit_bigram(seq, k):
N = np.zeros((V, V))
np.add.at(N, (seq[:-1], seq[1:]), 1) # N[a, b] = c(a, b)
S = (N + k).sum(axis=1, keepdims=True)
# a character never seen as context (S=0) is undefined, so give it a uniform distribution
return np.where(S > 0, (N + k) / np.maximum(S, 1e-300), 1.0 / V)
def nll(P, seq):
p = P[seq[:-1], seq[1:]] # probability given to the true next character
with np.errstate(divide="ignore"):
return -np.log(p).mean()
print(f"V = {V}, train chars {len(train)}, eval chars {len(test)}")
print(f"uniform model : NLL = {np.log(V):.3f} nats PPL = {V:.1f}")
for k in [0.0, 0.01, 0.1, 1.0]:
P = fit_bigram(train, k)
tr, te = nll(P, train), nll(P, test)
print(f"bigram k={k:<4}: train PPL = {np.exp(tr):6.2f} held-out PPL = {np.exp(te):6.2f}"
f" ({te / np.log(2):.2f} bits/char)")
# ancestral sampling: draw one character at a time from the conditional and append it
P = fit_bigram(train, 0.1)
rng = np.random.default_rng(0)
cur, out = stoi["t"], ["t"]
for _ in range(80):
cur = rng.choice(V, p=P[cur])
out.append(chars[cur])
print("\nsample:", "".join(out))Because the corpus is repeated three times, most bigrams in the evaluation span already appeared in training, so here even does not go infinite. Real data is not this lucky. The next block is a trigram model, with the context extended to two characters. A longer context lowers the training PPL, but the table becomes sparse and smoothing matters more. This time we split a non-repeated corpus into a front and a back part to create unseen contexts on purpose.
words = ("the cat sat on the mat the dog sat on the log a cat and a dog met on the mat "
"the cat ran to the log the dog ran after the cat then the cat sat on the dog "
"a model of language gives a probability to every string it predicts the next "
"letter from the letters before it the better it predicts the lower its loss "
"a good model puts high probability on the text that comes next a bad model "
"spreads its bets thin and pays for it in nats the dog sat on the mat at last ")
ids2 = np.array([stoi[c] for c in words])
cut2 = int(len(ids2) * 0.8)
tr2, te2 = ids2[:cut2], ids2[cut2 - 2:]
def fit_trigram(seq, k):
N = np.zeros((V, V, V))
np.add.at(N, (seq[:-2], seq[1:-1], seq[2:]), 1)
S = (N + k).sum(axis=2, keepdims=True)
return np.where(S > 0, (N + k) / np.maximum(S, 1e-300), 1.0 / V)
def nll3(P, seq):
p = P[seq[:-2], seq[1:-1], seq[2:]]
with np.errstate(divide="ignore"):
return -np.log(p).mean()
unseen = sum(1 for a, b, c in zip(te2[:-2], te2[1:-1], te2[2:])
if not np.any((tr2[:-2] == a) & (tr2[1:-1] == b) & (tr2[2:] == c)))
print(f"of {len(te2) - 2} eval trigrams, unseen in training: {unseen}\n")
print(" k bigram train/held-out trigram train/held-out")
for k in [0.0, 0.003, 0.03, 0.1, 0.3, 1.0]:
P2 = fit_bigram(tr2, k)
P3 = fit_trigram(tr2, k)
f = lambda x: f"{np.exp(x):7.2f}" if np.isfinite(x) else " ∞"
print(f"{k:<6} {f(nll(P2, tr2))} / {f(nll(P2, te2[1:]))} "
f"{f(nll3(P3, tr2))} / {f(nll3(P3, te2))}")How to read the table: at both held-out values are ∞. Raising makes them finite; the held-out PPL reaches a minimum at some point and then gets worse again. The trigram’s training PPL is much lower than the bigram’s (it sees more context). On held-out text, however, it beats the bigram only slightly and only near the best ; move a little and it is worse than the bigram. More than a third of the evaluation trigrams are unseen combinations, so the smoothing rule decides performance. It is the theme of the scaling-laws lesson at the smallest possible scale: model capacity and the amount of data to fill it have to grow together.
A language model's average held-out NLL is ln(4) nats per token. What is its perplexity?
. The model is as confused as if it guessed uniformly among 4 candidates at every token. In bits that is bits per token.
Model A has PPL 8 and averages 4 bytes per token. Model B has PPL 4 and averages 2 bytes per token. Which compresses (predicts) the same text better?
Bits per token are for A and for B. Dividing by bytes, A gets BPB and B gets BPB. PPL is per token, so it should not be compared directly across tokenizers, but converted to BPB the comparison works, and A is better.
Summary
- By the chain rule, holds with no assumptions. A language model learns this one conditional distribution.
- The training loss is per-token NLL cross-entropy . The model can only reduce the KL.
- is “the geometric mean of one over the probability of the right answer” — the effective number of choices. Across tokenizers, compare in BPB.
- The n-gram MLE is a ratio of counts. Unseen combinations send PPL to infinity, so smoothing is needed, and sparsity explodes as grows.
- Neural LMs replace the table with embeddings and shared parameters, turning that sparsity into generalisation. The loss and the factorisation stay the same.
그림에서 확인할 것:
- k를 0으로 내리면 학습 PPL은 최소가 되지만 held-out PPL은 ∞다. “학습 데이터를 가장 잘 설명하는 모델”과 “새 글을 가장 잘 예측하는 모델”은 다르다. 과적합의 가장 노골적인 형태다.
- 영어 말뭉치에서 bigram PPL은 균등 PPL()보다 훨씬 낮다. 직전 글자 하나만 알아도 다음 글자 후보가 크게 줄어든다. ‘q’ 다음엔 거의 ‘u’가 오는 식이다.
- 한국어로 바꾸면 음절 단위 어휘가 수백 개로 늘어난다. 같은 길이의 글에서 칸짜리 표를 채워야 하니 대부분의 칸이 비고, held-out에서 처음 보는 쌍이 쏟아진다. 다음 레슨에서 바이트 수준 토크나이저가 이 문제를 어떻게 피하는지 본다.
- 샘플 생성을 눌러 보면 단어 비슷한 조각은 나오지만 문장은 되지 않는다. bigram은 직전 한 글자 밖을 못 본다.
n을 키우면 생기는 일
을 키우면 문맥이 길어지지만 표의 크기는 으로 폭발하고, 각 칸을 채울 데이터는 그만큼 희소해진다. 이것이 Bengio et al.(2003)이 말한 차원의 저주다. 고전적 해법은 평활을 정교하게 하는 것이었다. 긴 문맥의 추정이 불확실하면 짧은 문맥의 추정과 섞는 보간(interpolation), 0이면 짧은 문맥으로 내려가는 backoff, 그리고 “얼마나 다양한 문맥 뒤에 나타나는가”를 쓰는 Kneser–Ney 평활이 대표적이다(Chen & Goodman, 1999).
Bengio et al.(2003)의 해법은 표를 버리는 것이었다. 각 단어를 차원 벡터(embedding)로 바꾸고, 직전 개 단어의 벡터를 이어 붙여 작은 신경망에 넣어 softmax로 다음 단어 분포를 낸다. 매개변수는 이 아니라 대략 로 늘고, “고양이가 매트에 앉았다”를 학습하면 비슷한 벡터를 가진 “개가 매트에 앉았다”에도 확률이 퍼진다. 비슷한 단어가 비슷한 벡터를 가지기 때문이다. 이 구조에서 고정 길이 문맥을 attention으로 바꾸고 깊이를 쌓으면 GPT가 된다(GPT 레슨).
직접 구현하기
먼저 문자 bigram을 NumPy로 세어 확률표를 만들고, NLL·PPL을 계산하고, 샘플을 뽑는다. 위 그림과 같은 계산이다.
import numpy as np
text = (
"the cat sat on the mat. the dog sat on the log. a cat and a dog met on the mat "
"and the cat ran to the log. the dog ran after the cat. then the cat sat on the dog "
"and the dog sat on the log. that is the tale of the cat and the dog. the end. "
"a model of language gives a probability to every string. it predicts the next letter "
"from the letters before it. the better it predicts, the lower its loss and the lower "
"its perplexity. a good model puts high probability on the text that actually comes next. "
"a bad model spreads its bets thin, and pays for it in nats. "
) * 3
chars = sorted(set(text))
V = len(chars)
stoi = {c: i for i, c in enumerate(chars)}
ids = np.array([stoi[c] for c in text])
cut = int(len(ids) * 0.85)
train, test = ids[:cut], ids[cut - 1:]
def fit_bigram(seq, k):
N = np.zeros((V, V))
np.add.at(N, (seq[:-1], seq[1:]), 1) # N[a, b] = c(a, b)
S = (N + k).sum(axis=1, keepdims=True)
# 한 번도 문맥으로 안 나온 글자(S=0)는 정의되지 않으니 균등분포로 둔다
return np.where(S > 0, (N + k) / np.maximum(S, 1e-300), 1.0 / V)
def nll(P, seq):
p = P[seq[:-1], seq[1:]] # 정답 다음 글자에 준 확률
with np.errstate(divide="ignore"):
return -np.log(p).mean()
print(f"V = {V}, 학습 글자 {len(train)}, 평가 글자 {len(test)}")
print(f"균등 모델 : NLL = {np.log(V):.3f} nats PPL = {V:.1f}")
for k in [0.0, 0.01, 0.1, 1.0]:
P = fit_bigram(train, k)
tr, te = nll(P, train), nll(P, test)
print(f"bigram k={k:<4}: train PPL = {np.exp(tr):6.2f} held-out PPL = {np.exp(te):6.2f}"
f" ({te / np.log(2):.2f} bits/char)")
# ancestral sampling: 한 글자씩 조건부 분포에서 뽑아 이어 붙인다
P = fit_bigram(train, 0.1)
rng = np.random.default_rng(0)
cur, out = stoi["t"], ["t"]
for _ in range(80):
cur = rng.choice(V, p=P[cur])
out.append(chars[cur])
print("\n샘플:", "".join(out))말뭉치를 세 번 반복했기 때문에 평가 구간의 bigram도 대부분 학습에 이미 나왔다. 그래서 여기서는 도 무한대가 되지 않는다. 실제 데이터라면 이렇게 운이 좋지 않다. 다음 블록은 문맥을 두 글자로 늘린 trigram이다. 문맥이 길어지면 학습 PPL은 내려가지만 표가 희소해져 평활의 영향이 커진다. 이번에는 반복 없는 말뭉치의 앞뒤를 나눠서 처음 보는 문맥을 일부러 만든다.
words = ("the cat sat on the mat the dog sat on the log a cat and a dog met on the mat "
"the cat ran to the log the dog ran after the cat then the cat sat on the dog "
"a model of language gives a probability to every string it predicts the next "
"letter from the letters before it the better it predicts the lower its loss "
"a good model puts high probability on the text that comes next a bad model "
"spreads its bets thin and pays for it in nats the dog sat on the mat at last ")
ids2 = np.array([stoi[c] for c in words])
cut2 = int(len(ids2) * 0.8)
tr2, te2 = ids2[:cut2], ids2[cut2 - 2:]
def fit_trigram(seq, k):
N = np.zeros((V, V, V))
np.add.at(N, (seq[:-2], seq[1:-1], seq[2:]), 1)
S = (N + k).sum(axis=2, keepdims=True)
return np.where(S > 0, (N + k) / np.maximum(S, 1e-300), 1.0 / V)
def nll3(P, seq):
p = P[seq[:-2], seq[1:-1], seq[2:]]
with np.errstate(divide="ignore"):
return -np.log(p).mean()
unseen = sum(1 for a, b, c in zip(te2[:-2], te2[1:-1], te2[2:])
if not np.any((tr2[:-2] == a) & (tr2[1:-1] == b) & (tr2[2:] == c)))
print(f"평가 trigram {len(te2) - 2}개 중 학습에 없던 것: {unseen}개\n")
print(" k bigram train/held-out trigram train/held-out")
for k in [0.0, 0.003, 0.03, 0.1, 0.3, 1.0]:
P2 = fit_bigram(tr2, k)
P3 = fit_trigram(tr2, k)
f = lambda x: f"{np.exp(x):7.2f}" if np.isfinite(x) else " ∞"
print(f"{k:<6} {f(nll(P2, tr2))} / {f(nll(P2, te2[1:]))} "
f"{f(nll3(P3, tr2))} / {f(nll3(P3, te2))}")표를 읽는 법: 에서는 둘 다 held-out이 ∞다. 를 올리면 유한해지고, 어느 지점에서 held-out PPL이 가장 낮아진 뒤 다시 나빠진다. trigram은 학습 PPL이 bigram보다 훨씬 낮다(문맥을 더 보니까). 그런데 held-out에서는 가장 좋은 근처에서만 bigram을 조금 이기고, 가 조금만 어긋나도 bigram보다 못하다. 평가 trigram의 3분의 1 이상이 처음 보는 조합이라 평활 규칙이 성능을 좌우하기 때문이다. 모델 용량을 늘리는 것과 그것을 채울 데이터의 양은 같이 가야 한다는, 스케일링 법칙 레슨의 주제를 가장 작은 규모에서 본 셈이다.
어떤 언어 모델의 held-out 평균 NLL이 토큰당 ln(4) nat이다. perplexity는?
. 매 토큰 4개 후보 중 하나를 균등하게 찍는 것만큼 헷갈린다는 뜻이다. 비트로는 토큰당 비트다.
모델 A는 PPL 8, 토큰당 평균 4바이트. 모델 B는 PPL 4, 토큰당 평균 2바이트. 같은 글을 더 잘 압축(예측)하는 쪽은?
토큰당 비트는 A가 , B가 . 바이트로 나누면 A는 BPB, B는 BPB다. PPL은 토큰 단위라서 토크나이저가 다르면 직접 비교하면 안 되지만, BPB로 바꾸면 비교할 수 있고 A가 더 낫다.
정리
- 연쇄법칙으로 는 가정 없이 성립한다. 언어 모델은 이 조건부 분포 하나를 배운다.
- 학습 손실은 토큰당 NLL cross-entropy . 모델은 KL만 줄일 수 있다.
- 은 “정답 확률 역수의 기하평균”, 즉 실효 선택지 수다. 토크나이저가 다르면 BPB로 비교한다.
- n-gram의 MLE는 빈도의 비율이다. 처음 보는 조합이 PPL을 무한대로 만들기 때문에 평활이 필요하고, 을 키울수록 희소성이 폭발한다.
- 신경망 LM은 표를 embedding과 공유 매개변수로 바꿔 이 희소성을 일반화로 바꾼다. 손실과 분해는 그대로다.
더 읽을거리Further reading
- Shannon, Prediction and Entropy of Printed English (Bell System Technical Journal, 1951) — 사람에게 다음 글자를 맞히게 해서 영어의 엔트로피를 추정한 고전. 언어 모델링 평가의 원형.The classic that estimated the entropy of English by having people guess the next letter; the prototype of language-model evaluation.
- Bengio, Ducharme, Vincent, Jauvin, A Neural Probabilistic Language Model (JMLR, 2003) — count 표 대신 embedding + 신경망으로 조건부 분포를 표현. 오늘날 LLM의 직계 조상.Represents the conditional distribution with embeddings and a neural network instead of a count table; the direct ancestor of today's LLMs.
- Jurafsky & Martin, Speech and Language Processing (3rd ed. draft), Ch. 3 N-gram Language Models — n-gram, perplexity, 평활(Laplace, interpolation, Kneser–Ney)의 표준 교과서 서술.The standard textbook treatment of n-grams, perplexity and smoothing (Laplace, interpolation, Kneser–Ney).
- Chen & Goodman, An Empirical Study of Smoothing Techniques for Language Modeling (Computer Speech & Language, 1999) — 평활 기법을 체계적으로 비교. 왜 add-k가 실전에서 약한지 알 수 있다.A systematic comparison of smoothing techniques; shows why add-k is weak in practice.
- Karpathy, Neural Networks: Zero to Hero — makemore (2022) — 이 레슨의 bigram 실습과 같은 출발점에서 MLP·Transformer까지 올라가는 강의.Lectures that start from the same bigram exercise as this lesson and climb up to an MLP and a Transformer.
- Lambert, Reinforcement Learning from Human Feedback (rlhfbook.com) — 사후학습 전체를 log-prob의 조작으로 보는 관점. 이 트랙의 post-training 연결 고리.Views all of post-training as manipulating log-probs; this track's link to post-training.