Track III · LLM Fundamentals · 04/07

디코딩Decoding

모델이 낸 다음 토큰 분포를 실제 텍스트로 바꾸는 규칙들. greedy·beam이 찾는 "가장 그럴듯한 시퀀스"와 sampling이 재현하는 "분포"의 차이, temperature를 logit 스케일링으로 유도하고 top-k·top-p·min-p가 분포를 어떻게 자르는지 직접 조작해 본다.The rules that turn the model's next-token distribution into actual text. The difference between the "most likely sequence" that greedy and beam search look for and the "distribution" that sampling reproduces; temperature derived as logit scaling, and a hands-on look at how top-k, top-p and min-p cut the distribution.

35 분min decoding · sampling · temperature · top-k · top-p · min-p · beam search · entropy 먼저 볼 것:Before this: GPT를 바닥부터GPT from scratch

At every position the model outputs a distribution over the next token, pθ(⋅∣x,y<t)p_\theta(\cdot \mid x, y_{<t}). 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 y=(y1,…,yT)y = (y_1, \dots, y_T) is a product of conditional probabilities; take the log and it becomes a sum.

log⁡pθ(y∣x)=∑t=1Tlog⁡pθ(yt∣x,y<t)\log p_\theta(y \mid x) = \sum_{t=1}^{T} \log p_\theta(y_t \mid x, y_{<t})

Decoding has one of two goals.

  1. Search: arg⁡max⁡ypθ(y∣x)\arg\max_y p_\theta(y \mid x), find the single most likely sequence. There are VTV^T 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”.
  2. Sampling: y∼pθ(⋅∣x)y \sim p_\theta(\cdot \mid x), 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 pθ(y∣x)p_\theta(y \mid x). Open-ended tasks with many valid answers, such as dialogue and creative writing, belong here — and so do RL rollouts.

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 BB prefixes (beams) by cumulative log-prob at every step. Each beam is extended by VV tokens and, out of the B⋅VB \cdot V candidates, the top BB are kept again. B=1B = 1 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 log⁡p(y)/∣y∣α\log p(y) / |y|^\alpha is usually applied (GNMT, Wu et al. 2016, divides by ((5+∣y∣)/6)α\big((5+|y|)/6\big)^\alpha).

모델은 매 위치에서 다음 토큰의 분포 pθ(⋅∣x,y<t)p_\theta(\cdot \mid x, y_{<t})를 낸다. 그 분포에서 토큰 하나를 고르는 규칙이 디코딩(decoding)이다. 같은 모델이라도 디코딩에 따라 지루한 반복, 자연스러운 글, 횡설수설이 모두 나온다. 그리고 사후학습에서 디코딩은 단순한 출력 옵션이 아니다. RL은 모델이 샘플링한 응답으로 학습하므로, 샘플링 규칙이 곧 학습 데이터의 분포다.

두 가지 목표: 최빈값 찾기 vs 분포 재현

응답 y=(y1,…,yT)y = (y_1, \dots, y_T)의 확률은 조건부 확률의 곱이고, 로그를 씌우면 합이다.

log⁡pθ(y∣x)=∑t=1Tlog⁡pθ(yt∣x,y<t)\log p_\theta(y \mid x) = \sum_{t=1}^{T} \log p_\theta(y_t \mid x, y_{<t})

디코딩의 목표는 둘 중 하나다.

  1. 탐색(search): arg⁡max⁡ypθ(y∣x)\arg\max_y p_\theta(y \mid x), 가장 그럴듯한 시퀀스 하나를 찾는다. 가능한 시퀀스가 VTV^T개라 정확히 풀 수 없으니 greedy나 beam search로 근사한다. 번역·음성인식처럼 “정답에 가까운 하나”가 필요한 닫힌 과제에 맞다.
  2. 샘플링(sampling): y∼pθ(⋅∣x)y \sim p_\theta(\cdot \mid x), 분포 자체에서 뽑는다. 한 토큰씩 조건부 분포에서 뽑으면(ancestral sampling) 연쇄법칙에 의해 정확히 pθ(y∣x)p_\theta(y \mid x)에서 뽑은 것이 된다. 대화·창작처럼 다양한 답이 가능한 열린 과제, 그리고 RL rollout이 여기에 속한다.

