The mathematics of the previous lessons assumes real numbers. The hardware has a finite set of them. Most of the time the difference is invisible; on this site it surfaces as named problems — a softmax that returns NaN, a trainer and an inference engine that disagree about the log-probability of the same token, a result that changes with batch size, FP8 training that needs per-block scales. This lesson builds the small model of floating point that explains all of them.
What a float is
A binary floating-point number with exponent bits and mantissa (fraction) bits stores a sign , an exponent field and a fraction :
Between and there are exactly equally spaced values, so the spacing — the ulp (unit in the last place) — is for . The spacing grows with magnitude, but the relative spacing stays within a factor of two: . Rounding to nearest therefore has relative error at most the unit roundoff
and IEEE arithmetic guarantees the same for each operation: , , for and . This one-line standard model is all the error analysis below uses. (Some texts call , the gap from 1 to the next float, “machine epsilon”; NumPy’s finfo.eps is that .)
The exponent field’s extreme values are reserved. encodes subnormals , which fill the gap down to zero with the fixed spacing of the smallest binade — so relative precision degrades gradually instead of falling off a cliff. The all-ones field encodes and NaN (E4M3 drops infinities to gain one more binade of values). Rounding is round-to-nearest, ties to even (the last mantissa bit 0), which avoids a systematic upward bias.
| format | sign/exp/mantissa | largest | smallest normal | smallest subnormal | |
|---|---|---|---|---|---|
| FP32 | 1 / 8 / 23 | ||||
| BF16 | 1 / 8 / 7 | ||||
| FP16 | 1 / 5 / 10 | 65504 | |||
| FP8 E5M2 | 1 / 5 / 2 | 57344 | |||
| FP8 E4M3 | 1 / 4 / 3 | 448 |
Exponent bits buy range, mantissa bits buy precision. BF16 is FP32 with the mantissa cut to 7 bits: same range, about 2–3 significant decimal digits. FP16 has three more mantissa bits but overflows at 65504 and flushes values below to zero.
앞의 레슨들의 수학은 실수를 가정한다. 하드웨어에는 유한한 수의 집합만 있다. 대개 그 차이는 보이지 않지만, 이 사이트에서는 이름 붙은 문제로 드러난다. NaN을 돌려주는 softmax, 같은 토큰의 log-prob을 두고 엇갈리는 trainer와 추론 엔진, 배치 크기에 따라 바뀌는 결과, 블록마다 scale이 필요한 FP8 학습. 이 레슨은 이것들을 모두 설명하는 작은 부동소수점 모형을 만든다.
float란 무엇인가
지수 비트 개, 가수(fraction) 비트 개인 이진 부동소수점 수는 부호 , 지수 필드 , 가수 를 저장한다.
와 사이에는 같은 간격의 값이 정확히 개 있으므로, 간격 — ulp(unit in the last place) — 은 에서 이다. 간격은 크기와 함께 커지지만 상대 간격은 두 배 범위 안에 머문다: . 그래서 가장 가까운 값으로 반올림한 상대 오차는 많아야 단위 반올림(unit roundoff) 이다.
IEEE 산술은 각 연산에도 같은 것을 보장한다. 와 에 대해 , . 아래의 오차 분석은 이 한 줄짜리 표준 모형만 쓴다. (1과 그다음 float 사이의 간격 을 “machine epsilon”이라 부르는 책도 있다. NumPy의 finfo.eps가 그 다.)
지수 필드의 양 끝 값은 예약되어 있다. 은 subnormal 을 나타내며, 가장 작은 구간의 고정 간격으로 0까지의 틈을 메운다. 그래서 상대 정밀도가 절벽처럼 떨어지지 않고 서서히 나빠진다. 모든 비트가 1인 필드는 와 NaN이다(E4M3은 무한대를 버리고 값의 구간 하나를 더 얻는다). 반올림은 가장 가까운 값으로, 동률이면 짝수로(ties to even)(마지막 가수 비트가 0인 쪽) 한다. 체계적으로 위로 치우치는 편향을 피하기 위해서다.
| 형식 | 부호/지수/가수 | 최댓값 | 최소 정규 수 | 최소 subnormal | |
|---|---|---|---|---|---|
| FP32 | 1 / 8 / 23 | ||||
| BF16 | 1 / 8 / 7 | ||||
| FP16 | 1 / 5 / 10 | 65504 | |||
| FP8 E5M2 | 1 / 5 / 2 | 57344 | |||
| FP8 E4M3 | 1 / 4 / 3 | 448 |
지수 비트는 범위를, 가수 비트는 정밀도를 산다. BF16은 FP32에서 가수를 7비트로 자른 것이다. 범위는 같고 유효 숫자는 십진 2–3자리다. FP16은 가수가 3비트 더 많지만 65504에서 overflow하고 아래는 0으로 사라진다.
Things to see in the figure. Type 0.1: no binary format holds it exactly, and BF16 stores 0.10009765625. Type 300 in E4M3 and the neighbours are 288 and 320 — an 11% step. Type 65520 in FP16 and it overflows: 65520 is exactly halfway between 65504 and the next binade’s first value, and ties-to-even rounds up. On the lower plot the solid sawtooth is the current format; every format’s teeth have the same shape, only shifted by mantissa width and truncated by exponent range.
import numpy as np
import math
def round_to(v, m):
"""Round v to the nearest float with m mantissa bits (ties to even). Range limits ignored."""
if v == 0.0:
return 0.0
e = math.frexp(v)[1] # v = f * 2**e with 0.5 <= |f| < 1
q = 2.0 ** (e - 1 - m) # ulp of v
return round(v / q) * q # Python's round() is round-half-to-even
BITS = {"fp32": 23, "fp16": 10, "bf16": 7}
for name, dt in [("float64", np.float64), ("float32", np.float32), ("float16", np.float16)]:
fi = np.finfo(dt)
print(f"{name:8s} eps = {fi.eps:.3e} max = {fi.max:.4e} min normal = {fi.tiny:.3e} ulp(1000) = {np.spacing(dt(1000)):.3e}")
print(f"bfloat16 eps = {2**-7:.3e} 1.01 -> {round_to(1.01, 7)} 1000.0 + 2 -> {round_to(1002.0, 7)}")
print(f"\n0.1 is stored as {np.float32(0.1):.12f} in fp32 and {round_to(0.1, 7):.12f} in bf16")
print("0.1 + 0.2 == 0.3 in float64?", 0.1 + 0.2 == 0.3, f" (off by {0.1 + 0.2 - 0.3:.1e})")
a, b, c = np.float32(1e8), np.float32(-1e8), np.float32(1.0)
print("fp32: (a + b) + c =", (a + b) + c, " a + (b + c) =", a + (b + c))
# Summing 16384 numbers in U(0,1) with an accumulator that rounds after every add
rs = np.random.default_rng(0)
N = 1 << 14
x = [round_to(v, 7) for v in rs.random(N)] # the inputs are bf16 numbers
exact = math.fsum(x)
def sequential(x, m):
s = 0.0
for v in x:
s = round_to(s + v, m)
return s
def pairwise(x, m):
while len(x) > 1:
x = [round_to(x[i] + x[i + 1], m) for i in range(0, len(x) - 1, 2)] + ([x[-1]] if len(x) % 2 else [])
return x[0]
def kahan(x, m):
s = c = 0.0
for v in x:
y = round_to(v - c, m)
t = round_to(s + y, m)
c = round_to(round_to(t - s, m) - y, m) # the low-order bits that t lost
s = t
return s
print(f"\nexact sum = {exact:.1f}, which rounds to {round_to(exact, 7):.1f} in bf16 and {round_to(exact, 10):.1f} in fp16 (N = {N})")
for name in ["bf16", "fp16", "fp32"]:
m = BITS[name]
r = [sequential(x, m), pairwise(x, m), kahan(x, m)]
print(f"{name} accumulator: sequential {r[0]:9.1f} pairwise {r[1]:9.1f} Kahan {r[2]:9.1f}")
# The same numbers, cut into c chunks (as a split-K kernel would), each summed, then the partials summed
for c in [1, 2, 3, 4, 8, 16]:
parts = [sequential(x[i * N // c:(i + 1) * N // c], 10) for i in range(c)]
print(f"fp16, {c:2d} chunks: {sequential(parts, 10):7.1f}", end=" " if c % 3 else "\n")
print()Cancellation
Subtracting two nearby numbers is exact for the stored values, but it exposes the error those values already had. If and , then
The factor is the condition number of subtraction; when it is huge and the leading digits cancel, leaving rounding noise. The cure is always algebraic — rewrite so the small quantity is computed directly:
-
log1p(x),expm1(x), . - Variance: cancels when the mean is large compared with the spread; subtract the mean first (two-pass) or use Welford’s update. LayerNorm and RMSNorm kernels care about this.
- KL estimators: with small is , the difference of two numbers of size . Compute it as
expm1(d) - dfrom log-probabilities, never from probabilities. - Log-ratios in general: take of log-probabilities, not of probabilities.
Non-associativity and summation order
Every rounding step loses up to of the running result, so the order of a sum matters. For computed left to right, applying the standard model times gives (Higham ch. 4)
The bound grows linearly because each partial sum — which grows — is rounded. Two classic fixes:
- Pairwise (tree) summation adds neighbours, then neighbours of neighbours; each passes through only additions, so the bound becomes . NumPy’s
sumand GPU reductions are tree-shaped. - Kahan (compensated) summation carries the low-order bits lost at each step in a second variable and feeds them back: , , , . The bound becomes , independent of to first order.
In low precision the failure is not just slow growth but stagnation: once the running sum exceeds times the next term, adding that term changes nothing at all. A BF16 accumulator summing numbers around 0.5 stops at 256. That is why tensor cores multiply BF16/FP16/FP8 inputs but accumulate in FP32, and why DeepSeek-V3’s FP8 GEMMs promote partial sums to FP32 at fixed intervals.
그림에서 볼 것. 0.1을 입력해 보면 어떤 이진 형식도 그것을 정확히 담지 못하고, BF16은 0.10009765625를 저장한다. E4M3에 300을 넣으면 이웃이 288과 320, 11%짜리 걸음이다. FP16에 65520을 넣으면 overflow한다. 65520은 65504와 다음 구간의 첫 값 사이 정확히 가운데이고, ties-to-even이 위로 올림하기 때문이다. 아래 그림의 실선 톱니가 현재 형식이다. 모든 형식의 톱니는 모양이 같고, 가수 폭만큼 위아래로 옮겨지고 지수 범위만큼 잘렸을 뿐이다.
import numpy as np
import math
def round_to(v, m):
"""v를 가수 m비트인 가장 가까운 float로 반올림(동률이면 짝수). 범위 한계는 무시."""
if v == 0.0:
return 0.0
e = math.frexp(v)[1] # v = f * 2**e with 0.5 <= |f| < 1
q = 2.0 ** (e - 1 - m) # v의 ulp
return round(v / q) * q # 파이썬 round()는 동률이면 짝수로 간다
BITS = {"fp32": 23, "fp16": 10, "bf16": 7}
for name, dt in [("float64", np.float64), ("float32", np.float32), ("float16", np.float16)]:
fi = np.finfo(dt)
print(f"{name:8s} eps = {fi.eps:.3e} max = {fi.max:.4e} min normal = {fi.tiny:.3e} ulp(1000) = {np.spacing(dt(1000)):.3e}")
print(f"bfloat16 eps = {2**-7:.3e} 1.01 -> {round_to(1.01, 7)} 1000.0 + 2 -> {round_to(1002.0, 7)}")
print(f"\n0.1 is stored as {np.float32(0.1):.12f} in fp32 and {round_to(0.1, 7):.12f} in bf16")
print("0.1 + 0.2 == 0.3 in float64?", 0.1 + 0.2 == 0.3, f" (off by {0.1 + 0.2 - 0.3:.1e})")
a, b, c = np.float32(1e8), np.float32(-1e8), np.float32(1.0)
print("fp32: (a + b) + c =", (a + b) + c, " a + (b + c) =", a + (b + c))
# U(0,1)의 수 16384개를, 덧셈마다 반올림하는 누산기로 더한다
rs = np.random.default_rng(0)
N = 1 << 14
x = [round_to(v, 7) for v in rs.random(N)] # 입력은 bf16 수
exact = math.fsum(x)
def sequential(x, m):
s = 0.0
for v in x:
s = round_to(s + v, m)
return s
def pairwise(x, m):
while len(x) > 1:
x = [round_to(x[i] + x[i + 1], m) for i in range(0, len(x) - 1, 2)] + ([x[-1]] if len(x) % 2 else [])
return x[0]
def kahan(x, m):
s = c = 0.0
for v in x:
y = round_to(v - c, m)
t = round_to(s + y, m)
c = round_to(round_to(t - s, m) - y, m) # t가 잃은 아래 자리 비트
s = t
return s
print(f"\nexact sum = {exact:.1f}, which rounds to {round_to(exact, 7):.1f} in bf16 and {round_to(exact, 10):.1f} in fp16 (N = {N})")
for name in ["bf16", "fp16", "fp32"]:
m = BITS[name]
r = [sequential(x, m), pairwise(x, m), kahan(x, m)]
print(f"{name} accumulator: sequential {r[0]:9.1f} pairwise {r[1]:9.1f} Kahan {r[2]:9.1f}")
# 같은 수들을 (split-K 커널처럼) c개 조각으로 잘라 각각 더한 뒤 부분합을 더한다
for c in [1, 2, 3, 4, 8, 16]:
parts = [sequential(x[i * N // c:(i + 1) * N // c], 10) for i in range(c)]
print(f"fp16, {c:2d} chunks: {sequential(parts, 10):7.1f}", end=" " if c % 3 else "\n")
print()상쇄(cancellation)
가까운 두 수의 뺄셈은 저장된 값에 대해서는 정확하지만, 그 값들이 이미 가진 오차를 드러낸다. , 라면
가 뺄셈의 조건수다. 면 이것이 거대해지고, 앞자리가 상쇄되어 반올림 잡음만 남는다. 처방은 언제나 대수적이다. 작은 양을 직접 계산하도록 식을 고쳐 쓴다.
-
log1p(x),expm1(x), . - 분산: 평균이 퍼짐에 비해 크면 가 상쇄된다. 평균을 먼저 빼거나(two-pass) Welford 갱신을 쓴다. LayerNorm·RMSNorm 커널이 신경 쓰는 부분이다.
- KL 추정량: 가 작을 때 는 크기 인 두 수의 차다. 확률이 아니라 log-prob에서 출발해
expm1(d) - d로 계산한다. - 로그 비율 일반: 확률의 가 아니라 log-prob의 를 쓴다.
비결합성과 합산 순서
반올림할 때마다 누적값의 최대 만큼을 잃으므로 합의 순서가 중요하다. 왼쪽부터 더한 에 표준 모형을 번 적용하면(Higham 4장)
커지는 부분합이 매번 반올림되기 때문에 상한이 선형으로 자란다. 고전적인 처방 두 가지.
- 쌍별(트리) 합산은 이웃끼리, 그다음 이웃의 이웃끼리 더한다. 각 는 번의 덧셈만 거치므로 상한이 가 된다. NumPy의
sum과 GPU reduction이 트리 모양이다. - Kahan(보정) 합산은 매 단계 잃은 아래 자리 비트를 두 번째 변수 에 담아 되먹인다. , , , . 상한이 로, 1차까지는 과 무관하다.
낮은 정밀도에서는 느린 증가가 아니라 정체(stagnation) 가 문제다. 누적합이 다음 항의 배를 넘으면 그 항을 더해도 아무것도 바뀌지 않는다. 0.5 근처의 수를 더하는 BF16 누산기는 256에서 멈춘다. 텐서 코어가 BF16/FP16/FP8 입력을 곱하되 FP32로 누산하는 이유이고, DeepSeek-V3의 FP8 GEMM이 일정 간격마다 부분합을 FP32로 올리는 이유다.
Why batch size changes the answer
A matrix multiply is independent dot products, each a sum over . How that sum is cut up — tile size along , how many split-K partial sums, whether they are combined in a tree or a chain — is the kernel’s choice, and libraries pick the kernel from the shape. In an inference server the batch dimension depends on load, so the same request lands in different kernels and gets different reduction orders. With the error bound above, each order gives a slightly different result at the level of ; after a few dozen layers and a softmax, the log-probability of the same token differs in the third or fourth digit, and occasionally greedy decoding takes a different token. The same happens in RMSNorm (a reduction over the hidden dimension), attention (split-KV in decode, online-softmax merges) and all-reduce across tensor-parallel ranks. It is not randomness: run the same batch twice and the bits are identical. Batch-invariant kernels fix the reduction strategy independently of the batch size, at some cost in speed.
Logsumexp, softmax and log-softmax
overflows FP32 for and FP16 for , and underflows to zero long before is very negative. The fix uses one identity, valid for any constant :
With the maximum, every exponent is (no overflow) and at least one term equals 1 (the sum is , so the log is safe). This logsumexp (LSE) satisfies , and its gradient is the softmax, . Then
Rules that follow:
- Compute cross-entropy from logits with log-softmax, never as
log(softmax(z)): a target probability of underflows FP32 to 0 and its log is , while is just . - Softmax is shift-invariant, but rounding error is not: an FP number’s error scales with its magnitude, so large logits carry large absolute errors even after the shift. That is the mechanism behind keeping the LM head in FP32 in RL (Track IX).
- The max-shift can be done online: carry with and merge two blocks as , . That merge is the core of FlashAttention and of fused linear-cross-entropy kernels.
- The two-class case: , computed as . This is the Bradley–Terry and DPO loss.
- z-loss penalises to keep the free shift of the logits near zero.
def logsumexp(z, axis=-1):
m = np.max(z, axis=axis, keepdims=True)
return m + np.log(np.sum(np.exp(z - m), axis=axis, keepdims=True))
def log_softmax(z, axis=-1):
return z - logsumexp(z, axis)
z = np.array([1000.0, 999.0, 990.0], dtype=np.float32)
with np.errstate(all="ignore"):
naive = np.exp(z) / np.exp(z).sum()
print("naive softmax :", naive)
print("stable softmax:", np.exp(log_softmax(z)))
print("fp16: exp(11.0) =", np.exp(np.float16(11.0)), " exp(11.1) =", np.exp(np.float16(11.1)), " (max 65504)")
# Cross-entropy from probabilities vs from logits: the target's probability underflows
z = np.array([0.0, -120.0], dtype=np.float32)
with np.errstate(all="ignore"):
p = np.exp(z) / np.exp(z).sum()
print(f"\nlog(softmax(z))[1] = {np.log(p)[1]} log_softmax(z)[1] = {log_softmax(z)[1]}")
# Catastrophic cancellation and the functions that avoid it
x = 1e-10
print(f"\nlog(1+x) = {np.log(1 + x):.15e} log1p(x) = {np.log1p(x):.15e}")
t = np.float32(1e-4)
print(f"fp32 1-cos(t) = {np.float32(1) - np.cos(t):.6e} 2 sin^2(t/2) = {2 * np.sin(t / 2) ** 2:.6e} (true {1e-8 / 2:.6e})")
# The k3 KL estimator r - 1 - log r with log r = d small, in float32
for d in [1e-2, 1e-3, 1e-4]:
d32 = np.float32(d)
naive_k3 = np.exp(d32) - np.float32(1) - d32
good_k3 = np.expm1(d32) - d32
true = np.expm1(d) - d
print(f"d = {d:.0e}: exp(d)-1-d = {naive_k3:.4e} expm1(d)-d = {good_k3:.4e} true {true:.4e}")
# Variance by E[x^2] - E[x]^2 vs two-pass, data with a large mean, in float32
rs = np.random.default_rng(0)
v = (1e4 + rs.normal(0, 1, 100_000)).astype(np.float32)
one_pass = np.mean(v * v) - np.mean(v) ** 2
two_pass = np.mean((v - v.mean()) ** 2)
print(f"\nvariance (true ~1): E[x^2]-E[x]^2 = {one_pass:.3f} two-pass = {two_pass:.4f}")Numerical differentiation and gradient checks
A finite difference trades two errors. Taylor’s theorem gives the truncation error; the standard model gives the rounding error of subtracting two nearly equal function values, each known only to about :
The best achievable error is about : in FP64, in FP32, in BF16. The central difference cancels the even Taylor terms:
The complex step avoids the subtraction entirely: for real-analytic , , so with no cancellation, and works.
배치 크기가 답을 바꾸는 이유
행렬곱은 개의 독립된 내적이고, 각각은 에 대한 합이다. 그 합을 어떻게 자르는지 — 방향 타일 크기, split-K 부분합의 개수, 부분합을 트리로 합치는지 사슬로 합치는지 — 는 커널이 고르고, 라이브러리는 shape을 보고 커널을 고른다. 추론 서버에서 배치 차원 은 부하에 따라 달라지므로, 같은 요청이 다른 커널에 들어가 다른 reduction 순서를 얻는다. 위의 오차 상한대로 순서마다 수준에서 결과가 조금씩 다르고, 수십 개 층과 softmax를 지나면 같은 토큰의 log-prob이 셋째·넷째 자리에서 달라지며, 가끔은 greedy 디코딩이 다른 토큰을 고른다. RMSNorm(hidden 차원에 대한 reduction), attention(decode의 split-KV, online softmax 병합), tensor-parallel rank 사이의 all-reduce에서도 같은 일이 일어난다. 무작위성은 아니다. 같은 배치를 두 번 돌리면 비트가 똑같다. batch-invariant 커널은 배치 크기와 무관하게 reduction 전략을 고정한다. 속도를 조금 내준다.
Logsumexp, softmax, log-softmax
는 FP32에서 , FP16에서 면 overflow하고, 가 아주 음수가 되기 훨씬 전에 0으로 underflow한다. 처방은 임의의 상수 에 대해 성립하는 항등식 하나다.
를 최댓값으로 두면 모든 지수가 이고(overflow 없음), 적어도 한 항이 1이다(합이 이라 로그가 안전하다). 이 logsumexp(LSE)는 를 만족하고, gradient가 softmax다: . 그러면
여기서 나오는 규칙들.
- Cross-entropy는
log(softmax(z))가 아니라 logit에서 log-softmax로 계산한다. 정답 확률 은 FP32에서 0으로 underflow해 로그가 가 되지만, 는 그냥 이다. - Softmax는 shift에 불변이지만 반올림 오차는 아니다. FP 수의 오차는 크기에 비례하므로, 큰 logit은 shift를 한 뒤에도 큰 절대 오차를 지닌다. RL에서 LM head를 FP32로 유지하는(Track IX) 메커니즘이 이것이다.
- 최댓값 shift는 online으로 할 수 있다. 인 를 들고 다니며 두 블록을 , 로 합친다. 이 병합이 FlashAttention과 fused linear-cross-entropy 커널의 핵심이다.
- 두 클래스의 경우: 를 로 계산한다. Bradley–Terry와 DPO의 손실이다.
- z-loss는 에 벌점을 줘서 logit의 자유로운 shift를 0 근처에 묶는다.
def logsumexp(z, axis=-1):
m = np.max(z, axis=axis, keepdims=True)
return m + np.log(np.sum(np.exp(z - m), axis=axis, keepdims=True))
def log_softmax(z, axis=-1):
return z - logsumexp(z, axis)
z = np.array([1000.0, 999.0, 990.0], dtype=np.float32)
with np.errstate(all="ignore"):
naive = np.exp(z) / np.exp(z).sum()
print("naive softmax :", naive)
print("stable softmax:", np.exp(log_softmax(z)))
print("fp16: exp(11.0) =", np.exp(np.float16(11.0)), " exp(11.1) =", np.exp(np.float16(11.1)), " (max 65504)")
# 확률에서 vs logit에서 계산한 cross-entropy: 정답 확률이 underflow한다
z = np.array([0.0, -120.0], dtype=np.float32)
with np.errstate(all="ignore"):
p = np.exp(z) / np.exp(z).sum()
print(f"\nlog(softmax(z))[1] = {np.log(p)[1]} log_softmax(z)[1] = {log_softmax(z)[1]}")
# 파국적 상쇄와 그것을 피하는 함수들
x = 1e-10
print(f"\nlog(1+x) = {np.log(1 + x):.15e} log1p(x) = {np.log1p(x):.15e}")
t = np.float32(1e-4)
print(f"fp32 1-cos(t) = {np.float32(1) - np.cos(t):.6e} 2 sin^2(t/2) = {2 * np.sin(t / 2) ** 2:.6e} (true {1e-8 / 2:.6e})")
# k3 KL 추정량 r - 1 - log r, log r = d가 작을 때, float32에서
for d in [1e-2, 1e-3, 1e-4]:
d32 = np.float32(d)
naive_k3 = np.exp(d32) - np.float32(1) - d32
good_k3 = np.expm1(d32) - d32
true = np.expm1(d) - d
print(f"d = {d:.0e}: exp(d)-1-d = {naive_k3:.4e} expm1(d)-d = {good_k3:.4e} true {true:.4e}")
# 분산: E[x^2] - E[x]^2 vs two-pass, 평균이 큰 데이터, float32에서
rs = np.random.default_rng(0)
v = (1e4 + rs.normal(0, 1, 100_000)).astype(np.float32)
one_pass = np.mean(v * v) - np.mean(v) ** 2
two_pass = np.mean((v - v.mean()) ** 2)
print(f"\nvariance (true ~1): E[x^2]-E[x]^2 = {one_pass:.3f} two-pass = {two_pass:.4f}")수치 미분과 gradient check
유한 차분은 두 오차를 맞바꾼다. 테일러 정리가 절단(truncation) 오차를 주고, 표준 모형이 거의 같은 두 함숫값 — 각각 약 까지만 알려진 — 을 빼는 반올림 오차를 준다.
얻을 수 있는 최선의 오차는 약 다. FP64에서 , FP32에서 , BF16에서 . 중심 차분은 테일러의 짝수 차 항을 지운다.
복소 간격(complex step) 은 뺄셈을 아예 피한다. 실해석적인 에 대해 이므로 이고 상쇄가 없어서 도 된다.
A gradient check compares an analytic or autograd gradient with central differences via the relative error . Practical rules follow from the V:
- Do it in FP64 with –; expect about –. In FP32 the result swings between about and depending on , and real bugs hide in that noise.
- A bug that is wrong by a few percent shows up as ; ” in FP64” is already suspicious.
- For many parameters, check directional derivatives: pick a random and compare with — two loss evaluations, whatever the dimension. That is a JVP checked against a VJP.
- Kinks (ReLU, max, clipping, top- routing) break the Taylor model where straddles them; move the test point or shrink .
# Finite differences of sin at x = 1: the error is a V in h
x0, truth = 1.0, np.cos(1.0)
print(" h forward(f64) central(f64) central(f32) complex step")
for k in [1, 3, 5, 6, 8, 10, 12]:
h = 10.0 ** -k
fwd = (np.sin(x0 + h) - np.sin(x0)) / h
cen = (np.sin(x0 + h) - np.sin(x0 - h)) / (2 * h)
x32, h32 = np.float32(x0), np.float32(h)
c32 = (np.sin(x32 + h32) - np.sin(x32 - h32)) / (np.float32(2) * h32)
cs = np.sin(x0 + 1j * h).imag / h # no subtraction, so no cancellation
print(f" 1e-{k:<2d} {abs(fwd - truth):11.1e} {abs(cen - truth):11.1e} {abs(c32 - truth):11.1e} {abs(cs - truth):11.1e}")
# Gradient check of softmax regression: analytic gradient vs central differences
rs = np.random.default_rng(0)
n, d, K = 32, 5, 4
X64, y = rs.normal(size=(n, d)), rs.integers(0, K, n)
def loss(W, X):
return -np.mean(log_softmax(X @ W)[np.arange(n), y])
def grad(W, X):
P = np.exp(log_softmax(X @ W))
P[np.arange(n), y] -= 1 # softmax - onehot
return X.T @ P / n
def numgrad(W, X, eps):
G = np.zeros_like(W)
for idx in np.ndindex(W.shape):
E = np.zeros_like(W)
E[idx] = eps
G[idx] = (loss(W + E, X) - loss(W - E, X)) / (2 * eps)
return G
rel = lambda a, b: np.max(np.abs(a - b)) / max(np.max(np.abs(a)), np.max(np.abs(b)))
W = rs.normal(size=(d, K))
W32, X32 = W.astype(np.float32), X64.astype(np.float32)
print(f"\nfloat64, eps=1e-5: rel. error {rel(grad(W, X64), numgrad(W, X64, 1e-5)):.1e}")
print(f"float32, eps=1e-5: rel. error {rel(grad(W32, X32), numgrad(W32, X32, np.float32(1e-5))):.1e} <- rounding noise, not a bug")
print(f"float32, eps=1e-2: rel. error {rel(grad(W32, X32), numgrad(W32, X32, np.float32(1e-2))):.1e}")
buggy = grad(W, X64) * np.array([1, 1, 1, 0.9]) # a planted 10% bug in one column
print(f"float64, buggy gradient: rel. error {rel(buggy, numgrad(W, X64, 1e-5)):.1e}")
# Directional check: one random direction, two loss evaluations, any number of parameters
V = rs.normal(size=W.shape)
dd = (loss(W + 1e-5 * V, X64) - loss(W - 1e-5 * V, X64)) / 2e-5
print(f"directional: (L(W+eV) - L(W-eV)) / 2e = {dd:.10f} <grad, V> = {np.sum(grad(W, X64) * V):.10f}")Mixed precision and loss scaling
Training in 16 bits needs three things beyond the format (Micikevicius et al., 2018):
- FP32 master weights. An update is applied to a weight as . If , rounding returns unchanged: in BF16 a weight of 1.0 ignores any update smaller than . Keeping an FP32 copy for the update (and casting down for the forward pass) avoids this swamping. Optimizer states such as Adam’s second moment are kept in FP32 for the same reason. Stochastic rounding — round up with probability equal to the fractional distance — is an alternative: unbiased in expectation, so small updates survive on average.
- FP32 accumulation in matmuls and reductions, for the reasons in the summation section.
- Loss scaling (FP16 only). Gradients of activations are often tiny, and FP16 flushes everything below to zero. Multiplying the loss by multiplies every gradient by (the chain rule is linear in the output gradient), shifting the histogram into range; the gradients are divided by in FP32 before the update. Dynamic loss scaling starts with a large , skips the step and halves when an inf/NaN appears, and doubles after a run of clean steps (PyTorch’s
GradScalerdoes this).
BF16 has FP32’s exponent range, so step 3 is usually unnecessary — the main reason BF16 replaced FP16 for training. FP8 has neither enough range nor precision for a single global scale: E4M3 (more precision) is used for weights and activations, E5M2 (more range) for gradients, and each tensor — or, in DeepSeek-V3 and the MX/NVFP4 formats, each block — carries its own scale.
# 1) Why master weights stay in fp32: 1000 SGD steps of size 1e-4 on a weight equal to 1.0
steps, upd = 1000, 1e-4
w_bf16, w_fp32 = 1.0, 1.0
for _ in range(steps):
w_bf16 = round_to(w_bf16 - upd, 7) # weight stored in bf16
w_fp32 = float(np.float32(w_fp32 - upd)) # fp32 master copy
print(f"after {steps} updates of {upd}: bf16 weight {w_bf16}, fp32 master weight {w_fp32:.4f} (exact 0.9)")
def stochastic_round(v, m, rs):
"""Round down or up with probability proportional to the distance: unbiased on average."""
q = 2.0 ** (math.frexp(v)[1] - 1 - m)
lo = math.floor(v / q) * q
return lo + q * (rs.random() < (v - lo) / q)
rs = np.random.default_rng(0)
w_sr = 1.0
for _ in range(steps):
w_sr = stochastic_round(w_sr - upd, 7, rs)
print(f"bf16 weight with stochastic rounding: {w_sr}")
# 2) Loss scaling for fp16 gradients: magnitudes spread over many binades
g = np.exp2(rs.normal(-27, 3.5, 200_000)) * rs.choice([-1, 1], 200_000) # fp32 "true" gradients
for log2S in [0, 8, 16, 24, 40]:
S = 2.0 ** log2S
with np.errstate(over="ignore"):
g16 = (g * S).astype(np.float16) # what the fp16 backward pass would hold
finite = np.isfinite(g16).all()
back = g16.astype(np.float64) / S # unscale in fp32/fp64 before the update
zero = np.mean(g16 == 0)
err = np.median(np.abs(back - g) / np.abs(g)) if finite else float("nan")
print(f"S = 2^{log2S:<2d}: flushed to zero {zero:6.1%} overflow {not finite!s:5} median rel. error {err:.1e}")
print("bf16 has fp32's exponent range: smallest normal", f"{2.0**-126:.1e}", "so the same gradients need no scaling")A weight equal to 1.0 is stored in BF16 and receives the SGD update −0.003. What value is stored afterwards?
Below 1, in , BF16’s spacing is , so the neighbours of 0.997 are and . 0.997 is closer to the latter, so the stored step is — 30% larger than intended. An update smaller than would have been lost entirely. Either way the update is not what the optimizer computed, which is why master weights are FP32.
Roughly what is the largest logit z for which exp(z) is still finite in FP16?
FP16’s largest value is 65504 and . (88.7 is the FP32/BF16 limit, 709.8 the FP64 one.) A logit of 12 is unremarkable, which is why softmax is never computed as exp(z) / sum(exp(z)) without subtracting the maximum.
Summary
- A float with mantissa bits has relative precision everywhere in its normal range; exponent bits set the range. , .
- Subtracting nearby numbers amplifies their relative error by ; rewrite with
log1p,expm1, two-pass variance, log-space ratios. - Sequential sums have error and can stagnate in low precision; pairwise gives , Kahan . Reduction order depends on kernel choice, which depends on batch shape.
- Use logsumexp/log-softmax from logits; the max shift prevents overflow, and the online version is FlashAttention’s merge.
- Finite differences have a V-shaped error with optimum (forward) or (central): gradient-check in FP64, or use directional checks.
- Mixed precision = low-precision compute + FP32 master weights and accumulation + loss scaling for FP16 (not BF16) + per-tensor or per-block scales for FP8.
Where this is used
- Linear models, GPT from scratch — stable softmax and cross-entropy from logits.
- Backprop — the finite-difference gradient check of a hand-written MLP.
- Training deep nets, Optimizers — normalisation layers, Adam’s ε, precision of optimizer state.
- Attention kernels, Long context — online softmax as a merge, fused linear-cross-entropy.
- Stability components — z-loss, logit soft-capping, BF16 resolution of attention logits.
- Quantisation, DeepSeek-V3 — FP8 E4M3/E5M2, MX and NVFP4 block scales, FP32 promotion in FP8 GEMMs.
- Inference for RL, Mismatch engineering, Off-policy mismatch — batch-dependent reductions, batch-invariant kernels, FP32 LM head.
- Regularisation, KL-regularised RL — computing k1/k3 from log-probabilities.
- Training parallelism — all-reduce order across ranks, mixed-precision memory accounting.
- Previous: Information theory — the quantities these numerics protect.
Gradient check은 해석적(또는 autograd) gradient 를 중심 차분 와 상대 오차 로 비교한다. V 모양에서 실전 규칙이 나온다.
- FP64에서 –로 한다. – 정도를 기대한다. FP32에서는 에 따라 결과가 대략 에서 사이를 오가고, 진짜 버그가 그 잡음 속에 숨는다.
- 몇 퍼센트 틀린 버그는 로 나타난다. “FP64에서 “이면 이미 의심스럽다.
- 매개변수가 많으면 방향 미분을 검사한다. 무작위 를 골라 를 와 비교한다. 차원과 무관하게 손실 계산 두 번이다. JVP로 VJP를 검사하는 셈이다.
- 꺾이는 점(ReLU, max, clipping, top- routing)이 사이에 걸리면 테일러 모형이 깨진다. 시험 지점을 옮기거나 를 줄인다.
# x = 1에서 sin의 유한 차분: 오차는 h에 대해 V 모양
x0, truth = 1.0, np.cos(1.0)
print(" h forward(f64) central(f64) central(f32) complex step")
for k in [1, 3, 5, 6, 8, 10, 12]:
h = 10.0 ** -k
fwd = (np.sin(x0 + h) - np.sin(x0)) / h
cen = (np.sin(x0 + h) - np.sin(x0 - h)) / (2 * h)
x32, h32 = np.float32(x0), np.float32(h)
c32 = (np.sin(x32 + h32) - np.sin(x32 - h32)) / (np.float32(2) * h32)
cs = np.sin(x0 + 1j * h).imag / h # 뺄셈이 없으니 상쇄도 없다
print(f" 1e-{k:<2d} {abs(fwd - truth):11.1e} {abs(cen - truth):11.1e} {abs(c32 - truth):11.1e} {abs(cs - truth):11.1e}")
# softmax 회귀의 gradient check: 해석적 gradient vs 중심 차분
rs = np.random.default_rng(0)
n, d, K = 32, 5, 4
X64, y = rs.normal(size=(n, d)), rs.integers(0, K, n)
def loss(W, X):
return -np.mean(log_softmax(X @ W)[np.arange(n), y])
def grad(W, X):
P = np.exp(log_softmax(X @ W))
P[np.arange(n), y] -= 1 # softmax - onehot
return X.T @ P / n
def numgrad(W, X, eps):
G = np.zeros_like(W)
for idx in np.ndindex(W.shape):
E = np.zeros_like(W)
E[idx] = eps
G[idx] = (loss(W + E, X) - loss(W - E, X)) / (2 * eps)
return G
rel = lambda a, b: np.max(np.abs(a - b)) / max(np.max(np.abs(a)), np.max(np.abs(b)))
W = rs.normal(size=(d, K))
W32, X32 = W.astype(np.float32), X64.astype(np.float32)
print(f"\nfloat64, eps=1e-5: rel. error {rel(grad(W, X64), numgrad(W, X64, 1e-5)):.1e}")
print(f"float32, eps=1e-5: rel. error {rel(grad(W32, X32), numgrad(W32, X32, np.float32(1e-5))):.1e} <- rounding noise, not a bug")
print(f"float32, eps=1e-2: rel. error {rel(grad(W32, X32), numgrad(W32, X32, np.float32(1e-2))):.1e}")
buggy = grad(W, X64) * np.array([1, 1, 1, 0.9]) # 한 열에 심어 둔 10% 버그
print(f"float64, buggy gradient: rel. error {rel(buggy, numgrad(W, X64, 1e-5)):.1e}")
# 방향 검사: 무작위 방향 하나, 손실 계산 두 번, 매개변수 수와 무관
V = rs.normal(size=W.shape)
dd = (loss(W + 1e-5 * V, X64) - loss(W - 1e-5 * V, X64)) / 2e-5
print(f"directional: (L(W+eV) - L(W-eV)) / 2e = {dd:.10f} <grad, V> = {np.sum(grad(W, X64) * V):.10f}")Mixed precision과 loss scaling
16비트로 학습하려면 형식 말고도 세 가지가 필요하다(Micikevicius et al., 2018).
- FP32 master weight. 업데이트는 가중치에 로 적용된다. 이면 반올림이 를 그대로 돌려준다. BF16에서 1.0인 가중치는 보다 작은 업데이트를 모두 무시한다. 업데이트용 FP32 사본을 두고(forward에는 낮춰서 쓰고) 이 swamping을 피한다. Adam의 2차 모멘트 같은 optimizer 상태를 FP32로 두는 이유도 같다. 확률적 반올림(stochastic rounding) — 소수 부분의 거리만큼의 확률로 올림 — 도 대안이다. 기댓값으로 편향이 없어서 작은 업데이트가 평균적으로 살아남는다.
- 행렬곱과 reduction의 FP32 누산. 이유는 합산 절에서 본 그대로다.
- Loss scaling(FP16에서만). activation의 gradient는 아주 작은 경우가 많고, FP16은 아래를 모두 0으로 만든다. 손실에 를 곱하면 모든 gradient가 배가 되어(연쇄 법칙은 출력 gradient에 대해 선형) 히스토그램이 범위 안으로 옮겨진다. 업데이트 전에 FP32에서 로 나눈다. 동적 loss scaling은 큰 로 시작해, inf/NaN이 나오면 그 step을 건너뛰고 를 반으로 줄이고, 깨끗한 step이 이어지면 를 두 배로 늘린다(PyTorch의
GradScaler가 이렇게 한다).
BF16은 FP32의 지수 범위를 가지므로 3번은 대개 필요 없다. BF16이 학습에서 FP16을 대체한 주된 이유다. FP8은 전역 scale 하나로 버틸 범위도 정밀도도 없다. 가중치와 activation에는 E4M3(정밀도 우선), gradient에는 E5M2(범위 우선)를 쓰고, 텐서마다 — DeepSeek-V3와 MX/NVFP4 형식에서는 블록마다 — scale을 따로 둔다.
# 1) master weight를 fp32로 두는 이유: 1.0인 가중치에 크기 1e-4인 SGD step 1000번
steps, upd = 1000, 1e-4
w_bf16, w_fp32 = 1.0, 1.0
for _ in range(steps):
w_bf16 = round_to(w_bf16 - upd, 7) # bf16으로 저장한 가중치
w_fp32 = float(np.float32(w_fp32 - upd)) # fp32 master 사본
print(f"after {steps} updates of {upd}: bf16 weight {w_bf16}, fp32 master weight {w_fp32:.4f} (exact 0.9)")
def stochastic_round(v, m, rs):
"""거리에 비례하는 확률로 내림 또는 올림: 평균적으로 편향이 없다."""
q = 2.0 ** (math.frexp(v)[1] - 1 - m)
lo = math.floor(v / q) * q
return lo + q * (rs.random() < (v - lo) / q)
rs = np.random.default_rng(0)
w_sr = 1.0
for _ in range(steps):
w_sr = stochastic_round(w_sr - upd, 7, rs)
print(f"bf16 weight with stochastic rounding: {w_sr}")
# 2) fp16 gradient의 loss scaling: 크기가 여러 2배 구간에 걸쳐 퍼져 있다
g = np.exp2(rs.normal(-27, 3.5, 200_000)) * rs.choice([-1, 1], 200_000) # fp32 "참" gradient
for log2S in [0, 8, 16, 24, 40]:
S = 2.0 ** log2S
with np.errstate(over="ignore"):
g16 = (g * S).astype(np.float16) # fp16 backward가 담게 될 값
finite = np.isfinite(g16).all()
back = g16.astype(np.float64) / S # 업데이트 전에 fp32/fp64에서 scale을 되돌린다
zero = np.mean(g16 == 0)
err = np.median(np.abs(back - g) / np.abs(g)) if finite else float("nan")
print(f"S = 2^{log2S:<2d}: flushed to zero {zero:6.1%} overflow {not finite!s:5} median rel. error {err:.1e}")
print("bf16 has fp32's exponent range: smallest normal", f"{2.0**-126:.1e}", "so the same gradients need no scaling")1.0인 가중치가 BF16으로 저장되어 있고 SGD 업데이트 −0.003을 받는다. 업데이트 후 저장되는 값은?
1 아래 에서 BF16의 간격은 이므로 0.997의 이웃은 과 다. 0.997은 뒤의 것에 더 가까우니 저장되는 걸음은 , 의도보다 30% 크다. 보다 작은 업데이트였다면 통째로 사라졌을 것이다. 어느 쪽이든 optimizer가 계산한 업데이트가 아니다. master weight를 FP32로 두는 이유다.
FP16에서 exp(z)가 유한한 가장 큰 logit z는 대략?
FP16의 최댓값은 65504이고 다(88.7은 FP32/BF16, 709.8은 FP64의 한계). logit 12는 흔한 값이다. 최댓값을 빼지 않고 exp(z) / sum(exp(z))로 softmax를 계산하지 않는 이유다.
정리
- 가수 비트가 개인 float는 정규 범위 어디서나 상대 정밀도 을 가진다. 지수 비트가 범위를 정한다. , .
- 가까운 수의 뺄셈은 상대 오차를 배 키운다.
log1p,expm1, two-pass 분산, 로그 공간의 비율로 고쳐 쓴다. - 순차 합의 오차는 이고 낮은 정밀도에서는 정체할 수 있다. 쌍별 합은 , Kahan은 . reduction 순서는 커널 선택에, 커널 선택은 배치 shape에 달려 있다.
- logit에서 logsumexp/log-softmax를 쓴다. 최댓값 shift가 overflow를 막고, 그 online 버전이 FlashAttention의 병합이다.
- 유한 차분의 오차는 V 모양이고 최적이 (전진) 또는 (중심)이다. gradient check은 FP64에서 하거나 방향 검사를 쓴다.
- Mixed precision = 낮은 정밀도 연산 + FP32 master weight와 누산 + FP16의(BF16은 아님) loss scaling + FP8의 텐서별·블록별 scale.
이 사이트에서 쓰이는 곳
- 선형 모델, GPT를 바닥부터 — 안정적 softmax와 logit에서 계산하는 cross-entropy.
- 역전파 — 손으로 짠 MLP의 유한 차분 gradient check.
- 깊은 신경망 학습, Optimizer — 정규화 층, Adam의 ε, optimizer 상태의 정밀도.
- Attention 커널, 긴 문맥 — 병합으로서의 online softmax, fused linear-cross-entropy.
- 안정화 부품 — z-loss, logit soft-capping, attention logit의 BF16 해상도.
- 양자화, DeepSeek-V3 — FP8 E4M3/E5M2, MX·NVFP4 블록 scale, FP8 GEMM의 FP32 승격.
- RL을 위한 추론, 불일치 엔지니어링, Off-policy 불일치 — 배치에 따라 바뀌는 reduction, batch-invariant 커널, FP32 LM head.
- 정규화, KL 정규화 RL — log-prob에서 k1/k3 계산하기.
- 학습 병렬화 — rank 사이 all-reduce 순서, mixed precision의 메모리 계산.
- 이전: 정보 이론 — 이 수치 기법들이 지키는 양들.
더 읽을거리Further reading
- Goldberg, What Every Computer Scientist Should Know About Floating-Point Arithmetic (ACM Computing Surveys, 1991) — 부동소수점의 고전. ulp, 상쇄, guard digit, 반올림 오차 분석.The classic on floating point — ulps, cancellation, guard digits, rounding-error analysis.
- Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed. (SIAM, 2002), ch. 2–4 — 표준 모형 fl(a∘b) = (a∘b)(1+δ), 합산 알고리즘(순차·쌍별·보정 합)의 오차 한계.The standard model fl(a∘b) = (a∘b)(1+δ) and error bounds for recursive, pairwise and compensated summation.
- Kahan, Further Remarks on Reducing Truncation Errors (CACM, 1965) — 보정 합산(Kahan summation)의 원전.The original compensated (Kahan) summation.
- Micikevicius et al., Mixed Precision Training (ICLR 2018) — FP32 master weight, loss scaling, FP32 누산이라는 mixed precision의 세 요소.The three ingredients of mixed precision — FP32 master weights, loss scaling, FP32 accumulation.
- Kalamkar et al., A Study of BFLOAT16 for Deep Learning Training (2019) — FP32와 같은 지수 범위를 가진 BF16이 loss scaling 없이 학습되는 이유.Why BF16, with FP32's exponent range, trains without loss scaling.
- Micikevicius et al., FP8 Formats for Deep Learning (2022) — E4M3과 E5M2의 정의와 쓰임새.The definitions and roles of E4M3 and E5M2.
- He & Thinking Machines Lab, Defeating Nondeterminism in LLM Inference (2025) — LLM 추론의 비결정성이 배치 크기에 따라 바뀌는 reduction 순서에서 온다는 분석과 batch-invariant 커널.Traces LLM-inference nondeterminism to reduction orders that change with batch size; batch-invariant kernels.
- Squire & Trapp, Using Complex Variables to Estimate Derivatives of Real Functions (SIAM Review, 1998) — 뺄셈 없는 복소 간격 미분.The complex-step derivative, which needs no subtraction.