Track 0 · Math Foundations · 09/10

극값과 Gumbel 트릭Extremes: maxima, tails and the Gumbel trick

N개 중 최댓값의 분포(N·F^(N−1)·f), 최댓값이 √(2 ln N)보다 느리게 자라는 이유와 보정식 z_N, 로그정규 꼬리의 straggler, Gumbel 극한과 logsumexp, Gumbel-max·top-k 샘플링과 Bradley–Terry를 Best-of-N·rollout 꼬리·MoE 부하에 바로 쓸 수 있게 정리한다.The distribution of the largest of N draws (N·F^(N−1)·f), why it grows like √(2 ln N) and the sharper z_N, log-normal stragglers, the Gumbel limit and its link to logsumexp, and Gumbel-max / top-k sampling and Bradley–Terry — the tools behind Best-of-N, rollout tails and MoE load.

35 분min order statistics · extreme values · maximum · Gumbel · Gumbel-max · Gumbel-top-k · log-normal · quantile · best-of-N · Bradley-Terry 먼저 볼 것:Before this: 확률Probability, 통계와 추정Statistics and estimation

Averages are what most statistics is about, but many numbers on this site are maxima. Best-of-N keeps the highest-reward sample. A synchronous RL step waits for the longest rollout. An expert-parallel MoE layer waits for the busiest GPU. Sampling from a softmax can be written as an argmax of noisy logits. This lesson collects the few facts about maxima that those lessons use, and derives them.

The distribution of the maximum

Let X1,…,XNX_1, \ldots, X_N be i.i.d. with CDF FF and density ff, and MN=max⁡iXiM_N = \max_i X_i. The max is below xx exactly when every draw is, so

P(MN≤x)=F(x)N,fMN(x)=N F(x)N−1f(x).P(M_N \le x) = F(x)^N, \qquad f_{M_N}(x) = N\,F(x)^{N-1} f(x).

The density reweights ff by NFN−1NF^{N-1}, which is tiny wherever FF is not close to 1: the maximum lives in the top tail, and only the tail of FF matters. (The minimum is the mirror image: P(min⁡>x)=(1−F(x))NP(\min > x) = (1 - F(x))^N.)

It is often cleaner to work with the rank U=F(MN)U = F(M_N). Since F(Xi)F(X_i) is uniform, UU is the largest of NN uniforms, with P(U≤u)=uNP(U \le u) = u^N — a Beta(N,1)\mathrm{Beta}(N, 1) law with E[U]=NN+1\mathbb{E}[U] = \frac{N}{N+1}. So the maximum sits around the 1−1N+11 - \frac1{N+1} quantile, whatever FF is, and

P(MN≤F−1(1−1N))=(1−1N)N→e−1≈0.37.P\big(M_N \le F^{-1}(1 - \tfrac1N)\big) = \big(1 - \tfrac1N\big)^N \to e^{-1} \approx 0.37 .

The rule of thumb used everywhere below: the typical maximum of NN draws is the 1−1/N1 - 1/N quantile, i.e. the xx solving N (1−F(x))=1N\,(1 - F(x)) = 1.

How fast the maximum grows

For a standard normal, 1−Φ(z)1 - \Phi(z) has no closed form, but for large zz the Mills-ratio approximation 1−Φ(z)≈φ(z)/z1 - \Phi(z) \approx \varphi(z)/z is accurate. Taking logs of Nφ(z)/z=1N\varphi(z)/z = 1:

z22+ln⁡z+12ln⁡2π=ln⁡N.\tfrac{z^2}{2} + \ln z + \tfrac12\ln 2\pi = \ln N .

The leading term gives z≈s=2ln⁡Nz \approx s = \sqrt{2\ln N}. Put z=s+δz = s + \delta, use z2/2≈s2/2+sδz^2/2 \approx s^2/2 + s\delta and ln⁡z≈ln⁡s=12(ln⁡2+ln⁡ln⁡N)\ln z \approx \ln s = \tfrac12(\ln 2 + \ln\ln N):

zN=2ln⁡N−ln⁡ln⁡N+ln⁡4π22ln⁡N.z_N = \sqrt{2\ln N} - \frac{\ln\ln N + \ln 4\pi}{2\sqrt{2\ln N}} .

The correction is not small for practical NN: for N=64N = 64, 2ln⁡N=2.88\sqrt{2\ln N} = 2.88 but zN=2.20z_N = 2.20, close to the exact median of the max (2.30). The fluctuations shrink too: the max has spread of order 1/2ln⁡N1/\sqrt{2\ln N} (below). Three consequences used on the site:

  • Best-of-N gains are logarithmic. Each factor of 4 in NN adds less reward than the last (with standard normal rewards, 4→16 adds 0.73, 64→256 adds 0.47), while cost grows linearly.
  • Log-normal tails are multiplicative. If lengths are ℓ=eμ+σZ\ell = e^{\mu + \sigma Z}, the longest of NN is about eμ+σzNe^{\mu + \sigma z_N}, while the mean is eμ+σ2/2e^{\mu + \sigma^2/2}. The ratio eσzN−σ2/2e^{\sigma z_N - \sigma^2/2} is the fraction of a synchronous rollout step spent waiting; it grows exponentially in σ\sigma. (The mean of the max is larger still, because eσMNe^{\sigma M_N} is convex in the spread of MNM_N.)
  • Sums of many small things are nearly normal. If each of GG GPUs receives about Poisson(μ\mu) tokens, the busiest has about μ+zGμ\mu + z_G\sqrt{\mu}, an imbalance of 1+zG/μ1 + z_G/\sqrt\mu that only more tokens per GPU can shrink.

