At every position the model outputs a distribution over the next token, . The rule that picks one token from that distribution is decoding. With the same model, decoding alone can yield dull repetition, natural prose, or gibberish. And in post-training, decoding is not just an output option: RL learns from responses the model sampled, so the sampling rule is the distribution of the training data.
Two goals: finding the mode vs reproducing the distribution
The probability of a response is a product of conditional probabilities; take the log and it becomes a sum.
Decoding has one of two goals.
- Search: , find the single most likely sequence. There are possible sequences, so it cannot be solved exactly and is approximated with greedy or beam search. It suits closed tasks such as translation or speech recognition, where you need “one answer close to the right one”.
- Sampling: , draw from the distribution itself. Drawing one token at a time from the conditional distributions (ancestral sampling) is, by the chain rule, exactly a draw from . Open-ended tasks with many valid answers, such as dialogue and creative writing, belong here — and so do RL rollouts.
Greedy and beam search
Greedy picks the most probable token at every step. It is the best choice at each step but may not be the best for the sequence as a whole. You may pick a 0.5 token first and find that everything after it is uncertain, whereas the 0.4 token might have been followed by a confident 0.9.
Beam search keeps the top prefixes (beams) by cumulative log-prob at every step. Each beam is extended by tokens and, out of the candidates, the top are kept again. is greedy. The cumulative log-prob adds a negative number per token, so short sequences are favoured. That is why a length normalisation (length penalty) such as is usually applied (GNMT, Wu et al. 2016, divides by ).
모델은 매 위치에서 다음 토큰의 분포 를 낸다. 그 분포에서 토큰 하나를 고르는 규칙이 디코딩(decoding)이다. 같은 모델이라도 디코딩에 따라 지루한 반복, 자연스러운 글, 횡설수설이 모두 나온다. 그리고 사후학습에서 디코딩은 단순한 출력 옵션이 아니다. RL은 모델이 샘플링한 응답으로 학습하므로, 샘플링 규칙이 곧 학습 데이터의 분포다.
두 가지 목표: 최빈값 찾기 vs 분포 재현
응답 의 확률은 조건부 확률의 곱이고, 로그를 씌우면 합이다.
디코딩의 목표는 둘 중 하나다.
- 탐색(search): , 가장 그럴듯한 시퀀스 하나를 찾는다. 가능한 시퀀스가 개라 정확히 풀 수 없으니 greedy나 beam search로 근사한다. 번역·음성인식처럼 “정답에 가까운 하나”가 필요한 닫힌 과제에 맞다.
- 샘플링(sampling): , 분포 자체에서 뽑는다. 한 토큰씩 조건부 분포에서 뽑으면(ancestral sampling) 연쇄법칙에 의해 정확히 에서 뽑은 것이 된다. 대화·창작처럼 다양한 답이 가능한 열린 과제, 그리고 RL rollout이 여기에 속한다.
Greedy와 beam search
Greedy는 매 단계 가장 확률이 높은 토큰을 고른다. 각 단계에서는 최선이지만 시퀀스 전체로는 최선이 아닐 수 있다. 첫 토큰에서 확률 0.5짜리를 골랐는데 그 뒤가 전부 애매하고, 0.4짜리를 골랐다면 그 뒤가 0.9로 확실했을 수 있다.
Beam search는 매 단계 누적 log-prob 상위 개의 접두사(beam)를 유지한다. 각 beam을 개 토큰으로 확장한 개 후보 중 다시 상위 개를 남긴다. 이면 greedy다. 누적 log-prob은 토큰마다 음수를 더하므로 짧은 시퀀스가 유리하다. 그래서 보통 같은 길이 정규화(length penalty)를 쓴다(GNMT, Wu et al. 2016은 로 나눈다).
Why beam search is rarely used for open-ended generation
If beam search finds more probable sequences, it seems it should always be better — but not in open-ended generation. Holtzman et al. (2020) showed that if you measure the per-token probabilities of human-written text with a model, they are jagged: people do not always use the most obvious word. Beam search output, by contrast, has uniformly high probability at every token, and as a result it is bland and generic and, above all, prone to repetition loops, because a phrase repeated once raises the probability of the next repetition. “The most likely text” is not “human-like text”. For translation models it has even been reported that the empty string is the mode (Stahlberg & Byrne, 2019). Computationally, too, beam search has to carry the KV cache of sequences, which does not fit well with batching in inference servers.
Pure sampling and the tail problem
Then should we just sample from the distribution as is? The problem is the tail. With a vocabulary of 100k, the sum of many odd tokens, each with tiny probability, can hold non-negligible mass. If the tail totals 5%, you draw an odd token about once every 20 tokens. And once an odd token enters the context, the model keeps generating conditioned on that context, so errors compound. The methods below all address this by reshaping the distribution or cutting off the tail.
Temperature: logit scaling
Divide the logits by a temperature , then apply softmax.
The probability ratio of two tokens is . Looking at the limits:
- : for every with the ratio goes to . The distribution collapses onto the argmax. Same as greedy.
- : every , so the ratios go to 1. It becomes the uniform distribution.
- : the model’s original distribution.
There is another derivation. Find the distribution on the probability simplex that maximises “expected logit + temperature × entropy”:
So temperature is the exchange rate between “the greed to pick high logits” and “entropy (diversity)”. This has the same form as the solution of RLHF’s KL-regularised objective, , with playing the role of temperature (lessons rlhf/rlhf-ppo and rlhf/dpo).
Top-k, top-p, min-p: cutting the tail
- Top-k (Fan et al., 2018): keep only the most probable tokens and renormalise. Simple, but it ignores the shape of the distribution: it keeps tokens even where the next token is nearly certain, and cuts to even where there are many candidates.
- Top-p / nucleus (Holtzman et al., 2020): accumulate in descending order of probability and keep only the smallest set whose mass reaches . A peaked distribution keeps one or two tokens; a flat one keeps many.
- Min-p (Nguyen et al., 2024): discard tokens below a threshold proportional to the top probability, . When the model is confident the threshold is high and the tail is cut aggressively; when it is unsure the threshold is low and many candidates survive. It is reported to be especially stable at high temperature.
The entropy measures how spread out a distribution is, and can be read, like the perplexity of the previous lesson, as the “effective number of choices”.
왜 열린 생성에서 beam을 거의 안 쓰나
beam이 확률 높은 시퀀스를 더 잘 찾는다면 항상 좋을 것 같지만, 열린 생성에서는 그렇지 않다. Holtzman et al.(2020)은 사람이 쓴 글의 토큰별 확률을 모델로 재 보면 들쭉날쭉하다는 것을 보였다. 사람은 늘 가장 뻔한 단어를 쓰지 않는다. 반면 beam search의 출력은 모든 토큰이 고르게 높은 확률을 갖고, 그 결과 밋밋하고 일반적이며, 무엇보다 반복 루프에 빠지기 쉽다. 한 번 반복한 구절은 다음 반복의 확률을 더 높이기 때문이다. “가장 그럴듯한 글”은 “사람다운 글”이 아니다. 번역 모델에서는 아예 빈 문자열이 최빈값인 경우도 보고되었다(Stahlberg & Byrne, 2019). 계산 측면에서도 beam은 개 시퀀스의 KV cache를 들고 다녀야 해서 추론 서버의 배칭과 잘 맞지 않는다.
순수 샘플링과 꼬리 문제
그렇다면 분포에서 그대로 뽑으면 될까? 문제는 꼬리(tail) 다. 어휘가 10만 개이면 각각은 확률이 아주 작은 이상한 토큰들의 합이 무시할 수 없는 질량을 가질 수 있다. 꼬리 전체가 5%라면 20토큰에 한 번꼴로 이상한 토큰을 뽑는다. 그리고 한 번 이상한 토큰이 문맥에 들어가면 모델은 그 문맥에 조건부로 계속 생성하므로 오류가 누적된다. 아래 방법들은 모두 분포의 모양을 바꾸거나 꼬리를 잘라서 이 문제를 다룬다.
Temperature: logit 스케일링
logit 를 온도 으로 나눈 뒤 softmax한다.
두 토큰의 확률 비는 다. 극한을 보면
- : 인 모든 에 대해 비가 으로 간다. 분포가 argmax에 몰린다. greedy와 같다.
- : 모든 이므로 비가 1로 간다. 균등분포가 된다.
- : 모델의 원래 분포다.
또 다른 유도도 있다. 확률 단체 위에서 “기대 logit + 온도 × 엔트로피”를 최대화하는 분포를 찾으면
즉 temperature는 “높은 logit을 고르고 싶은 욕심”과 “엔트로피(다양성)” 사이의 교환비다. 이 식은 RLHF의 KL 정규화 목적함수의 해 와 같은 꼴이다. 가 온도 역할을 한다(rlhf/rlhf-ppo, rlhf/dpo 레슨).
Top-k, top-p, min-p: 꼬리 자르기
- Top-k(Fan et al., 2018): 확률 상위 개만 남기고 재정규화한다. 단순하지만 분포의 모양을 무시한다. 다음 토큰이 거의 확실한 곳에서도 개를 남기고, 후보가 많은 곳에서도 개로 자른다.
- Top-p / nucleus(Holtzman et al., 2020): 확률 내림차순으로 누적했을 때 질량이 이상이 되는 가장 작은 집합만 남긴다. 분포가 뾰족하면 한두 개, 평평하면 많이 남는다.
- Min-p(Nguyen et al., 2024): 최대 확률에 비례하는 문턱 보다 작은 토큰을 버린다. 모델이 확신할 때는 문턱이 높아 꼬리를 과감히 자르고, 확신이 없을 때는 문턱이 낮아 여러 후보를 살린다. 높은 온도와 같이 쓸 때 특히 안정적이라고 보고되었다.
엔트로피 는 분포의 퍼짐을 재는 숫자이고, 는 지난 레슨의 perplexity처럼 “실효 선택지 수”로 읽을 수 있다.
Things to check in the figure:
- In the Confident preset, lower T to 0.05: the surviving tokens stay the same but the distribution piles onto ” mat” alone (entropy ≈ 0). Raise T to 4 and the entropy approaches .
- In the Long tail preset with top-p = 0.9, many tokens survive. Apply the same top-p to the Confident preset and only a few survive. top-k keeps the same number in both cases.
- In the Confident preset (T = 1), top-p 0.9 keeps 3 tokens but min-p 0.1 keeps only 1. The top probability is 0.84, so the threshold is 0.084, and the second token (0.05) is below it. Raise T so the distribution flattens: the top probability drops, the threshold drops with it, and more tokens survive. A threshold tied to the model’s confidence is the whole point of min-p. (In real models with vocabularies of tens of thousands, the tail becomes very long at high temperature, so this difference shows up even more.)
- Press 100 samples several times: the red dots (sample frequencies) converge to the blue bars. Truncated tokens never appear.
Implementing it
Every sampler can be written as a “logit vector → logit vector” function. Set the logits of tokens to be cut to and apply softmax at the end, and renormalisation happens automatically. For each setting we compare the analytic distribution with the empirical distribution from 20,000 samples.
import numpy as np
words = ["mat", "floor", "sofa", "bed", "rug", "chair", "couch", "table",
"roof", "grass", "windowsill", "keyboard", "moon", "banana", "piano", "quantum"]
logits = np.array([6.0, 3.2, 2.6, 2.4, 2.2, 1.6, 1.4, 1.0, 0.4, 0.2, 0.1, -0.4, -1.5, -2.0, -2.2, -3.0])
def softmax(z):
e = np.exp(z - z[np.isfinite(z)].max()) # exp(-inf) = 0
return e / e.sum()
def top_k(z, k):
kth = np.sort(z)[-k]
return np.where(z >= kth, z, -np.inf)
def top_p(z, p):
probs = softmax(z)
order = np.argsort(-probs)
before = np.cumsum(probs[order]) - probs[order] # cumulative mass just before this token
keep = np.zeros(len(z), dtype=bool)
keep[order] = before < p # include up to the first token whose cumulative mass exceeds p
return np.where(keep, z, -np.inf)
def min_p(z, m):
probs = softmax(z)
return np.where(probs >= m * probs.max(), z, -np.inf)
def process(z, T=1.0, k=None, p=None, mp=None):
z = z / T # 1. temperature
if k is not None: z = top_k(z, k) # 2. top-k
if p is not None: z = top_p(z, p) # 3. top-p
if mp is not None: z = min_p(z, mp) # 4. min-p
return softmax(z)
def entropy(pr):
pr = pr[pr > 0]
return -(pr * np.log(pr)).sum()
print("T limits: ln V =", round(np.log(len(logits)), 3))
for T in [0.05, 0.5, 1.0, 2.0, 100.0]:
pr = process(logits, T)
print(f" T={T:<6} H={entropy(pr):.3f} nat p(mat)={pr[0]:.3f}")
rng = np.random.default_rng(0)
print("\nsetting kept tokens H(nat) max |analytic - empirical|")
for name, kw in [("T=1 (unchanged)", {}), ("top-k=3", {"k": 3}), ("top-p=0.9", {"p": 0.9}),
("T=2, top-p=0.9", {"T": 2.0, "p": 0.9}), ("T=2, min-p=0.1", {"T": 2.0, "mp": 0.1})]:
pr = process(logits, **kw)
draws = rng.choice(len(pr), size=20000, p=pr)
emp = np.bincount(draws.astype(np.intp), minlength=len(pr)) / len(draws) # intp: Pyodide is 32-bit
print(f"{name:<24} {int((pr > 0).sum()):>5} {entropy(pr):.3f} {np.abs(emp - pr).max():.4f}")Next we compare greedy, beam search and exhaustive search on the tree from the figure. It is written so that it works with any model, as long as you have a function that returns the next-token distribution.
tree = {"The": {"nice": (0.5, {"woman": (0.4, {"is": 0.5, "who": 0.5}),
"house": (0.3, {"is": 0.7, "was": 0.3}),
"guy": (0.3, {"is": 0.6, "said": 0.4})}),
"dog": (0.4, {"has": (0.9, {"a": 0.6, "been": 0.4}),
"runs": (0.1, {"fast": 0.8, "away": 0.2})}),
"car": (0.1, {"is": (0.6, {"red": 0.5, "fast": 0.5}),
"drives": (0.4, {"fast": 0.7, "away": 0.3})})}}
def next_dist(prefix):
"""prefix -> {next token: prob}. Empty dict at a leaf. (For an LM: softmax(logits))"""
node = tree["The"]
for w in prefix[1:]:
entry = node[w]
node = entry[1] if isinstance(entry, tuple) else {}
return {w: (e[0] if isinstance(e, tuple) else e) for w, e in node.items()}
def seq_logprob(seq):
return sum(np.log(next_dist(seq[:t])[seq[t]]) for t in range(1, len(seq)))
def beam_search(B, steps=3):
beams = [(["The"], 0.0)]
for _ in range(steps):
cand = [(s + [w], lp + np.log(p)) for s, lp in beams for w, p in next_dist(s).items()]
beams = sorted(cand, key=lambda c: -c[1])[:B] # top B by cumulative log-prob
return beams[0]
def all_sequences(prefix=["The"]):
d = next_dist(prefix)
return [prefix] if not d else [s for w in d for s in all_sequences(prefix + [w])]
for B in [1, 2, 3]:
s, lp = beam_search(B)
print(f"beam B={B} ({'greedy' if B == 1 else 'beam'}): {' '.join(s):<20} log p = {lp:.3f} p = {np.exp(lp):.3f}")
best = max(all_sequences(), key=seq_logprob)
print(f"exhaustive search max: {' '.join(best):<20} log p = {seq_logprob(best):.3f} p = {np.exp(seq_logprob(best)):.3f}")
print(f"{len(all_sequences())} sequences in total, probabilities sum to {sum(np.exp(seq_logprob(s)) for s in all_sequences()):.3f}")
# ancestral sampling reproduces the sequence distribution itself
rng = np.random.default_rng(1)
def sample():
s = ["The"]
while (d := next_dist(s)):
w = list(d); s.append(w[rng.choice(len(w), p=list(d.values()))])
return " ".join(s)
draws = [sample() for _ in range(5000)]
for seq in ["The dog has a", "The nice woman is", "The car drives fast"]:
print(f"p({seq!r}) = {np.exp(seq_logprob(seq.split())):.3f} sample frequency = {draws.count(seq) / len(draws):.3f}")The next-token probabilities are [0.5, 0.3, 0.15, 0.05]. With top-p = 0.9, how many tokens remain, and what is the renormalised probability of the first token?
The cumulative mass goes 0.5 → 0.8 → 0.95. The smallest set reaching 0.9 or more is the first three. Dividing by the remaining mass 0.95, the first token gets .
Temperature sampling with T lowered close to 0 becomes the same as which decoding method?
Since , all the mass piles onto the argmax token. Picking the argmax at every step is greedy. (Note that this is not the argmax over whole sequences.)
Summary
- Decoding has two branches: search (approximating : greedy, beam) and sampling (). Open-ended generation and RL are on the sampling side.
- Greedy is best per step, not best per sequence. Beam finds a better mode but produces bland, repetitive text in open-ended generation.
- Temperature divides the logits by : . is greedy, is uniform. It is the solution to maximising “expected logit + ·entropy”.
- Top-k cuts the tail by count, top-p by cumulative mass, min-p by ratio to the top probability. The latter two adapt to the shape of the distribution.
- Samplers and penalties all change the distribution. If the samples are used for training, that fact must be reflected in the log-prob computation.
그림에서 확인할 것:
- 확신 프리셋에서 T를 0.05까지 내리면 남은 토큰은 그대로인데 분포가 ” mat” 하나에 몰린다(엔트로피 ≈ 0). T를 4까지 올리면 엔트로피가 에 다가간다.
- 긴 꼬리 프리셋에서 top-p = 0.9로 두면 많은 토큰이 남는다. 같은 top-p를 확신 프리셋에 적용하면 몇 개만 남는다. top-k는 두 경우 모두 같은 개수다.
- 확신 프리셋(T = 1)에서 top-p 0.9는 3개를 남기지만 min-p 0.1은 1개만 남긴다. 1위 확률이 0.84라서 문턱이 0.084가 되고, 2위(0.05)가 그 아래이기 때문이다. T를 올려 분포가 평평해지면 최대 확률이 내려가고 문턱도 같이 내려가서 남는 토큰이 늘어난다. 문턱이 모델의 확신도에 연동된다는 것이 min-p의 요점이다. (어휘가 수만 개인 실제 모델에서는 높은 온도에서 꼬리가 아주 길어지므로 이 차이가 더 크게 드러난다.)
- 100개 샘플을 여러 번 누르면 빨간 점(샘플 빈도)이 파란 막대에 수렴한다. 잘린 토큰은 한 번도 나오지 않는다.
직접 구현하기
샘플러는 전부 “logit 벡터 → logit 벡터” 함수로 쓸 수 있다. 잘라 낼 토큰의 logit을 로 바꾸고 마지막에 softmax하면 재정규화가 저절로 된다. 각 설정에서 해석적 분포와 20,000번 샘플링한 경험적 분포를 비교한다.
import numpy as np
words = ["mat", "floor", "sofa", "bed", "rug", "chair", "couch", "table",
"roof", "grass", "windowsill", "keyboard", "moon", "banana", "piano", "quantum"]
logits = np.array([6.0, 3.2, 2.6, 2.4, 2.2, 1.6, 1.4, 1.0, 0.4, 0.2, 0.1, -0.4, -1.5, -2.0, -2.2, -3.0])
def softmax(z):
e = np.exp(z - z[np.isfinite(z)].max()) # exp(-inf) = 0
return e / e.sum()
def top_k(z, k):
kth = np.sort(z)[-k]
return np.where(z >= kth, z, -np.inf)
def top_p(z, p):
probs = softmax(z)
order = np.argsort(-probs)
before = np.cumsum(probs[order]) - probs[order] # 이 토큰 직전까지의 누적 질량
keep = np.zeros(len(z), dtype=bool)
keep[order] = before < p # 누적이 p를 넘는 첫 토큰까지 포함
return np.where(keep, z, -np.inf)
def min_p(z, m):
probs = softmax(z)
return np.where(probs >= m * probs.max(), z, -np.inf)
def process(z, T=1.0, k=None, p=None, mp=None):
z = z / T # 1. temperature
if k is not None: z = top_k(z, k) # 2. top-k
if p is not None: z = top_p(z, p) # 3. top-p
if mp is not None: z = min_p(z, mp) # 4. min-p
return softmax(z)
def entropy(pr):
pr = pr[pr > 0]
return -(pr * np.log(pr)).sum()
print("T 극한: ln V =", round(np.log(len(logits)), 3))
for T in [0.05, 0.5, 1.0, 2.0, 100.0]:
pr = process(logits, T)
print(f" T={T:<6} H={entropy(pr):.3f} nat p(mat)={pr[0]:.3f}")
rng = np.random.default_rng(0)
print("\n설정 남은 토큰 H(nat) 해석 vs 경험 최대 오차")
for name, kw in [("T=1 (그대로)", {}), ("top-k=3", {"k": 3}), ("top-p=0.9", {"p": 0.9}),
("T=2, top-p=0.9", {"T": 2.0, "p": 0.9}), ("T=2, min-p=0.1", {"T": 2.0, "mp": 0.1})]:
pr = process(logits, **kw)
draws = rng.choice(len(pr), size=20000, p=pr)
emp = np.bincount(draws.astype(np.intp), minlength=len(pr)) / len(draws) # intp: Pyodide는 32비트
print(f"{name:<24} {int((pr > 0).sum()):>5} {entropy(pr):.3f} {np.abs(emp - pr).max():.4f}")다음은 그림의 트리에서 greedy, beam search, 전수 탐색을 비교한다. 다음 토큰 분포를 주는 함수만 있으면 어떤 모델에도 쓸 수 있는 형태로 썼다.
tree = {"The": {"nice": (0.5, {"woman": (0.4, {"is": 0.5, "who": 0.5}),
"house": (0.3, {"is": 0.7, "was": 0.3}),
"guy": (0.3, {"is": 0.6, "said": 0.4})}),
"dog": (0.4, {"has": (0.9, {"a": 0.6, "been": 0.4}),
"runs": (0.1, {"fast": 0.8, "away": 0.2})}),
"car": (0.1, {"is": (0.6, {"red": 0.5, "fast": 0.5}),
"drives": (0.4, {"fast": 0.7, "away": 0.3})})}}
def next_dist(prefix):
"""접두사 -> {다음 토큰: 확률}. 잎이면 빈 dict. (LM이라면 softmax(logits))"""
node = tree["The"]
for w in prefix[1:]:
entry = node[w]
node = entry[1] if isinstance(entry, tuple) else {}
return {w: (e[0] if isinstance(e, tuple) else e) for w, e in node.items()}
def seq_logprob(seq):
return sum(np.log(next_dist(seq[:t])[seq[t]]) for t in range(1, len(seq)))
def beam_search(B, steps=3):
beams = [(["The"], 0.0)]
for _ in range(steps):
cand = [(s + [w], lp + np.log(p)) for s, lp in beams for w, p in next_dist(s).items()]
beams = sorted(cand, key=lambda c: -c[1])[:B] # 누적 log-prob 상위 B개
return beams[0]
def all_sequences(prefix=["The"]):
d = next_dist(prefix)
return [prefix] if not d else [s for w in d for s in all_sequences(prefix + [w])]
for B in [1, 2, 3]:
s, lp = beam_search(B)
print(f"beam B={B} ({'greedy' if B == 1 else 'beam'}): {' '.join(s):<20} log p = {lp:.3f} p = {np.exp(lp):.3f}")
best = max(all_sequences(), key=seq_logprob)
print(f"전수 탐색 최댓값 : {' '.join(best):<20} log p = {seq_logprob(best):.3f} p = {np.exp(seq_logprob(best)):.3f}")
print(f"전체 시퀀스 {len(all_sequences())}개, 확률 합 = {sum(np.exp(seq_logprob(s)) for s in all_sequences()):.3f}")
# ancestral sampling은 시퀀스 분포 자체를 재현한다
rng = np.random.default_rng(1)
def sample():
s = ["The"]
while (d := next_dist(s)):
w = list(d); s.append(w[rng.choice(len(w), p=list(d.values()))])
return " ".join(s)
draws = [sample() for _ in range(5000)]
for seq in ["The dog has a", "The nice woman is", "The car drives fast"]:
print(f"p({seq!r}) = {np.exp(seq_logprob(seq.split())):.3f} 샘플 빈도 = {draws.count(seq) / len(draws):.3f}")다음 토큰 확률이 [0.5, 0.3, 0.15, 0.05]일 때 top-p = 0.9를 적용하면 몇 개가 남고, 첫 토큰의 재정규화된 확률은?
누적 질량은 0.5 → 0.8 → 0.95. 0.9 이상이 되는 가장 작은 집합은 앞의 세 개다. 남은 질량 0.95로 나누면 첫 토큰은 .
온도 T를 0에 가깝게 내린 temperature sampling은 어떤 디코딩과 같아지나?
이므로 모든 질량이 argmax 토큰에 몰린다. 매 단계 argmax를 고르는 것은 greedy다. (시퀀스 전체의 argmax가 아니라는 점에 주의.)
정리
- 디코딩은 탐색( 근사: greedy, beam)과 샘플링() 두 갈래다. 열린 생성과 RL은 샘플링 쪽이다.
- Greedy는 단계별 최선이지 시퀀스 최선이 아니다. Beam은 더 나은 최빈값을 찾지만 열린 생성에서는 밋밋하고 반복적인 글을 낳는다.
- Temperature는 logit을 로 나누는 것: . 이면 greedy, 이면 균등. “기대 logit + ·엔트로피” 최대화의 해다.
- Top-k는 개수로, top-p는 누적 질량으로, min-p는 최대 확률 대비 비율로 꼬리를 자른다. 뒤의 둘은 분포의 모양에 적응한다.
- 샘플러와 penalty는 모두 분포를 바꾼다. 학습에 쓸 샘플이라면 그 사실을 log-prob 계산에 반영해야 한다.
더 읽을거리Further reading
- Holtzman, Buys, Du, Forbes, Choi, The Curious Case of Neural Text Degeneration (ICLR, 2020) — beam search가 왜 지루하고 반복적인 글을 만드는지 분석하고 nucleus(top-p) sampling을 제안.Analyses why beam search produces dull, repetitive text and proposes nucleus (top-p) sampling.
- Fan, Lewis, Dauphin, Hierarchical Neural Story Generation (ACL, 2018) — top-k sampling을 대중화한 이야기 생성 논문.The story-generation paper that popularised top-k sampling.
- Nguyen et al., Turning Up the Heat: Min-p Sampling for Creative and Coherent LLM Outputs (2024) — 최대 확률에 비례하는 임계값으로 자르는 min-p. 높은 온도에서도 일관성을 유지한다.Min-p, which truncates at a threshold proportional to the top probability; stays coherent even at high temperature.
- Keskar et al., CTRL: A Conditional Transformer Language Model for Controllable Generation (2019) — 이미 나온 토큰의 logit을 깎는 repetition penalty의 출처.Source of the repetition penalty, which shrinks the logits of tokens already generated.
- Wu et al., Google's Neural Machine Translation System (2016) — beam search의 길이 정규화(length penalty)를 포함한 실전 번역 디코딩.Production translation decoding, including length normalisation (length penalty) for beam search.
- von Platen, How to generate text: using different decoding methods (Hugging Face blog, 2020) — greedy·beam·top-k·top-p를 예제로 비교. 이 레슨 트리 그림의 "The nice woman / The dog has" 예가 여기서 왔다.Compares greedy, beam, top-k and top-p with examples; the "The nice woman / The dog has" tree in this lesson's figure comes from here.