Greedy는 매 단계 가장 확률이 높은 토큰을 고른다. 각 단계에서는 최선이지만 시퀀스 전체로는 최선이 아닐 수 있다. 첫 토큰에서 확률 0.5짜리를 골랐는데 그 뒤가 전부 애매하고, 0.4짜리를 골랐다면 그 뒤가 0.9로 확실했을 수 있다.

Beam search는 매 단계 누적 log-prob 상위 BB개의 접두사(beam)를 유지한다. 각 beam을 VV개 토큰으로 확장한 B⋅VB \cdot V개 후보 중 다시 상위 BB개를 남긴다. B=1B = 1이면 greedy다. 누적 log-prob은 토큰마다 음수를 더하므로 짧은 시퀀스가 유리하다. 그래서 보통 log⁡p(y)/∣y∣α\log p(y) / |y|^\alpha 같은 길이 정규화(length penalty)를 쓴다(GNMT, Wu et al. 2016은 ((5+∣y∣)/6)α\big((5+|y|)/6\big)^\alpha로 나눈다).

A small tree that appends three tokens after "The". Numbers on edges are conditional probabilities; numbers at the leaves are sequence probabilities p(y). Greedy takes the largest edge at every step (nice, 0.5), but its sequence probability is only 0.1. Beam keeps the top B by cumulative probability at every step (faded nodes are pruned). Already at B=2 it finds "dog has a" (0.216). Press 1000 samples and the bars to the right of the leaves (red) grow to match the sequence probabilities (grey ticks). Sampling reproduces the whole distribution, not its mode. "The" 뒤에 세 토큰을 이어 붙이는 작은 트리. 간선의 숫자는 조건부 확률, 끝(잎)의 숫자는 시퀀스 확률 p(y)이다. Greedy는 매 단계 가장 큰 간선(nice, 0.5)을 고르지만 시퀀스 확률은 0.1에 그친다. Beam은 단계마다 누적 확률 상위 B개를 남긴다(흐린 노드는 탈락). B=2만 되어도 "dog has a"(0.216)를 찾는다. 샘플 1000개를 누르면 잎 오른쪽 막대(빨강)가 시퀀스 확률(회색 눈금)에 맞춰 자란다. 샘플링은 최빈값이 아니라 분포 전체를 재현한다.

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 BB 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 zz by a temperature T>0T > 0, then apply softmax.

pT(v)=exp⁡(zv/T)∑uexp⁡(zu/T)  ∝  p(v)1/Tp_T(v) = \frac{\exp(z_v / T)}{\sum_u \exp(z_u / T)} \;\propto\; p(v)^{1/T}

The probability ratio of two tokens is pT(v)/pT(u)=exp⁡((zv−zu)/T)p_T(v)/p_T(u) = \exp\big((z_v - z_u)/T\big). Looking at the limits:

  • T→0T \to 0: for every vv with zv<zmax⁡z_v < z_{\max} the ratio goes to exp⁡(−∞)=0\exp(-\infty) = 0. The distribution collapses onto the argmax. Same as greedy.
  • T→∞T \to \infty: every zv/T→0z_v/T \to 0, so the ratios go to 1. It becomes the uniform distribution.
  • T=1T = 1: the model’s original distribution.

There is another derivation. Find the distribution on the probability simplex that maximises “expected logit + temperature × entropy”:

max⁡p  ∑vpvzv+T H(p)s.t. ∑vpv=1    ⇒    zv−T(log⁡pv+1)−λ=0  ⇒  pv∝ezv/T\max_{p}\; \sum_v p_v z_v + T\, H(p) \quad \text{s.t. } \textstyle\sum_v p_v = 1 \;\;\Rightarrow\;\; z_v - T(\log p_v + 1) - \lambda = 0 \;\Rightarrow\; p_v \propto e^{z_v / T}

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, π∗(y)∝πref(y)exp⁡(r(y)/β)\pi^*(y) \propto \pi_{\text{ref}}(y) \exp(r(y)/\beta), with β\beta 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 kk most probable tokens and renormalise. Simple, but it ignores the shape of the distribution: it keeps kk tokens even where the next token is nearly certain, and cuts to kk 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 pp. 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, pmin⁡⋅max⁡vp(v)p_{\min} \cdot \max_v p(v). 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 H(p)=−∑vp(v)log⁡p(v)H(p) = -\sum_v p(v)\log p(v) measures how spread out a distribution is, and eHe^{H} 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은 BB개 시퀀스의 KV cache를 들고 다녀야 해서 추론 서버의 배칭과 잘 맞지 않는다.

순수 샘플링과 꼬리 문제

그렇다면 분포에서 그대로 뽑으면 될까? 문제는 꼬리(tail) 다. 어휘가 10만 개이면 각각은 확률이 아주 작은 이상한 토큰들의 합이 무시할 수 없는 질량을 가질 수 있다. 꼬리 전체가 5%라면 20토큰에 한 번꼴로 이상한 토큰을 뽑는다. 그리고 한 번 이상한 토큰이 문맥에 들어가면 모델은 그 문맥에 조건부로 계속 생성하므로 오류가 누적된다. 아래 방법들은 모두 분포의 모양을 바꾸거나 꼬리를 잘라서 이 문제를 다룬다.

Temperature: logit 스케일링

logit zz를 온도 T>0T > 0으로 나눈 뒤 softmax한다.

pT(v)=exp⁡(zv/T)∑uexp⁡(zu/T)  ∝  p(v)1/Tp_T(v) = \frac{\exp(z_v / T)}{\sum_u \exp(z_u / T)} \;\propto\; p(v)^{1/T}

두 토큰의 확률 비는 pT(v)/pT(u)=exp⁡((zv−zu)/T)p_T(v)/p_T(u) = \exp\big((z_v - z_u)/T\big)다. 극한을 보면

  • T→0T \to 0: zv<zmax⁡z_v < z_{\max}인 모든 vv에 대해 비가 exp⁡(−∞)=0\exp(-\infty) = 0으로 간다. 분포가 argmax에 몰린다. greedy와 같다.
  • T→∞T \to \infty: 모든 zv/T→0z_v/T \to 0이므로 비가 1로 간다. 균등분포가 된다.
  • T=1T = 1: 모델의 원래 분포다.

또 다른 유도도 있다. 확률 단체 위에서 “기대 logit + 온도 × 엔트로피”를 최대화하는 분포를 찾으면

max⁡p  ∑vpvzv+T H(p)s.t. ∑vpv=1    ⇒    zv−T(log⁡pv+1)−λ=0  ⇒  pv∝ezv/T\max_{p}\; \sum_v p_v z_v + T\, H(p) \quad \text{s.t. } \textstyle\sum_v p_v = 1 \;\;\Rightarrow\;\; z_v - T(\log p_v + 1) - \lambda = 0 \;\Rightarrow\; p_v \propto e^{z_v / T}

즉 temperature는 “높은 logit을 고르고 싶은 욕심”과 “엔트로피(다양성)” 사이의 교환비다. 이 식은 RLHF의 KL 정규화 목적함수의 해 π∗(y)∝πref(y)exp⁡(r(y)/β)\pi^*(y) \propto \pi_{\text{ref}}(y) \exp(r(y)/\beta)와 같은 꼴이다. β\beta가 온도 역할을 한다(rlhf/rlhf-ppo, rlhf/dpo 레슨).

Top-k, top-p, min-p: 꼬리 자르기

  • Top-k(Fan et al., 2018): 확률 상위 kk개만 남기고 재정규화한다. 단순하지만 분포의 모양을 무시한다. 다음 토큰이 거의 확실한 곳에서도 kk개를 남기고, 후보가 많은 곳에서도 kk개로 자른다.
  • Top-p / nucleus(Holtzman et al., 2020): 확률 내림차순으로 누적했을 때 질량이 pp 이상이 되는 가장 작은 집합만 남긴다. 분포가 뾰족하면 한두 개, 평평하면 많이 남는다.
  • Min-p(Nguyen et al., 2024): 최대 확률에 비례하는 문턱 pmin⁡⋅max⁡vp(v)p_{\min} \cdot \max_v p(v)보다 작은 토큰을 버린다. 모델이 확신할 때는 문턱이 높아 꼬리를 과감히 자르고, 확신이 없을 때는 문턱이 낮아 여러 후보를 살린다. 높은 온도와 같이 쓸 때 특히 안정적이라고 보고되었다.