Tails decide everything: for exponential tails the max grows like ln⁡N\ln N (for Exp(1), E[MN]=1+12+⋯+1N≈ln⁡N+γ\mathbb{E}[M_N] = 1 + \tfrac12 + \cdots + \tfrac1N \approx \ln N + \gamma), for power-law tails P(X>x)∼x−αP(X > x) \sim x^{-\alpha} it grows like N1/αN^{1/\alpha}, and for bounded variables it saturates.

통계는 대부분 평균을 다루지만, 이 사이트의 많은 숫자는 최댓값이다. Best-of-N은 보상이 가장 높은 샘플을 남긴다. 동기식 RL step은 가장 긴 rollout을 기다린다. expert-parallel MoE 층은 가장 바쁜 GPU를 기다린다. softmax에서 샘플링하는 것도 잡음 섞인 logit의 argmax로 쓸 수 있다. 이 레슨은 그 레슨들이 쓰는 최댓값에 관한 몇 가지 사실을 모아서 유도한다.

최댓값의 분포

X1,…,XNX_1, \ldots, X_N이 CDF FF, 밀도 ff로 i.i.d.이고 MN=max⁡iXiM_N = \max_i X_i라 하자. 최댓값이 xx 아래인 것은 모든 표본이 xx 아래인 것과 같으므로

P(MN≤x)=F(x)N,fMN(x)=N F(x)N−1f(x).P(M_N \le x) = F(x)^N, \qquad f_{M_N}(x) = N\,F(x)^{N-1} f(x).

밀도는 ff를 NFN−1NF^{N-1}로 다시 가중한 것이고, 이 가중치는 FF가 1에 가깝지 않은 곳에서 아주 작다. 최댓값은 위쪽 꼬리에 살고, FF의 꼬리만 중요하다. (최솟값은 거울상이다: P(min⁡>x)=(1−F(x))NP(\min > x) = (1 - F(x))^N.)

순위 U=F(MN)U = F(M_N)로 보면 더 깔끔할 때가 많다. F(Xi)F(X_i)는 균등분포이므로 UU는 균등분포 NN개 중 최댓값이고, P(U≤u)=uNP(U \le u) = u^N, 곧 E[U]=NN+1\mathbb{E}[U] = \frac{N}{N+1}인 Beta(N,1)\mathrm{Beta}(N, 1) 분포다. 그래서 FF가 무엇이든 최댓값은 1−1N+11 - \frac1{N+1} 분위수 근처에 있고

P(MN≤F−1(1−1N))=(1−1N)N→e−1≈0.37.P\big(M_N \le F^{-1}(1 - \tfrac1N)\big) = \big(1 - \tfrac1N\big)^N \to e^{-1} \approx 0.37 .

아래 어디서나 쓰는 어림 규칙: NN개 중 전형적인 최댓값은 1−1/N1 - 1/N 분위수, 곧 N (1−F(x))=1N\,(1 - F(x)) = 1을 푸는 xx다.

최댓값은 얼마나 빨리 자라나

표준정규에서 1−Φ(z)1 - \Phi(z)는 닫힌 꼴이 없지만, 큰 zz에서는 Mills 비 근사 1−Φ(z)≈φ(z)/z1 - \Phi(z) \approx \varphi(z)/z가 정확하다. Nφ(z)/z=1N\varphi(z)/z = 1에 로그를 취하면

z22+ln⁡z+12ln⁡2π=ln⁡N.\tfrac{z^2}{2} + \ln z + \tfrac12\ln 2\pi = \ln N .

주항에서 z≈s=2ln⁡Nz \approx s = \sqrt{2\ln N}이다. z=s+δz = s + \delta로 두고 z2/2≈s2/2+sδz^2/2 \approx s^2/2 + s\delta, ln⁡z≈ln⁡s=12(ln⁡2+ln⁡ln⁡N)\ln z \approx \ln s = \tfrac12(\ln 2 + \ln\ln N)을 쓰면

zN=2ln⁡N−ln⁡ln⁡N+ln⁡4π22ln⁡N.z_N = \sqrt{2\ln N} - \frac{\ln\ln N + \ln 4\pi}{2\sqrt{2\ln N}} .

