Track 0 · Math Foundations · 08/10

수치 계산Numerics

부동소수점의 구조(부호·지수·가수, ulp, 단위 반올림)와 FP32·BF16·FP16·FP8의 차이, 상쇄와 합산 순서가 만드는 오차, 배치 크기가 결과를 바꾸는 이유, logsumexp·안정적 softmax, 수치 미분과 gradient check, mixed precision과 loss scaling을 직접 조작하며 익힌다.How floating point works (sign, exponent, mantissa, ulp, unit roundoff) and how FP32, BF16, FP16 and FP8 differ; the errors made by cancellation and by summation order, and why batch size changes results; logsumexp and stable softmax; numerical differentiation and gradient checks; mixed precision and loss scaling.

45 분min floating point · bf16 · fp16 · fp8 · ulp · rounding · cancellation · summation · Kahan · logsumexp · softmax · finite differences · gradient check · mixed precision · loss scaling 먼저 볼 것:Before this: 미분·연쇄법칙·JacobianDerivatives, the chain rule and Jacobians

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 ee exponent bits and mm mantissa (fraction) bits stores a sign ss, an exponent field EE and a fraction ff:

x=(−1)s×1.f1f2…fm(2)×2E−bias,bias=2e−1−1.x = (-1)^s \times 1.f_1f_2\ldots f_m{}_{(2)} \times 2^{E - \text{bias}}, \qquad \text{bias} = 2^{e-1} - 1 .

Between 2k2^k and 2k+12^{k+1} there are exactly 2m2^m equally spaced values, so the spacing — the ulp (unit in the last place) — is ulp(x)=2k−m\mathrm{ulp}(x) = 2^{k - m} for x∈[2k,2k+1)x \in [2^k, 2^{k+1}). The spacing grows with magnitude, but the relative spacing stays within a factor of two: 2−m−1<ulp(x)/∣x∣≤2−m2^{-m-1} < \mathrm{ulp}(x)/|x| \le 2^{-m}. Rounding to nearest therefore has relative error at most the unit roundoff

u=2−(m+1),fl(x)=x(1+δ), ∣δ∣≤u,u = 2^{-(m+1)}, \qquad \mathrm{fl}(x) = x(1 + \delta),\ |\delta| \le u ,

and IEEE arithmetic guarantees the same for each operation: fl(a∘b)=(a∘b)(1+δ)\mathrm{fl}(a \circ b) = (a \circ b)(1 + \delta), ∣δ∣≤u|\delta| \le u, for ∘∈{+,−,×,÷}\circ \in \{+,-,\times,\div\} and ⋅\sqrt{\cdot}. This one-line standard model is all the error analysis below uses. (Some texts call ϵ=2−m\epsilon = 2^{-m}, the gap from 1 to the next float, “machine epsilon”; NumPy’s finfo.eps is that ϵ=2u\epsilon = 2u.)

The exponent field’s extreme values are reserved. E=0E = 0 encodes subnormals 0.f×21−bias0.f \times 2^{1-\text{bias}}, 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 ±∞\pm\infty 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.

formatsign/exp/mantissalargestsmallest normalsmallest subnormaluu
FP321 / 8 / 233.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}1.4×10−451.4\times10^{-45}2−24≈6.0×10−82^{-24} \approx 6.0\times10^{-8}
BF161 / 8 / 73.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}9.2×10−419.2\times10^{-41}2−8≈3.9×10−32^{-8} \approx 3.9\times10^{-3}
FP161 / 5 / 10655046.1×10−56.1\times10^{-5}6.0×10−86.0\times10^{-8}2−11≈4.9×10−42^{-11} \approx 4.9\times10^{-4}
FP8 E5M21 / 5 / 2573446.1×10−56.1\times10^{-5}1.5×10−51.5\times10^{-5}2−3=0.1252^{-3} = 0.125
FP8 E4M31 / 4 / 34481.6×10−21.6\times10^{-2}2.0×10−32.0\times10^{-3}2−4=0.06252^{-4} = 0.0625

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 6×10−86\times10^{-8} to zero.

앞의 레슨들의 수학은 실수를 가정한다. 하드웨어에는 유한한 수의 집합만 있다. 대개 그 차이는 보이지 않지만, 이 사이트에서는 이름 붙은 문제로 드러난다. NaN을 돌려주는 softmax, 같은 토큰의 log-prob을 두고 엇갈리는 trainer와 추론 엔진, 배치 크기에 따라 바뀌는 결과, 블록마다 scale이 필요한 FP8 학습. 이 레슨은 이것들을 모두 설명하는 작은 부동소수점 모형을 만든다.

float란 무엇인가

지수 비트 ee개, 가수(fraction) 비트 mm개인 이진 부동소수점 수는 부호 ss, 지수 필드 EE, 가수 ff를 저장한다.

x=(−1)s×1.f1f2…fm(2)×2E−bias,bias=2e−1−1.x = (-1)^s \times 1.f_1f_2\ldots f_m{}_{(2)} \times 2^{E - \text{bias}}, \qquad \text{bias} = 2^{e-1} - 1 .