엔트로피 H(p)=−∑vp(v)log⁡p(v)H(p) = -\sum_v p(v)\log p(v)는 분포의 퍼짐을 재는 숫자이고, eHe^{H}는 지난 레슨의 perplexity처럼 “실효 선택지 수”로 읽을 수 있다.

logit 프리셋logit preset 위 막대를 위아래로 끌어 logit을 직접 바꿀 수 있다drag the top bars up or down to edit the logits
남은 토큰tokens kept – 엔트로피entropy – 실효 선택지effective choices eH – 원래(T=1) 엔트로피original (T=1) entropy – 샘플samples 0
Next-token logits (top) and the sampling distribution (bottom) for the context "The cat sat on the ___". In the bottom bars the grey outline is the untouched softmax, the coloured bar is the distribution actually sampled after processing, and faded slots are tokens that were cut. The order is T → top-k → top-p → min-p → renormalise. Push T all the way left to the end stop T = 0 (greedy): only the argmax survives. One notch to the right, T = 0.05 is still a distribution, not greedy; on the flat preset the top two tokens keep about 83% and 11%, since greedy is only the T → 0 limit. All the way right (T ≈ 4) it approaches uniform. Compare top-k and top-p on the long tail preset: top-k cuts by count regardless of the shape of the distribution, while top-p and min-p keep many tokens when it is flat and few when it is peaked. 문맥 "The cat sat on the ___"의 다음 토큰 logit(위)과 샘플링 분포(아래). 아래 막대의 회색 윤곽은 아무 처리도 안 한 softmax, 색 막대는 처리 후 실제로 뽑는 분포, 흐린 칸은 잘려 나간 토큰이다. 처리 순서는 T → top-k → top-p → min-p → 재정규화. T를 왼쪽 끝으로 보내면 끝 칸이 T = 0(greedy)이고 argmax 하나만 남는다. 한 칸 오른쪽인 T = 0.05는 아직 분포이지 greedy가 아니다. 평평 프리셋에서는 상위 두 토큰이 약 83%와 11%를 나눠 갖는데, greedy는 T → 0의 극한일 뿐이기 때문이다. 오른쪽 끝(T ≈ 4)으로 보내면 균등분포에 가까워진다. 긴 꼬리 프리셋에서 top-k와 top-p를 비교해 보자. top-k는 분포 모양과 무관하게 개수로 자르고, top-p와 min-p는 분포가 평평하면 많이, 뾰족하면 적게 남긴다.

Things to check in the figure:

  1. 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 ln⁡16≈2.77\ln 16 \approx 2.77.
  2. 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.
  3. 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.)
  4. 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 −∞-\infty 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.

NumPy temperature · top-k · top-p · min-p samplers and an empirical check
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.