실용적인 NN에서 이 보정은 작지 않다. N=64N = 64에서 2ln⁡N=2.88\sqrt{2\ln N} = 2.88이지만 zN=2.20z_N = 2.20이고, 최댓값의 정확한 중앙값(2.30)에 가깝다. 요동도 줄어든다. 최댓값의 퍼짐은 1/2ln⁡N1/\sqrt{2\ln N} 정도다(아래). 이 사이트에서 쓰이는 결과 세 가지.

  • Best-of-N의 이득은 로그적이다. NN을 4배 할 때마다 더해지는 보상이 직전보다 작고(표준정규 보상이면 4→16에서 0.73, 64→256에서 0.47), 비용은 선형으로 는다.
  • 로그정규 꼬리는 곱셈적이다. 길이가 ℓ=eμ+σZ\ell = e^{\mu + \sigma Z}면 NN개 중 가장 긴 것은 약 eμ+σzNe^{\mu + \sigma z_N}이고 평균은 eμ+σ2/2e^{\mu + \sigma^2/2}다. 비 eσzN−σ2/2e^{\sigma z_N - \sigma^2/2}는 동기식 rollout step이 기다리며 보내는 몫이고, σ\sigma에 대해 지수적으로 커진다. (최댓값의 평균은 더 크다. eσMNe^{\sigma M_N}이 MNM_N의 퍼짐에 대해 볼록하기 때문이다.)
  • 작은 것 여럿의 합은 거의 정규다. GPU GG개가 각각 대략 Poisson(μ\mu)개의 토큰을 받으면 가장 바쁜 GPU는 약 μ+zGμ\mu + z_G\sqrt{\mu}개, 불균형은 1+zG/μ1 + z_G/\sqrt\mu이고, GPU당 토큰을 늘려야만 줄어든다.

모든 것은 꼬리가 정한다. 지수 꼬리면 최댓값은 ln⁡N\ln N처럼 자라고(Exp(1)이면 E[MN]=1+12+⋯+1N≈ln⁡N+γ\mathbb{E}[M_N] = 1 + \tfrac12 + \cdots + \tfrac1N \approx \ln N + \gamma), 거듭제곱 꼬리 P(X>x)∼x−αP(X > x) \sim x^{-\alpha}면 N1/αN^{1/\alpha}처럼 자라며, 유계 변수면 포화한다.

E[max Z] – √(2 ln N) – zN – sd(max) – E[max ℓ] / E[ℓ] –
Left: the density of one standard normal draw (grey) and of the largest of N draws, N·FN−1·f (red). Drag N: each doubling moves the maximum right by less than the last, and it gets narrower. √(2 ln N) (amber) overestimates it for any practical N; the corrected zN (green) lands near the peak. Right: the same maximum for log-normal lengths ℓ = eσZ, as a multiple of the mean length — how long a synchronous batch of N rollouts waits for its slowest member. Raise σ and it grows exponentially in σ. 왼쪽: 표준정규 한 번(회색)과 N번 중 최댓값(빨강)의 밀도 N·FN−1·f. N을 끌면 두 배로 늘릴 때마다 최댓값이 오른쪽으로 가는 폭이 직전보다 작아지고, 분포는 좁아진다. √(2 ln N)(주황)은 실용적인 N에서 언제나 과대추정이고, 보정한 zN(초록)이 봉우리 근처에 놓인다. 오른쪽: 길이가 로그정규 ℓ = eσZ일 때 같은 최댓값을 평균 길이의 배수로 그렸다. rollout N개짜리 동기 배치가 가장 느린 하나를 기다리는 시간이다. σ를 올리면 σ에 대해 지수적으로 커진다.
NumPy The maximum of N: exact, asymptotic, and three uses
import numpy as np
from math import erfc, sqrt, log, exp, pi
rs = np.random.default_rng(0)
GAMMA = 0.5772156649

def Phi(z):
    """Standard normal CDF (works on arrays)."""
    return 1 - 0.5 * np.vectorize(erfc)(np.asarray(z) / sqrt(2))

def z_N(N):
    """Centre of the max of N standard normals: solves N * (1 - Phi(z)) = 1 to second order."""
    s = sqrt(2 * log(N))
    return s - (log(log(N)) + log(4 * pi)) / (2 * s)

def median_max(N):
    """Exact median of the max: Phi(m)^N = 1/2, by bisection."""
    lo, hi = -5.0, 8.0
    for _ in range(60):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if Phi(mid) ** N < 0.5 else (lo, mid)
    return lo

