import os
import re
from torch.utils.checkpoint import checkpoint13.8 사례 연구: 트랜스포머 최적화하기
이 장의 앞선 절들에서는 훈련 스텝을 느리게 만드는 원인과 이를 제거하는 해법을 하나씩 분리해 다루었습니다. 호스트 디스패치 오버헤드, 작은 커널들의 메모리 트래픽, 넓은 수 형식, 그리고 단일 GPU의 한계가 그것입니다. 실제 훈련 스텝은 이 중 여러 문제를 동시에 겪으며, 하나를 제거하면 병목이 다른 곳으로 옮겨 갑니다. 여기서는 실무자의 관점에서 단일 모델 하나를 선택하여 그 훈련 스텝이 얼마나 빨라질 수 있는지, 그리고 어떤 순서로 최적화를 적용해야 하는지 살펴봅니다.
대상 모델은 폭을 512로 두 배 넓힌 11.2절 의 GPT(매개변수 1,900만 개)입니다. 128바이트 윈도 64개(\(8{,}192\) 토큰)에 대한 훈련 스텝 1회는 약 \(6 \times 1.9 \times 10^{7} \times 8{,}192 \approx 9 \times 10^{11}\) FLOPs를 수행합니다(순전파에서 매개변수·토큰당 2회, 역전파에서 4회). RTX 4090(bf16 기준 \(165\text{ TFLOP/s}\))에서 이 산술 연산 자체는 \(6\text{ ms}\) 도 걸리지 않습니다. 그러나 AdamW를 쓴 기본 fp32 스텝은 약 \(25\text{ ms}\) 가 걸립니다. 그 \(19\text{ ms}\) 간극 중 약 \(6\text{ ms}\) 는 수 형식 차이만으로 설명되며(tf32 텐서 코어는 bf16의 절반 속도로 동작하여 \(11\text{ ms}\) 필요), 나머지 약 \(13\text{ ms}\) 는 텐서 코어가 피크 미만으로 돌거나 아예 유휴 상태로 쉬는 시간입니다.
13.1절 의 방법론을 그대로 따릅니다. 즉, 세고, 예측하고, 측정한 뒤 그 차이를 설명합니다. 각 변경을 적용하기 전에 직전 스텝의 프로파일로 해당 변경이 얻을 수 있는 최대 이득의 상한을 먼저 구하고, 적용 후 실측값과 대조합니다. 각 변경은 이전 변경들 위에 누적하여 측정합니다. 마지막에는 가장 빨라진 스텝이 여전히 모델을 제대로 훈련시키는지 확인하고 남은 시간이 어디에 쓰이는지 정산하며 마무리합니다.
# Let XLA overlap collectives with computation. JAX reads XLA_FLAGS once,
# when it starts, so this cell runs before the imports. Our outputs come
# from a run with three more settings in the environment, which you set
# before starting: --xla_gpu_enable_triton_gemm=false in XLA_FLAGS, so that
# XLA calls cuBLAS for the matrix products (the Triton kernels it would
# generate run the products of the large minibatches more slowly on the
# RTX 4090); NCCL_LOCAL_REGISTER=0, since NCCL's buffer registration fails
# on GPUs without peer-to-peer access and would print a warning at every
# collective; and XLA_PYTHON_CLIENT_ALLOCATOR=vmm, which maps each array
# into one contiguous range: the fp32 step of the training check needs
# about 13 GiB in one piece after many other arrays have come and gone.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_enable_latency_hiding_scheduler=true')import re
from jax.sharding import NamedSharding, PartitionSpec as Ptorch.set_float32_matmul_precision('high') # fp32 products on tf32 cores
# Detach PyTorch's profiler from the GPU when a profile ends; without this,
# every kernel launch after the first profile stays about 30% slower
os.environ['TEARDOWN_CUPTI'] = '1'13.8.1 실험 설정
이 절의 모든 변경은 동일한 잣대로 평가되어야 하므로 모델, 데이터, 처리량 벤치마크는 내내 고정합니다.
13.8.1.1 모델과 데이터
훈련할 모델은 d2l.GPT(11.2절)입니다. 각각 8개의 어텐션 헤드, 회전 위치 임베딩(RoPE), RMSNorm, SwiGLU를 갖춘 6개의 사전 정규화(Pre-Norm) 블록과 출력 층에 가중치가 묶인 입력 임베딩으로 구성됩니다. 데이터는 256바이트 어휘 사전 위에서 무작위 오프셋으로 추출한 WikiText-103의 128바이트 윈도들입니다(d2l.WikiText103, 9.3절).
행렬 곱셈들이 연산 병목 영역에 여유 있게 자리 잡도록 폭을 256에서 512로 두 배 키웠습니다(13.1절). \(n \times d\) 활성화 행렬에 \(d \times d'\) 가중치 행렬을 곱하면 \(2ndd'\) FLOPs를 수행하고 \(b(nd + dd' + nd')\) 바이트(원소당 \(b\) 바이트)를 옮깁니다. 폭 \(d = 512\) 에서 \(n = 8{,}192\) 토큰일 때 블록 투영들은 tf32(\(b = 4\))에서 \(125\text{--}185\text{ FLOP/byte}\), bf16(\(b = 2\))에서 \(250\text{--}370\text{ FLOP/byte}\) 에 도달하여 RTX 4090의 리지 포인트(tf32 기준 \(82\text{ FLOP/byte}\), bf16 기준 \(164\text{ FLOP/byte}\))를 훌쩍 넘습니다. 따라서 더 빠른 수 형식을 쓰면 이 행렬 곱셈 시간들이 곧바로 단축됩니다. 반면 폭 256에서는 행렬 곱들이 리지 포인트 언저리에 걸칩니다(6 참조).
270 MB 훈련 말뭉치는 평탄한 바이트 배열 형태로 GPU 메모리에 통째로 들어갑니다. 다음 셀은 말뭉치를 GPU에 올리고 호스트 전송 없이 장치 위에서 직접 미니배치를 샘플링하는 windows 를 정의한 뒤 모델을 생성합니다.
device = d2l.try_gpu()
data = d2l.WikiText103(batch_size=64, num_steps=128)
corpus = torch.tensor(data.train, device=device) # One byte per token
def windows(corpus, batch_size, num_steps=128):
"""Endless minibatches of windows at random offsets, each position with
the next byte as its target."""
offsets = torch.arange(num_steps + 1, device=corpus.device)
while True:
starts = torch.randint(len(corpus) - num_steps, (batch_size, 1),
device=corpus.device)
W = corpus[starts + offsets].long()
yield W[:, :-1], W[:, 1:]
model = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
num_params = d2l.num_params(model)
print(f'{num_params / 1e6:.1f}M parameters, '
f'{len(corpus) / 1e6:.0f}M training bytes on the GPU')19.0M parameters, 270M training bytes on the GPU
data = d2l.WikiText103(batch_size=64, num_steps=128)
corpus = jnp.asarray(data.train) # One byte per token
def windows(corpus, batch_size, num_steps=128, *, sharding=None):
"""Endless minibatches of windows at random offsets, each position with
the next byte as its target; `sharding` spreads them over devices."""
offsets = jnp.arange(num_steps + 1)
while True:
starts = jax.random.randint(d2l.get_key(), (batch_size, 1), 0,
len(corpus) - num_steps)
if sharding is not None:
starts = jax.device_put(starts, sharding)
W = corpus[starts + offsets].astype(jnp.int32)
yield W[:, :-1], W[:, 1:]
model = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
num_params = d2l.num_params(model)
print(f'{num_params / 1e6:.1f}M parameters, '
f'{len(corpus) / 1e6:.0f}M training bytes on the GPU')19.0M parameters, 270M training bytes on the GPU
매개변수당 16바이트(가중치, 그레이디언트, 두 Adam 모멘트) 기준 19M 매개변수의 훈련 상태는 불과 \(0.3\text{ GiB}\) 만 차지하므로 그레이디언트 누적도 샤딩도 필요 없습니다(13.4절, 13.7절). 말뭉치를 GPU 위에 두면 훈련 스텝을 입력 파이프라인(13.2절)으로부터 깔끔하게 분리할 수도 있습니다.
13.8.1.2 처리량 측정
미니배치 샘플링, 순전파 및 역전파, 옵티마이저 업데이트를 모두 포함하여 초당 토큰 수로 종단간 훈련 처리량을 측정합니다.
| 설정 항목 | 값 |
|---|---|
| 하드웨어 | RTX 4090 GPU 4장 중 1장 (데이터 병렬화에서는 2장 및 4장) |
| 모델 | d2l.GPT: 6블록, 폭 512, 헤드 8개, 바이트 어휘 사전, 컨텍스트 128 |
| 데이터 | 매 스텝 GPU 위에서 무작위 추출하는 WikiText-103 128바이트 윈도 |
| 옵티마이저 | AdamW (\(\text{lr} = 10^{-3}\), 가중치 감쇠 \(0.01\)) |
| 정밀도 | bf16 도입 전까지 tf32 행렬 곱을 쓰는 fp32 |
| 타이밍 | d2l.Benchmark: 워밍업 20스텝 후 장치 동기화 사이 50스텝 윈도 3회 측정 |
| 결과 보고 | 3개 윈도의 초당 토큰 중앙값, 직전 채택 구성 대비 비율, 상대 윈도 편차 |
tokens_per_second 는 d2l.Benchmark(13.1절)를 통해 이 규칙들을 적용합니다. record 는 각 결과를 저장하고 세 측정 윈도 간의 상대 편차(\(\text{range} / \text{median}\))와 함께 직전 채택 구성 대비 가속비를 출력합니다. kept=False 로 전달된 구성은 후속 구성들이 토대로 삼지 않는 별도 분기로 기록됩니다.
def tokens_per_second(step, batches, warmup=20, repeats=50, num_windows=3):
"""Median training throughput of `step` on minibatches drawn from
`batches`, over `num_windows` timed windows of `repeats` steps each, and
the spread of the windows (largest minus smallest) relative to it."""
X, _ = next(batches)
speeds = [math.prod(X.shape) / d2l.Benchmark(
lambda: step(*next(batches)), warmup if i == 0 else 0,
repeats).time for i in range(num_windows)]
return np.median(speeds), np.ptp(speeds) / np.median(speeds)
results, branches = {}, {}
def record(name, measured, kept=True):
"""Store a measured throughput and print it with its ratio to the last
kept configuration and the spread of its windows; a configuration that
is not kept is stored in `branches`."""
speed, spread = measured
previous = list(results.values())[-1] if results else speed
(results if kept else branches)[name] = speed
print(f'{name}: {speed:,.0f} tokens/s ({speed / previous:.2f}x), '
f'windows within {spread:.1%}')def tokens_per_second(step, batches, warmup=20, repeats=50, num_windows=3):
"""Median training throughput of `step` on minibatches drawn from
`batches`, over `num_windows` timed windows of `repeats` steps each, and
the spread of the windows (largest minus smallest) relative to it."""
X, _ = next(batches)
speeds = [math.prod(X.shape) / d2l.Benchmark(
lambda: step(*next(batches)), warmup if i == 0 else 0,
repeats).time for i in range(num_windows)]
return np.median(speeds), np.ptp(speeds) / np.median(speeds)
results, branches = {}, {}
def record(name, measured, kept=True):
"""Store a measured throughput and print it with its ratio to the last
kept configuration and the spread of its windows; a configuration that
is not kept is stored in `branches`."""
speed, spread = measured
previous = list(results.values())[-1] if results else speed
(results if kept else branches)[name] = speed
print(f'{name}: {speed:,.0f} tokens/s ({speed / previous:.2f}x), '
f'windows within {spread:.1%}')상당한 양의 호스트 작업을 수행하는 스텝은 백그라운드 호스트 활동에 민감하여 컴파일되거나 그래프 캡처된 스텝보다 윈도 간 편차가 넓게 나타납니다. 단일 실행 내의 연속 윈도보다 날마다 달라지는 호스트 부하 변동이 더 크므로, 가속비는 소수점 첫째 자리까지만 읽고 몇 퍼센트 수준의 작은 이득은 프로파일이 이를 뒷받침할 때만 신뢰합니다.
13.8.2 단일 GPU 최적화
먼저 11.2절 의 베이스라인 구현에서 출발해 한 번에 하나씩 변경을 적용하며 단일 GPU 위의 훈련 스텝을 최적화합니다.
13.8.2.1 베이스라인
베이스라인은 순전파, 교차 엔트로피 손실, 역전파, 매개변수 업데이트로 이루어진 11.2절 의 표준 AdamW 훈련 스텝입니다.
스텝은 즉시 실행 방식으로 동작합니다. Python과 autograd가 순전파 및 역전파의 각 연산을 개별 커널 발행으로 디스패치하는 반면, AdamW(fused=True)는 소수의 융합 커널로 모든 매개변수와 모멘트를 갱신합니다. make_step 이 훈련 스텝을 패키징하며 forward 와 bf16 인자는 이어질 소절들의 수정을 지원합니다.
train_step 은 d2l.train_steps(9.3절)에서와 마찬가지로 nnx.jit 으로 컴파일됩니다. 모델과 옵티마이저를 인자로 받아 fp32 로짓으로부터 교차 엔트로피 손실을 계산합니다.
def make_step(model, forward=None, bf16=False, warmup=0):
"""An AdamW training step of `model` on a minibatch (X, Y); `forward`
replaces the model's forward pass, `bf16` turns on autocast, and a
`warmup` > 0 raises the learning rate linearly to 1e-3 over as many
steps."""
forward = model if forward is None else forward
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3,
weight_decay=0.01, fused=True)
if warmup:
schedule = torch.optim.lr_scheduler.LambdaLR(
optimizer, lambda i: min(1, (i + 1) / warmup))
def step(X, Y):
with torch.autocast('cuda', torch.bfloat16, enabled=bf16):
loss = F.cross_entropy(forward(X).flatten(0, 1), Y.flatten())
optimizer.zero_grad(set_to_none=True)
loss.backward()
optimizer.step()
if warmup:
schedule.step()
return loss
return step
step = make_step(model)
record('baseline', tokens_per_second(step, windows(corpus, 64)))baseline: 317,736 tokens/s (1.00x), windows within 1.9%
def train_step(model, optimizer, X, Y):
"""Loss, gradients, and AdamW update for one minibatch."""
def loss_fn(model):
logits = model(X).astype(jnp.float32)
return optax.softmax_cross_entropy_with_integer_labels(
logits, Y).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
optimizer.update(model, grads)
return loss
adamw = optax.adamw(1e-3, weight_decay=0.01)
optimizer = nnx.Optimizer(model, adamw, wrt=nnx.Param)
jit_step = nnx.jit(train_step)
step = lambda X, Y: jit_step(model, optimizer, X, Y)
record('baseline', tokens_per_second(step, windows(corpus, 64)))baseline: 340,062 tokens/s (1.00x), windows within 10.7%
예상대로 베이스라인 윈도들은 매 스텝 호스트 작업 때문에 이후 구성들보다 편차가 약 열 배 더 넓게 벌어집니다. 스텝이 어디에 시간을 쓰는지 확인하기 위해 profile 은 d2l.kernel_times 로 다섯 스텝을 기록하고 d2l.show_profile(13.1.4절)로 세부 내역(벽시계 스텝 시간 대 총 장치 커널 시간, 융합 어텐션 커널을 포함한 행렬 곱셈 비중, 상위 커널 목록)을 출력한 뒤 최종 정산을 위해 프로파일을 저장합니다.
profiles = {}
def profile(step, batches):
"""Kernel profile of `step`, the configuration recorded last, on
minibatches drawn from `batches`: printed against the throughput that
`record` measured, and stored in `profiles` under the same name."""
name, speed = list(results.items())[-1]
X, _ = next(batches)
kernels = d2l.kernel_times(lambda: step(*next(batches)), steps=5)
d2l.show_profile(kernels, 1e3 * math.prod(X.shape) / speed, rows=4)
profiles[name] = kernels
profile(step, windows(corpus, 64))wall clock 25.78 ms per step, device busy 24.44 ms (95%), matrix products 64%
3.28 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.08 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.84 ms 12% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
2.41 ms 10% vectorized_elementwise_kernel<4, BinaryFunctor<float
profiles = {}
def profile(step, batches):
"""Kernel profile of `step`, the configuration recorded last, on
minibatches drawn from `batches`: printed against the throughput that
`record` measured, and stored in `profiles` under the same name."""
name, speed = list(results.items())[-1]
X, _ = next(batches)
kernels = d2l.kernel_times(lambda: step(*next(batches)), steps=5)
d2l.show_profile(kernels, 1e3 * math.prod(X.shape) / speed, rows=4)
profiles[name] = kernels
profile(step, windows(corpus, 64))wall clock 24.09 ms per step, device busy 23.61 ms (98%), matrix products 65%
3.02 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.99 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.90 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
1.39 ms 6% loop_add_multiply_fusion_5
거의 전체 스텝 동안 장치가 커널을 실행하며 행렬 곱셈이 약 3분의 2를 차지합니다. 호스트가 대체로 속도를 따라잡고 있으므로 스텝의 병목은 장치 작업입니다.
행렬 곱셈 바깥의 나머지 3분의 1은 각각 장치 메모리를 읽고 쓰느라 메모리 대역폭에 제한되는 수많은 짧은 커널들(SwiGLU, 회전 위치 임베딩, 잔차 덧셈, RMSNorm)로 잘게 쪼개져 있습니다(13.3.2절).
nnx.jit 이 전체 스텝을 컴파일하므로 XLA는 이미 원소별 연산들을 주변 커널에 융합해 두었습니다. 행렬 곱셈 바깥의 장치 시간 3분의 1은 이렇게 융합된 커널들에 쓰이며, 이들은 여전히 이동시키는 바이트 수에 의해 제한됩니다.
13.8.2.2 호스트 오버헤드와 작은 커널들
두 가지 해결책이 행렬 곱셈 바깥에서 쓰이는 시간을 겨냥하며, 프로파일이 각 해결책의 최대 이득 상한을 정해 줍니다. 그 상한이 바로 Amdahl의 법칙 (Amdahl 1967년) 입니다. 어떤 변경이 스텝의 비율 \(f\) 를 \(s\) 배 빠르게 만들면 전체 스텝은 \(1/(1 - f + f/s)\) 배 빨라지며, 이는 \(s\) 가 아무리 커져도 \(1/(1 - f)\) 아래에 머뭅니다. 두 해결책에 이를 적용하면 다음과 같습니다.
- 호스트 오버헤드 줄이기는 장치가 호스트를 기다리는 유휴 간격을 겨냥하며(13.1절), 가속비는 스텝의 유휴 비율에 의해 상한이 정해집니다.
- 커널 융합은 중간 배열이 칩 위에 머물도록 대역폭 병목 원소별 커널 사슬을 병합하며, 가속비는 비행렬곱 장치 시간에 의해 상한이 정해집니다.
베이스라인은 두 번째 영역에 속합니다. 스텝 중 GPU 유휴 시간은 몇 퍼센트에 불과한 반면, 비행렬곱 커널이 장치 시간 \(24.5\text{ ms}\) 중 \(8.8\text{ ms}\) 를 소비합니다. 설령 컴파일이 모든 비행렬곱 커널과 유휴 간격을 완전히 없앤다 해도 스텝은 행렬 곱셈 시간인 \(15.6\text{ ms}\) 까지만 줄어들 수 있어 최대 \(1.6\times\) 가속이 상한입니다. torch.compile(13.3절)은 행렬 곱셈과 융합 옵티마이저 업데이트는 그대로 둔 채 순전파와 역전파 전반의 원소별 연산들을 융합합니다. 여기에 mode='reduce-overhead' 와 dynamic=False 를 전달하면 정적 형상 CUDA 그래프(13.3.4절)까지 캡처하여 당장의 몇 퍼센트 호스트 유휴 시간을 없애고 나중에 장치 실행이 짧아졌을 때 호스트 디스패치가 새로운 병목으로 떠오르는 것을 미리 막아 줍니다. 먼저 컴파일된 모델이 즉시 실행 로짓과 일치하는지 검증합니다.
스텝이 이미 XLA로 융합되어 있고 GPU가 기다리는 비중은 스텝의 2%뿐이므로 당장 호스트 작업을 줄여 얻을 수 있는 이득은 최대 2%입니다. 그럼에도 이를 미리 제거하는 이유는 이후 최적화로 장치 실행이 짧아지면 이 고정 스텝당 비용이 수면 위로 드러나기 때문입니다. 매 호출마다 nnx.jit 은 배열을 추출하고 갱신하기 위해 Python 모델 및 옵티마이저 객체를 순회합니다. 아래에서는 기본 nnx.jit, nnx.jit(..., graph=False)(트리 모드), 그리고 모델과 옵티마이저 상태를 한 번 바인딩해 매 스텝 미니배치만 전달하는 nnx.jit_partial(..., graph=False) 를 사용해 빈 함수(no-op) 위에서 이 순회 오버헤드를 벤치마킹합니다.
compiled = torch.compile(model, dynamic=False, mode='reduce-overhead')
X, _ = next(windows(corpus, 64))
high = model(X)
error = ((compiled(X) - high).norm() / high.norm()).item()
print(f'relative difference of the compiled logits: {error:.1e}')
assert error < 1e-4
step = make_step(model, compiled)
record('+ compile', tokens_per_second(step, windows(corpus, 64)))relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%
print(f'{len(jax.tree.leaves(nnx.state((model, optimizer))))} arrays in '
'the model and the optimizer')
noop = lambda model, optimizer: None
walk, tree = nnx.jit(noop), nnx.jit(noop, graph=False)
bound = nnx.jit_partial(noop, model, optimizer, graph=False)
for name, call in (('nnx.jit', lambda: walk(model, optimizer)),
('nnx.jit, graph=False', lambda: tree(model, optimizer)),
('nnx.jit_partial', bound)):
seconds = d2l.Benchmark(call, repeats=100).time
print(f'{name}: {1e3 * seconds:.2f} ms per call that does nothing')146 arrays in the model and the optimizer
nnx.jit: 8.69 ms per call that does nothing
nnx.jit, graph=False: 1.76 ms per call that does nothing
nnx.jit_partial: 0.23 ms per call that does nothing
컴파일된 로짓은 유효숫자 네 자리까지 일치합니다(미세한 차이는 융합 커널 내부의 재정렬된 fp32 반올림이 tf32 행렬 곱을 거치며 증폭된 것임). 처리량은 10% 이상 상승하여 \(1.6\times\) 상한 안에 깔끔히 들어옵니다.
nnx.jit 을 거치는 빈 호출 하나에만 스텝 장치 시간의 3분의 1이 넘는 거의 \(9\text{ ms}\) 의 호스트 시간이 걸립니다. 호스트가 장치보다 앞서 달리는 동안에만 그 비용이 가려져 있을 뿐입니다. 트리 순회로 전환하면 대부분이 사라지고 nnx.jit_partial 로 바인딩하면 나머지마저 거의 완전히 제거됩니다. 다음으로 nnx.jit_partial 이 nnx.jit 과 완전히 동일한 손실과 가중치 업데이트를 내는지 검증합니다.
twin = nnx.clone((model, optimizer)) # Equal states for the check
step = nnx.jit_partial(train_step, model, optimizer, graph=False)
X, Y = next(windows(corpus, 64))
loss, twin_loss = step(X, Y), jit_step(*twin, X, Y)
gaps = jax.tree.map(lambda a, b: jnp.abs(a - b).max(),
nnx.state(model, nnx.Param), nnx.state(twin[0], nnx.Param))
gap = max(float(g) for g in jax.tree.leaves(gaps))
print(f'losses {loss:.4f} and {twin_loss:.4f}, largest difference of the '
f'updated weights {gap:.1e}')
assert gap < 1e-6
record('+ jit_partial', tokens_per_second(step, windows(corpus, 64)))losses 2.3074 and 2.3074, largest difference of the updated weights 0.0e+00
+ jit_partial: 343,869 tokens/s (1.01x), windows within 0.2%
갱신된 가중치는 정확히 일치하며, 처리량은 2% 상한 및 베이스라인 잡음 편차 범위 안인 약 1%만큼 상승합니다.
두 번째 프로파일을 통해 스텝이 어떻게 달라졌는지 확인합니다.
profile(step, windows(corpus, 64))wall clock 22.22 ms per step, device busy 22.27 ms (100%), matrix products 71%
4.01 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.05 ms 14% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.83 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.44 ms 6% fmha_cutlassB_f32_aligned_64x64_k64_sm80
profile(step, windows(corpus, 64))wall clock 23.82 ms per step, device busy 23.61 ms (99%), matrix products 65%
3.03 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.99 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.90 ms 8% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
1.39 ms 6% loop_add_multiply_fusion_5
장치는 여전히 거의 전체 스텝 동안 바쁘게 돌며, 이제 행렬 곱셈이 장치 시간의 약 3분의 2 이상을 차지합니다.
스텝당 장치 시간이 \(24.5\text{ ms}\) 에서 \(22.3\text{ ms}\) 로 줄었고 커널 간 간격이 사라졌습니다. Inductor 융합이 \(2.2\text{ ms}\)(비행렬곱 시간의 4분의 1)를 깎아 냈고 CUDA 그래프 리플레이가 약 \(1\text{ ms}\) 의 호스트 발행 간격을 메웠습니다.
nnx.jit_partial 은 호스트 측 디스패치 오버헤드만 줄였으므로 장치 커널 시간 자체는 변하지 않습니다.
13.8.2.3 정밀도 낮추기
GPU가 쉬지 않고 돌며 행렬 곱셈이 장치 시간을 지배하게 되었으니 다음 단계는 행렬 곱셈 자체를 빠르게 만드는 것입니다. tf32에서 bf16으로 전환하면 RTX 4090 텐서 코어의 피크 처리량이 \(165\text{ TFLOP/s}\) 로 두 배 높아지고 bf16 활성화값의 메모리 사용량이 절반으로 줄어듭니다(13.4절). 행렬 곱셈이 스텝의 비율 \(f \in [2/3, 0.7]\) 을 차지하고 오직 행렬 곱셈만 두 배 빨라진다면 스텝 시간은 기존의 \(1 - f/2\) 로 줄어들어 약 \(1.5\times\) 가속됩니다(비행렬곱 커널들도 이동 바이트 수가 절반으로 줄면 \(2\times\) 를 향해 더 올라감).
13.4.2절 의 혼합 정밀도 레시피를 적용합니다. 행렬 곱셈(어텐션 포함)과 중간 원소별 연산은 bf16으로 실행하고, 마스터 가중치, 그레이디언트, Adam 모멘트, 정규화, 손실, 잔차 스트림은 fp32로 유지합니다(잔차 스트림을 fp32로 유지해야 작은 블록 업데이트가 bf16의 8비트 유효숫자에서 반올림되어 사라지지 않음). bf16은 fp32와 지수 범위가 같으므로 손실 스케일링은 필요 없습니다. 시간을 재기 전에 bf16 순전파가 fp32 로짓과 bf16 정밀도 범위(~1%) 안에서 일치하는지 검증합니다.
X, _ = next(windows(corpus, 64))
with torch.autocast('cuda', torch.bfloat16):
low = compiled(X).float()
high = compiled(X)
error = ((low - high).norm() / high.norm()).item()
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = make_step(model, compiled, bf16=True)
record('+ bf16', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 2.0e-03
+ bf16: 643,350 tokens/s (1.74x), windows within 0.1%
xla16 = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(xla16, nnx.state(model, nnx.Param)) # The same weights
d2l.to_bf16(xla16)
X, _ = next(windows(corpus, 64))
high = model(X)
error = float(jnp.linalg.norm(xla16(X) - high) / jnp.linalg.norm(high))
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = nnx.jit_partial(train_step, xla16,
nnx.Optimizer(xla16, adamw, wrt=nnx.Param), graph=False)
record('+ bf16', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 2.0e-03
+ bf16: 499,090 tokens/s (1.45x), windows within 0.4%
bf16 로짓은 fp32와 1% 이내로 일치합니다.
처리량이 약 \(1.75\times\) 상승합니다. bf16 GEMM이 tf32보다 더 높은 활용률로 실행되고 중간 융합 커널들이 4바이트 부동소수점 대신 2바이트 bf16 활성화값을 옮기기 때문에 71% 행렬 곱 비중만 절반으로 줄였을 때의 예측치인 \(1.55\times\) 를 웃돕니다. 참고로 F.scaled_dot_product_attention 은 베이스라인부터 이미 융합 FlashAttention 커널을 사용하고 있었습니다.
처리량이 \(1.45\times\) 상승하여 65% 행렬 곱 비중만 절반으로 줄였을 때의 예측치인 \(1.48\times\) 직전에 머무는데, 이는 비행렬곱 커널들이 빨라지지 않았음을 뜻합니다. 주범 중 하나는 어텐션입니다. 기본적으로 jax.nn.dot_product_attention 은 장치 메모리에 전체 어텐션 행렬을 실체화하는 XLA 구현을 사용합니다(10.5절). 이제 활성화값이 16비트 정밀도가 되었으므로 어텐션 스코어를 칩 위에 유지하는 cuDNN 융합 FlashAttention 커널(implementation='cudnn')로 전환할 수 있습니다.
class FusedGPT(d2l.GPT):
"""d2l.GPT with cuDNN's fused attention."""
class CausalAttention(d2l.GPT.CausalAttention):
@staticmethod
def attend(q, k, v): # cuDNN takes 16-bit inputs only
return jax.nn.dot_product_attention(q, k, v, is_causal=True,
implementation='cudnn')동일한 매개변수를 bf16으로 변환해 FusedGPT 로부터 model16 을 인스턴스화하고, 로짓이 여전히 fp32 기준 high 와 1% 이내로 일치하는지 검증한 뒤 훈련 스텝을 벤치마킹합니다.
model16 = FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(model16, nnx.state(model, nnx.Param)) # The same weights
d2l.to_bf16(model16)
error = float(jnp.linalg.norm(model16(X) - high) / jnp.linalg.norm(high))
print(f'relative difference of the bf16 logits: {error:.1e}')
assert error < 0.01
step = nnx.jit_partial(train_step, model16,
nnx.Optimizer(model16, adamw, wrt=nnx.Param),
graph=False)
record('+ fused attention', tokens_per_second(step, windows(corpus, 64)))relative difference of the bf16 logits: 1.9e-03
+ fused attention: 675,436 tokens/s (1.35x), windows within 0.2%
cuDNN 융합 어텐션으로 전환하면 1% 로짓 일치를 유지하면서 처리량이 추가로 3분의 1 더 높아져, bf16 + 융합 어텐션 누적 가속비가 \(2\times\) 가까이에 이릅니다.
13.8.2.4 더 큰 미니배치
미니배치 크기를 키우면 고정된 스텝당 비용이 더 많은 토큰에 걸쳐 상각됩니다. 장치가 이미 스텝 내내 바쁘게 돌고 있으므로 토큰 수가 아니라 매개변수 수에 비례하는 장치 작업만 상각 대상이 됩니다.
- AdamW가 가중치, 그레이디언트, 두 모멘트를 읽고 가중치와 두 모멘트를 기록합니다(fp32에서 \(28\text{ bytes/param}\)).
- 혼합 정밀도가 순전파에서 fp32 마스터 가중치를 bf16으로 캐스팅하고 역전파에서 bf16 가중치 그레이디언트를 다시 fp32로 캐스팅합니다(\(12\text{ bytes/param}\)).
이 둘을 합치면 \(40\text{ bytes/param}\), 즉 \(0.76\text{ GB/step}\) 를 이동시킵니다. \(1.0\text{ TB/s}\) 메모리 대역폭에서 이 고정 작업은 약 \(0.75\text{ ms}\)—배치 크기 64에서의 \(12\text{--}13\text{ ms}\) bf16 스텝 중 대략 \(1/16\)—가 걸립니다. 미니배치를 윈도 64개에서 512개(\(65{,}536\) 토큰)로 \(8\times\) 키우면 이 고정 비용의 \(7/8\) 이 상각되어 약 5%의 처리량 향상이 예측됩니다.
단일 GPU에서의 이득이 소폭이더라도 데이터 병렬화는 GPU당 스텝 시간이 그레이디언트 올리듀스보다 훨씬 길어야만 잘 스케일링되므로 충분히 가치 있는 변경입니다(13.8.3절). 다만 배치 크기가 임계 배치 크기를 넘어서면 표본 효율이 떨어진다는 점은 유념해야 합니다(9.8절, 5 참조). 활성화 메모리는 배치 크기에 선형으로 비례해 커지므로 가중치와 옵티마이저 상태를 제외한 추가 피크 메모리도 함께 기록합니다(13.4.1.4절).
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
record('+ batch 512', tokens_per_second(step, windows(corpus, 512)))
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB
batches = windows(corpus, 512)
plan = step.lower(*next(batches)).compile().memory_analysis()
record('+ batch 512', tokens_per_second(step, batches))
memory = plan.temp_size_in_bytes / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ batch 512: 718,714 tokens/s (1.06x), windows within 0.0%
memory beyond weights and optimizer state: 7.4 GiB
배치 크기 512에서 활성화 메모리는 GPU \(24\text{ GiB}\) 의 약 3분의 1을 사용하며 처리량은 몇 퍼센트 증가합니다(2 에서 여러 배치 크기에 걸쳐 스텝당 고정 비용과 토큰당 비용을 분리함). 세 번째 프로파일이 배치 크기 512에서의 시간 구성을 보여 줍니다.
profile(step, windows(corpus, 512))wall clock 100.34 ms per step, device busy 100.33 ms (100%), matrix products 57%
11.62 ms 12% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
10.78 ms 11% ampere_bf16_s16816gemm_bf16_128x64_ldg8_f2f_tn
7.45 ms 7% Kernel2<cutlass_80_tensorop_bf16_s16816gemm_relu_bf1
5.62 ms 6% triton_poi_fused__unsafe_view_mm_mul_silu_silu_backw
profile(step, windows(corpus, 512))wall clock 91.19 ms per step, device busy 90.91 ms (100%), matrix products 59%
14.54 ms 16% ampere_bf16_s1688gemm_bf16_64x128_sliced1x2_ldg8_f2f
11.90 ms 13% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_nn
8.36 ms 9% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_tn
6.72 ms 7% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
전체 스텝 내내 장치가 바쁘게 가동됩니다. 행렬 곱셈(융합 어텐션 포함)이 시간의 60% 남짓을 차지하고, RMSNorm, SwiGLU, 회전 위치 임베딩, fp32/bf16 캐스팅을 위한 융합 대역폭 병목 커널들이 나머지를 차지합니다.
13.8.2.5 활성화 체크포인팅
활성화 체크포인팅(13.4.3절)은 순전파 중 각 블록의 입력만 저장하고 역전파 중 내부 활성화값을 다시 계산해 메모리를 아낍니다. 배치 크기 512가 GPU 메모리의 3분의 1밖에 쓰지 않으므로 여기서는 체크포인팅이 불필요하며 오히려 스텝을 느리게 만들 뿐입니다. 감속 정도는 두 가지 방법으로 예측할 수 있습니다.
- FLOP 수 기준: 순전파를 다시 계산하면 토큰당 블록 산술량이 \(6\) 에서 \(8\text{ FLOPs/param}\) 으로 늘어나므로 비체크포인팅 처리량의 \(6/8 = 0.75\) 가 예측됩니다.
- 순전파 시간 측정 기준: 아래에서 배치 크기 512의 단독 순전파 시간 \(t_{\text{fwd}}\) 를 측정하여 \(1 / (1 + t_{\text{fwd}} / t_{\text{step}})\) 을 계산합니다.
X512, _ = next(windows(corpus, 512)) # One minibatch of the last step
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
t_forward = d2l.Benchmark(lambda: compiled(X512)).timeX512, _ = next(windows(corpus, 512)) # One minibatch of the last step
forward = nnx.jit_partial(lambda model, X: model(X), model16, graph=False)
t_forward = d2l.Benchmark(lambda: forward(X512)).time배치 크기 512에서 전체 스텝 시간 t_step 과 단독 순전파 시간 t_forward 를 비교하면 모든 블록의 순전파를 반복할 때 유지되는 처리량 비율 1 / (1 + t_forward / t_step) 이 예측됩니다.
t_step = 512 * 128 / results['+ batch 512'] # Seconds per step
print(f'forward pass {1e3 * t_forward:.1f} ms of a {1e3 * t_step:.1f} ms '
f'step: repeating it keeps at least {1 / (1 + t_forward / t_step):.2f} '
f'of the throughput')forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput
t_step = 512 * 128 / results['+ batch 512'] # Seconds per step
print(f'forward pass {1e3 * t_forward:.1f} ms of a {1e3 * t_step:.1f} ms '
f'step: repeating it keeps at least {1 / (1 + t_forward / t_step):.2f} '
f'of the throughput')forward pass 29.4 ms of a 91.2 ms step: repeating it keeps at least 0.76 of the throughput
두 추정치가 일치합니다. 순전파가 스텝의 약 3분의 1을 차지하므로 이를 반복하면 최소 4분의 3 이상의 처리량이 유지될 것입니다(임베딩과 출력 투영은 체크포인팅하지 않으므로 약간 더 높음). 이제 각 블록을 Checkpointed 로 감싸고 로짓 일치를 검증한 뒤 처리량(kept=False)과 활성화 메모리를 모두 측정합니다.
Checkpointed 는 torch.utils.checkpoint.checkpoint 를 호출합니다.
Checkpointed 는 nnx.remat 을 호출합니다.
class Checkpointed(nn.Module):
"""A module that keeps only its input for the backward pass."""
def __init__(self, module):
super().__init__()
self.module = module
def forward(self, X, **kwargs):
return checkpoint(self.module, X, use_reentrant=False, **kwargs)
remat = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
remat.load_state_dict(model.state_dict())
remat.blks = nn.ModuleList(Checkpointed(blk) for blk in remat.blks)
assert torch.allclose(remat(X), model(X), atol=1e-6)
step = make_step(remat, torch.compile(remat, dynamic=False,
mode='reduce-overhead'), bf16=True)
with torch.no_grad(), torch.autocast('cuda', torch.bfloat16):
forward = d2l.kernel_times(lambda: compiled(X512), steps=5) # Alone
torch.cuda.reset_peak_memory_stats()
start = torch.cuda.memory_allocated()
batches = windows(corpus, 512)
record('+ checkpointing', tokens_per_second(step, batches), kept=False)
memory = (torch.cuda.max_memory_allocated() - start) / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')
def split(kernels):
"""Device ms per step of the matrix products and of all other kernels."""
products = sum(ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
return np.array([products, sum(kernels.values()) - products])
alone = split(forward)
added = (split(d2l.kernel_times(lambda: step(*next(batches)), steps=5))
- split(profiles['+ batch 512']))
print(f'forward pass alone: products {alone[0]:4.1f} ms, other kernels '
f'{alone[1]:4.1f} ms\nadded to the step: products {added[0]:4.1f} ms, '
f'other kernels {added[1]:4.1f} ms')+ checkpointing: 556,390 tokens/s (0.85x), windows within 0.0%
memory beyond weights and optimizer state: 3.2 GiB
forward pass alone: products 17.4 ms, other kernels 13.4 ms
added to the step: products 14.5 ms, other kernels 3.1 ms
class Checkpointed(nnx.Module):
"""A module that keeps only its input for the backward pass."""
def __init__(self, module):
self.module = module
def __call__(self, X, **kwargs):
return nnx.remat(lambda module, X, kwargs: module(X, **kwargs))(
self.module, X, kwargs)
remat = FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(remat, nnx.state(model16, nnx.Param))
remat.blks = nnx.List(Checkpointed(blk) for blk in remat.blks)
d2l.to_bf16(remat)
assert jnp.allclose(remat(X), model16(X), atol=1e-6)
optimizer = nnx.Optimizer(remat, adamw, wrt=nnx.Param)
step = nnx.jit_partial(train_step, remat, optimizer, graph=False)
batches = windows(corpus, 512)
plan = step.lower(*next(batches)).compile().memory_analysis()
record('+ checkpointing', tokens_per_second(step, batches), kept=False)
memory = plan.temp_size_in_bytes / 2**30
print(f'memory beyond weights and optimizer state: {memory:.1f} GiB')+ checkpointing: 565,754 tokens/s (0.79x), windows within 0.0%
memory beyond weights and optimizer state: 2.6 GiB
체크포인팅은 활성화 메모리를 약 3분의 2만큼 줄이면서 단독 순전파 시간 기반 예측보다 더 높은 처리량을 유지합니다.
처리량은 \(0.85\times\) 로 낮아집니다(\(0.77\times\) 하한보다 높음). 커널 분해에서 드러나듯 블록 행렬 곱 재계산은 \(14\text{ ms}\) 를 더하는 반면(출력 투영을 포함한 전체 순전파 행렬 곱 \(17\text{ ms}\) 에 근접), 비행렬곱 커널 재계산은 \(13\text{ ms}\) 대신 단 \(3\text{ ms}\) 만 더합니다. Inductor가 재계산된 원소별 연산들을 이를 소비하는 역전파 커널에 직접 융합하여 재계산의 메모리 트래픽을 거의 공짜로 만들기 때문입니다.
XLA 역시 재계산된 원소별 작업을 역전파 안에 똑같이 융합하므로 처리량이 \(0.79\times\)(\(0.76\times\) 하한보다 높음)로 낮아집니다(3 참조).
모델이나 배치 크기가 장치 메모리를 초과할 때는 체크포인팅이 필수적이지만, 여기서는 메모리가 넉넉하므로 이어지는 구성들에서는 제외합니다.
13.8.3 데이터 병렬화
가장 빠른 단일 GPU 스텝조차 머신에 장착된 네 장의 RTX 4090 중 세 장을 유휴 상태로 놀리고 있습니다. 다중 GPU로 실행하기 전에 13.5.4절 의 비용 모델로 데이터 병렬 가속비를 먼저 예측합니다.
13.8.3.1 가속비 예측
데이터 병렬화(13.5절)에서는 \(k\) 개 GPU 각각이 모델 복제본을 보유하고 자기 미니배치에서 그레이디언트를 계산한 뒤 \(c\) 개의 버킷으로 나뉜 크기 \(S\) 바이트의 올리듀스를 통해 그레이디언트를 합산합니다.
\[ t_{\textrm{compute}}(B/k) + c\,\alpha + \frac{2(k-1)}{k}\,S\,\beta_{\textrm{link}}. \]
피어 투 피어 접근이 없는 PCIe 머신에서는 GPU 전송이 대략 \(2.4\text{ GB/s}\) 버스 대역폭(13.6절), 즉 \(\beta_{\textrm{link}} \approx 0.42\text{ ns/byte}\) 로 호스트 메모리를 거쳐 스테이징됩니다. 약한 스케일링(고정 GPU당 배치 크기) 아래에서 버킷당 지연 시간 \(c\,\alpha\) 는 1밀리초 미만으로 수십 밀리초의 스텝 시간 옆에서는 무시할 수 있으므로 비중첩 스텝 시간은 다음과 같이 단순화됩니다.
\[t_{\textrm{step}}(k) \approx t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k), \tag{13.8.1}\]
따라서 처리량 배수는 \(k\, t_{\textrm{step}}(1) / (t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k))\) 가 됩니다. 두 번째 GPU를 추가해 처리량이 늘어나려면 \(t_{\textrm{allreduce}}(2) < t_{\textrm{step}}(1)\) 이어야 합니다.
19M 매개변수 GPT의 경우 fp32 그레이디언트가 \(S = 76\text{ MB}\) 를 차지하므로 2 GPU에서는 \(t_{\textrm{allreduce}}(2) \approx S\beta_{\textrm{link}} \approx 31\text{ ms}\), 4 GPU에서는 \(t_{\textrm{allreduce}}(4) \approx 1.5\,S\beta_{\textrm{link}} \approx 47\text{ ms}\) 가 걸립니다.
- GPU당 배치 64의 컴파일된 fp32(\(t_{\textrm{step}}(1) \approx 22\text{ ms}\)): 올리듀스가 스텝 자체보다 더 오래 걸립니다. 식 13.8.1 에서는 2 GPU에서의 감속(\(\sim 0.85\times\))과 4 GPU에서의 불과 \(\sim 1.3\times\) 가속을 예측합니다.
- GPU당 배치 512의 컴파일된 bf16(\(t_{\textrm{step}}(1) \approx 90\text{--}100\text{ ms}\)): 스텝이 올리듀스보다 훨씬 길어 2 GPU에서 \(\sim 1.5\times\), 4 GPU에서 \(2.6\text{--}2.7\times\) 를 예측합니다.
프레임워크들이 그레이디언트 올리듀스 버킷을 역전파와 중첩시키므로(그림 13.6.1), 식 13.8.1 의 값은 대개 가속비의 하한이 되며 이를 웃도는 여유분이 역전파 연산 뒤로 통신이 얼마나 숨겨졌는지를 나타냅니다. 다만 항상 보장되는 하한은 아닙니다. NCCL 복사 커널이 역전파와 동일한 GPU 자원을 두고 경쟁하며(13.6.2절), 이 경합이 여유분을 갉아먹을 수 있기 때문입니다.
13.8.3.2 실측 가속비
data_parallel(k, bf16, batch_size) 는 동일한 GPU들에서의 \(76\text{ MB}\) 그레이디언트 버퍼 단독 올리듀스 시간과 함께 \(k\) 개 GPU에서의 훈련 처리량을 측정합니다.
DistributedDataParallel 은 d2l.torchrun(13.6절)을 통해 GPU당 프로세스 하나씩을 실행하며 버킷 단위 올리듀스를 역전파와 중첩시킵니다. CUDA 그래프 없이 컴파일하고(장치 실행이 호스트 디스패치를 숨기기에 충분히 김) 동일한 조건에서 \(k = 1\) 도 벤치마킹합니다.
JAX는 단일 프로세스에서 \(k\) 개 GPU 전체를 구동하며(13.6절), Auto 메시 위에 모델·옵티마이저·말뭉치를 복제하고 각 \(k \times \text{batch\_size}\) 미니배치를 'data' 에 걸쳐 샤딩합니다. XLA는 그레이디언트 올리듀스를 자동으로 삽입하고 첫 셀에서 활성화한 지연 시간 은닉 스케줄러를 통해 이를 역전파와 중첩시킵니다.
DDP_GPT = r'''
import json, sys, torch
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
bf16, batch_size = sys.argv[1] == 'bf16', int(sys.argv[2])
torch.set_float32_matmul_precision('high')
torch._inductor.config.compile_threads = 1 # k processes compile at once
data = d2l.WikiText103(batch_size, 128)
corpus = torch.tensor(data.train, device=device)
model = DDP(d2l.GPT(len(data.vocab), num_hiddens=512).to(device))
step = d2l.make_step(model, torch.compile(model, dynamic=False), bf16)
batches = d2l.windows(corpus, batch_size)
seconds = d2l.Benchmark(lambda: step(*next(batches)), 20, 50).time
grads = torch.zeros(d2l.num_params(model), device=device)
allreduce = d2l.Benchmark(lambda: torch.distributed.all_reduce(grads),
repeats=10).time
if rank == 0:
print(json.dumps({'speed': k * batch_size * 128 / seconds,
'allreduce': allreduce}))
torch.distributed.destroy_process_group()
'''
# The CUDA graphs of the compiled steps above hold memory on GPU 0, which
# the process of rank 0 needs: reset the compiler and return the memory
torch.compiler.reset()
torch.cuda.empty_cache()
def data_parallel(k, bf16, batch_size):
"""Tokens per second on k GPUs, and seconds per allreduce of all
gradients."""
r = d2l.torchrun(DDP_GPT, k, 'bf16' if bf16 else 'fp32', batch_size)[0]
return r['speed'], r['allreduce']def data_parallel(k, bf16, batch_size):
"""Tokens per second on k GPUs, and seconds per allreduce of all
gradients."""
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
# Auto: the compiler places intermediate results
axis_types=(jax.sharding.AxisType.Auto,))
copy, split = NamedSharding(mesh, P()), NamedSharding(mesh, P('data'))
net = (FusedGPT if bf16 else d2l.GPT)(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
net = d2l.to_bf16(net) if bf16 else net
optimizer = nnx.Optimizer(net, adamw, wrt=nnx.Param)
nnx.update((net, optimizer),
jax.device_put(nnx.state((net, optimizer)), copy))
step = nnx.jit_partial(train_step, net, optimizer, graph=False)
batches = windows(jax.device_put(corpus, copy), k * batch_size,
sharding=split)
speed, _ = tokens_per_second(step, batches)
grads = jnp.zeros((k, num_params), device=split) # All gradients per GPU
psum = jax.jit(jax.shard_map(lambda g: jax.lax.psum(g, 'data'),
mesh=mesh, in_specs=P('data'),
out_specs=P('data')))
return speed, d2l.Benchmark(lambda: psum(grads), repeats=10).time이제 \(k \in \{1, 2, 4\}\) 개 GPU에 걸쳐 짧은 fp32 스텝(batch_size=64)과 긴 bf16 스텝(batch_size=512) 모두에 대해 data_parallel 을 실행하고 식 13.8.1 의 비중첩 예측을 실측 가속비와 비교합니다.
for bf16, batch_size in ((False, 64), (True, 512)):
tokens = batch_size * 128 # Per GPU and step
one, _ = data_parallel(1, bf16, batch_size)
print(f'{"bf16" if bf16 else "fp32"}, batch {batch_size} per GPU: '
f'{one:,.0f} tokens/s on one GPU')
for k in (2, 4):
if k <= d2l.num_gpus():
speed, allreduce = data_parallel(k, bf16, batch_size)
predicted = k * tokens / (tokens / one + allreduce)
print(f' {k} GPUs: allreduce {1e3 * allreduce:3.0f} ms, '
f'speedup predicted {predicted / one:.2f}x, '
f'measured {speed / one:.2f}x')fp32, batch 64 per GPU: 364,947 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.83x, measured 0.91x
4 GPUs: allreduce 48 ms, speedup predicted 1.27x, measured 1.36x
bf16, batch 512 per GPU: 662,971 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.52x, measured 1.63x
4 GPUs: allreduce 48 ms, speedup predicted 2.69x, measured 2.92x
for bf16, batch_size in ((False, 64), (True, 512)):
tokens = batch_size * 128 # Per GPU and step
one, _ = data_parallel(1, bf16, batch_size)
print(f'{"bf16" if bf16 else "fp32"}, batch {batch_size} per GPU: '
f'{one:,.0f} tokens/s on one GPU')
for k in (2, 4):
if k <= d2l.num_gpus():
speed, allreduce = data_parallel(k, bf16, batch_size)
predicted = k * tokens / (tokens / one + allreduce)
print(f' {k} GPUs: allreduce {1e3 * allreduce:3.0f} ms, '
f'speedup predicted {predicted / one:.2f}x, '
f'measured {speed / one:.2f}x')fp32, batch 64 per GPU: 343,542 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.87x, measured 0.89x
4 GPUs: allreduce 48 ms, speedup predicted 1.33x, measured 1.43x
bf16, batch 512 per GPU: 718,085 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.50x, measured 1.71x
4 GPUs: allreduce 48 ms, speedup predicted 2.62x, measured 3.22x
단독 올리듀스는 2 GPU에서 \(31\text{ ms}\), 4 GPU에서 \(48\text{ ms}\) 가 걸려 링크 속도 추정치와 1밀리초 이내로 일치합니다. 부호가 정반대인 두 예측이 모두 그대로 들어맞습니다. 배치 64에서는 2 GPU가 1 GPU보다 느리고 4 GPU도 \(1.5\times\) 미만에 그치지만, bf16 배치 512에서는 4 GPU가 단일 GPU 처리량의 대략 \(3\times\)(이 절의 모든 단일 변경 중 가장 큰 가속비)에 도달하며 통신 중첩이 실측 가속비를 비중첩 하한 식 13.8.1 위로 밀어 올립니다. (단방향 \(900\text{ GB/s}\) NVLink 머신에서는 \(76\text{ MB}\) 올리듀스가 1밀리초 미만에 끝나 배치 64에서도 거의 선형으로 스케일링됩니다.)
13.8.4 결과 종합
이제 모든 단일 GPU 최적화를 나란히 요약하고, 최종 스텝이 여전히 모델을 올바로 훈련시키는지 검증한 뒤 남은 시간이 어디에 쓰이는지 정산합니다.
13.8.4.1 누적 비교
아래 표는 단일 GPU 구성들을 적용 순서대로 나열합니다. 각 step 비율은 바로 윗줄 대비 값이고 total 은 베이스라인 대비 누적 가속비이며, 체크포인팅은 채택하지 않은 분기로 구분선 아래에 표시했습니다. TFLOP/s 는 매개변수·토큰당 \(6\text{ FLOPs}\) 로 처리량을 산술 속도로 환산한 값이고, MFU 는 이를 RTX 4090의 bf16 피크인 \(165.2\text{ TFLOP/s}\) 로 나눈 값입니다(모델 FLOPs 활용률, model FLOPs utilization, Chowdhery 기타 (2022년); 1 에서 어텐션 스코어 FLOPs를 추가함).
flops = 6 * num_params # Per token, without the attention scores
peak = {'tf32': 82.6e12, 'bf16': 165.2e12} # FLOP/s of the RTX 4090
print(f'{"configuration":18}{"tokens/s":>10}{"step":>7}{"total":>7}'
f'{"TFLOP/s":>9}{"MFU":>6}')
first = previous = next(iter(results.values()))
for name, speed in results.items():
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x'
f'{speed / first:6.2f}x{speed * flops / 1e12:9.1f}'
f'{speed * flops / peak["bf16"]:6.0%}')
previous = speed
print('-' * 57)
for name, speed in branches.items(): # Measured on top of the last row
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x{"":7}'
f'{speed * flops / 1e12:9.1f}{speed * flops / peak["bf16"]:6.0%}'
' (not kept)')configuration tokens/s step total TFLOP/s MFU
baseline 317,736 1.00x 1.00x 36.2 22%
+ compile 368,688 1.16x 1.16x 42.1 25%
+ bf16 643,350 1.74x 2.02x 73.4 44%
+ batch 512 653,141 1.02x 2.06x 74.5 45%
---------------------------------------------------------
+ checkpointing 556,390 0.85x 63.5 38% (not kept)
flops = 6 * num_params # Per token, without the attention scores
peak = {'tf32': 82.6e12, 'bf16': 165.2e12} # FLOP/s of the RTX 4090
print(f'{"configuration":18}{"tokens/s":>10}{"step":>7}{"total":>7}'
f'{"TFLOP/s":>9}{"MFU":>6}')
first = previous = next(iter(results.values()))
for name, speed in results.items():
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x'
f'{speed / first:6.2f}x{speed * flops / 1e12:9.1f}'
f'{speed * flops / peak["bf16"]:6.0%}')
previous = speed
print('-' * 57)
for name, speed in branches.items(): # Measured on top of the last row
print(f'{name:18}{speed:10,.0f}{speed / previous:6.2f}x{"":7}'
f'{speed * flops / 1e12:9.1f}{speed * flops / peak["bf16"]:6.0%}'
' (not kept)')configuration tokens/s step total TFLOP/s MFU
baseline 340,062 1.00x 1.00x 38.8 23%
+ jit_partial 343,869 1.01x 1.01x 39.2 24%
+ bf16 499,090 1.45x 1.47x 56.9 34%
+ fused attention 675,436 1.35x 1.99x 77.0 47%
+ batch 512 718,714 1.06x 2.11x 82.0 50%
---------------------------------------------------------
+ checkpointing 565,754 0.79x 64.5 39% (not kept)
단일 GPU 최적화들을 누적 적용하면 훈련 처리량이 두 배로 늘어나 RTX 4090 bf16 피크의 약 50%에 도달합니다. 프로파일이 예측한 그대로 거의 모든 이득은 행렬 곱 가속(bf16)과 주변 메모리 트래픽 절감(커널 융합)에서 나오며, 호스트 오버헤드 제거와 미니배치 확대는 각각 몇 퍼센트씩 보탭니다.
각 가속비 수치는 적용 순서(7 참조)와 하드웨어 균형에 따라 달라진다는 점에 유의하십시오. 더 빠른 GPU(또는 더 작은 모델)에서는 장치 실행이 더 짧아지므로 호스트 디스패치 제거의 영향력이 훨씬 커집니다.
13.8.4.2 훈련 검증
최적화가 소리 없이 훈련을 망가뜨렸다면 높은 처리량은 아무 소용이 없습니다. 동일하게 초기화된 두 모델(하나는 베이스라인 스텝, 다른 하나는 최종 컴파일 bf16 스텝 사용)을 512개 윈도짜리 똑같은 미니배치 200개(\(\sim 13\text{M}\) 토큰)로 훈련하여 정합성을 검증합니다(후반 AdamW 손실 스파이크를 막기 위해 50스텝 선형 학습률 웜업 적용, 11.2절). 마지막 20스텝 평균 손실과 검증 손실(d2l.lm_perplexity, 9.3절)에서 두 모델이 \(0.15\text{ nats/byte}\) 이내로 일치하고 둘 다 11.2절 의 바이그램 베이스라인인 \(2.45\text{ nats/byte}\) 를 넘어서는지 확인합니다.
learner = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference = d2l.GPT(len(data.vocab), num_hiddens=512).to(device)
reference.load_state_dict(learner.state_dict()) # One initialization
steps = {'baseline': make_step(reference, warmup=50),
'final': make_step(learner, torch.compile(
learner, dynamic=False, mode='reduce-overhead'), bf16=True,
warmup=50)}
batches = windows(corpus, 512)
minibatches = [next(batches) for _ in range(200)] # The same for both
losses = {name: torch.stack([step(X, Y).detach()
for X, Y in minibatches]).tolist()
for name, step in steps.items()}
validation = {name: math.log(d2l.lm_perplexity(net, data.val_dataloader()))
for name, net in (('baseline', reference), ('final', learner))}learner = d2l.to_bf16(FusedGPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key())))
reference = d2l.GPT(len(data.vocab), num_hiddens=512,
rngs=nnx.Rngs(d2l.get_key()))
nnx.update(reference, nnx.state(learner, nnx.Param)) # One initialization
# The learning rate rises linearly to 1e-3 over the first 50 steps
warm = optax.adamw(optax.linear_schedule(1e-3 / 50, 1e-3, 49),
weight_decay=0.01)
reference_optimizer = nnx.Optimizer(reference, warm, wrt=nnx.Param)
steps = {'baseline': lambda X, Y: jit_step(reference, reference_optimizer,
X, Y),
'final': nnx.jit_partial(train_step, learner, nnx.Optimizer(
learner, warm, wrt=nnx.Param), graph=False)}
batches = windows(corpus, 512)
minibatches = [next(batches) for _ in range(200)] # The same for both
losses = {name: jnp.stack([step(X, Y) for X, Y in minibatches]).tolist()
for name, step in steps.items()}
validation = {name: math.log(d2l.lm_perplexity(net, data.val_dataloader()))
for name, net in (('baseline', reference), ('final', learner))}이제 마지막 20스텝 평균(late) 및 검증 로그 혼란도(validation)와 함께 스텝 1, 50, 100, 200에서의 훈련 손실 궤적을 비교하고, 두 실행 모두 \(2.45\text{ nats/byte}\) 바이그램 임곗값을 넘고 서로 \(0.15\text{ nats/byte}\) 이내로 일치함을 단언합니다.
checkpoints = (1, 50, 100, 200)
late = {name: np.mean(curve[-20:]) for name, curve in losses.items()}
print(f'{"loss at step":14}' + ''.join(f'{i:>7}' for i in checkpoints)
+ f'{"mean of last 20":>17}{"validation":>12}')
for name, curve in losses.items():
print(f'{name:14}' + ''.join(f'{curve[i - 1]:7.2f}' for i in checkpoints)
+ f'{late[name]:17.2f}{validation[name]:12.2f}')
assert validation[name] < 2.45 # Better than the bigram model
for values in (late, validation): # The final step trains like the baseline
assert abs(values['baseline'] - values['final']) < 0.15loss at step 1 50 100 200 mean of last 20 validation
baseline 5.66 2.52 2.03 1.49 1.52 1.47
final 5.66 2.51 2.06 1.50 1.53 1.47
checkpoints = (1, 50, 100, 200)
late = {name: np.mean(curve[-20:]) for name, curve in losses.items()}
print(f'{"loss at step":14}' + ''.join(f'{i:>7}' for i in checkpoints)
+ f'{"mean of last 20":>17}{"validation":>12}')
for name, curve in losses.items():
print(f'{name:14}' + ''.join(f'{curve[i - 1]:7.2f}' for i in checkpoints)
+ f'{late[name]:17.2f}{validation[name]:12.2f}')
assert validation[name] < 2.45 # Better than the bigram model
for values in (late, validation): # The final step trains like the baseline
assert abs(values['baseline'] - values['final']) < 0.15loss at step 1 50 100 200 mean of last 20 validation
baseline 5.59 2.60 2.16 1.64 1.68 1.62
final 5.59 2.60 2.16 1.64 1.69 1.62
두 곡선 모두 \(\log 256 \approx 5.55\) 에서 시작해 200스텝 내내 나란히 내려가며 바이그램 임곗값 훨씬 아래의 거의 동일한 검증 손실에 도달합니다. 다만 배치 크기 512로 200스텝(\(13\text{M}\) 토큰)을 돈 결과가 11.2절 에서 코사인 감쇠와 함께 배치 크기 64로 1,000스텝(\(8\text{M}\) 토큰)을 돈 결과보다 더 높은 손실에서 끝난다는 점에 주목하십시오. 단순 토큰 처리량이 곧 목표 손실 도달 시간과 같지는 않습니다(5 참조).
13.8.4.3 최종 스텝 정산
마지막으로 account 는 베이스라인과 최종 프로파일을 \(8{,}192\) 토큰당 밀리초 단위로 정규화하여 총 벽시계 시간을 이상적인 피크 산술 시간, 실제 행렬 곱 커널 시간, 비행렬곱 커널 시간과 대조합니다.
def account(kernels, tokens, speed):
"""Milliseconds per 8,192 tokens of a step of `tokens` tokens that runs
at `speed` tokens/s: the step, its matrix products, and all its other
kernels."""
per_step = 8192 / tokens # Steps per 8,192 tokens
products = per_step * sum( # Kernel names as in d2l.show_profile
ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
other = per_step * sum(kernels.values()) - products
return 1e3 * 8192 / speed, products, other
print(f'{"ms per 8,192 tokens":24}{"step":>6}{"at peak":>9}'
f'{"products":>10}{"other":>7}')
for name, tokens, fmt in (('baseline', 64 * 128, 'tf32'),
('+ batch 512', 512 * 128, 'bf16')):
wall, products, other = account(profiles[name], tokens, results[name])
arithmetic = 1e3 * 8192 * flops / peak[fmt] # At the peak of the format
print(f'{name + " (" + fmt + ")":24}{wall:6.1f}{arithmetic:9.1f}'
f'{products:10.1f}{other:7.1f}')ms per 8,192 tokens step at peak products other
baseline (tf32) 25.8 11.3 15.6 8.8
+ batch 512 (bf16) 12.5 5.7 7.1 5.4
def account(kernels, tokens, speed):
"""Milliseconds per 8,192 tokens of a step of `tokens` tokens that runs
at `speed` tokens/s: the step, its matrix products, and all its other
kernels."""
per_step = 8192 / tokens # Steps per 8,192 tokens
products = per_step * sum( # Kernel names as in d2l.show_profile
ms for name, ms in kernels.items()
if re.search(d2l.PRODUCT_KERNELS, name, re.I))
other = per_step * sum(kernels.values()) - products
return 1e3 * 8192 / speed, products, other
print(f'{"ms per 8,192 tokens":24}{"step":>6}{"at peak":>9}'
f'{"products":>10}{"other":>7}')
for name, tokens, fmt in (('baseline', 64 * 128, 'tf32'),
('+ batch 512', 512 * 128, 'bf16')):
wall, products, other = account(profiles[name], tokens, results[name])
arithmetic = 1e3 * 8192 * flops / peak[fmt] # At the peak of the format
print(f'{name + " (" + fmt + ")":24}{wall:6.1f}{arithmetic:9.1f}'
f'{products:10.1f}{other:7.1f}')ms per 8,192 tokens step at peak products other
baseline (tf32) 24.1 11.3 15.3 8.3
+ batch 512 (bf16) 11.4 5.7 6.7 4.7
\(8{,}192\) 토큰당 최종 스텝은 행렬 곱에 약 \(7\text{ ms}\)(\(5.7\text{ ms}\) bf16 이상치의 80%가 넘는 효율로 실행)를 쓰고 그 사이의 대역폭 병목 커널들에 \(5\text{ ms}\) 를 씁니다. 행렬 수축 연산이 전체 FLOPs의 99% 이상을 수행하면서도 시간은 약 60%만 차지하는 전형적인 Roofline 분할 구도입니다 (Ivanov 기타 2021년). \(7\text{ ms}\) 대 \(5\text{ ms}\) 로 나뉜 스텝은 더 빠른 산술(예: fp8)만으로도, 비행렬곱 메모리 트래픽 제거만으로도 절반으로 줄일 수 없으므로 또 한 번의 \(2\times\) 가속을 얻으려면 두 가지가 동시에 필요합니다.
13.8.5 요약
커널 프로파일은 훈련 스텝의 병목을 분류하고 각 후보 최적화를 적용하기 전에 얻을 수 있는 이득의 상한을 제시해 줍니다. 호스트 디스패치 절감은 최대 장치 유휴 시간만큼 아낄 수 있고, 커널 융합은 최대 비행렬곱 장치 시간만큼 아낄 수 있으며, 행렬 곱셈이 스텝의 비율 \(f\) 를 차지할 때 텐서 코어 정밀도 처리량을 두 배 높이면 \(1/(1 - f/2)\) 에서 \(2\) 사이의 가속비를 얻습니다. 병목 하나를 제거하면 스텝의 나머지 비중이 이동하므로 각 최적화는 수치적 동치성을 검증하며 누적 측정해야 합니다. 단일 RTX 4090에서 19M 매개변수 GPT 스텝은 거의 전적으로 bf16 행렬 곱과 커널 융합에 힘입어 속도가 두 배로 빨라져 45–50% MFU에 도달했으며, 최종 스텝은 피크 근처에서 도는 행렬 수축 연산과 대역폭 병목 커널 사이에 대략 60 대 40으로 나뉘었습니다. 마지막으로 데이터 병렬 비용 모델 \(t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k)\) 는 짧은 fp32 스텝(\(22\text{ ms}\) 스텝 대 \(31\text{ ms}\) PCIe 올리듀스)에서의 2-GPU 감속과 배치-512 bf16 스텝(\(90\text{--}100\text{ ms}\) 스텝 대 \(48\text{ ms}\) 올리듀스)에서의 약 \(3\times\) 4-GPU 가속을 모두 정확히 예측했습니다.
13.8.6 연습 문제
- [code] 모델 FLOPs 활용률. 13.8.1절 의 GPT는 폭 \(d = 512\), 컨텍스트 길이 \(T = 128\) 인 \(L = 6\) 개 블록을 가집니다. SwiGLU 반올림을 무시하면 각 블록은 행렬 곱에 \(12d^2\) 개의 가중치를 보유하며 훈련에는 가중치·토큰당 약 \(6\text{ FLOPs}\) 가 듭니다.
- 어텐션 스코어 곱 \(\mathbf{Q}\mathbf{K}^\top\) 와 값 집계는 가중치가 없는 행렬 곱입니다. 블록당 토큰당 이들의 훈련 FLOPs를 세십시오(역전파는 순전파의 두 배로 잡고 마스킹된 항목도 포함). 가중치 FLOPs에 대한 비율이 \(T/(6d)\) 임을 보이고 \(T = 128\) 과 \(T = 1{,}024\) 에서 이 비율을 계산하십시오.
- 어텐션 FLOPs를 포함하여 누적 비교 표의
TFLOP/s및MFU열을 다시 계산하고, 각 구성의 고유 수 형식 피크(bf16 \(165\text{ TFLOP/s}\), tf32 \(83\text{ TFLOP/s}\)) 대비 비율도 함께 구하십시오. - 13.8.2절 에서 이론적 모델 FLOPs와 실제 하드웨어 실행 FLOPs가 달라지는 구성이나 커널을 두 가지 들고 각각 어느 쪽이 더 큰지 서술하십시오.
- [code] 스텝의 고정 비용. 배치 크기 \(B\) 윈도에서의 bf16 스텝 시간을 스텝당 고정 비용 \(a\) 와 윈도당 비용 \(b\) 를 써서 \(t(B) = a + bB\) 로 모델링하십시오.
- \(B = 32, 64, 128, 256, 512\) 에서 스텝 시간을 측정하여 최소제곱법으로 \(a\) 와 \(b\) 를 피팅하고, \(B = 64\) 스텝 중 \(a\) 가 차지하는 비율을 보고하십시오.
- 본문에서는 AdamW 업데이트와 fp32/bf16 가중치 캐스팅을 \(\sim 0.75\text{ ms/step}\) 로 추정했습니다. 이는 \(a\) 의 몇 분의 몇을 설명합니까? \(B\) 와 무관한 다른 작업을 찾아내고 \(B = 32\) 프로파일과 대조해 확인하십시오.
- 선형 피팅을 사용해 \(B = 1{,}024\) 와 \(B = 2{,}048\) 에서의 처리량을 예측하고, \(24\text{ GiB}\) GPU 메모리에 들어가는지 확인한 뒤 들어가는 구성을 실측하십시오.
- [code] 재계산 비용. 13.8.2절 의 활성화 체크포인팅은 FLOP 수 기반 추정치와 단독 순전파 시간 추정치를 모두 앞질렀습니다.
d2l.kernel_times로 단독 순전파와 체크포인팅 스텝을 프로파일링하십시오. 체크포인팅으로 추가된 커널들을 단독 순전파 커널들과 대조하여 어떤 커널이 그대로 다시 나타나고 어떤 커널이 역전파 커널에 융합되었는지 밝히십시오.- 여섯 개 블록만의 순전파 시간(임베딩과 출력 층 제외)을 재고 처리량 하한을 다시 계산하십시오.
- 두 블록마다 하나씩만 체크포인팅하십시오. 실행 전에 측정값들로부터 처리량과 메모리를 먼저 예측한 뒤 실측하여 비교하십시오.
- [code] 인과성 검증 게이트. 결함이 있는 어텐션 커널이 인과 마스크를 소리 없이 무시한다고 가정합시다.
- 베이스라인과 학습 모델이 모두 이 결함 커널을 사용한다면 왜 13.8.4절 의 훈련 손실, 검증 윈도 손실, \(2.45\text{ nats/byte}\) 바이그램 임곗값이 모두 이 결함을 잡아내지 못하는지 설명하십시오.
- 미니배치 내 모든 시퀀스의 마지막 입력 토큰을 교란했을 때 그보다 앞선 모든 위치의 로짓이 수치 허용 오차 안에서 변하지 않는지 검증하는 테스트를 작성하십시오. 이를
learner와 어텐션에서 인과 마스크를 뺀 사본에 각각 실행하십시오.
- 처리량 대 목표 도달 시간. 9.8절 의 모델에 따르면 배치 크기 \(b\) 로 훈련할 때 목표 손실에 도달하려면 \(E(b) = E_{\min}(1 + b / b_{\textrm{noise}})\) 개의 훈련 표본이 필요하며, 여기서 \(b_{\textrm{noise}}\) 는 그레이디언트 잡음 스케일입니다.
- 배치 64 대비 배치 512의 처리량 비율을 \(\rho > 1\) 이라 합시다. 배치 512가 더 짧은 벽시계 시간에 목표 손실에 도달하기 위한 필요충분조건이 \[b_{\textrm{noise}} > \frac{512 - 64\rho}{\rho - 1}, \tag{13.8.2}\] 임을 보이고, \(\rho = 1.2\), \(\rho = 1.7\), 그리고 13.8.4절 의 실측 \(\rho\) 에 대해 이 임곗값을 계산하십시오.
- 13.8.2절 의 각 변경, 약한 스케일링 데이터 병렬화, 그리고 Muon(9.6절)으로의 전환을 각각 \(E(b)\) 를 바꾸는지, 토큰 처리량을 바꾸는지, 아니면 둘 다 바꾸는지 분류하십시오.
- [code] 폭 256 실험.
num_hiddens=256일 때d2l.GPT는 11.2절 에서 훈련한 아키텍처와 일치합니다. - [code] 변경 적용 순서. 누적 비교 표의 각 가속비는 그보다 먼저 적용된 최적화들에 따라 달라집니다.
- 베이스라인 프로파일과 13.8.2.3절 의 상한을 사용해 컴파일하지 않은 베이스라인에 곧바로 bf16을 적용했을 때의 가속비를 예측하십시오.
- 그 가속비를 측정하여 예측치 및 누적 표의
+ bf16행과 비교하십시오. 이어서 bf16 위에 컴파일(표의 두 번째 행)을 적용하고 커널 프로파일을 사용해 두 비율이 왜 그렇게 이동했는지 설명하십시오.