import json
import os
import random
import sys13.6 실전 데이터 병렬화
13.5절 에서 직접 작성한 데이터 병렬 루프는 두 가지 이유 때문에 두 GPU에서 오히려 LeNet을 느리게 만들었습니다. 단일 Python 스레드가 두 GPU에 순차적으로 커널을 디스패치했고, 마지막 층들의 그레이디언트는 훨씬 일찍 준비되었음에도 전체 역전파가 끝날 때까지 올리듀스가 기다렸기 때문입니다.
상용 데이터 병렬 도구들은 이 두 가지 병목을 모두 제거합니다. GPU마다 별도의 호스트 프로세스를 하나씩 실행하거나 모든 GPU에 걸친 단일 샤딩 프로그램을 컴파일하며, 그레이디언트들을 버킷(bucket)으로 묶어 역전파 도중 각 버킷이 채워지는 즉시 올리듀스를 시작합니다. 역전파 연산 뒤로 그레이디언트 교환을 얼마나 숨길 수 있는지 시험하기 위해, LeNet에서 \(64 \times 64\) Fashion-MNIST 이미지 위의 ResNet-18(이미지당 2.2G회 곱셈-덧셈, 45 MB 그레이디언트 1바이트당 ~300 훈련 FLOPs로 256장 이미지 스텝마다 RTX 4090 한 장을 ~100 ms 동안 바쁘게 유지함)로 옮겨 갑니다. 1-스텝 점검으로 병렬 스텝이 계산하는 값을 검증하고, GPU 1장, 2장, 4장에서 약한 스케일링과 강한 스케일링을 측정해 비용 모델과 대조합니다.
# JAX and NCCL read these settings once, when they start, so this cell runs
# before the imports. XLA overlaps a collective with computation only when
# its latency-hiding scheduler is on. The 'vmm' allocator reserves nothing
# up front and maps each array into one contiguous range, where JAX's
# default allocator reserves most of every GPU at start-up and carves every
# array out of that block: one step below needs about 10 GB in one piece
# after many smaller arrays have come and gone, and a later cell starts a
# second JAX process on the same GPUs.
# On GPUs without peer-to-peer access, such as ours, set
# NCCL_LOCAL_REGISTER=0 in the environment before starting: NCCL's buffer
# registration fails there and prints a warning at every collective.
import os
os.environ.setdefault('XLA_PYTHON_CLIENT_ALLOCATOR', 'vmm')
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
' --xla_gpu_enable_latency_hiding_scheduler=true')import json
import re
import subprocess
import sys
from jax.sharding import NamedSharding, PartitionSpec as P13.6.1 상용 데이터 병렬화
13.6.1.1 실행 모델
모든 현대 프레임워크는 두 가지 단일 프로그램 다중 데이터(single program, multiple data, SPMD) 설계 중 하나로 \(k\) 개의 GPU를 구동합니다.
- 다중 프로세스(\(k\) 개 복제 프로세스 + 집합 통신 라이브러리): 런처가 GPU마다 하나씩, 각자 \(\{0, \ldots, k-1\}\) 범위의 고유 랭크(rank)와 전용 CPU 스레드를 가진 독립 Python 프로세스 \(k\) 개를 시작하여 NCCL을 통해 그레이디언트를 동기화합니다. 각 프로세스 안에서는 어떤 임의의 Python 코드도 실행될 수 있습니다.
- 컴파일러 분할 단일 프로그램: 사용자가 단일 장치 스텝을 작성하고 장치 메시 위에서 입력의 샤딩 방식만 어노테이션으로 지정하면, 컴파일러가 연산을 분할하고 집합 통신 연산을 자동으로 삽입 및 스케줄링합니다 (Xu 기타 2021년).
PyTorch는 다중 프로세스 설계를 사용합니다. torchrun 이 \(k\) 개의 프로세스를 띄우고 DistributedDataParallel(DDP)이 모델을 감쌉니다. 노트북은 단일 프로세스 환경이므로, 보조 함수 torchrun 은 독립 실행 스크립트를 임시 파일로 기록하고 torchrun --standalone --nproc-per-node=k 를 실행한 뒤 각 랭크의 JSON 출력을 파싱합니다.
JAX는 컴파일러 분할 설계를 사용합니다. nnx.jit 이 단일 장치 훈련 스텝을 컴파일하며, 복제된 매개변수(P())와 배치 샤딩된 입력(P('data'))을 함께 전달하면 Shardy/GSPMD 파티셔너가 그레이디언트 올리듀스를 자동으로 삽입합니다.
import glob
import subprocess
import tempfile
def torchrun(script, nproc, *args, env=None):
"""Run Python source in nproc processes; return their JSON lines."""
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, 'script.py')
with open(path, 'w') as f:
f.write(script)
launcher = os.path.join(os.path.dirname(sys.executable), 'torchrun')
# Each process prints to a file of its own (--redirects 1), so that
# the lines of different processes cannot interleave
run = subprocess.run(
[launcher, '--standalone', f'--nproc-per-node={nproc}',
'--log-dir', tmp, '--redirects', '1', path, *map(str, args)],
capture_output=True, text=True, env={**os.environ, **(env or {})})
if run.returncode != 0:
raise RuntimeError(run.stderr[-3000:])
logs = sorted(glob.glob(f'{tmp}/*/attempt_0/*/stdout.log'),
key=lambda log: int(log.split(os.sep)[-2])) # By rank
return [json.loads(line) for log in logs for line in open(log)
if line.startswith('{')]
def init_distributed():
"""Join the process group of torchrun; return the rank, the number of
processes, and the GPU of this process."""
device = torch.device('cuda', int(os.environ['LOCAL_RANK']))
torch.cuda.set_device(device)
torch.distributed.init_process_group('nccl', device_id=device)
return (torch.distributed.get_rank(), torch.distributed.get_world_size(),
device)13.6.1.2 역전파와 통신 중첩하기
상용 프레임워크들은 역전파가 그레이디언트를 생성하는 역순(마지막 층부터 첫 층 방향)으로 그레이디언트들을 수십 메가바이트 크기의 버킷에 채워 넣고, 각 버킷의 마지막 그레이디언트가 준비되자마자 해당 버킷의 비동기 올리듀스를 발행합니다 (Li 기타 2020년) (그림 13.6.1).
버킷 크기는 호출당 지연 시간 \(\alpha\) 와 중첩 효과 사이의 트레이드오프를 조절합니다. 너무 작은 버킷은 \(\alpha\) 를 여러 번 지불하고, 거대한 단일 버킷은 역전파가 다 끝날 때까지 시작할 수 없습니다. 이상적인 중첩 버킷 모델—GPU 간 링크가 충분히 빨라 다음 버킷이 차기 전에 각 버킷 전송이 끝나고, 통신이 동시에 실행 중인 역전파 커널을 느리게 만들지 않는다고 가정—아래에서는 마지막 버킷을 제외한 모든 버킷이 역전파 뒤로 숨겨집니다.
DDP는 첫 번째 버킷을 1 MiB에서 닫고 이후 버킷들을 25 MiB(bucket_cap_mb)에서 닫습니다. ResNet-18의 45 MB 그레이디언트에 대해 DDP는 ~9, 26, 9 MB의 세 버킷을 형성합니다(마지막 9 MB 버킷은 가장 나중에 계산되는 초기 층들을 담음).
XLA는 최대 30 MiB 임계치(--xla_gpu_all_reduce_combine_threshold_bytes)까지 그레이디언트 올리듀스들을 결합하여, ResNet-18의 45 MB 그레이디언트를 역전파 연산과 동시에 스케줄링되는 두 쌍의 비동기 all-reduce-start / all-reduce-done 으로 묶습니다.
13.6.1.3 훈련 스텝
7.4절 의 소형 이미지용 ResNet-18(20장 (영문판) 에서 재사용하도록 #@save 처리됨)을 정의하고 그레이디언트 바이트 수 \(S\)(fp32 기준 45 MB)를 셉니다.
def resnet18(num_classes, in_channels=1):
"""ResNet-18 for small images: a 3x3 stem without max-pooling, He
initialization."""
def stage(num_channels, first=False):
return [d2l.Residual(num_channels, use_1x1conv=not first,
strides=1 if first else 2),
d2l.Residual(num_channels)]
net = nn.Sequential(
# No stem bias: the batch normalization after the conv removes it
nn.Conv2d(in_channels, 64, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(64), nn.ReLU(),
*stage(64, first=True), *stage(128), *stage(256), *stage(512),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(512, num_classes))
with torch.no_grad(): # Create the lazy parameters of the blocks
net.eval()(torch.zeros(1, in_channels, 32, 32))
for m in net.modules(): # He initialization, zero biases
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight, nonlinearity='relu')
if m.bias is not None:
nn.init.zeros_(m.bias)
return net.train()def resnet18(num_classes, in_channels=1, *, rngs):
"""ResNet-18 for small images: a 3x3 stem without max-pooling, He
initialization."""
he = nnx.initializers.variance_scaling(2.0, 'fan_in', 'normal')
def stage(num_channels, in_channels, first=False):
return [d2l.Residual(num_channels, use_1x1conv=not first,
strides=1 if first else 2,
in_channels=in_channels, rngs=rngs),
d2l.Residual(num_channels, in_channels=num_channels,
rngs=rngs)]
return nnx.Sequential(
# No stem bias: the batch normalization after the conv removes it.
# Running averages decay 0.9, two-pass variance
nnx.Conv(in_channels, 64, (3, 3), padding='same', use_bias=False,
kernel_init=he, rngs=rngs),
nnx.BatchNorm(64, momentum=0.9, use_fast_variance=False, rngs=rngs),
nnx.relu,
*stage(64, 64, first=True), *stage(128, 64), *stage(256, 128),
*stage(512, 256),
lambda X: X.mean(axis=(1, 2)), # Global average pooling
nnx.Linear(512, num_classes, kernel_init=he, rngs=rngs))다음으로 Fashion-MNIST를 적재하고 ResNet-18의 매개변수 수 num_params 와 fp32 그레이디언트 용량 S 를 계산합니다.
DDP가 올리듀스를 발행하기 전에 묶는 역순 1 MiB 및 25 MiB 그레이디언트 buckets 도 함께 계산합니다.
d2l.FashionMNIST() # Download once, before any process runs
net = resnet18(10)
num_params = d2l.num_params(net)
S = 4 * num_params # Gradient bytes in fp32
# DDP's buckets: the gradients in the order in which the backward pass
# produces them, the reverse of the parameters', the first bucket closed
# at 1 MiB and every later one at 25 MiB
buckets, size = [], 0
for p in reversed(list(net.parameters())):
size += 4 * p.numel()
if size >= (25 if buckets else 1) * 2**20:
buckets, size = buckets + [size], 0
buckets += [size] if size else []
last_bucket = buckets[-1] # Bytes of the bucket sent last
print(f'{num_params / 1e6:.1f}M parameters, S = {S / 1e6:.0f} MB in buckets '
f'of {", ".join(f"{b / 1e6:.1f}" for b in buckets)} MB')11.2M parameters, S = 45 MB in buckets of 9.5, 26.5, 8.7 MB
data = d2l.FashionMNIST()
X_train = jax.image.resize(data.train[0][..., None] / np.float32(255),
(len(data.train[0]), 64, 64, 1), 'bilinear')
y_train = jnp.asarray(data.train[1], jnp.int32)
num_params = d2l.num_params(resnet18(10, rngs=nnx.Rngs(d2l.get_key())))
S = 4 * num_params # Gradient bytes in fp32
print(f'{num_params / 1e6:.1f}M parameters, S = {S / 1e6:.0f} MB')11.2M parameters, S = 45 MB
이제 \(64 \times 64\) Fashion-MNIST 이미지 위에서의 데이터 병렬 훈련 스텝을 정의합니다.
TRAIN_DDP 는 resnet18 을 DDP 로 감싸고 여러 프로세스에 걸쳐 train_step 의 시간을 측정합니다(선택적 model.no_sync() 및 커널 프로파일링 지원).
setup 은 'data' 메시에 모델과 데이터셋을 복제하며, train_step 은 샤딩된 미니배치 인덱스 idx 에 대해 JIT 컴파일된 SGD 업데이트를 실행합니다.
TRAIN_DDP = r'''
import contextlib, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.benchmark = True # Tune convolutions for fixed shapes
# b examples per GPU and step; sync=0 skips the gradient allreduce, and
# profile=1 also reports the device time per step of NCCL and other kernels
b, num_steps, seed, sync, profile = map(int, sys.argv[1:])
torch.manual_seed(seed) # The same permutations everywhere
data = d2l.FashionMNIST().train # A copy on every GPU, at 64 x 64
X = F.interpolate(data.data.to(device)[:, None] / 255, 64, mode='bilinear')
y = data.targets.to(device)
model = DDP(d2l.resnet18(10).to(device), device_ids=[device])
opt = torch.optim.SGD(model.parameters(), lr=0.1)
def minibatches():
"""This process's b examples of every global minibatch of k * b."""
while True:
perm = torch.randperm(len(y), device=device)
for s in range(len(y) // (k * b)):
yield perm[(s * k + rank) * b:][:b]
def train_step(i):
opt.zero_grad(set_to_none=True)
# Under no_sync, which must enclose the forward pass as well, each GPU
# keeps its own gradient
with model.no_sync() if not sync else contextlib.nullcontext():
F.cross_entropy(model(X[i]), y[i]).backward()
opt.step()
batches = minibatches()
t = d2l.Benchmark(lambda: train_step(next(batches)), warmup=10,
repeats=num_steps).time
result = {'rank': rank, 'step_time': t}
if profile:
kernels = d2l.kernel_times(lambda: train_step(next(batches)))
result['comm'] = sum(ms for name, ms in kernels.items() if 'nccl' in name)
result['compute'] = sum(kernels.values()) - result['comm']
print(json.dumps(result))
dist.destroy_process_group()
'''def setup(k, key):
"""ResNet-18 with SGD and the training set, replicated on k GPUs."""
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
axis_types=(jax.sharding.AxisType.Auto,))
replicated = NamedSharding(mesh, P())
model = resnet18(10, rngs=nnx.Rngs(key))
opt = nnx.Optimizer(model, optax.sgd(0.1), wrt=nnx.Param)
for m in (model, opt):
nnx.update(m, jax.device_put(nnx.state(m), replicated))
return mesh, model, opt, jax.device_put((X_train, y_train), replicated)
def minibatches(mesh, batch_size):
"""Indices of random minibatches, split across the GPUs of the mesh."""
rng, n = np.random.default_rng(), len(y_train)
while True:
perm = rng.permutation(n)
for i in range(0, n - batch_size + 1, batch_size):
yield jax.device_put(perm[i:i + batch_size],
NamedSharding(mesh, P('data')))
@nnx.jit
def train_step(model, opt, X, y, idx):
"""One SGD step on the examples idx, written for a single device."""
def loss_fn(model):
return optax.softmax_cross_entropy_with_integer_labels(
model(X[idx]), y[idx]).mean()
loss, grads = nnx.value_and_grad(loss_fn)(model)
opt.update(model, grads)
return loss13.6.1.4 1-스텝 정합성 점검
LeNet과 달리 ResNet-18에는 각 채널을 미니배치 평균과 분산으로 정규화하는 배치 정규화(7.3절)가 들어 있습니다. 표본 256개짜리 미니배치를 두 GPU로 나눌 때, 각 GPU는 자기 몫인 128개 표본 샤드 통계량으로 정규화할까요(단일 GPU에서 128개 표본 마이크로배치 두 개를 그레이디언트 누적한 것과 일치), 아니면 카드 간에 전역 256개 표본 통계량을 동기화할까요? 두 단일 GPU 기준값 모두에 대해 2-GPU 업데이트를 대조해 봅시다.
CHECK_DDP = r'''
import copy, json, sys, torch
import torch.distributed as dist
from torch.nn import functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from d2l import torch as d2l
rank, k, device = d2l.init_distributed()
torch.backends.cudnn.allow_tf32 = False # Full fp32 convolutions
torch.manual_seed(int(sys.argv[1])) # The same model and data everywhere
X = torch.rand(256, 1, 64, 64, device=device)
y = torch.randint(0, 10, (256,), device=device)
model = d2l.resnet18(10).to(device)
ref = copy.deepcopy(model) # An unwrapped copy for one GPU
def update(net, shards):
"""Parameter change of one SGD step on the mean loss over the shards."""
before = [p.detach().clone() for p in net.parameters()]
for X_j, y_j in shards:
(F.cross_entropy(net(X_j), y_j) / len(shards)).backward()
with torch.no_grad():
for p, b in zip(net.parameters(), before):
p -= 0.1 * p.grad
return [p.detach() - b for p, b in zip(net.parameters(), before)]
ddp = update(DDP(model, device_ids=[device]),
[(X.chunk(k)[rank], y.chunk(k)[rank])])
if rank == 0:
gap = lambda u: max((a - b).abs().max().item() for a, b in zip(ddp, u))
halves = update(copy.deepcopy(ref), list(zip(X.chunk(k), y.chunk(k))))
print(json.dumps({'largest': max(u.abs().max().item() for u in ddp),
'full': gap(update(ref, [(X, y)])),
'halves': gap(halves)}))
dist.destroy_process_group()
'''
if d2l.num_gpus() >= 2:
r = d2l.torchrun(CHECK_DDP, 2, random.getrandbits(32))[0]
print(f"largest update {r['largest']:.1e}\n"
f"largest difference from one GPU on all 256: {r['full']:.1e}\n"
f"largest difference from one GPU on two accumulated halves: "
f"{r['halves']:.1e}")largest update 1.7e-02
largest difference from one GPU on all 256: 1.0e-03
largest difference from one GPU on two accumulated halves: 1.2e-07
key = d2l.get_key() # One initialization for every step
idx = np.random.default_rng().permutation(len(y_train))[:256]
def update(k, idx):
"""Parameter change of one step on k GPUs on the examples idx."""
mesh, model, opt, (X, y) = setup(k, key)
before = jax.tree.map(np.asarray, nnx.state(model, nnx.Param))
train_step(model, opt, X, y,
jax.device_put(idx, NamedSharding(mesh, P('data'))))
return jax.tree.leaves(jax.tree.map(lambda p, b: np.asarray(p) - b,
nnx.state(model, nnx.Param), before))
with jax.default_matmul_precision('highest'): # Full fp32 convolutions
two = update(min(2, jax.device_count()), idx)
full = update(1, idx)
# For SGD, the mean of the steps on the two halves is the step on
# their accumulated gradients
halves = [(a + b) / 2 for a, b in zip(*(update(1, half)
for half in np.split(idx, 2)))]
gap = lambda u: max(np.abs(a - b).max() for a, b in zip(two, u))
print(f'largest update {max(np.abs(u).max() for u in two):.1e}\n'
f'largest difference from one GPU on all 256: {gap(full):.1e}\n'
f'largest difference from one GPU on two accumulated halves: '
f'{gap(halves):.1e}')largest update 2.4e-02
largest difference from one GPU on all 256: 2.5e-05
largest difference from one GPU on two accumulated halves: 1.7e-02
기본적으로 PyTorch DDP는 각 GPU의 샤드를 로컬 샤드별 통계량으로 정규화하므로, 누적된 두 절반과는 ~\(10^{-7}\) 수준으로 일치하는 반면 전체 배치 통계량과는 몇 퍼센트 차이를 보입니다(nn.SyncBatchNorm 으로 변환하면 추가 집합 통신을 치르는 대신 전역 통계량을 동기화함; 4 참조).
Auto 모드에서 배치 축이 'data' 메시 축에 걸쳐 샤딩되어 있으므로, XLA 파티셔너는 전체 미니배치에 걸쳐 전역적으로 배치 정규화 평균과 분산을 계산합니다. 따라서 단일 GPU 256개 표본 스텝과 일치하며 두 개의 큰 그레이디언트 버퍼 옆에 채널별 배치 정규화 통계량을 위한 작은 올리듀스들을 삽입합니다.
def allreduce_megabytes(compiled):
"""Megabytes of fp32 results of each allreduce in a compiled program,
in the order in which the program runs them."""
sizes = []
for line in compiled.as_text().splitlines():
# A synchronous all-reduce, or the -done half of an asynchronous
# pair, whose result type lists the summed arrays only
if re.search(r' all-reduce(-done)?\(', line):
result = line.split(' = ')[1].split(' all-reduce')[0]
sizes.append(sum(4 * math.prod(map(int, dims.split(',')))
for dims in re.findall(r'f32\[([\d,]+)\]',
result)) / 1e6)
return sizes다중 GPU 메시 위에서 train_step 을 컴파일하고 allreduce_megabytes 를 적용하면 채널별 배치 정규화용 작은 올리듀스들과 함께 두 개의 큰 그레이디언트 올리듀스(big, 마지막 버퍼는 last_bucket 으로 기록됨)가 확인됩니다.
mesh, model, opt, (X, y) = setup(jax.device_count(), d2l.get_key())
idx = next(minibatches(mesh, 256 * mesh.size))
compiled = train_step.lower(model, opt, X, y, idx).compile()
sizes = allreduce_megabytes(compiled) # One entry per allreduce
big = [m for m in sizes if m > 1] # Gradient buffers, above 1 MB
last_bucket = 1e6 * big[-1] # Bytes of the buffer sent last
print(f'{len(sizes)} allreduces: {len(big)} of '
f'{" and ".join(f"{m:.1f}" for m in big)} MB, the other '
f'{len(sizes) - len(big)} of {sum(sizes) - sum(big):.2f} MB together')76 allreduces: 2 of 25.8 and 18.9 MB, the other 74 of 0.10 MB together
13.6.2 GPU 4장에서의 스케일링
이제 \(k \in \{1, 2, 4\}\) 개 GPU에 걸쳐 약한 스케일링(GPU당 표본 256개)과 강한 스케일링(전역 표본 512개)을 측정합니다.
def step_time(k, b, num_steps=50):
"""Seconds per DDP step on k GPUs with b examples per GPU."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, num_steps, random.getrandbits(32),
1, 0) # Allreduce the gradients, no profile
return max(r['step_time'] for r in ranks)def stepper(k, b):
"""One data-parallel step on k GPUs with b examples per GPU, as a
function without arguments."""
mesh, model, opt, (X, y) = setup(k, d2l.get_key())
batches = minibatches(mesh, k * b)
return lambda: train_step(model, opt, X, y, next(batches))
def step_time(k, b, num_steps=50):
"""Seconds per data-parallel step on k GPUs with b examples per GPU."""
return d2l.Benchmark(stepper(k, b), warmup=10, repeats=num_steps).time먼저 NCCL을 통한 순수 256 MB 올리듀스에서 \(\beta_\textrm{link}\) 를 측정하고, 약한 스케일링 아래에서 밖으로 노출되는 통신 시간 \(t_{\textrm{step}}(k) - t_{\textrm{step}}(1)\) 에 대한 두 가지 예측을 비교합니다.
- 중첩 없음: \(S = 45\) MB의 전체 링 올리듀스가 그대로 노출됩니다(\(\frac{2(k-1)}{k} S \beta_\textrm{link}\)).
- 완전 버킷 중첩: 역전파가 끝난 뒤 마지막 버킷/버퍼(\(last\_bucket\))만 노출됩니다.
ALLREDUCE = r'''
import json, torch
import torch.distributed as dist
from d2l import torch as d2l
_, _, device = d2l.init_distributed()
x = torch.zeros(2**26, device=device) # 64M floats: 256 MB
t = d2l.Benchmark(lambda: dist.all_reduce(x), repeats=10).time
print(json.dumps({'beta_link': t / x.nbytes})) # Each GPU sends S at k = 2
dist.destroy_process_group()
'''
def allreduce_beta(env=None):
"""beta_link of a bare 256 MB allreduce on two GPUs: the seconds
per byte that each GPU sends."""
return max(r['beta_link'] for r in d2l.torchrun(ALLREDUCE, 2, env=env))ALLREDUCE = r'''
import json, jax
from jax import numpy as jnp
from jax.sharding import NamedSharding, PartitionSpec as P
from d2l import jax as d2l
mesh = jax.make_mesh((2,), ('data',), devices=jax.devices()[:2])
x = jnp.zeros((2, 2**26), device=NamedSharding(mesh, P('data'))) # 256 MB
psum = jax.jit(jax.shard_map(lambda x: jax.lax.psum(x, 'data'), mesh=mesh,
in_specs=P('data'), out_specs=P('data')))
t = d2l.Benchmark(lambda: psum(x), repeats=10).time
print(json.dumps({'beta_link': t / (x.nbytes / mesh.size)})) # S per GPU
'''
def allreduce_beta(env=None):
"""beta_link of a bare 256 MB allreduce on two GPUs: the seconds
per byte that each GPU sends."""
run = subprocess.run([sys.executable, '-c', ALLREDUCE], check=True,
capture_output=True, text=True,
env={**os.environ, **(env or {})})
return json.loads(run.stdout.splitlines()[-1])['beta_link']allreduce_beta() 를 호출하면 실측 링크 비용 beta_link 가 구해지며, 이로부터 비중첩(\(2(k-1)S\beta_\textrm{link}/k\)) 모델과 완전 중첩(last_bucket) 모델 아래에서 \(k \in \{2, 4\}\) 개 GPU에 대한 exposed[k] 를 계산합니다.
if d2l.num_gpus() >= 2:
beta_link = allreduce_beta()
print(f'bus bandwidth = {1e-9 / beta_link:.2f} GB/s '
f'(beta_link = {1e9 * beta_link:.2f} ns/byte)')
exposed = {} # Predicted exposed seconds per step
for k in (2, 4):
ring = 2 * (k - 1) / k # Bytes that each GPU sends, per byte of S
exposed[k] = (ring * S * beta_link, ring * last_bucket * beta_link)
print(f'k={k}: exposed {1e3 * exposed[k][0]:.0f} ms without overlap '
f'({ring:.1f} S beta_link), {1e3 * exposed[k][1]:.0f} ms with '
f'full overlap (last bucket)')bus bandwidth = 2.44 GB/s (beta_link = 0.41 ns/byte)
k=2: exposed 18 ms without overlap (1.0 S beta_link), 4 ms with full overlap (last bucket)
k=4: exposed 27 ms without overlap (1.5 S beta_link), 5 ms with full overlap (last bucket)
if d2l.num_gpus() >= 2:
beta_link = allreduce_beta()
print(f'bus bandwidth = {1e-9 / beta_link:.2f} GB/s '
f'(beta_link = {1e9 * beta_link:.2f} ns/byte)')
exposed = {} # Predicted exposed seconds per step
for k in (2, 4):
ring = 2 * (k - 1) / k # Bytes that each GPU sends, per byte of S
exposed[k] = (ring * S * beta_link, ring * last_bucket * beta_link)
print(f'k={k}: exposed {1e3 * exposed[k][0]:.0f} ms without overlap '
f'({ring:.1f} S beta_link), {1e3 * exposed[k][1]:.0f} ms with '
f'full overlap (last bucket)')bus bandwidth = 2.43 GB/s (beta_link = 0.41 ns/byte)
k=2: exposed 18 ms without overlap (1.0 S beta_link), 8 ms with full overlap (last bucket)
k=4: exposed 28 ms without overlap (1.5 S beta_link), 12 ms with full overlap (last bucket)
이제 \(k \in \{1, 2, 4\}\) 개 GPU에서 GPU당 표본 256개로 약한 스케일링(step_time(k, 256))을 벤치마킹하고, 실측 처리량, 스케일링 효율, 노출 오버헤드 weak[k] - weak[1] 을 두 예측치와 비교합니다.
ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]
weak = {k: step_time(k, 256) for k in ks}
for k in ks:
print(f'{k} GPU(s): {k * 256 / weak[k]:5.0f} examples/s, speedup '
f'{k * weak[1] / weak[k]:.2f}, efficiency {weak[1] / weak[k]:.0%}')
if k > 1: # Predicted: the one-GPU step plus the exposed communication
none, full = (weak[1] / (weak[1] + e) for e in exposed[k])
print(f'{"":10s}predicted {none:.0%} without overlap, {full:.0%} '
f'with full overlap; exposed {1e3 * (weak[k] - weak[1]):.0f} ms')1 GPU(s): 2285 examples/s, speedup 1.00, efficiency 100%
2 GPU(s): 4039 examples/s, speedup 1.77, efficiency 88%
predicted 86% without overlap, 97% with full overlap; exposed 15 ms
4 GPU(s): 7573 examples/s, speedup 3.31, efficiency 83%
predicted 80% without overlap, 95% with full overlap; exposed 23 ms
ks = [k for k in (1, 2, 4) if k <= d2l.num_gpus()]
weak = {k: step_time(k, 256) for k in ks}
for k in ks:
print(f'{k} GPU(s): {k * 256 / weak[k]:5.0f} examples/s, speedup '
f'{k * weak[1] / weak[k]:.2f}, efficiency {weak[1] / weak[k]:.0%}')
if k > 1: # Predicted: the one-GPU step plus the exposed communication
none, full = (weak[1] / (weak[1] + e) for e in exposed[k])
print(f'{"":10s}predicted {none:.0%} without overlap, {full:.0%} '
f'with full overlap; exposed {1e3 * (weak[k] - weak[1]):.0f} ms')1 GPU(s): 2555 examples/s, speedup 1.00, efficiency 100%
2 GPU(s): 4275 examples/s, speedup 1.67, efficiency 84%
predicted 84% without overlap, 93% with full overlap; exposed 20 ms
4 GPU(s): 7859 examples/s, speedup 3.08, efficiency 77%
predicted 78% without overlap, 90% with full overlap; exposed 30 ms
~2.4 GB/s 버스 대역폭에서 45 MB의 비중첩 올리듀스는 2 GPU에서 ~18 ms, 4 GPU에서 ~28 ms가 걸립니다. 약한 스케일링 실측에서 4개의 GPU는 단일 GPU 처리량의 \(3.1\text{--}3.3\times\)(스케일링 효율 77–83%)를 달성하며, 이는 완전 중첩 버킷 예측치에는 한참 못 미치고 중첩 없음 예측치와 가깝게 일치합니다.
강한 스케일링(전역 배치 512개 표본 고정, 즉 통신량은 그대로인 채 \(k\) 개 GPU 각각이 \(512/k\) 개 표본만 처리) 아래에서는 \(k = 4\) 에서 효율이 더욱 떨어집니다.
strong = {k: step_time(k, 512 // k) for k in ks}
for k in ks:
print(f'{k} GPU(s), {512 // k} examples each: speedup '
f'{strong[1] / strong[k]:.2f}, efficiency '
f'{strong[1] / strong[k] / k:.0%}')
d2l.plot(ks, [ks, [k * weak[1] / weak[k] for k in ks],
[strong[1] / strong[k] for k in ks]], 'GPUs', 'speedup',
legend=['linear', 'weak (256 per GPU)', 'strong (512 in all)'],
fmts=('k:', '-o', '--s'))1 GPU(s), 512 examples each: speedup 1.00, efficiency 100%
2 GPU(s), 256 examples each: speedup 1.78, efficiency 89%
4 GPU(s), 128 examples each: speedup 2.81, efficiency 70%
strong = {k: step_time(k, 512 // k) for k in ks}
for k in ks:
print(f'{k} GPU(s), {512 // k} examples each: speedup '
f'{strong[1] / strong[k]:.2f}, efficiency '
f'{strong[1] / strong[k] / k:.0%}')
d2l.plot(ks, [ks, [k * weak[1] / weak[k] for k in ks],
[strong[1] / strong[k] for k in ks]], 'GPUs', 'speedup',
legend=['linear', 'weak (256 per GPU)', 'strong (512 in all)'],
fmts=('k:', '-o', '--s'))1 GPU(s), 512 examples each: speedup 1.00, efficiency 100%
2 GPU(s), 256 examples each: speedup 1.70, efficiency 85%
4 GPU(s), 128 examples each: speedup 2.55, efficiency 64%
13.6.2.1 버킷 모델의 가정 점검
왜 중첩이 통신을 거의 숨기지 못했을까요? 버킷 모델은 (1) 각 버킷의 올리듀스가 역전파 도중에 시작되고, (2) NCCL이 단독 벤치마크 속도로 실행되며, (3) NCCL이 옆에서 함께 돌아도 역전파 연산 커널이 느려지지 않는다고 가정합니다. 세 가지 구성—1 GPU, 통신 없는 2 GPU, 통신을 켠 2 GPU—에 걸쳐 GPU 0을 프로파일링하면 세 가정을 모두 검증할 수 있습니다.
def profile_step(k, b, communicate=True):
"""Seconds per DDP step on k GPUs with b examples per GPU, and device
milliseconds per step on GPU 0 of computation and of NCCL's kernels;
without communication, every GPU steps on its own shard's gradient."""
ranks = d2l.torchrun(TRAIN_DDP, k, b, 50, random.getrandbits(32),
int(communicate), 1)
return (max(r['step_time'] for r in ranks), ranks[0]['compute'],
ranks[0]['comm'])def local_stepper(k, b):
"""The step of `stepper` without communication: inside shard_map every
GPU sees only its shard, normalizes it with the shard's own batch
statistics, and steps on its own shard's gradient."""
mesh, model, opt, (X, y) = setup(k, d2l.get_key())
batches = minibatches(mesh, k * b)
graphdef, state = nnx.split((model, opt))
def local(state, X, y, idx):
model, opt = nnx.merge(graphdef, state)
train_step(model, opt, X, y, idx)
return nnx.state((model, opt))
# With check_vma=False autodiff adds no sum over the GPUs, and the
# copies, which then drift apart, are returned as if they were equal
local = jax.jit(jax.shard_map(local, mesh=mesh, check_vma=False,
in_specs=(P(), P(), P(), P('data')),
out_specs=P()))
def step():
nonlocal state
state = local(state, X, y, next(batches))
return state
return step
def profile_step(k, b, communicate=True):
"""Seconds per step on k GPUs with b examples per GPU, and device
milliseconds per step on GPU 0 of computation and of NCCL's kernels:
the two gradient allreduces and the small allreduces of the batch
normalization statistics."""
step = stepper(k, b) if communicate else local_stepper(k, b)
t = d2l.Benchmark(step, warmup=10, repeats=50).time
kernels = d2l.kernel_times(step)
comm = sum(ms for name, ms in kernels.items() if 'nccl' in name.lower())
return t, sum(kernels.values()) - comm, commGPU당 표본 \(b = 256\) 개에서 세 구성—1 GPU, 그레이디언트 동기화 없는 2 GPU, 올리듀스를 켠 2 GPU—에 대해 profile_step 을 실행하면 벽시계 스텝 시간이 장치 연산 시간과 NCCL 커널 시간으로 분리됩니다.
if d2l.num_gpus() >= 2:
for k, communicate in ((1, True), (2, False), (2, True)):
t, compute, comm = profile_step(k, 256, communicate)
name = f'{k} GPU' + ('s' if k > 1 else '') + (
'' if communicate else ' without communication')
print(f'{name + ":":30s}{1e3 * t:6.1f} ms per step; GPU 0 computes '
f'{compute:6.1f} ms, communicates {comm:5.1f} ms')1 GPU: 112.1 ms per step; GPU 0 computes 111.9 ms, communicates 0.0 ms
2 GPUs without communication: 111.9 ms per step; GPU 0 computes 111.5 ms, communicates 0.0 ms
2 GPUs: 126.8 ms per step; GPU 0 computes 124.6 ms, communicates 20.0 ms
if d2l.num_gpus() >= 2:
for k, communicate in ((1, True), (2, False), (2, True)):
t, compute, comm = profile_step(k, 256, communicate)
name = f'{k} GPU' + ('s' if k > 1 else '') + (
'' if communicate else ' without communication')
print(f'{name + ":":30s}{1e3 * t:6.1f} ms per step; GPU 0 computes '
f'{compute:6.1f} ms, communicates {comm:5.1f} ms')1 GPU: 100.3 ms per step; GPU 0 computes 100.1 ms, communicates 0.0 ms
2 GPUs without communication: 100.6 ms per step; GPU 0 computes 100.0 ms, communicates 0.0 ms
2 GPUs: 119.1 ms per step; GPU 0 computes 107.8 ms, communicates 21.0 ms
통신 없는 두 GPU는 단일 GPU와 정확히 같은 속도로 스텝을 밟고, NCCL 커널은 20–22 ms 동안 실행됩니다(18 ms 단독 벤치마크와 일치). 무너진 것은 세 번째 가정입니다. NCCL이 역전파와 동시에 실행되면 연산 커널 자체도 8–13 ms 느려집니다. 피어 투 피어 접근이 없는 GPU에서 NCCL은 자체 GPU SM 커널을 띄워 호스트 메모리를 통해 데이터를 복사하는데, 이 커널들이 역전파가 써야 할 스트리밍 멀티프로세서와 메모리 대역폭을 점유해 버리기 때문입니다.
문서화되지 않은 NCCL 플래그(NCCL_SHM_USE_CUDA_MEMCPY=1, NCCL 2.28–2.30에 존재)를 쓰면 단독 마이크로벤치마크에서는 이러한 호스트 메모리 복사를 GPU의 DMA 복사 엔진으로 오프로드할 수 있습니다.
그러나 똑같은 플래그를 역전파 연산과 올리듀스가 중첩되는 DDP에 켜면 데드락(교착 상태)에 빠집니다.
if d2l.num_gpus() >= 2:
# An undocumented parameter of NCCL's transport through host memory. It
# exists in NCCL 2.28.9 (bundled with PyTorch 2.11) and 2.30.4 (with
# jaxlib 0.12); the library of NCCL 2.31.2 no longer contains it
beta_ce = allreduce_beta({'NCCL_SHM_USE_CUDA_MEMCPY': '1'})
print(f'bus bandwidth {1e-9 / beta_link:.2f} GB/s by default, '
f'{1e-9 / beta_ce:.2f} GB/s with the copy engines '
f'({beta_link / beta_ce:.1f}x)')bus bandwidth 2.44 GB/s by default, 11.53 GB/s with the copy engines (4.7x)
if d2l.num_gpus() >= 2:
# An undocumented parameter of NCCL's transport through host memory. It
# exists in NCCL 2.28.9 (bundled with PyTorch 2.11) and 2.30.4 (with
# jaxlib 0.12); the library of NCCL 2.31.2 no longer contains it
beta_ce = allreduce_beta({'NCCL_SHM_USE_CUDA_MEMCPY': '1'})
print(f'bus bandwidth {1e-9 / beta_link:.2f} GB/s by default, '
f'{1e-9 / beta_ce:.2f} GB/s with the copy engines '
f'({beta_link / beta_ce:.1f}x)')bus bandwidth 2.43 GB/s by default, 10.98 GB/s with the copy engines (4.5x)
NVLink(단방향 450–900 GB/s, 13.2.4.2절)로 연결된 데이터센터 GPU에서는 ResNet-18의 45 MB 올리듀스가 1밀리초 훨씬 미만에 끝나 거의 선형에 가까운 스케일링을 달성합니다. 하지만 이상적인 스케일링을 얻더라도 데이터 병렬화는 여전히 모든 카드에 매개변수 및 옵티마이저 상태 \(16N\) 바이트 전체를 복제합니다. 13.7절 에서는 그 상태를 여러 GPU에 분할합니다.
13.6.3 요약
상용 데이터 병렬화는 NCCL로 동기화되는 \(k\) 개의 독립 프로세스 또는 컴파일러가 분할한 단일 프로그램을 통해 \(k\) 개의 GPU를 구동하며, 그레이디언트를 25–30 MiB 크기의 버킷으로 묶어 올리듀스와 역전파를 중첩시킵니다. 단일 GPU 기준값과 대조하는 1-스텝 점검을 수행하면 배치 정규화가 샤드별 로컬 통계량을 쓰는지 추가 집합 통신을 통한 전역 통계량을 쓰는지 명확히 드러납니다. 실험용 RTX 4090 4장(호스트 메모리를 거쳐 2.4 GB/s 버스 대역폭으로 통신)에서는 약한 스케일링 아래 4개 GPU가 단일 GPU 처리량의 \(3.1\text{--}3.3\times\) 를 제공하며, 커널 프로파일링을 통해 호스트 경유 NCCL 커널과의 SM 경합이 역전파 중첩으로 아낀 시간 대부분을 상쇄함을 확인했습니다.
13.6.4 연습 문제
- [code] 데이터 분할하기.
TRAIN_DDP에서 랭크 \(r\) 은 공유 무작위 순열로부터 스텝 \(s\) 마다 \((sk + r)b\) 에서 시작하는 슬라이스를 가져옵니다.- 모든 프로세스가 똑같은 \(b\) 개의 표본을 가져오도록 이 오프셋에서
rank를 제거하십시오. \(k = 2\) 에서의step_time과 평균 그레이디언트가 어떻게 동작할지 예측하고 각 랭크에서 미니배치 체크섬을 출력해 확인하십시오. - 오프셋은 복원하되 각 랭크에 서로 다른 난수 시드를 부여하십시오. 미니배치 분할의 어떤 성질이 깨집니까?
- 첫 번째 스텝에서 랭크 간 동일한 데이터 샤드를 포착하는 가벼운 런타임 단언문(assertion)을 제안하십시오.
- 모든 프로세스가 똑같은 \(b\) 개의 표본을 가져오도록 이 오프셋에서
- 약한 스케일링 외삽. \(k\) 개 GPU에서의 한 스텝이 단일 GPU 시간 \(t_1\) 에 링 트래픽 \(2(k-1)S/k\) 에 비례하는 노출 통신 시간을 더한 만큼 걸린다고 가정합시다.
- 약한 스케일링 효율 \(E(k) = t_1 / t_{\textrm{step}}(k)\) 를 단일 상수로 표현하여 실측된 \(E(2)\) 로 보정한 뒤, \(E(4)\) 에 대한 예측치를 13.6.2절 의 측정값과 비교하십시오.
- GPU당 표본 256개짜리 마이크로배치 \(a\) 개에 걸쳐 그레이디언트를 누적할 때(마지막 마이크로배치에서만 통신), \(E(4)\) 를 95%로 끌어올리는 최소 \(a\) 를 구하고 전역 배치 크기가 어떻게 달라지는지 서술하십시오.
- [code] 버킷 크기. ● 지속 시간 \(t_b\) 인 역전파가 시각 \(i\,t_b/n\)(\(i = 1, \ldots, n\))에 크기가 같은 버킷 \(n\) 개를 내놓고 각 버킷의 올리듀스가 순차적으로 \(\alpha + \tau/n\)(\(\tau = S\,\beta_\textrm{link}\))씩 걸린다고 가정하여 버킷 중첩(그림 13.6.1)을 모델링하십시오.
- 역전파가 끝난 뒤 노출되는 통신 시간이 \[t_{\textrm{exposed}}(n) = \max\Bigl(\alpha + \frac{\tau}{n},\; n\alpha + \tau - \frac{n-1}{n}\,t_b\Bigr), \tag{13.6.1}\] 임을 보이고, \(\tau < t_b\) 일 때와 \(\tau > t_b\) 일 때의 최적 \(n\) 을 각각 구하십시오.
- \(k = 2\) 에서
DDP의bucket_cap_mb를 1 MB부터 100 MB까지 스윕하며 실측된 노출 통신 시간을 모델과 비교하십시오.
- [code] 동기화 배치 정규화. ● 13.6.1절 의 1-스텝 점검은 DDP가 기본적으로 각 샤드를 로컬 통계량으로 정규화함을 보였습니다.
DDP로 감싸기 전에CHECK_DDP의model을nn.SyncBatchNorm.convert_sync_batchnorm으로 변환하고 점검을 다시 실행하십시오. 이제 어느 단일 GPU 기준값과 일치합니까?SyncBatchNorm이 스텝당 추가하는 집합 통신 횟수를 세고 \(k = 2\) 와 \(k = 4\) 에서step_time을 측정한 뒤, 왜 추가 소요 시간이 바이트 전송량에 \(\beta_\textrm{link}\) 를 곱한 값을 초과하는지 설명하십시오.
- [code] 데이터 분할하기.
minibatches에서 인덱스는P('data')로 배치됩니다.- 모든 GPU가 전체 인덱스를 받도록 이를
P()로 바꾸십시오. 컴파일된train_step에 어떤 집합 통신이 포함될지와step_time(2, 256)이step_time(1, 256)과 어떻게 비교될지 예측한 뒤 둘 다 확인하십시오. P('data')를 복원하고train_step내부에서 이미지 높이를 GPU들에 분할하도록X[idx]를NamedSharding(mesh, P(None, 'data'))로 제약하십시오. \(3 \times 3\) 합성곱을 위해 이웃 GPU들이 어떤 경계 값들을 교환해야 하며 컴파일된 HLO에 어떤 집합 통신이 나타납니까?
- 모든 GPU가 전체 인덱스를 받도록 이를
- 약한 스케일링 외삽. \(k\) 개 GPU에서의 한 스텝이 단일 GPU 시간 \(t_1\) 에 링 트래픽 \(2(k-1)S/k\) 에 비례하는 노출 통신 시간을 더한 만큼 걸린다고 가정합시다.
- 약한 스케일링 효율 \(E(k) = t_1 / t_{\textrm{step}}(k)\) 를 단일 상수로 표현하여 실측된 \(E(2)\) 로 보정한 뒤, \(E(4)\) 에 대한 예측치를 13.6.2절 의 측정값과 비교하십시오.
- GPU당 표본 256개짜리 마이크로배치 \(a\) 개에 걸쳐 그레이디언트를 누적할 때(마지막 마이크로배치에서만 통신), \(E(4)\) 를 95%로 끌어올리는 최소 \(a\) 를 구하고 전역 배치 크기가 어떻게 달라지는지 서술하십시오.
- [code] 버킷 크기. ● 지속 시간 \(t_b\) 인 역전파가 시각 \(i\,t_b/n\)(\(i = 1, \ldots, n\))에 크기가 같은 버킷 \(n\) 개를 내놓고 각 버킷의 올리듀스가 순차적으로 \(\alpha + \tau/n\)(\(\tau = S\,\beta_\textrm{link}\))씩 걸린다고 가정하여 버킷 중첩(그림 13.6.1)을 모델링하십시오.
- 역전파가 끝난 뒤 노출되는 통신 시간이 \[t_{\textrm{exposed}}(n) = \max\Bigl(\alpha + \frac{\tau}{n},\; n\alpha + \tau - \frac{n-1}{n}\,t_b\Bigr),\] 임을 보이고, \(\tau < t_b\) 일 때와 \(\tau > t_b\) 일 때의 최적 \(n\) 을 각각 구하십시오.
- 새 프로세스들에서
--xla_gpu_all_reduce_combine_threshold_bytes를 1 MB부터 100 MB까지 스윕하며 생성된 그레이디언트 올리듀스 개수를 세고 실측 노출 통신 시간을 모델과 비교하십시오.
- [code] 배치 정규화 통계량. ●
Auto메시 축을 쓰는nnx.jit아래에서 배치 정규화는 모든 GPU에 걸쳐 전역 통계량을 계산합니다.resnet18의BatchNorm층 개수 및 순전파·역전파 구조로부터allreduce_megabytes(compiled)에 나타난 74개의 작은 올리듀스가 어떻게 나왔는지 설명하십시오.BatchNorm이 배치 통계량 대신 이동 평균을 사용하도록 컴파일 전에model.eval()을 호출하고, 작은 올리듀스들이 사라짐을 확인한 뒤 \(k = 1, 2, 4\) 에서 이들이 차지하던 스텝 시간을 측정하십시오.