print("    N  E[max] MC  sd(max)  sqrt(2lnN)   z_N   z_N+gamma/sqrt(2lnN)  exact median")
for N in [4, 16, 64, 256, 1024, 4096]:
    M = rs.standard_normal((400_000 // N + 400, N)).max(1)
    s = sqrt(2 * log(N))
    print(f"{N:5d}  {M.mean():8.3f}  {M.std():7.3f}  {s:9.3f}  {z_N(N):6.3f}  {z_N(N) + GAMMA / s:12.3f}  {median_max(N):14.3f}")

# Best-of-N: the max is a quantile. Its CDF rank U = F(max) is Beta(N, 1): E[U] = N/(N+1)
N = 16
U = Phi(rs.standard_normal((20_000, N)).max(1))
print(f"\nBoN N={N}: E[F(max)] = {U.mean():.4f} vs N/(N+1) = {N / (N + 1):.4f};  "
      f"P(max below the 1-1/N quantile) = {(U < 1 - 1 / N).mean():.3f}  (exact (1-1/N)^N = {(1 - 1 / N) ** N:.3f} -> 1/e)")

# Stragglers: lengths l = exp(sigma Z); the slowest of N sets a synchronous step
sigma, N = 0.9, 64
L = np.exp(sigma * rs.standard_normal((20_000, N)))
print(f"\nlog-normal lengths, sigma={sigma}, N={N}: E[max]/E[mean] = {L.max(1).mean() / L.mean():.2f}   "
      f"exp(sigma z_N - sigma^2/2) = {exp(sigma * z_N(N) - sigma**2 / 2):.2f}")

# Load balance: the busiest of G GPUs, each holding ~Poisson(mu) tokens
mu, G = 400, 64
loads = rs.poisson(mu, (5_000, G)).max(1)
print(f"Poisson({mu}) on {G} GPUs: E[max]/mu = {loads.mean() / mu:.3f}   1 + z_G/sqrt(mu) = {1 + z_N(G) / sqrt(mu):.3f}   "
      f"1 + sqrt(2 ln G / mu) = {1 + sqrt(2 * log(G) / mu):.3f}")
 

Read the table column by column: 2ln⁡N\sqrt{2\ln N} overshoots everywhere, zNz_N tracks the median, and zN+γ/2ln⁡Nz_N + \gamma/\sqrt{2\ln N} tracks the mean — the Gumbel limit below explains that last column.

The Gumbel limit and logsumexp

For light-tailed parents (normal, exponential, log-normal on the log scale), the centred and scaled maximum converges to one shape, the Gumbel distribution:

P(MN−bNaN≤x)→exp⁡(−e−x),for the normal: bN=zN, aN≈1/2ln⁡N.P\Big(\frac{M_N - b_N}{a_N} \le x\Big) \to \exp(-e^{-x}), \qquad \text{for the normal: } b_N = z_N,\ a_N \approx 1/\sqrt{2\ln N}.

(Power-law tails give the Fréchet law instead, bounded variables the Weibull law; these three are the only possible limits, by the Fisher–Tippett–Gnedenko theorem.) The standard Gumbel has mean γ≈0.577\gamma \approx 0.577 and standard deviation π/6≈1.28\pi/\sqrt6 \approx 1.28, which gives the mean zN+γaNz_N + \gamma a_N and spread ≈1.28/2ln⁡N\approx 1.28/\sqrt{2\ln N} of the normal maximum.

Gumbel variables are max-stable, and the algebra produces a familiar function. If GiG_i are i.i.d. standard Gumbel and ziz_i are constants,

P(max⁡i(zi+Gi)≤x)=∏iexp⁡(−e−(x−zi))=exp⁡(−e−x∑iezi)=exp⁡(−e−(x−LSE(z))).P\big(\max_i (z_i + G_i) \le x\big) = \prod_i \exp\big(-e^{-(x - z_i)}\big) = \exp\Big(-e^{-x}\sum_i e^{z_i}\Big) = \exp\big(-e^{-(x - \mathrm{LSE}(z))}\big).

The maximum of Gumbel-perturbed values is itself Gumbel, located at LSE(z)=log⁡∑iezi\mathrm{LSE}(z) = \log\sum_i e^{z_i}, with E[max⁡i(zi+Gi)]=LSE(z)+γ\mathbb{E}[\max_i(z_i + G_i)] = \mathrm{LSE}(z) + \gamma. This is the precise sense in which logsumexp is a “soft maximum”.

The Gumbel-max trick

Which index wins? With F(x)=exp⁡(−e−x)F(x) = \exp(-e^{-x}) and density F′(x)=e−xF(x)F'(x) = e^{-x}F(x), index kk wins when zk+Gk=xz_k + G_k = x and all others are below xx:

P(arg⁡max⁡i(zi+Gi)=k)=∫e−(x−zk)∏iexp⁡(−e−(x−zi)) dx=ezk∫0∞e−uZ du=ezkZ,P\big(\arg\max_i (z_i + G_i) = k\big) = \int e^{-(x - z_k)} \prod_{i} \exp\big(-e^{-(x - z_i)}\big)\,dx = e^{z_k}\int_0^\infty e^{-uZ}\,du = \frac{e^{z_k}}{Z},

substituting u=e−xu = e^{-x} with Z=∑ieziZ = \sum_i e^{z_i}. So argmax of logits plus independent Gumbel noise is an exact sample from the softmax; with temperature, use z/τz/\tau. Three consequences on the site:

  • Deterministic sampling. Sampling becomes an argmax of z/τ+Gz/\tau + G where GG is derived from a seed and the position, so the sampled token no longer depends on what else is in the batch.
  • Gumbel-top-kk. The kk largest of zi+Giz_i + G_i are distributed exactly like kk draws without replacement from the softmax (Kool et al., 2019) — used for sampling distinct candidates and for noisy top-kk routing.
  • Bradley–Terry. The difference of two independent standard Gumbels is standard logistic, so with utilities r+Gr + G, P(a≻b)=σ(ra−rb)P(a \succ b) = \sigma(r_a - r_b); with KK items and repeated argmax this is the Plackett–Luce model.
NumPy N개 중 최댓값: 정확값, 점근식, 그리고 세 가지 쓰임
import numpy as np
from math import erfc, sqrt, log, exp, pi
rs = np.random.default_rng(0)
GAMMA = 0.5772156649

def Phi(z):
    """표준정규 CDF (배열에도 동작)."""
    return 1 - 0.5 * np.vectorize(erfc)(np.asarray(z) / sqrt(2))

def z_N(N):
    """표준정규 N개 최댓값의 중심: N * (1 - Phi(z)) = 1을 2차까지 푼다."""
    s = sqrt(2 * log(N))
    return s - (log(log(N)) + log(4 * pi)) / (2 * s)

def median_max(N):
    """최댓값의 정확한 중앙값: Phi(m)^N = 1/2을 이분법으로."""
    lo, hi = -5.0, 8.0
    for _ in range(60):
        mid = (lo + hi) / 2
        lo, hi = (mid, hi) if Phi(mid) ** N < 0.5 else (lo, mid)
    return lo

print("    N  E[max] MC  sd(max)  sqrt(2lnN)   z_N   z_N+gamma/sqrt(2lnN)  exact median")
for N in [4, 16, 64, 256, 1024, 4096]:
    M = rs.standard_normal((400_000 // N + 400, N)).max(1)
    s = sqrt(2 * log(N))
    print(f"{N:5d}  {M.mean():8.3f}  {M.std():7.3f}  {s:9.3f}  {z_N(N):6.3f}  {z_N(N) + GAMMA / s:12.3f}  {median_max(N):14.3f}")

# Best-of-N: 최댓값은 분위수다. CDF 순위 U = F(max)는 Beta(N, 1): E[U] = N/(N+1)
N = 16
U = Phi(rs.standard_normal((20_000, N)).max(1))
print(f"\nBoN N={N}: E[F(max)] = {U.mean():.4f} vs N/(N+1) = {N / (N + 1):.4f};  "
      f"P(max below the 1-1/N quantile) = {(U < 1 - 1 / N).mean():.3f}  (exact (1-1/N)^N = {(1 - 1 / N) ** N:.3f} -> 1/e)")

# Straggler: 길이 l = exp(sigma Z). N개 중 가장 느린 것이 동기식 step을 정한다
sigma, N = 0.9, 64
L = np.exp(sigma * rs.standard_normal((20_000, N)))
print(f"\nlog-normal lengths, sigma={sigma}, N={N}: E[max]/E[mean] = {L.max(1).mean() / L.mean():.2f}   "
      f"exp(sigma z_N - sigma^2/2) = {exp(sigma * z_N(N) - sigma**2 / 2):.2f}")

# 부하 균형: 각각 ~Poisson(mu)개 토큰을 받는 GPU G개 중 가장 바쁜 것
mu, G = 400, 64
loads = rs.poisson(mu, (5_000, G)).max(1)
print(f"Poisson({mu}) on {G} GPUs: E[max]/mu = {loads.mean() / mu:.3f}   1 + z_G/sqrt(mu) = {1 + z_N(G) / sqrt(mu):.3f}   "
      f"1 + sqrt(2 ln G / mu) = {1 + sqrt(2 * log(G) / mu):.3f}")
 

표를 열 단위로 읽어 보자. 2ln⁡N\sqrt{2\ln N}은 어디서나 과대추정이고, zNz_N은 중앙값을, zN+γ/2ln⁡Nz_N + \gamma/\sqrt{2\ln N}은 평균을 따라간다. 마지막 열은 아래의 Gumbel 극한이 설명한다.

Gumbel 극한과 logsumexp

꼬리가 가벼운 분포(정규, 지수, 로그 척도의 로그정규)에서는 중심을 옮기고 scale한 최댓값이 한 가지 모양, Gumbel 분포로 수렴한다.

P(MN−bNaN≤x)→exp⁡(−e−x),정규분포면 bN=zN, aN≈1/2ln⁡N.P\Big(\frac{M_N - b_N}{a_N} \le x\Big) \to \exp(-e^{-x}), \qquad \text{정규분포면 } b_N = z_N,\ a_N \approx 1/\sqrt{2\ln N}.

(거듭제곱 꼬리는 Fréchet, 유계 변수는 Weibull 극한을 준다. Fisher–Tippett–Gnedenko 정리에 따르면 가능한 극한은 이 셋뿐이다.) 표준 Gumbel의 평균은 γ≈0.577\gamma \approx 0.577, 표준편차는 π/6≈1.28\pi/\sqrt6 \approx 1.28이고, 여기서 정규 최댓값의 평균 zN+γaNz_N + \gamma a_N과 퍼짐 ≈1.28/2ln⁡N\approx 1.28/\sqrt{2\ln N}이 나온다.

Gumbel 변수는 max-stable하고, 그 대수에서 낯익은 함수가 나온다. GiG_i가 i.i.d. 표준 Gumbel이고 ziz_i가 상수면

P(max⁡i(zi+Gi)≤x)=∏iexp⁡(−e−(x−zi))=exp⁡(−e−x∑iezi)=exp⁡(−e−(x−LSE(z))).P\big(\max_i (z_i + G_i) \le x\big) = \prod_i \exp\big(-e^{-(x - z_i)}\big) = \exp\Big(-e^{-x}\sum_i e^{z_i}\Big) = \exp\big(-e^{-(x - \mathrm{LSE}(z))}\big).

Gumbel로 교란한 값들의 최댓값도 Gumbel이고, 위치가 LSE(z)=log⁡∑iezi\mathrm{LSE}(z) = \log\sum_i e^{z_i}이며, E[max⁡i(zi+Gi)]=LSE(z)+γ\mathbb{E}[\max_i(z_i + G_i)] = \mathrm{LSE}(z) + \gamma다. logsumexp가 “부드러운 최댓값”이라는 말의 정확한 뜻이 이것이다.

Gumbel-max 트릭

어느 인덱스가 이기나? F(x)=exp⁡(−e−x)F(x) = \exp(-e^{-x}), 밀도 F′(x)=e−xF(x)F'(x) = e^{-x}F(x)로 두면, 인덱스 kk는 zk+Gk=xz_k + G_k = x이고 나머지가 모두 xx 아래일 때 이긴다.

P(arg⁡max⁡i(zi+Gi)=k)=∫e−(x−zk)∏iexp⁡(−e−(x−zi)) dx=ezk∫0∞e−uZ du=ezkZ,P\big(\arg\max_i (z_i + G_i) = k\big) = \int e^{-(x - z_k)} \prod_{i} \exp\big(-e^{-(x - z_i)}\big)\,dx = e^{z_k}\int_0^\infty e^{-uZ}\,du = \frac{e^{z_k}}{Z},

u=e−xu = e^{-x}, Z=∑ieziZ = \sum_i e^{z_i}로 치환했다. 즉 logit에 독립 Gumbel 잡음을 더한 argmax는 softmax의 정확한 샘플이다. 온도가 있으면 z/τz/\tau를 쓴다. 이 사이트에서의 결과 세 가지.

  • 결정적 샘플링. 샘플링이 z/τ+Gz/\tau + G의 argmax가 되고 GG를 시드와 위치에서 만들면, 샘플된 토큰이 배치에 무엇이 함께 들어 있는지와 무관해진다.
  • Gumbel-top-kk. zi+Giz_i + G_i 중 큰 kk개는 softmax에서 비복원으로 kk번 뽑은 것과 정확히 같은 분포다(Kool et al., 2019). 서로 다른 후보를 뽑을 때와 잡음 섞인 top-kk routing에 쓰인다.
  • Bradley–Terry. 독립 표준 Gumbel 둘의 차는 표준 로지스틱이므로, 효용이 r+Gr + G면 P(a≻b)=σ(ra−rb)P(a \succ b) = \sigma(r_a - r_b)다. KK개 항목에 argmax를 반복하면 Plackett–Luce 모형이다.
뽑은 횟수draws 0 TV(경험empirical, 정확exact) – maxi(zi/τ + Gi) 평균mean – vs LSE(z/τ) + γ –
Left: one draw. Grey bars are the scaled logits z/τ, the coloured caps are independent Gumbel noise, and the winner (or the top two) is outlined. Press +1000: on the right the blue empirical frequencies settle onto the red exact values — softmax(z/τ) for the argmax, and the probability of being in a without-replacement sample of two for top-2. Lower τ and the noise matters less relative to the gaps, so the argmax becomes nearly deterministic. The running mean of the winning perturbed value tracks logsumexp(z/τ) + γ. 왼쪽: 한 번 뽑기. 회색 막대는 scale한 logit z/τ, 색 덧칠은 독립 Gumbel 잡음이고, 이긴 것(또는 상위 둘)에 테두리를 그렸다. +1000을 누르면 오른쪽의 파란 경험 빈도가 빨간 정확값에 내려앉는다. argmax면 softmax(z/τ), top-2면 비복원으로 둘을 뽑을 때 포함될 확률이다. τ를 낮추면 간격에 비해 잡음이 작아져 argmax가 거의 결정적이 된다. 이긴 교란값의 이동 평균은 logsumexp(z/τ) + γ를 따라간다.
NumPy Gumbel-max, the Gumbel maximum, top-k without replacement, Bradley–Terry
def gumbel(shape):
    return -np.log(-np.log(rs.random(shape)))

z = np.array([2.0, 1.4, 0.9, 0.4, -0.3, -1.0])
p = np.exp(z - z.max()); p /= p.sum()
n = 200_000
Gz = z + gumbel((n, len(z)))

# 1) Gumbel-max: argmax(z + G) is a sample from softmax(z)
freq = np.bincount(Gz.argmax(1).astype(np.intp), minlength=len(z)) / n
print("softmax(z):     ", np.round(p, 4))
print("argmax freq:    ", np.round(freq, 4))

# 2) The max itself is Gumbel, centred at logsumexp(z): E[max] = LSE(z) + gamma
lse = z.max() + np.log(np.exp(z - z.max()).sum())
print(f"\nE[max(z+G)] = {Gz.max(1).mean():.4f}   LSE(z) + gamma = {lse + GAMMA:.4f}")

# 3) Gumbel-top-k = sampling k without replacement (here: the ordered first two picks)
top2 = np.argsort(-Gz, axis=1)[:, :2]
i, j = 0, 1
emp = np.mean((top2[:, 0] == i) & (top2[:, 1] == j))
print(f"P(first = {i}, second = {j}): Gumbel-top-2 {emp:.4f}   sequential without replacement {p[i] * p[j] / (1 - p[i]):.4f}")

# 4) The difference of two Gumbels is logistic: P(r_a + G_a > r_b + G_b) = sigmoid(r_a - r_b)  (Bradley-Terry)
ra, rb = 0.7, 0.0
win = np.mean(ra + gumbel(n) > rb + gumbel(n))
print(f"P(a beats b) = {win:.4f}   sigmoid(r_a - r_b) = {1 / (1 + np.exp(-(ra - rb))):.4f}")
 

Quantiles from samples

The same order-statistics view answers “how accurate is an empirical quantile?”. The kk-th smallest of NN uniforms is Beta(k,N+1−k)\mathrm{Beta}(k, N + 1 - k), so the sample qq-quantile x^q=X(⌈qN⌉)\hat x_q = X_{(\lceil qN\rceil)} has, for large NN,

sd⁡(x^q)≈q(1−q)/Nf(xq).\operatorname{sd}(\hat x_q) \approx \frac{\sqrt{q(1-q)/N}}{f(x_q)} .

Extreme quantiles are expensive: as q→1q \to 1, f(xq)f(x_q) falls faster than 1−q\sqrt{1-q}, so the error blows up. Thresholds set from sample quantiles — clip ranges, length cut-offs, Quantile Balancing’s per-expert bias in Kimi K3 — inherit this noise, which is why they are usually set from large batches or smoothed over steps.

확인 문제Check yourself

Rollout lengths are log-normal with σ = 1. Roughly how much longer is the typical longest of 256 rollouts than the mean rollout?

z256≈2.69z_{256} \approx 2.69, so the typical max is eμ+2.69e^{\mu + 2.69} while the mean is eμ+0.5e^{\mu + 0.5}: the ratio is e2.19≈9e^{2.19} \approx 9. That is the typical (median-like) maximum; the mean of the maximum is somewhat larger (about 11× for σ = 1, as the figure shows), so “about 9×” is the closest answer. Doubling σ to 2 would make it roughly e2⋅2.69−2≈30×e^{2\cdot2.69 - 2} \approx 30\times.

Summary

  • P(max⁡≤x)=FNP(\max \le x) = F^N, density NFN−1fNF^{N-1}f; the rank F(max⁡)F(\max) is Beta(N,1)\mathrm{Beta}(N, 1); the typical max is the 1−1/N1 - 1/N quantile.
  • Normal maxima: zN=2ln⁡N−ln⁡ln⁡N+ln⁡4π22ln⁡Nz_N = \sqrt{2\ln N} - \frac{\ln\ln N + \ln 4\pi}{2\sqrt{2\ln N}}, spread ≈1.28/2ln⁡N\approx 1.28/\sqrt{2\ln N}. 2ln⁡N\sqrt{2\ln N} alone overestimates.
  • Log-normal max/mean ≈eσzN−σ2/2\approx e^{\sigma z_N - \sigma^2/2}; Poisson(μ\mu) max ≈μ+zNμ\approx \mu + z_N\sqrt\mu; tails decide the growth rate.
  • Light-tailed maxima converge to Gumbel; max⁡i(zi+Gi)\max_i(z_i + G_i) is Gumbel at LSE(z)\mathrm{LSE}(z).
  • arg⁡max⁡i(zi+Gi)∼softmax(z)\arg\max_i(z_i + G_i) \sim \mathrm{softmax}(z); top-kk is sampling without replacement; Gumbel differences give Bradley–Terry.

Where this is used

NumPy Gumbel-max, Gumbel 최댓값, 비복원 top-k, Bradley–Terry
def gumbel(shape):
    return -np.log(-np.log(rs.random(shape)))

z = np.array([2.0, 1.4, 0.9, 0.4, -0.3, -1.0])
p = np.exp(z - z.max()); p /= p.sum()
n = 200_000
Gz = z + gumbel((n, len(z)))

# 1) Gumbel-max: argmax(z + G)는 softmax(z)의 샘플
freq = np.bincount(Gz.argmax(1).astype(np.intp), minlength=len(z)) / n
print("softmax(z):     ", np.round(p, 4))
print("argmax freq:    ", np.round(freq, 4))

# 2) 최댓값 자체는 logsumexp(z)에 중심을 둔 Gumbel: E[max] = LSE(z) + gamma
lse = z.max() + np.log(np.exp(z - z.max()).sum())
print(f"\nE[max(z+G)] = {Gz.max(1).mean():.4f}   LSE(z) + gamma = {lse + GAMMA:.4f}")

# 3) Gumbel-top-k = k개 비복원 샘플링 (여기서는 순서 있는 처음 두 개)
top2 = np.argsort(-Gz, axis=1)[:, :2]
i, j = 0, 1
emp = np.mean((top2[:, 0] == i) & (top2[:, 1] == j))
print(f"P(first = {i}, second = {j}): Gumbel-top-2 {emp:.4f}   sequential without replacement {p[i] * p[j] / (1 - p[i]):.4f}")

# 4) 두 Gumbel의 차는 로지스틱: P(r_a + G_a > r_b + G_b) = sigmoid(r_a - r_b)  (Bradley-Terry)
ra, rb = 0.7, 0.0
win = np.mean(ra + gumbel(n) > rb + gumbel(n))
print(f"P(a beats b) = {win:.4f}   sigmoid(r_a - r_b) = {1 / (1 + np.exp(-(ra - rb))):.4f}")
 

표본에서 분위수 구하기

같은 순서통계량 관점이 “경험 분위수는 얼마나 정확한가?”에 답한다. 균등분포 NN개 중 kk번째로 작은 값은 Beta(k,N+1−k)\mathrm{Beta}(k, N + 1 - k)이므로, 표본 qq-분위수 x^q=X(⌈qN⌉)\hat x_q = X_{(\lceil qN\rceil)}는 큰 NN에서

sd⁡(x^q)≈q(1−q)/Nf(xq).\operatorname{sd}(\hat x_q) \approx \frac{\sqrt{q(1-q)/N}}{f(x_q)} .

극단 분위수는 비싸다. q→1q \to 1이면 f(xq)f(x_q)가 1−q\sqrt{1-q}보다 빨리 작아져 오차가 폭발한다. 표본 분위수로 정하는 문턱 — clip 범위, 길이 컷오프, Kimi K3 Quantile Balancing의 expert별 bias — 은 이 잡음을 물려받는다. 그래서 대개 큰 배치에서 정하거나 step에 걸쳐 평활한다.

확인 문제Check yourself

rollout 길이가 σ = 1인 로그정규분포다. rollout 256개 중 전형적인 최장 길이는 평균 길이의 대략 몇 배인가?

z256≈2.69z_{256} \approx 2.69이므로 전형적인 최댓값은 eμ+2.69e^{\mu + 2.69}, 평균은 eμ+0.5e^{\mu + 0.5}다. 비는 e2.19≈9e^{2.19} \approx 9. 이것은 전형적인(중앙값 같은) 최댓값이고, 최댓값의 평균은 더 크다. σ = 1이면 그림에서 보듯 약 11배다. 그래서 가장 가까운 답은 “약 9배”다. σ를 2로 두 배 하면 대략 e2⋅2.69−2≈30e^{2\cdot2.69 - 2} \approx 30배가 된다.

정리

  • P(max⁡≤x)=FNP(\max \le x) = F^N, 밀도 NFN−1fNF^{N-1}f. 순위 F(max⁡)F(\max)는 Beta(N,1)\mathrm{Beta}(N, 1). 전형적인 최댓값은 1−1/N1 - 1/N 분위수다.
  • 정규 최댓값: zN=2ln⁡N−ln⁡ln⁡N+ln⁡4π22ln⁡Nz_N = \sqrt{2\ln N} - \frac{\ln\ln N + \ln 4\pi}{2\sqrt{2\ln N}}, 퍼짐 ≈1.28/2ln⁡N\approx 1.28/\sqrt{2\ln N}. 2ln⁡N\sqrt{2\ln N}만으로는 과대추정이다.
  • 로그정규 최댓값/평균 ≈eσzN−σ2/2\approx e^{\sigma z_N - \sigma^2/2}, Poisson(μ\mu) 최댓값 ≈μ+zNμ\approx \mu + z_N\sqrt\mu. 증가 속도는 꼬리가 정한다.
  • 가벼운 꼬리의 최댓값은 Gumbel로 수렴하고, max⁡i(zi+Gi)\max_i(z_i + G_i)는 위치가 LSE(z)\mathrm{LSE}(z)인 Gumbel이다.
  • arg⁡max⁡i(zi+Gi)∼softmax(z)\arg\max_i(z_i + G_i) \sim \mathrm{softmax}(z). top-kk는 비복원 샘플링이고, Gumbel의 차는 Bradley–Terry를 준다.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading