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 be i.i.d. with CDF and density , and . The max is below exactly when every draw is, so
The density reweights by , which is tiny wherever is not close to 1: the maximum lives in the top tail, and only the tail of matters. (The minimum is the mirror image: .)
It is often cleaner to work with the rank . Since is uniform, is the largest of uniforms, with — a law with . So the maximum sits around the quantile, whatever is, and
The rule of thumb used everywhere below: the typical maximum of draws is the quantile, i.e. the solving .
How fast the maximum grows
For a standard normal, has no closed form, but for large the Mills-ratio approximation is accurate. Taking logs of :
The leading term gives . Put , use and :
The correction is not small for practical : for , but , close to the exact median of the max (2.30). The fluctuations shrink too: the max has spread of order (below). Three consequences used on the site:
- Best-of-N gains are logarithmic. Each factor of 4 in 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 , the longest of is about , while the mean is . The ratio is the fraction of a synchronous rollout step spent waiting; it grows exponentially in . (The mean of the max is larger still, because is convex in the spread of .)
- Sums of many small things are nearly normal. If each of GPUs receives about Poisson() tokens, the busiest has about , an imbalance of that only more tokens per GPU can shrink.
Tails decide everything: for exponential tails the max grows like (for Exp(1), ), for power-law tails it grows like , and for bounded variables it saturates.
통계는 대부분 평균을 다루지만, 이 사이트의 많은 숫자는 최댓값이다. Best-of-N은 보상이 가장 높은 샘플을 남긴다. 동기식 RL step은 가장 긴 rollout을 기다린다. expert-parallel MoE 층은 가장 바쁜 GPU를 기다린다. softmax에서 샘플링하는 것도 잡음 섞인 logit의 argmax로 쓸 수 있다. 이 레슨은 그 레슨들이 쓰는 최댓값에 관한 몇 가지 사실을 모아서 유도한다.
최댓값의 분포
이 CDF , 밀도 로 i.i.d.이고 라 하자. 최댓값이 아래인 것은 모든 표본이 아래인 것과 같으므로
밀도는 를 로 다시 가중한 것이고, 이 가중치는 가 1에 가깝지 않은 곳에서 아주 작다. 최댓값은 위쪽 꼬리에 살고, 의 꼬리만 중요하다. (최솟값은 거울상이다: .)
순위 로 보면 더 깔끔할 때가 많다. 는 균등분포이므로 는 균등분포 개 중 최댓값이고, , 곧 인 분포다. 그래서 가 무엇이든 최댓값은 분위수 근처에 있고
아래 어디서나 쓰는 어림 규칙: 개 중 전형적인 최댓값은 분위수, 곧 을 푸는 다.
최댓값은 얼마나 빨리 자라나
표준정규에서 는 닫힌 꼴이 없지만, 큰 에서는 Mills 비 근사 가 정확하다. 에 로그를 취하면
주항에서 이다. 로 두고 , 을 쓰면
실용적인 에서 이 보정은 작지 않다. 에서 이지만 이고, 최댓값의 정확한 중앙값(2.30)에 가깝다. 요동도 줄어든다. 최댓값의 퍼짐은 정도다(아래). 이 사이트에서 쓰이는 결과 세 가지.
- Best-of-N의 이득은 로그적이다. 을 4배 할 때마다 더해지는 보상이 직전보다 작고(표준정규 보상이면 4→16에서 0.73, 64→256에서 0.47), 비용은 선형으로 는다.
- 로그정규 꼬리는 곱셈적이다. 길이가 면 개 중 가장 긴 것은 약 이고 평균은 다. 비 는 동기식 rollout step이 기다리며 보내는 몫이고, 에 대해 지수적으로 커진다. (최댓값의 평균은 더 크다. 이 의 퍼짐에 대해 볼록하기 때문이다.)
- 작은 것 여럿의 합은 거의 정규다. GPU 개가 각각 대략 Poisson()개의 토큰을 받으면 가장 바쁜 GPU는 약 개, 불균형은 이고, GPU당 토큰을 늘려야만 줄어든다.
모든 것은 꼬리가 정한다. 지수 꼬리면 최댓값은 처럼 자라고(Exp(1)이면 ), 거듭제곱 꼬리 면 처럼 자라며, 유계 변수면 포화한다.
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: overshoots everywhere, tracks the median, and 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:
(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 and standard deviation , which gives the mean and spread of the normal maximum.
Gumbel variables are max-stable, and the algebra produces a familiar function. If are i.i.d. standard Gumbel and are constants,
The maximum of Gumbel-perturbed values is itself Gumbel, located at , with . This is the precise sense in which logsumexp is a “soft maximum”.
The Gumbel-max trick
Which index wins? With and density , index wins when and all others are below :
substituting with . So argmax of logits plus independent Gumbel noise is an exact sample from the softmax; with temperature, use . Three consequences on the site:
- Deterministic sampling. Sampling becomes an argmax of where is derived from a seed and the position, so the sampled token no longer depends on what else is in the batch.
- Gumbel-top-. The largest of are distributed exactly like draws without replacement from the softmax (Kool et al., 2019) — used for sampling distinct candidates and for noisy top- routing.
- Bradley–Terry. The difference of two independent standard Gumbels is standard logistic, so with utilities , ; with items and repeated argmax this is the Plackett–Luce model.
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}")표를 열 단위로 읽어 보자. 은 어디서나 과대추정이고, 은 중앙값을, 은 평균을 따라간다. 마지막 열은 아래의 Gumbel 극한이 설명한다.
Gumbel 극한과 logsumexp
꼬리가 가벼운 분포(정규, 지수, 로그 척도의 로그정규)에서는 중심을 옮기고 scale한 최댓값이 한 가지 모양, Gumbel 분포로 수렴한다.
(거듭제곱 꼬리는 Fréchet, 유계 변수는 Weibull 극한을 준다. Fisher–Tippett–Gnedenko 정리에 따르면 가능한 극한은 이 셋뿐이다.) 표준 Gumbel의 평균은 , 표준편차는 이고, 여기서 정규 최댓값의 평균 과 퍼짐 이 나온다.
Gumbel 변수는 max-stable하고, 그 대수에서 낯익은 함수가 나온다. 가 i.i.d. 표준 Gumbel이고 가 상수면
Gumbel로 교란한 값들의 최댓값도 Gumbel이고, 위치가 이며, 다. logsumexp가 “부드러운 최댓값”이라는 말의 정확한 뜻이 이것이다.
Gumbel-max 트릭
어느 인덱스가 이기나? , 밀도 로 두면, 인덱스 는 이고 나머지가 모두 아래일 때 이긴다.
, 로 치환했다. 즉 logit에 독립 Gumbel 잡음을 더한 argmax는 softmax의 정확한 샘플이다. 온도가 있으면 를 쓴다. 이 사이트에서의 결과 세 가지.
- 결정적 샘플링. 샘플링이 의 argmax가 되고 를 시드와 위치에서 만들면, 샘플된 토큰이 배치에 무엇이 함께 들어 있는지와 무관해진다.
- Gumbel-top-. 중 큰 개는 softmax에서 비복원으로 번 뽑은 것과 정확히 같은 분포다(Kool et al., 2019). 서로 다른 후보를 뽑을 때와 잡음 섞인 top- routing에 쓰인다.
- Bradley–Terry. 독립 표준 Gumbel 둘의 차는 표준 로지스틱이므로, 효용이 면 다. 개 항목에 argmax를 반복하면 Plackett–Luce 모형이다.
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 -th smallest of uniforms is , so the sample -quantile has, for large ,
Extreme quantiles are expensive: as , falls faster than , 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.
Rollout lengths are log-normal with σ = 1. Roughly how much longer is the typical longest of 256 rollouts than the mean rollout?
, so the typical max is while the mean is : the ratio is . 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 .
Summary
- , density ; the rank is ; the typical max is the quantile.
- Normal maxima: , spread . alone overestimates.
- Log-normal max/mean ; Poisson() max ; tails decide the growth rate.
- Light-tailed maxima converge to Gumbel; is Gumbel at .
- ; top- is sampling without replacement; Gumbel differences give Bradley–Terry.
Where this is used
- Best-of-N and rejection sampling, Over-optimisation — the BoN density , gains, ranks.
- Inference for RL, Async and staleness, Async systems, Framework landscape — log-normal rollout tails, utilisation , seeded Gumbel-max sampling.
- Parallelism for MoE serving, MoE anatomy, Kimi K3 — max of Poisson loads, Gumbel top- routing, quantile-based balancing.
- Reward models, DPO — Bradley–Terry from Gumbel noise, Plackett–Luce.
- Decoding — temperature and top- sampling as operations on logits.
- Related: Numerics for logsumexp, Statistics for estimation and quantiles.
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}")표본에서 분위수 구하기
같은 순서통계량 관점이 “경험 분위수는 얼마나 정확한가?”에 답한다. 균등분포 개 중 번째로 작은 값은 이므로, 표본 -분위수 는 큰 에서
극단 분위수는 비싸다. 이면 가 보다 빨리 작아져 오차가 폭발한다. 표본 분위수로 정하는 문턱 — clip 범위, 길이 컷오프, Kimi K3 Quantile Balancing의 expert별 bias — 은 이 잡음을 물려받는다. 그래서 대개 큰 배치에서 정하거나 step에 걸쳐 평활한다.
rollout 길이가 σ = 1인 로그정규분포다. rollout 256개 중 전형적인 최장 길이는 평균 길이의 대략 몇 배인가?
이므로 전형적인 최댓값은 , 평균은 다. 비는 . 이것은 전형적인(중앙값 같은) 최댓값이고, 최댓값의 평균은 더 크다. σ = 1이면 그림에서 보듯 약 11배다. 그래서 가장 가까운 답은 “약 9배”다. σ를 2로 두 배 하면 대략 배가 된다.
정리
- , 밀도 . 순위 는 . 전형적인 최댓값은 분위수다.
- 정규 최댓값: , 퍼짐 . 만으로는 과대추정이다.
- 로그정규 최댓값/평균 , Poisson() 최댓값 . 증가 속도는 꼬리가 정한다.
- 가벼운 꼬리의 최댓값은 Gumbel로 수렴하고, 는 위치가 인 Gumbel이다.
- . top-는 비복원 샘플링이고, Gumbel의 차는 Bradley–Terry를 준다.
이 사이트에서 쓰이는 곳
- Best-of-N과 rejection sampling, 과최적화 — BoN 밀도 , 이득, 순위.
- RL을 위한 추론, 비동기와 staleness, 비동기 시스템, 프레임워크 지형도 — 로그정규 rollout 꼬리, 활용률 , 시드 고정 Gumbel-max 샘플링.
- MoE 서빙 병렬화, MoE 해부, Kimi K3 — Poisson 부하의 최댓값, Gumbel top- routing, 분위수 기반 balancing.
- 보상모델, DPO — Gumbel 잡음에서 나오는 Bradley–Terry, Plackett–Luce.
- 디코딩 — logit에 대한 연산으로서의 온도와 top- 샘플링.
- 관련: logsumexp는 수치 계산, 추정과 분위수는 통계.
더 읽을거리Further reading
- David & Nagaraja, Order Statistics, 3rd ed. (Wiley, 2003) — 순서통계량의 분포, 균등 순서통계량의 Beta 분포, 극값 극한의 표준 교재.The standard reference on order statistics — their distributions, Beta laws of uniform order statistics, extreme-value limits.
- Gumbel, Statistics of Extremes (Columbia University Press, 1958) — Gumbel 분포와 극값 통계의 고전.The classic on the Gumbel distribution and the statistics of extremes.
- Kool, van Hoof & Welling, Stochastic Beams and Where to Find Them: The Gumbel-Top-k Trick (ICML 2019) — Gumbel-top-k가 비복원 샘플링과 같다는 것과 그 응용.Gumbel-top-k equals sampling without replacement, and its uses.
- Maddison, Tarlow & Minka, A* Sampling (NeurIPS 2014) — Gumbel-max 트릭과 Gumbel 과정의 정리.A careful treatment of the Gumbel-max trick and Gumbel processes.