2k2^k와 2k+12^{k+1} 사이에는 같은 간격의 값이 정확히 2m2^m개 있으므로, 간격 — ulp(unit in the last place) — 은 x∈[2k,2k+1)x \in [2^k, 2^{k+1})에서 ulp(x)=2k−m\mathrm{ulp}(x) = 2^{k - m}이다. 간격은 크기와 함께 커지지만 상대 간격은 두 배 범위 안에 머문다: 2−m−1<ulp(x)/∣x∣≤2−m2^{-m-1} < \mathrm{ulp}(x)/|x| \le 2^{-m}. 그래서 가장 가까운 값으로 반올림한 상대 오차는 많아야 단위 반올림(unit roundoff) 이다.

u=2−(m+1),fl(x)=x(1+δ), ∣δ∣≤u,u = 2^{-(m+1)}, \qquad \mathrm{fl}(x) = x(1 + \delta),\ |\delta| \le u ,

IEEE 산술은 각 연산에도 같은 것을 보장한다. ∘∈{+,−,×,÷}\circ \in \{+,-,\times,\div\}와 ⋅\sqrt{\cdot}에 대해 fl(a∘b)=(a∘b)(1+δ)\mathrm{fl}(a \circ b) = (a \circ b)(1 + \delta), ∣δ∣≤u|\delta| \le u. 아래의 오차 분석은 이 한 줄짜리 표준 모형만 쓴다. (1과 그다음 float 사이의 간격 ϵ=2−m\epsilon = 2^{-m}을 “machine epsilon”이라 부르는 책도 있다. NumPy의 finfo.eps가 그 ϵ=2u\epsilon = 2u다.)

지수 필드의 양 끝 값은 예약되어 있다. E=0E = 0은 subnormal 0.f×21−bias0.f \times 2^{1-\text{bias}}을 나타내며, 가장 작은 구간의 고정 간격으로 0까지의 틈을 메운다. 그래서 상대 정밀도가 절벽처럼 떨어지지 않고 서서히 나빠진다. 모든 비트가 1인 필드는 ±∞\pm\infty와 NaN이다(E4M3은 무한대를 버리고 값의 구간 하나를 더 얻는다). 반올림은 가장 가까운 값으로, 동률이면 짝수로(ties to even)(마지막 가수 비트가 0인 쪽) 한다. 체계적으로 위로 치우치는 편향을 피하기 위해서다.

형식부호/지수/가수최댓값최소 정규 수최소 subnormaluu
FP321 / 8 / 233.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}1.4×10−451.4\times10^{-45}2−24≈6.0×10−82^{-24} \approx 6.0\times10^{-8}
BF161 / 8 / 73.4×10383.4\times10^{38}1.2×10−381.2\times10^{-38}9.2×10−419.2\times10^{-41}2−8≈3.9×10−32^{-8} \approx 3.9\times10^{-3}
FP161 / 5 / 10655046.1×10−56.1\times10^{-5}6.0×10−86.0\times10^{-8}2−11≈4.9×10−42^{-11} \approx 4.9\times10^{-4}
FP8 E5M21 / 5 / 2573446.1×10−56.1\times10^{-5}1.5×10−51.5\times10^{-5}2−3=0.1252^{-3} = 0.125
FP8 E4M31 / 4 / 34481.6×10−21.6\times10^{-2}2.0×10−32.0\times10^{-3}2−4=0.06252^{-4} = 0.0625

지수 비트는 범위를, 가수 비트는 정밀도를 산다. BF16은 FP32에서 가수를 7비트로 자른 것이다. 범위는 같고 유효 숫자는 십진 2–3자리다. FP16은 가수가 3비트 더 많지만 65504에서 overflow하고 6×10−86\times10^{-8} 아래는 0으로 사라진다.

fl(x) – 상대 오차rel. error – ulp – u = 2−(m+1) – 범위range –
gradient → 0 (underflow)gradients → 0 (underflow) – subnormal (정밀도 손실)subnormal (lost precision) – overflow –
Type a value (try 0.1, 1/3 = 0.333333, 65520, 300, 1e-6) or drag log₂|x|, and switch formats. The top line shows the nearest representable neighbours: spacing doubles at every power of two. The lower plot is the relative spacing ulp(x)/|x| against magnitude — flat sawteeth (constant relative precision) inside the normal range, rising in the subnormal range, cut off at underflow and overflow. BF16 has FP32's range with 2¹⁶ = 65,536× coarser steps (spacing just above 1: 2⁻⁷ vs 2⁻²³); FP16 has finer steps but a narrow range. Raise the loss scale to slide the grey gradient histogram right: in FP16 it rescues gradients that would flush to zero, until the top tail overflows. 값을 입력하거나(0.1, 1/3 = 0.333333, 65520, 300, 1e-6 등) log₂|x|를 끌고, 형식을 바꿔 보세요. 위 줄은 표현 가능한 가장 가까운 이웃들이다. 2의 거듭제곱을 지날 때마다 간격이 두 배가 된다. 아래 그림은 크기에 따른 상대 간격 ulp(x)/|x|다. 정규 범위 안에서는 납작한 톱니(일정한 상대 정밀도), subnormal 범위에서는 솟아오르고, underflow와 overflow에서 잘린다. BF16은 FP32의 범위에 2¹⁶ = 65,536배 거친 간격(1 바로 위 간격 2⁻⁷ 대 2⁻²³), FP16은 간격이 촘촘한 대신 범위가 좁다. 손실 스케일을 올리면 회색 gradient 히스토그램이 오른쪽으로 밀린다. FP16에서는 0으로 사라질 gradient를 살려 내다가, 위쪽 꼬리가 overflow하기 시작한다.

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.

NumPy Floats up close: ulp, rounding, non-associativity, summation
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 a~=a(1+δa)\tilde a = a(1+\delta_a) and b~=b(1+δb)\tilde b = b(1+\delta_b), then

∣(a~−b~)−(a−b)∣∣a−b∣=∣aδa−bδb∣∣a−b∣≤u ∣a∣+∣b∣∣a−b∣.\frac{|(\tilde a - \tilde b) - (a - b)|}{|a - b|} = \frac{|a\delta_a - b\delta_b|}{|a-b|} \le u\,\frac{|a| + |b|}{|a - b|} .

The factor ∣a∣+∣b∣∣a−b∣\frac{|a|+|b|}{|a-b|} is the condition number of subtraction; when a≈ba \approx b it is huge and the leading digits cancel, leaving rounding noise. The cure is always algebraic — rewrite so the small quantity is computed directly:

  • log⁡(1+x)→\log(1+x) \to log1p(x), ex−1→e^x - 1 \to expm1(x), 1−cos⁡x→2sin⁡2(x/2)1 - \cos x \to 2\sin^2(x/2).
  • Variance: E[x2]−E[x]2\mathbb{E}[x^2] - \mathbb{E}[x]^2 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: k3=r−1−log⁡rk_3 = r - 1 - \log r with log⁡r=d\log r = d small is ≈d2/2\approx d^2/2, the difference of two numbers of size dd. Compute it as expm1(d) - d from log-probabilities, never from probabilities.
  • Log-ratios in general: take log⁡πθ−log⁡πold\log\pi_\theta - \log\pi_{\text{old}} of log-probabilities, not log⁡(πθ/πold)\log(\pi_\theta/\pi_{\text{old}}) of probabilities.

Non-associativity and summation order

Every rounding step loses up to uu of the running result, so the order of a sum matters. For S^\hat S computed left to right, applying the standard model n−1n-1 times gives (Higham ch. 4)

∣S^−S∣  ≤  (n−1) u∑i∣xi∣+O(u2).|\hat S - S| \;\le\; (n-1)\,u\sum_i |x_i| + O(u^2) .

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 xix_i passes through only ⌈log⁡2n⌉\lceil\log_2 n\rceil additions, so the bound becomes ⌈log⁡2n⌉ u∑∣xi∣\lceil \log_2 n\rceil\,u\sum|x_i|. NumPy’s sum and GPU reductions are tree-shaped.
  • Kahan (compensated) summation carries the low-order bits lost at each step in a second variable cc and feeds them back: y=xi−cy = x_i - c, t=s+yt = s + y, c=(t−s)−yc = (t - s) - y, s=ts = t. The bound becomes 2u∑∣xi∣+O(nu2)2u\sum|x_i| + O(nu^2), independent of nn to first order.

In low precision the failure is not just slow growth but stagnation: once the running sum exceeds 2m+12^{m+1} 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이 위로 올림하기 때문이다. 아래 그림의 실선 톱니가 현재 형식이다. 모든 형식의 톱니는 모양이 같고, 가수 폭만큼 위아래로 옮겨지고 지수 범위만큼 잘렸을 뿐이다.

NumPy float 가까이서 보기: ulp, 반올림, 비결합성, 합산
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)

가까운 두 수의 뺄셈은 저장된 값에 대해서는 정확하지만, 그 값들이 이미 가진 오차를 드러낸다. a~=a(1+δa)\tilde a = a(1+\delta_a), b~=b(1+δb)\tilde b = b(1+\delta_b)라면

∣(a~−b~)−(a−b)∣∣a−b∣=∣aδa−bδb∣∣a−b∣≤u ∣a∣+∣b∣∣a−b∣.\frac{|(\tilde a - \tilde b) - (a - b)|}{|a - b|} = \frac{|a\delta_a - b\delta_b|}{|a-b|} \le u\,\frac{|a| + |b|}{|a - b|} .

∣a∣+∣b∣∣a−b∣\frac{|a|+|b|}{|a-b|}가 뺄셈의 조건수다. a≈ba \approx b면 이것이 거대해지고, 앞자리가 상쇄되어 반올림 잡음만 남는다. 처방은 언제나 대수적이다. 작은 양을 직접 계산하도록 식을 고쳐 쓴다.

  • log⁡(1+x)→\log(1+x) \to log1p(x), ex−1→e^x - 1 \to expm1(x), 1−cos⁡x→2sin⁡2(x/2)1 - \cos x \to 2\sin^2(x/2).
  • 분산: 평균이 퍼짐에 비해 크면 E[x2]−E[x]2\mathbb{E}[x^2] - \mathbb{E}[x]^2가 상쇄된다. 평균을 먼저 빼거나(two-pass) Welford 갱신을 쓴다. LayerNorm·RMSNorm 커널이 신경 쓰는 부분이다.
  • KL 추정량: log⁡r=d\log r = d가 작을 때 k3=r−1−log⁡r≈d2/2k_3 = r - 1 - \log r \approx d^2/2는 크기 dd인 두 수의 차다. 확률이 아니라 log-prob에서 출발해 expm1(d) - d로 계산한다.
  • 로그 비율 일반: 확률의 log⁡(πθ/πold)\log(\pi_\theta/\pi_{\text{old}})가 아니라 log-prob의 log⁡πθ−log⁡πold\log\pi_\theta - \log\pi_{\text{old}}를 쓴다.

비결합성과 합산 순서

반올림할 때마다 누적값의 최대 uu만큼을 잃으므로 합의 순서가 중요하다. 왼쪽부터 더한 S^\hat S에 표준 모형을 n−1n-1번 적용하면(Higham 4장)

∣S^−S∣  ≤  (n−1) u∑i∣xi∣+O(u2).|\hat S - S| \;\le\; (n-1)\,u\sum_i |x_i| + O(u^2) .

커지는 부분합이 매번 반올림되기 때문에 상한이 선형으로 자란다. 고전적인 처방 두 가지.

  • 쌍별(트리) 합산은 이웃끼리, 그다음 이웃의 이웃끼리 더한다. 각 xix_i는 ⌈log⁡2n⌉\lceil\log_2 n\rceil번의 덧셈만 거치므로 상한이 ⌈log⁡2n⌉ u∑∣xi∣\lceil \log_2 n\rceil\,u\sum|x_i|가 된다. NumPy의 sum과 GPU reduction이 트리 모양이다.
  • Kahan(보정) 합산은 매 단계 잃은 아래 자리 비트를 두 번째 변수 cc에 담아 되먹인다. y=xi−cy = x_i - c, t=s+yt = s + y, c=(t−s)−yc = (t - s) - y, s=ts = t. 상한이 2u∑∣xi∣+O(nu2)2u\sum|x_i| + O(nu^2)로, 1차까지는 nn과 무관하다.

낮은 정밀도에서는 느린 증가가 아니라 정체(stagnation) 가 문제다. 누적합이 다음 항의 2m+12^{m+1}배를 넘으면 그 항을 더해도 아무것도 바뀌지 않는다. 0.5 근처의 수를 더하는 BF16 누산기는 256에서 멈춘다. 텐서 코어가 BF16/FP16/FP8 입력을 곱하되 FP32로 누산하는 이유이고, DeepSeek-V3의 FP8 GEMM이 일정 간격마다 부분합을 FP32로 올리는 이유다.

순차sequential – 쌍별pairwise – Kahan – FP32 누산FP32 accumulator – c = 1…32에서 서로 다른 결과distinct results over c = 1…32 –
Left: relative error |Ŝ − S| / Σ|xᵢ| of four ways to add the same N numbers (stored in the chosen format), against N. Dashed guides are the worst-case bounds (N−1)·u and log₂N·u. In BF16 with uniform data the sequential sum stalls: once the running total is about 2⁸ times larger than the next term, adding it changes nothing. Pairwise and Kahan stay near u; a wider accumulator removes the problem. Right: the same N numbers cut into c chunks, each summed then combined — the split a GEMM kernel might pick for a given batch size. Every c is a different answer; shuffle the order and the pattern changes. 왼쪽: 같은 N개 수(선택한 형식으로 저장)를 네 가지 방법으로 더했을 때의 상대 오차 |Ŝ − S| / Σ|xᵢ|를 N에 대해 그렸다. 점선은 최악의 경우 상한 (N−1)·u와 log₂N·u다. BF16에 균등분포 데이터라면 순차 합이 멈춘다. 누적합이 다음 항보다 약 2⁸배 커지면 더해도 아무것도 바뀌지 않는다. 쌍별 합과 Kahan은 u 근처에 머물고, 넓은 누산기는 문제를 없앤다. 오른쪽: 같은 N개 수를 c개 조각으로 잘라 각각 더한 뒤 합친 결과다. GEMM 커널이 배치 크기에 따라 고를 법한 분할이다. c마다 답이 다르다. 순서를 섞으면 무늬도 바뀐다.

Why batch size changes the answer

A matrix multiply is MNMN independent dot products, each a sum over KK. How that sum is cut up — tile size along KK, 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 MM 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 u∑∣xi∣u\sum|x_i|; 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

eze^z overflows FP32 for z>88.7z > 88.7 and FP16 for z>11.09z > 11.09, and underflows to zero long before zz is very negative. The fix uses one identity, valid for any constant cc:

log⁡∑jezj=c+log⁡∑jezj−c,c=max⁡jzj.\log\sum_j e^{z_j} = c + \log\sum_j e^{z_j - c}, \qquad c = \max_j z_j .

With cc the maximum, every exponent is ≤0\le 0 (no overflow) and at least one term equals 1 (the sum is ≥1\ge 1, so the log is safe). This logsumexp (LSE) satisfies max⁡jzj≤LSE(z)≤max⁡jzj+log⁡K\max_j z_j \le \mathrm{LSE}(z) \le \max_j z_j + \log K, and its gradient is the softmax, ∂ LSE/∂zi=softmax(z)i\partial\,\mathrm{LSE}/\partial z_i = \mathrm{softmax}(z)_i. Then

log⁡softmax(z)i=zi−LSE(z),softmax(z)i=ezi−LSE(z).\log\mathrm{softmax}(z)_i = z_i - \mathrm{LSE}(z), \qquad \mathrm{softmax}(z)_i = e^{z_i - \mathrm{LSE}(z)} .

Rules that follow:

  • Compute cross-entropy from logits with log-softmax, never as log(softmax(z)): a target probability of e−120e^{-120} underflows FP32 to 0 and its log is −∞-\infty, while zi−LSEz_i - \mathrm{LSE} is just −120-120.
  • 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 (m,s)(m, s) with s=∑ezj−ms = \sum e^{z_j - m} and merge two blocks as m=max⁡(m1,m2)m = \max(m_1, m_2), s=s1em1−m+s2em2−ms = s_1e^{m_1 - m} + s_2e^{m_2 - m}. That merge is the core of FlashAttention and of fused linear-cross-entropy kernels.
  • The two-class case: log⁡σ(x)=−log⁡(1+e−x)=−softplus(−x)\log\sigma(x) = -\log(1 + e^{-x}) = -\mathrm{softplus}(-x), computed as min⁡(x,0)−log1p(e−∣x∣)\min(x, 0) - \mathrm{log1p}(e^{-|x|}). This is the Bradley–Terry and DPO loss.
  • z-loss penalises LSE(z)2\mathrm{LSE}(z)^2 to keep the free shift of the logits near zero.
NumPy Logsumexp, stable softmax, cancellation, and the k3 estimator
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 u∣f∣u|f|:

f(x+h)−f(x)h−f′(x)≈h2f′′(x)⏟truncation+2u∣f(x)∣h⏟rounding,h⋆≈2u ∣f∣/∣f′′∣∼u.\frac{f(x+h) - f(x)}{h} - f'(x) \approx \underbrace{\tfrac{h}{2}f''(x)}_{\text{truncation}} + \underbrace{\frac{2u|f(x)|}{h}}_{\text{rounding}}, \qquad h^\star \approx 2\sqrt{u\,|f|/|f''|} \sim \sqrt{u}.

The best achievable error is about u\sqrt{u}: 10−810^{-8} in FP64, 3×10−43\times10^{-4} in FP32, 6×10−26\times10^{-2} in BF16. The central difference cancels the even Taylor terms:

f(x+h)−f(x−h)2h−f′(x)≈h26f′′′(x)+u∣f(x)∣h,h⋆∼u1/3, error∼u2/3.\frac{f(x+h) - f(x-h)}{2h} - f'(x) \approx \tfrac{h^2}{6}f'''(x) + \frac{u|f(x)|}{h}, \qquad h^\star \sim u^{1/3},\ \text{error} \sim u^{2/3}.

The complex step avoids the subtraction entirely: for real-analytic ff, f(x+ih)=f(x)+ihf′(x)−h22f′′(x)−…f(x + ih) = f(x) + ihf'(x) - \tfrac{h^2}{2}f''(x) - \ldots, so Im f(x+ih)/h=f′(x)+O(h2)\mathrm{Im}\,f(x+ih)/h = f'(x) + O(h^2) with no cancellation, and h=10−20h = 10^{-20} works.

배치 크기가 답을 바꾸는 이유

행렬곱은 MNMN개의 독립된 내적이고, 각각은 KK에 대한 합이다. 그 합을 어떻게 자르는지 — KK 방향 타일 크기, split-K 부분합의 개수, 부분합을 트리로 합치는지 사슬로 합치는지 — 는 커널이 고르고, 라이브러리는 shape을 보고 커널을 고른다. 추론 서버에서 배치 차원 MM은 부하에 따라 달라지므로, 같은 요청이 다른 커널에 들어가 다른 reduction 순서를 얻는다. 위의 오차 상한대로 순서마다 u∑∣xi∣u\sum|x_i| 수준에서 결과가 조금씩 다르고, 수십 개 층과 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

eze^z는 FP32에서 z>88.7z > 88.7, FP16에서 z>11.09z > 11.09면 overflow하고, zz가 아주 음수가 되기 훨씬 전에 0으로 underflow한다. 처방은 임의의 상수 cc에 대해 성립하는 항등식 하나다.

log⁡∑jezj=c+log⁡∑jezj−c,c=max⁡jzj.\log\sum_j e^{z_j} = c + \log\sum_j e^{z_j - c}, \qquad c = \max_j z_j .

cc를 최댓값으로 두면 모든 지수가 ≤0\le 0이고(overflow 없음), 적어도 한 항이 1이다(합이 ≥1\ge 1이라 로그가 안전하다). 이 logsumexp(LSE)는 max⁡jzj≤LSE(z)≤max⁡jzj+log⁡K\max_j z_j \le \mathrm{LSE}(z) \le \max_j z_j + \log K를 만족하고, gradient가 softmax다: ∂ LSE/∂zi=softmax(z)i\partial\,\mathrm{LSE}/\partial z_i = \mathrm{softmax}(z)_i. 그러면

log⁡softmax(z)i=zi−LSE(z),softmax(z)i=ezi−LSE(z).\log\mathrm{softmax}(z)_i = z_i - \mathrm{LSE}(z), \qquad \mathrm{softmax}(z)_i = e^{z_i - \mathrm{LSE}(z)} .

여기서 나오는 규칙들.

  • Cross-entropy는 log(softmax(z))가 아니라 logit에서 log-softmax로 계산한다. 정답 확률 e−120e^{-120}은 FP32에서 0으로 underflow해 로그가 −∞-\infty가 되지만, zi−LSEz_i - \mathrm{LSE}는 그냥 −120-120이다.
  • Softmax는 shift에 불변이지만 반올림 오차는 아니다. FP 수의 오차는 크기에 비례하므로, 큰 logit은 shift를 한 뒤에도 큰 절대 오차를 지닌다. RL에서 LM head를 FP32로 유지하는(Track IX) 메커니즘이 이것이다.
  • 최댓값 shift는 online으로 할 수 있다. s=∑ezj−ms = \sum e^{z_j - m}인 (m,s)(m, s)를 들고 다니며 두 블록을 m=max⁡(m1,m2)m = \max(m_1, m_2), s=s1em1−m+s2em2−ms = s_1e^{m_1 - m} + s_2e^{m_2 - m}로 합친다. 이 병합이 FlashAttention과 fused linear-cross-entropy 커널의 핵심이다.
  • 두 클래스의 경우: log⁡σ(x)=−log⁡(1+e−x)=−softplus(−x)\log\sigma(x) = -\log(1 + e^{-x}) = -\mathrm{softplus}(-x)를 min⁡(x,0)−log1p(e−∣x∣)\min(x, 0) - \mathrm{log1p}(e^{-|x|})로 계산한다. Bradley–Terry와 DPO의 손실이다.
  • z-loss는 LSE(z)2\mathrm{LSE}(z)^2에 벌점을 줘서 logit의 자유로운 shift를 0 근처에 묶는다.
NumPy Logsumexp, 안정적 softmax, 상쇄, k3 추정량
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) 오차를 주고, 표준 모형이 거의 같은 두 함숫값 — 각각 약 u∣f∣u|f|까지만 알려진 — 을 빼는 반올림 오차를 준다.

f(x+h)−f(x)h−f′(x)≈h2f′′(x)⏟truncation+2u∣f(x)∣h⏟rounding,h⋆≈2u ∣f∣/∣f′′∣∼u.\frac{f(x+h) - f(x)}{h} - f'(x) \approx \underbrace{\tfrac{h}{2}f''(x)}_{\text{truncation}} + \underbrace{\frac{2u|f(x)|}{h}}_{\text{rounding}}, \qquad h^\star \approx 2\sqrt{u\,|f|/|f''|} \sim \sqrt{u}.

얻을 수 있는 최선의 오차는 약 u\sqrt{u}다. FP64에서 10−810^{-8}, FP32에서 3×10−43\times10^{-4}, BF16에서 6×10−26\times10^{-2}. 중심 차분은 테일러의 짝수 차 항을 지운다.

f(x+h)−f(x−h)2h−f′(x)≈h26f′′′(x)+u∣f(x)∣h,h⋆∼u1/3, error∼u2/3.\frac{f(x+h) - f(x-h)}{2h} - f'(x) \approx \tfrac{h^2}{6}f'''(x) + \frac{u|f(x)|}{h}, \qquad h^\star \sim u^{1/3},\ \text{error} \sim u^{2/3}.

복소 간격(complex step) 은 뺄셈을 아예 피한다. 실해석적인 ff에 대해 f(x+ih)=f(x)+ihf′(x)−h22f′′(x)−…f(x + ih) = f(x) + ihf'(x) - \tfrac{h^2}{2}f''(x) - \ldots이므로 Im f(x+ih)/h=f′(x)+O(h2)\mathrm{Im}\,f(x+ih)/h = f'(x) + O(h^2)이고 상쇄가 없어서 h=10−20h = 10^{-20}도 된다.

전진 차분 최적 hforward: best h – (이론theory –) → – 중심 차분 최적 hcentral: best h – (이론theory –) → – complex step → –
Error of the numerical derivative against the step h (both on log scales). Right of the minimum the Taylor truncation error dominates (slope 1 for forward, 2 for central); left of it rounding error u·|f|/h dominates, rising with slope −1 as f(x+h) − f(x) cancels. Switch to FP32 or BF16: the V moves up and right — the best achievable error is about √u (forward) or u2/3 (central). The complex-step derivative (green) has no subtraction, so it keeps going down to u. 수치 미분의 오차를 간격 h에 대해 그렸다(둘 다 로그 축). 최소점 오른쪽은 테일러 절단 오차가 지배하고(전진 차분은 기울기 1, 중심 차분은 2), 왼쪽은 f(x+h) − f(x)가 상쇄되면서 반올림 오차 u·|f|/h가 기울기 −1로 커진다. FP32나 BF16으로 바꾸면 V가 위·오른쪽으로 이동한다. 얻을 수 있는 최선의 오차는 대략 √u(전진) 또는 u2/3(중심)이다. 복소 간격 미분(초록)은 뺄셈이 없어서 u까지 계속 내려간다.

A gradient check compares an analytic or autograd gradient gg with central differences g^\hat g via the relative error max⁡∣g−g^∣/max⁡(∣g∣,∣g^∣)\max|g - \hat g| / \max(|g|, |\hat g|). Practical rules follow from the V:

  • Do it in FP64 with h≈10−5h \approx 10^{-5}–10−610^{-6}; expect about 10−810^{-8}–10−1010^{-10}. In FP32 the result swings between about 10−410^{-4} and 10−210^{-2} depending on hh, and real bugs hide in that noise.
  • A bug that is wrong by a few percent shows up as 10−210^{-2}; ”10−410^{-4} in FP64” is already suspicious.
  • For many parameters, check directional derivatives: pick a random vv and compare L(θ+hv)−L(θ−hv)2h\frac{L(\theta + hv) - L(\theta - hv)}{2h} with ⟨g,v⟩\langle g, v\rangle — two loss evaluations, whatever the dimension. That is a JVP checked against a VJP.
  • Kinks (ReLU, max, clipping, top-kk routing) break the Taylor model where θ±h\theta \pm h straddles them; move the test point or shrink hh.
NumPy The V of finite differences, and a gradient check
# 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):

  1. FP32 master weights. An update is applied to a weight as w−ηgw - \eta g. If ∣ηg∣<12ulp(w)|\eta g| < \tfrac12\mathrm{ulp}(w), rounding returns ww unchanged: in BF16 a weight of 1.0 ignores any update smaller than 2−9≈0.0022^{-9} \approx 0.002. 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.
  2. FP32 accumulation in matmuls and reductions, for the reasons in the summation section.
  3. Loss scaling (FP16 only). Gradients of activations are often tiny, and FP16 flushes everything below 6×10−86\times10^{-8} to zero. Multiplying the loss by SS multiplies every gradient by SS (the chain rule is linear in the output gradient), shifting the histogram into range; the gradients are divided by SS in FP32 before the update. Dynamic loss scaling starts with a large SS, skips the step and halves SS when an inf/NaN appears, and doubles SS after a run of clean steps (PyTorch’s GradScaler does 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.

NumPy Master weights, stochastic rounding, and loss scaling
# 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")
 
확인 문제Check yourself

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 [0.5,1)[0.5, 1), BF16’s spacing is 2−8=0.003906252^{-8} = 0.00390625, so the neighbours of 0.997 are 1.01.0 and 0.996093750.99609375. 0.997 is closer to the latter, so the stored step is 0.00390.0039 — 30% larger than intended. An update smaller than 2−9≈0.001952^{-9} \approx 0.00195 would have been lost entirely. Either way the update is not what the optimizer computed, which is why master weights are FP32.

확인 문제Check yourself

Roughly what is the largest logit z for which exp(z) is still finite in FP16?

FP16’s largest value is 65504 and ln⁡65504≈11.09\ln 65504 \approx 11.09. (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 mm mantissa bits has relative precision u=2−(m+1)u = 2^{-(m+1)} everywhere in its normal range; exponent bits set the range. fl(a∘b)=(a∘b)(1+δ)\mathrm{fl}(a\circ b) = (a\circ b)(1+\delta), ∣δ∣≤u|\delta| \le u.
  • Subtracting nearby numbers amplifies their relative error by ∣a∣+∣b∣∣a−b∣\frac{|a|+|b|}{|a-b|}; rewrite with log1p, expm1, two-pass variance, log-space ratios.
  • Sequential sums have error ≲nu∑∣xi∣\lesssim nu\sum|x_i| and can stagnate in low precision; pairwise gives log⁡2n\log_2 n, Kahan O(1)O(1). 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 u\sqrt u (forward) or u2/3u^{2/3} (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

Gradient check은 해석적(또는 autograd) gradient gg를 중심 차분 g^\hat g와 상대 오차 max⁡∣g−g^∣/max⁡(∣g∣,∣g^∣)\max|g - \hat g| / \max(|g|, |\hat g|)로 비교한다. V 모양에서 실전 규칙이 나온다.

  • FP64에서 h≈10−5h \approx 10^{-5}–10−610^{-6}로 한다. 10−810^{-8}–10−1010^{-10} 정도를 기대한다. FP32에서는 hh에 따라 결과가 대략 10−410^{-4}에서 10−210^{-2} 사이를 오가고, 진짜 버그가 그 잡음 속에 숨는다.
  • 몇 퍼센트 틀린 버그는 10−210^{-2}로 나타난다. “FP64에서 10−410^{-4}“이면 이미 의심스럽다.
  • 매개변수가 많으면 방향 미분을 검사한다. 무작위 vv를 골라 L(θ+hv)−L(θ−hv)2h\frac{L(\theta + hv) - L(\theta - hv)}{2h}를 ⟨g,v⟩\langle g, v\rangle와 비교한다. 차원과 무관하게 손실 계산 두 번이다. JVP로 VJP를 검사하는 셈이다.
  • 꺾이는 점(ReLU, max, clipping, top-kk routing)이 θ±h\theta \pm h 사이에 걸리면 테일러 모형이 깨진다. 시험 지점을 옮기거나 hh를 줄인다.
NumPy 유한 차분의 V, 그리고 gradient check
# 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).

  1. FP32 master weight. 업데이트는 가중치에 w−ηgw - \eta g로 적용된다. ∣ηg∣<12ulp(w)|\eta g| < \tfrac12\mathrm{ulp}(w)이면 반올림이 ww를 그대로 돌려준다. BF16에서 1.0인 가중치는 2−9≈0.0022^{-9} \approx 0.002보다 작은 업데이트를 모두 무시한다. 업데이트용 FP32 사본을 두고(forward에는 낮춰서 쓰고) 이 swamping을 피한다. Adam의 2차 모멘트 같은 optimizer 상태를 FP32로 두는 이유도 같다. 확률적 반올림(stochastic rounding) — 소수 부분의 거리만큼의 확률로 올림 — 도 대안이다. 기댓값으로 편향이 없어서 작은 업데이트가 평균적으로 살아남는다.
  2. 행렬곱과 reduction의 FP32 누산. 이유는 합산 절에서 본 그대로다.
  3. Loss scaling(FP16에서만). activation의 gradient는 아주 작은 경우가 많고, FP16은 6×10−86\times10^{-8} 아래를 모두 0으로 만든다. 손실에 SS를 곱하면 모든 gradient가 SS배가 되어(연쇄 법칙은 출력 gradient에 대해 선형) 히스토그램이 범위 안으로 옮겨진다. 업데이트 전에 FP32에서 SS로 나눈다. 동적 loss scaling은 큰 SS로 시작해, inf/NaN이 나오면 그 step을 건너뛰고 SS를 반으로 줄이고, 깨끗한 step이 이어지면 SS를 두 배로 늘린다(PyTorch의 GradScaler가 이렇게 한다).

BF16은 FP32의 지수 범위를 가지므로 3번은 대개 필요 없다. BF16이 학습에서 FP16을 대체한 주된 이유다. FP8은 전역 scale 하나로 버틸 범위도 정밀도도 없다. 가중치와 activation에는 E4M3(정밀도 우선), gradient에는 E5M2(범위 우선)를 쓰고, 텐서마다 — DeepSeek-V3와 MX/NVFP4 형식에서는 블록마다 — scale을 따로 둔다.

NumPy Master weight, 확률적 반올림, loss scaling
# 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")
 
확인 문제Check yourself

1.0인 가중치가 BF16으로 저장되어 있고 SGD 업데이트 −0.003을 받는다. 업데이트 후 저장되는 값은?

1 아래 [0.5,1)[0.5, 1)에서 BF16의 간격은 2−8=0.003906252^{-8} = 0.00390625이므로 0.997의 이웃은 1.01.0과 0.996093750.99609375다. 0.997은 뒤의 것에 더 가까우니 저장되는 걸음은 0.00390.0039, 의도보다 30% 크다. 2−9≈0.001952^{-9} \approx 0.00195보다 작은 업데이트였다면 통째로 사라졌을 것이다. 어느 쪽이든 optimizer가 계산한 업데이트가 아니다. master weight를 FP32로 두는 이유다.

확인 문제Check yourself

FP16에서 exp(z)가 유한한 가장 큰 logit z는 대략?

FP16의 최댓값은 65504이고 ln⁡65504≈11.09\ln 65504 \approx 11.09다(88.7은 FP32/BF16, 709.8은 FP64의 한계). logit 12는 흔한 값이다. 최댓값을 빼지 않고 exp(z) / sum(exp(z))로 softmax를 계산하지 않는 이유다.

정리

  • 가수 비트가 mm개인 float는 정규 범위 어디서나 상대 정밀도 u=2−(m+1)u = 2^{-(m+1)}을 가진다. 지수 비트가 범위를 정한다. fl(a∘b)=(a∘b)(1+δ)\mathrm{fl}(a\circ b) = (a\circ b)(1+\delta), ∣δ∣≤u|\delta| \le u.
  • 가까운 수의 뺄셈은 상대 오차를 ∣a∣+∣b∣∣a−b∣\frac{|a|+|b|}{|a-b|}배 키운다. log1p, expm1, two-pass 분산, 로그 공간의 비율로 고쳐 쓴다.
  • 순차 합의 오차는 ≲nu∑∣xi∣\lesssim nu\sum|x_i|이고 낮은 정밀도에서는 정체할 수 있다. 쌍별 합은 log⁡2n\log_2 n, Kahan은 O(1)O(1). reduction 순서는 커널 선택에, 커널 선택은 배치 shape에 달려 있다.
  • logit에서 logsumexp/log-softmax를 쓴다. 최댓값 shift가 overflow를 막고, 그 online 버전이 FlashAttention의 병합이다.
  • 유한 차분의 오차는 V 모양이고 최적이 u\sqrt u(전진) 또는 u2/3u^{2/3}(중심)이다. gradient check은 FP64에서 하거나 방향 검사를 쓴다.
  • Mixed precision = 낮은 정밀도 연산 + FP32 master weight와 누산 + FP16의(BF16은 아님) loss scaling + FP8의 텐서별·블록별 scale.

이 사이트에서 쓰이는 곳

더 읽을거리Further reading