NumPy Sequence log-prob, 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):
    """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}")
 
확인 문제Check yourself

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 0.5/0.95≈0.5260.5/0.95 \approx 0.526.

확인 문제Check yourself

Temperature sampling with T lowered close to 0 becomes the same as which decoding method?

Since pT(v)/pT(v∗)=exp⁡((zv−zmax⁡)/T)→0p_T(v)/p_T(v^*) = \exp((z_v - z_{\max})/T) \to 0, 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 arg⁡max⁡yp(y)\arg\max_y p(y): greedy, beam) and sampling (y∼py \sim p). 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 TT: pT∝p1/Tp_T \propto p^{1/T}. T→0T \to 0 is greedy, T→∞T \to \infty is uniform. It is the solution to maximising “expected logit + TT·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.

그림에서 확인할 것:

  1. 확신 프리셋에서 T를 0.05까지 내리면 남은 토큰은 그대로인데 분포가 ” mat” 하나에 몰린다(엔트로피 ≈ 0). T를 4까지 올리면 엔트로피가 ln⁡16≈2.77\ln 16 \approx 2.77에 다가간다.
  2. 긴 꼬리 프리셋에서 top-p = 0.9로 두면 많은 토큰이 남는다. 같은 top-p를 확신 프리셋에 적용하면 몇 개만 남는다. top-k는 두 경우 모두 같은 개수다.
  3. 확신 프리셋(T = 1)에서 top-p 0.9는 3개를 남기지만 min-p 0.1은 1개만 남긴다. 1위 확률이 0.84라서 문턱이 0.084가 되고, 2위(0.05)가 그 아래이기 때문이다. T를 올려 분포가 평평해지면 최대 확률이 내려가고 문턱도 같이 내려가서 남는 토큰이 늘어난다. 문턱이 모델의 확신도에 연동된다는 것이 min-p의 요점이다. (어휘가 수만 개인 실제 모델에서는 높은 온도에서 꼬리가 아주 길어지므로 이 차이가 더 크게 드러난다.)
  4. 100개 샘플을 여러 번 누르면 빨간 점(샘플 빈도)이 파란 막대에 수렴한다. 잘린 토큰은 한 번도 나오지 않는다.

직접 구현하기

샘플러는 전부 “logit 벡터 → logit 벡터” 함수로 쓸 수 있다. 잘라 낼 토큰의 logit을 −∞-\infty로 바꾸고 마지막에 softmax하면 재정규화가 저절로 된다. 각 설정에서 해석적 분포와 20,000번 샘플링한 경험적 분포를 비교한다.

NumPy temperature · top-k · top-p · min-p 샘플러와 경험적 확인
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, 전수 탐색을 비교한다. 다음 토큰 분포를 주는 함수만 있으면 어떤 모델에도 쓸 수 있는 형태로 썼다.

NumPy 시퀀스 log-prob, 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}")
 
확인 문제Check yourself

다음 토큰 확률이 [0.5, 0.3, 0.15, 0.05]일 때 top-p = 0.9를 적용하면 몇 개가 남고, 첫 토큰의 재정규화된 확률은?

누적 질량은 0.5 → 0.8 → 0.95. 0.9 이상이 되는 가장 작은 집합은 앞의 세 개다. 남은 질량 0.95로 나누면 첫 토큰은 0.5/0.95≈0.5260.5/0.95 \approx 0.526.

확인 문제Check yourself

온도 T를 0에 가깝게 내린 temperature sampling은 어떤 디코딩과 같아지나?

pT(v)/pT(v∗)=exp⁡((zv−zmax⁡)/T)→0p_T(v)/p_T(v^*) = \exp((z_v - z_{\max})/T) \to 0 이므로 모든 질량이 argmax 토큰에 몰린다. 매 단계 argmax를 고르는 것은 greedy다. (시퀀스 전체의 argmax가 아니라는 점에 주의.)

정리

  • 디코딩은 탐색(arg⁡max⁡yp(y)\arg\max_y p(y) 근사: greedy, beam)과 샘플링(y∼py \sim p) 두 갈래다. 열린 생성과 RL은 샘플링 쪽이다.
  • Greedy는 단계별 최선이지 시퀀스 최선이 아니다. Beam은 더 나은 최빈값을 찾지만 열린 생성에서는 밋밋하고 반복적인 글을 낳는다.
  • Temperature는 logit을 TT로 나누는 것: pT∝p1/Tp_T \propto p^{1/T}. T→0T \to 0이면 greedy, T→∞T \to \infty이면 균등. “기대 logit + TT·엔트로피” 최대화의 해다.
  • Top-k는 개수로, top-p는 누적 질량으로, min-p는 최대 확률 대비 비율로 꼬리를 자른다. 뒤의 둘은 분포의 모양에 적응한다.
  • 샘플러와 penalty는 모두 분포를 바꾼다. 학습에 쓸 샘플이라면 그 사실을 log-prob 계산에 반영해야 한다.

더 읽을거리Further reading