13.7  훈련 상태 샤딩

13.4절 에서 fp32 Adam으로 훈련하면 매개변수당 16바이트—가중치, 그레이디언트, 그리고 Adam의 두 모멘트 추정치에 각각 4바이트씩—를 저장함을 보았습니다. 18블록 1B 매개변수 GPT의 경우 이 고정 상태만으로도 단 한 토큰을 읽기 전에 24 GiB 카드 중 15.1 GiB가 차버리며, 데이터 병렬화(13.5절, 13.6절)는 이 16바이트 전체를 모든 GPU에 그대로 복제합니다. 만약 GPT의 깊이를 36블록(1.92B 매개변수, 상태 메모리 28.6 GiB)으로 두 배 늘린다면 24 GiB GPU 네 장으로 데이터 병렬화를 돌려도 GPU 한 장일 때와 마찬가지로 아예 훈련할 수 없습니다.

그렇다면 단일 카드에는 도저히 들어가지 않는 모델을 \(k\) 개의 GPU로 훈련할 수 있을까요? 가능합니다. GPU는 특정 블록의 순전파나 역전파를 계산하는 동안에만 그 블록의 전체 가중치가 필요할 뿐이며, 전체 그레이디언트나 전체 옵티마이저 상태는 단 한 순간도 한꺼번에 필요하지 않기 때문입니다. 따라서 \(k\) 개 GPU 각각이 가중치, 그레이디언트, 옵티마이저 모멘트의 \(1/k\) 만 저장해 두고, 각 블록이 실행되기 직전에 필요한 가중치를 즉석에서 모으고(all-gather), 각 블록의 그레이디언트가 생성되자마자 즉시 리듀스-스캐터(reduce-scatter)하면 됩니다.

# XLA reads its flags once, when JAX starts, so this cell runs before the
# imports. The latency-hiding scheduler orders the step with its memory in
# view; without it, the sharded step needs more memory than JAX may
# allocate by default (see the note on stage 2). 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['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
                           ' --xla_gpu_enable_latency_hiding_scheduler=true')
import json
import collections
import re
from jax.sharding import NamedSharding, PartitionSpec as P

먼저 메타/형상 전용 장치 위에서 36블록 GPT의 훈련 상태 \(16N\) 바이트가 단일 RTX 4090의 24 GiB 용량을 초과함을 확인합니다.

config = dict(vocab_size=50257, num_hiddens=2048, num_heads=16,
              num_blks=36, pos='learned')
k = 2                       # GPUs, from the all-gather below on
with torch.device('meta'):  # Shapes and dtypes only, no data
    N = d2l.num_params(d2l.GPT(**config))
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
if d2l.num_gpus():
    total = torch.cuda.mem_get_info()[1]
    print(f'one GPU holds {total / 2**30:.1f} GiB')
1.92 billion parameters, 16N = 28.6 GiB
one GPU holds 23.5 GiB
config = dict(vocab_size=50257, num_hiddens=2048, num_heads=16,
              num_blks=36, pos='learned')
k = 2                       # GPUs, from the all-gather below on
key = d2l.get_key()
N = d2l.num_params(nnx.eval_shape(lambda: d2l.GPT(**config,
                                                  rngs=nnx.Rngs(key))))
print(f'{N / 1e9:.2f} billion parameters, 16N = {16 * N / 2**30:.1f} GiB')
if jax.default_backend() == 'gpu':
    limit = jax.devices()[0].memory_stats()['bytes_limit']
    print(f'JAX may allocate {limit / 2**30:.1f} GiB of one GPU')
1.92 billion parameters, 16N = 28.6 GiB
JAX may allocate 22.1 GiB of one GPU

13.7.1 옵티마이저 상태, 그레이디언트 및 가중치 분할

표준 데이터 병렬화에서는 \(k\) 개의 GPU가 모두 동일한 Adam 모멘트 추정치 사본을 들고 똑같은 옵티마이저 업데이트를 중복 수행합니다. ZeRO(무중복 옵티마이저, Zero Redundancy Optimizer) 계열 (Rajbhandari 기타 2020년) 은 세 가지 누적 단계(표 13.7.1)를 통해 이러한 중복을 차례로 제거합니다.

  • ZeRO 1단계(Stage 1)는 옵티마이저 상태만 분할합니다. 각 GPU는 전체 매개변수의 \(1/k\) 에 대해서만 Adam의 두 모멘트를 보유합니다(매개변수당 \(8 + 8/k\) 바이트). 올리듀스(\(=\text{reduce-scatter} + \text{all-gather}\), 13.5.3절) 대신 GPU들이 그레이디언트를 리듀스-스캐터하여 각 GPU가 자기 \(1/k\) 샤드의 합산 그레이디언트를 받고, 자신이 맡은 매개변수만 갱신한 뒤, 갱신된 가중치를 올개더합니다. 이동하는 총 바이트 수는 데이터 병렬화와 정확히 같습니다.
  • ZeRO 2단계(Stage 2)는 그레이디언트까지 함께 분할합니다(매개변수당 \(4 + 12/k\) 바이트). 역전파 도중 각 그레이디언트 버킷이 채워지는 즉시 리듀스-스캐터하고 자신이 소유하지 않은 \(1 - 1/k\) 그레이디언트 샤드들을 곧바로 해제하며, 이 역시 데이터 병렬화 대비 추가 바이트 전송 비용이 전혀 들지 않습니다.
  • ZeRO 3단계(Stage 3), 즉 완전 샤딩 데이터 병렬화(Fully Sharded Data Parallelism, FSDP) (Zhao 기타 2023년) 는 가중치마저 샤딩합니다(매개변수당 \(16/k\) 바이트). 순전파나 역전파에서 블록이 실행되기 직전에 올개더로 해당 블록의 전체 가중치를 조립하고, 블록 실행이 끝나자마자 비소유 가중치 샤드들을 즉시 해제하며 블록 그레이디언트를 리듀스-스캐터합니다(그림 13.7.1).
표 13.7.1: \(k\) 개 GPU에서 fp32 Adam을 쓸 때 역전파 종료 시점의 GPU당 훈련 상태, 그리고 \(k = 2\) 에서 36블록 19.2억 매개변수 GPT의 구체적인 수치.
각 GPU 보유 항목 가중치 그레이디언트 Adam 상태 매개변수당 바이트 GPT, \(k = 2\)
데이터 병렬화 전체 전체 전체 16 28.6 GiB
ZeRO 1단계 전체 전체 \(1/k\) \(8 + 8/k\) 21.4 GiB
ZeRO 2단계 전체 \(1/k\) \(1/k\) \(4 + 12/k\) 17.9 GiB
ZeRO 3단계 (FSDP) \(1/k\) \(1/k\) \(1/k\) \(16/k\) 14.3 GiB
그림 13.7.1: 단일 GPU에서 본 FSDP 아래 한 블록 가중치의 수명 주기. 사용되지 않는 동안 블록은 샤딩되어 각 GPU가 \(1/k\) 만 보유하며 다른 블록들은 내내 샤딩 상태를 유지합니다. 순전파를 위해 올개더가 블록 전체를 조립하고 직후 해제합니다. 역전파를 위해 두 번째 올개더가 다시 조립한 뒤 직후 해제하며, 리듀스-스캐터가 각 GPU에 자기 몫의 그레이디언트만 남깁니다.

FSDP는 스텝마다 \(S = 4N\) 바이트에 대해 올개더 두 번(순전파 및 역전파)과 리듀스-스캐터 한 번—링 올리듀스가 두 단계를 수행하는 자리에서 세 번의 집합 통신 단계—을 수행하므로 데이터 병렬화 통신량의 \(1.5\times\) 를 이동시킵니다. 표 13.7.2 에서는 병렬 훈련 전반에 쓰이는 네 가지 핵심 집합 통신을 요약하며, 그림 13.7.2 에서는 각각이 두 GPU 사이에서 무엇을 어떻게 옮기는지 보여 줍니다.

그림 13.7.2: 두 GPU 사이의 전후 데이터 이동으로 나타낸 네 가지 집합 통신. GPU 0은 청크 \(a_0, a_1\) 로, GPU 1은 \(b_0, b_1\) 로 시작하며, 올개더에서는 GPU \(g\) 가 자신의 고유 샤드인 청크 \(g\) 만 가지고 시작합니다. 원시 청크는 파란색, 합산된 청크는 초록색입니다.
표 13.7.2: 데이터 병렬 훈련과 샤딩 훈련을 뒷받침하는 집합 통신 연산들.
집합 통신 종료 후 모든 GPU가 갖는 결과 사용되는 곳
올리듀스 (allreduce) 전체 합 데이터 병렬화의 그레이디언트
리듀스-스캐터 (reduce-scatter) 전체 합의 고유한 \(1/k\) 샤드 하나 ZeRO와 FSDP의 그레이디언트
올개더 (all-gather) 모든 샤드를 이어붙인 전체 텐서 ZeRO와 FSDP의 가중치
올투올 (all-to-all) 각 GPU로부터 받은 서로 다른 슬라이스 전문가 혼합 모델의 토큰 라우팅 (11.7절)

13.7.2 메모리와 통신 비용

GPU당 길이 1,024짜리 시퀀스 2개와 블록별 활성화 체크포인팅(13.4.3절)을 적용하여 \(k = 2\) 개 GPU에서 FSDP로 실행할 때 36블록 GPT의 피크 메모리와 스텝 시간을 예측해 봅시다.

  • 메모리: 샤딩된 훈련 상태는 GPU당 \(16N/2 = 14.3\) GiB를 차지합니다. 체크포인팅된 활성화값이 ~1 MiB/token(2,048토큰에 ~2 GiB)을 쓰고, 현재 조립되어 실행 중인 한두 개의 블록(각 ~0.2 GB)을 더해도 GPU당 피크 메모리는 최대 ~17 GiB로 24 GiB 안에 여유 있게 들어갑니다.

  • 통신: 세 집합 통신 단계 각각이 GPU당 \((k-1)S/k\) 바이트를 전송하므로 총 통신 시간은 다음과 같습니다.

    \[ t_\textrm{comm} = \frac{3(k-1)}{k}\,S\,\beta_\textrm{link}. \tag{13.7.1}\]

    FSDP의 핵심 스케일링 성질에 주목하십시오. GPU를 더 추가하면 GPU당 상태 메모리는 \(k\) 로 나누어져 줄어들지만, 각 GPU가 스텝당 보내는 바이트 수는 \(1.5S\)(\(k = 2\) 일 때)에서 \(3S\)(큰 \(k\) 일 때)를 향해 오히려 늘어납니다. 오직 GPU당 더 많은 토큰을 처리하거나 더 빠른 인터커넥트를 써야만 스텝 내 통신 비중을 줄일 수 있습니다.

먼저 \(k = 2\) 개 GPU에 걸친 256 MiB 올개더로 \(\beta_\textrm{link}\) 를 측정합니다.

GATHER = r'''
import json, torch
import torch.distributed as dist
from d2l import torch as d2l

_, k, device = d2l.init_distributed()
x = torch.zeros(2**26 // k, device=device)  # This GPU's part
y = torch.empty(2**26, device=device)       # 256 MiB, gathered
t = d2l.Benchmark(lambda: dist.all_gather_into_tensor(y, x), repeats=10).time
print(json.dumps({'beta_link': t / ((k - 1) / k * y.nbytes)}))  # Per byte sent
dist.destroy_process_group()
'''
assert d2l.num_gpus() >= k, 'The cells from here on need two GPUs'
beta_link = max(r['beta_link'] for r in d2l.torchrun(GATHER, k))
print(f'bus bandwidth = {1e-9 / beta_link:.1f} GB/s in an all-gather on {k} '
      f'GPUs (beta_link = {1e9 * beta_link:.2f} ns/byte)')
bus bandwidth = 2.3 GB/s in an all-gather on 2 GPUs (beta_link = 0.44 ns/byte)
assert jax.device_count() >= k, 'The cells from here on need two GPUs'
mesh = jax.make_mesh((k,), ('data',), devices=jax.devices()[:k],
                     axis_types=(jax.sharding.AxisType.Auto,))
x = jnp.zeros(2**26, device=NamedSharding(mesh, P('data')))  # 256 MiB
# Asking for the result on every GPU makes the compiler gather the parts
gather = jax.jit(lambda x: x, out_shardings=NamedSharding(mesh, P()))
t = d2l.Benchmark(lambda: gather(x), repeats=10).time
beta_link = t / ((k - 1) / k * x.nbytes)  # Seconds per byte sent per GPU
del x                       # Frees its memory before the training step
print(f'bus bandwidth = {1e-9 / beta_link:.1f} GB/s in an all-gather on {k} '
      f'GPUs (beta_link = {1e9 * beta_link:.2f} ns/byte)')
bus bandwidth = 2.2 GB/s in an all-gather on 2 GPUs (beta_link = 0.46 ns/byte)

실측된 \(\beta_\textrm{link}\) 와 RTX 4090의 82.6 TFLOP/s tf32 피크(peak_flops)를 사용하면 GPU당 상태 메모리(\(16N/k\)), 통신 시간(\(3(k-1)S\beta_\textrm{link}/k\)), 체크포인팅 연산 시간(\(8NbT/P\))에 대한 이론 예측치를 계산할 수 있습니다.

b, T = 2, 1024        # Sequences of T tokens per GPU and step
S = 4 * N             # Bytes of the fp32 weights, and of the gradients
peak_flops = 82.6e12  # tf32 FLOP/s of the RTX 4090
print(f'state per GPU, 16N/k: {16 * N / k / 2**30:.1f} GiB')
print(f'communication, 3(k-1)S beta_link/k: '
      f'{3 * (k - 1) / k * S * beta_link:.1f} s per step')
print(f'arithmetic at the peak, 8N bT/P: '
      f'{8 * N * b * T / peak_flops:.2f} s per step')
state per GPU, 16N/k: 14.3 GiB
communication, 3(k-1)S beta_link/k: 5.0 s per step
arithmetic at the peak, 8N bT/P: 0.38 s per step
b, T = 2, 1024        # Sequences of T tokens per GPU and step
S = 4 * N             # Bytes of the fp32 weights, and of the gradients
peak_flops = 82.6e12  # tf32 FLOP/s of the RTX 4090
print(f'state per GPU, 16N/k: {16 * N / k / 2**30:.1f} GiB')
print(f'communication, 3(k-1)S beta_link/k: '
      f'{3 * (k - 1) / k * S * beta_link:.1f} s per step')
print(f'arithmetic at the peak, 8N bT/P: '
      f'{8 * N * b * T / peak_flops:.2f} s per step')
state per GPU, 16N/k: 14.3 GiB
communication, 3(k-1)S beta_link/k: 5.3 s per step
arithmetic at the peak, 8N bT/P: 0.38 s per step

호스트 메모리를 경유하는 ~2.2 GB/s 버스 대역폭에서 스텝당 \(1.5S = 11.5\) GB를 옮기는 데는 ~5 s가 걸리는 반면, 2,048토큰의 산술 연산에는 ~0.4 s밖에 걸리지 않습니다. 0.4 s의 연산으로 5 s의 통신을 숨길 수는 없으므로 전체 스텝은 ~5 s가 걸릴 것으로 예측됩니다.

13.7.3 두 GPU에서의 샤딩 훈련

이제 어느 단일 GPU도 28.6 GiB 상태 전체를 한꺼번에 실체화하지 않도록 모델을 구성하여 두 GPU에서 샤딩된 36블록 GPT 스텝을 실행해 봅시다.

PyTorch에서는 'meta' 장치 위에서 모델을 생성하고, 체크포인팅된 각 블록과 최상위 모델을 torch.distributed.fsdp 의 fully_shard 로 감싼 뒤, model.to_empty(device=device) 로 현재 랭크의 샤드만 실체화하여 인플레이스로 초기화합니다.

TRAIN_FSDP = r'''
import json, sys, torch
import torch.distributed as dist
from torch import nn
from torch.nn import functional as F
from torch.distributed.fsdp import fully_shard
from torch.utils.checkpoint import checkpoint
from d2l import torch as d2l

class Checkpointed(nn.Module):
    """A block whose activations the backward pass recomputes."""
    def __init__(self, blk):
        super().__init__()
        self.blk = blk

    def forward(self, X, **kwargs):
        return checkpoint(self.blk, X, use_reentrant=False, **kwargs)

config, b, T = json.loads(sys.argv[1]), int(sys.argv[2]), int(sys.argv[3])
_, k, device = d2l.init_distributed()
torch.set_float32_matmul_precision('high')  # fp32 products on tf32 cores
torch.manual_seed(0)        # The same seed in every process
with torch.device('meta'):  # Shapes only: no GPU holds the whole model
    model = d2l.GPT(**config)
model.blks = nn.ModuleList(Checkpointed(blk) for blk in model.blks)
for blk in model.blks:      # Each block is gathered and released on its own
    fully_shard(blk)
fully_shard(model)          # The rest: the embeddings and the final norm
model.to_empty(device=device)  # This GPU's shards, not yet initialized
with torch.no_grad():       # Initialize the shards as d2l.GPT does
    for m in model.modules():
        if isinstance(m, nn.RMSNorm):
            m.reset_parameters()
    for emb in (model.token_emb, model.pos_emb):
        nn.init.normal_(emb.weight, std=0.02)
    model.init_weights()
opt = torch.optim.Adam(model.parameters(), lr=1e-4, fused=True)
# The same tokens on every GPU: they only set the shapes of the step
X = torch.randint(0, config['vocab_size'], (b, T), device=device)

def step():
    loss = F.cross_entropy(model(X).flatten(0, 1), X.flatten())
    loss.backward()
    opt.step()
    opt.zero_grad()

step()                      # Warm-up; creates Adam's moment estimates
times = [d2l.Benchmark(step, warmup=0, repeats=1).time for _ in range(3)]
kernels = d2l.kernel_times(step, steps=1)
comm = sum(ms for name, ms in kernels.items() if 'nccl' in name.lower())
print(json.dumps({'peak': torch.cuda.max_memory_allocated(), 'times': times,
                  'comm': comm / 1e3}))
dist.destroy_process_group()
'''

이제 d2l.torchrun 으로 \(k\) 개 프로세스에 걸쳐 TRAIN_FSDP 를 실행하고 랭크 0으로부터 피크 할당 메모리(peak_bytes), 스텝 소요 시간(times), NCCL 통신 시간(comm)을 수집합니다.

ranks = d2l.torchrun(TRAIN_FSDP, k, json.dumps(config), b, T)
peak_bytes = max(r['peak'] for r in ranks)
times, comm = ranks[0]['times'], ranks[0]['comm']  # GPU 0

JAX에서는 fsdp_sharding 이 각 매개변수 텐서를 \(k\) 로 나누어떨어지는 첫 번째 축을 따라 샤딩(P('data'))하며, create 가 이 샤딩 제약을 적용하여 각 GPU가 model 과 opt 중 자신의 샤드만 초기화하게 합니다.

def fsdp_sharding(x):
    """Split the first axis of x whose length k divides across the GPUs;
    replicate x if there is none."""
    for i, n in enumerate(x.shape):
        if n % k == 0:
            return NamedSharding(mesh, P(*[None] * i, 'data'))
    return NamedSharding(mesh, P())

@nnx.jit
def create(key):
    # The key is an argument: XLA would fold a constant key into the program,
    # together with every weight drawn from it, as large constants
    model = d2l.GPT(**config, rngs=nnx.Rngs(key))
    opt = nnx.Optimizer(model, optax.adam(1e-4), wrt=nnx.Param)
    state = nnx.state((model, opt))
    nnx.update((model, opt), jax.lax.with_sharding_constraint(
        state, jax.tree.map(fsdp_sharding, state)))
    return model, opt

model, opt = create(d2l.get_key())  # Each GPU computes only its shards

다음으로 활성화 체크포인팅을 위해 각 블록을 nnx.remat 으로 감싸고, XLA가 FSDP의 올개더와 리듀스-스캐터를 자동으로 생성하도록 loss_fn 안에서 모든 블록의 활성화 출력이 배치 샤딩(data) 상태를 유지하게 제약하며, 갱신된 상태가 이전 샤드를 인플레이스로 덮어쓰도록 train_step 에서 model 과 opt 를 버퍼 기부(donate) 처리합니다.

data = NamedSharding(mesh, P('data'))     # Split along the batch
block = nnx.remat(lambda blk, H: blk(H))  # Recomputed in the backward pass

def loss_fn(model, X):
    H = model.token_emb(X) + model.pos_emb(jnp.arange(X.shape[1]))
    for blk in model.blks:  # Every block's output stays split by batch
        H = jax.lax.with_sharding_constraint(block(blk, H), data)
    logits = model.token_emb.attend(model.norm(H))
    return optax.softmax_cross_entropy_with_integer_labels(logits, X).mean()

# Donated, the old weights and moment estimates make room for the new ones
@nnx.jit(donate_argnums=(0, 1))
def train_step(model, opt, X):
    loss, grads = nnx.value_and_grad(loss_fn)(model, X)
    opt.update(model, grads)
    return loss

스텝을 실행하기 전에 형상이 \((kb, T)\) 인 배치 샤딩 토큰 배치 X 위에서 train_step 을 컴파일하고 compiled.memory_analysis() 를 질의하여 기부된 상태와 임시 버퍼의 GPU당 메모리 사용량을 점검합니다.

X = jax.device_put(jax.random.randint(d2l.get_key(), (k * b, T), 0,
                                      config['vocab_size']), data)
compiled = train_step.lower(model, opt, X).compile()
mem = compiled.memory_analysis()  # Bytes per GPU
print(f'per GPU: weights and moments '
      f'{mem.argument_size_in_bytes / 2**30:.1f} GiB (donated: '
      f'{mem.alias_size_in_bytes / 2**30:.1f} GiB), temporaries '
      f'{mem.temp_size_in_bytes / 2**30:.1f} GiB')
per GPU: weights and moments 10.7 GiB (donated: 10.7 GiB), temporaries 5.0 GiB

XLA가 예상한 FSDP 집합 통신을 생성했는지 확인하기 위해 collective_megabytes 가 컴파일된 HLO 텍스트를 파싱하여 GPU당 각 집합 통신 연산의 결과 바이트 총합을 집계합니다.

def collective_megabytes(compiled):
    """Megabytes of the results of each kind of collective in a compiled
    program, on one GPU."""
    sizes = collections.Counter()
    for line in compiled.as_text().splitlines():
        # A synchronous collective, or the -done half of an asynchronous
        # pair, whose result type lists only the arrays that it returns
        op = re.search(r' = (.*?) (all-gather|reduce-scatter|all-reduce|'
                       r'all-to-all|collective-permute)(-done)?\(', line)
        for bits, dims in re.findall(r'[a-z]+(\d+)\[([\d,]*)\]',
                                     op[1] if op else ''):
            n = math.prod(int(d) for d in dims.split(',') if d)
            sizes[op[2]] += int(bits) // 8 * n / 1e6
    return dict(sizes)

compiled 안의 집합 통신을 집계해 보면 all-gather(스텝당 2회)와 reduce-scatter(스텝당 1회)가 예측한 바이트 용량을 정확히 이동시킴을 확인할 수 있습니다.

for kind, mb in sorted(collective_megabytes(compiled).items(),
                       key=lambda kv: -kv[1]):
    print(f'{kind}: {mb / 1e3:.2f} GB')
all-gather: 14.92 GB
reduce-scatter: 3.83 GB
all-to-all: 0.03 GB
all-reduce: 0.00 GB

이제 train_step 을 워밍업하고 세 번 반복 측정한 뒤 스텝을 프로파일링하여 NCCL 통신 시간(comm)과 피크 장치 메모리(peak_bytes)를 기록합니다.

train_step(model, opt, X).block_until_ready()  # Warm-up, finished
times = [d2l.Benchmark(lambda: train_step(model, opt, X), warmup=0,
                       repeats=1).time for _ in range(3)]
kernels = d2l.kernel_times(lambda: train_step(model, opt, X), steps=1)
comm = sum(ms for name, ms in kernels.items() if 'nccl' in name.lower()) / 1e3
peak_bytes = jax.devices()[0].memory_stats()['peak_bytes_in_use']

마지막으로 GPU당 실측 피크 메모리, 스텝 소요 시간 중앙값, 그리고 GPU 0에서 NCCL 통신 커널에 소비된 시간을 보고합니다.

print(f'per GPU: peak memory {peak_bytes / 2**30:.1f} GiB; '
      f'{np.median(times):.2f} s per step ({min(times):.2f} to '
      f'{max(times):.2f})\nof each step, GPU 0 spends {comm:.2f} s in '
      f'communication kernels')
per GPU: peak memory 16.0 GiB; 5.73 s per step (5.70 to 5.74)
of each step, GPU 0 spends 5.69 s in communication kernels
print(f'per GPU: peak memory {peak_bytes / 2**30:.1f} GiB; '
      f'{np.median(times):.2f} s per step ({min(times):.2f} to '
      f'{max(times):.2f})\nof each step, GPU 0 spends {comm:.2f} s in '
      f'communication kernels')
per GPU: peak memory 15.8 GiB; 5.29 s per step (5.28 to 5.50)
of each step, GPU 0 spends 5.01 s in communication kernels

두 GPU 모두 카드당 ~16 GiB 피크(예측 상한인 17 GiB 미만)로 36블록 모델을 거뜬히 담으며, 각 스텝은 ~5.5 s가 걸리고 GPU 0은 스텝 시간의 90% 이상을 NCCL 통신 커널에서 보냅니다(이론 예측치인 5 s에서 6분의 1 이내). 반면 NVLink 5(단방향 900 GB/s) 위에서는 똑같은 11.5 GB의 집합 통신이 단 ~13 ms면 끝나 0.4 s 연산 시간의 30분의 1 미만에 불과합니다.

이 비교는 언제 샤딩해야 하는지도 분명히 알려 줍니다. 합리적인 마이크로배치와 함께 단일 GPU에 훈련 상태가 들어가는 모델(예: 18블록 GPT)은 PCIe 위에서 FSDP를 쓰는 것(매 마이크로배치마다 가중치를 두 번씩 다시 모음)보다 데이터 병렬화와 그레이디언트 누적을 결합하는 편(전역 스텝당 단 한 번만 통신)이 훨씬 빠르게 훈련됩니다.

13.7.4 요약

데이터 병렬화는 모든 GPU에 fp32 Adam 상태 \(16N\) 바이트 전체를 복제합니다. ZeRO는 이 상태를 \(k\) 개 GPU에 분할합니다. 1단계는 옵티마이저 모멘트를 샤딩하고(매개변수당 \(8 + 8/k\) 바이트), 2단계는 그레이디언트까지 샤딩하며(매개변수당 \(4 + 12/k\) 바이트), 두 단계 모두 스텝당 링 올리듀스와 정확히 동일한 \(2(k-1)S/k\) 바이트만 이동시킵니다. 3단계(FSDP)는 가중치마저 샤딩하여(매개변수당 \(16/k\) 바이트) 데이터 병렬화 통신량의 \(1.5\times\)(GPU당 \(3(k-1)S/k\) 바이트) 비용으로 순전파 및 역전파마다 각 블록의 가중치를 모으고 그레이디언트를 리듀스-스캐터합니다. 샤딩 덕분에 어느 한 카드에도 단독으로는 들어가지 않는 28.6 GiB 상태의 36블록 GPT를 24 GiB GPU 두 장으로 훈련할 수 있습니다.

13.7.5 연습 문제

  1. 샤딩의 비용. ● fp32 가중치 또는 그레이디언트 한 벌의 바이트 수인 \(S = 4N\) 을 단위로 GPU당 스텝당 통신량을 세어 보십시오.
    1. ZeRO 3단계의 한 변형은 조립된 모든 블록을 순전파부터 역전파가 끝날 때까지 메모리에 그대로 유지합니다. 이 방식은 어떤 집합 통신을 제거하며, 표 13.7.1 의 메모리 절감분 중 얼마만큼을 포기합니까?
    2. 혼합 정밀도 FSDP는 각 GPU의 마스터 가중치 샤드와 Adam 샤드를 fp32로 유지하면서 가중치 올개더와 그레이디언트 리듀스-스캐터는 bf16으로 수행합니다. 스텝당 전송 바이트 수를 fp32 데이터 병렬화와 비교하고, 매개변수당 메모리를 표 13.7.1 의 마지막 행과 비교하십시오.
    3. 실측된 \(\beta_\textrm{link}\) 를 갖는 \(k = 2\) 개 GPU의 36블록 GPT에서 체크포인팅 연산 시간(83 TFLOP/s에서 토큰당 \(8N\) FLOPs)이 식 13.7.1 의 통신 시간과 같아지려면 스텝당 GPU당 몇 개의 토큰이 필요합니까? 그 활성화값들이 카드에 들어가며, FSDP가 매 마이크로배치마다 가중치를 다시 모을 때는 왜 그레이디언트 누적이 도움이 되지 않습니까?
  2. [extended] 옵티마이저 상태 샤딩. ● torch.optim.Adam 과 함께 TRAIN_DDP(13.6절)에서 출발하여 ZeRO 1단계 (Rajbhandari 기타 2020년) 를 직접 구현하십시오.
    1. 각 랭크가 대략 \(1/k\) 의 매개변수를 소유해 소유한 텐서들에만 Adam을 실행하도록 매개변수 텐서들을 랭크별로 분할한 뒤, dist.broadcast 로 각 소유자로부터 갱신된 텐서를 브로드캐스트하십시오. 여러 스텝 후 매개변수가 전체 DDP Adam과 일치함을 확인하고 torch.distributed.optim.ZeroRedundancyOptimizer 와 비교하십시오.
    2. 샤딩 적용 전후로 \(k = 2\) 와 \(k = 4\) 에서 할당 및 피크 GPU 메모리를 측정하고, DDP 올리듀스 더하기 소유자 브로드캐스트가 보낸 총 바이트 수를 1단계의 리듀스-스캐터 더하기 올개더와 비교하십시오.
  3. [code] 텐서 병렬화 대 데이터 병렬화. ● \(k\) 개 장치에 걸친 MLP 블록 \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\)(\(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\))를 생각해 보십시오. 텐서 병렬화(그림 13.5.1, (Shoeybi 기타 2019년))는 \(\mathbf{W}_1\) 을 열 방향으로, \(\mathbf{W}_2\) 를 행 방향으로 분할합니다.
    1. 각 장치가 통신 없이 부분 \(n \times d\) 출력을 계산할 수 있고 \(k\) 개 부분 출력의 합이 \(\mathbf{Y}\) 가 됨을 보이십시오. 순전파에는 어떤 집합 통신이 필요하며, 역전파에서 \(\nabla_{\mathbf{X}}\) 를 구할 때는 어떤 집합 통신이 필요합니까?
    2. 텐서 병렬화와 데이터 병렬화에서 장치당 스텝당 전송되는 값의 개수를 비교하고, 텐서 병렬화가 더 적은 데이터를 보내는 토큰 수 \(n\) 의 조건을 구하십시오. 그럼에도 텐서 병렬화가 빠른 노드 내 NVLink 도메인으로 제한되는 이유는 무엇입니까?
    3. 1차원 DeviceMesh 위에서 ColwiseParallel() 및 RowwiseParallel() 과 함께 parallelize_module 을 사용하여 CommDebugMode 로 순전파 및 역전파 집합 통신 횟수를 세십시오.
  4. 다음 블록 프리페칭. FSDP 순전파에서 한 블록의 올개더 시간을 \(g\), 연산 시간을 \(c\) 라 합시다. 중첩이 없으면 \(L\) 개 블록에 \(L(g + c)\) 가 걸리지만, 프리페칭(사전 인출)은 블록 \(l\) 이 계산하는 동안 블록 \(l + 1\) 의 올개더를 미리 발행합니다.
    1. 프리페칭이 순전파 시간을 \(g + (L-1)\max(g, c) + c\) 로 줄여 줌을 보이고, 왜 어떤 스케줄도 \(L\max(g, c)\) 보다 더 나을 수 없는지 설명하십시오.
    2. 36블록 GPT의 단일 블록(매개변수 \(50\)M개, GPU당 2,048토큰, 83 TFLOP/s)에 대해 실험용 PCIe 링크와 NVLink 5(900 GB/s)에서 \(g\) 와 \(c\) 를 계산하고, 각 인터커넥트에서 프리페칭이 얼마나 시간을 절약하는지 서술하십시오.
  1. 샤딩의 비용. ● fp32 가중치 또는 그레이디언트 한 벌의 바이트 수인 \(S = 4N\) 을 단위로 GPU당 스텝당 통신량을 세어 보십시오.
    1. ZeRO 3단계의 한 변형은 조립된 모든 블록을 순전파부터 역전파가 끝날 때까지 메모리에 그대로 유지합니다. 이 방식은 어떤 집합 통신을 제거하며, 표 13.7.1 의 메모리 절감분 중 얼마만큼을 포기합니까?
    2. 혼합 정밀도 FSDP는 각 GPU의 마스터 가중치 샤드와 Adam 샤드를 fp32로 유지하면서 가중치 올개더와 그레이디언트 리듀스-스캐터는 bf16으로 수행합니다. 스텝당 전송 바이트 수를 fp32 데이터 병렬화와 비교하고, 매개변수당 메모리를 표 13.7.1 의 마지막 행과 비교하십시오.
    3. 실측된 \(\beta_\textrm{link}\) 를 갖는 \(k = 2\) 개 GPU의 36블록 GPT에서 체크포인팅 연산 시간(83 TFLOP/s에서 토큰당 \(8N\) FLOPs)이 식 13.7.1 의 통신 시간과 같아지려면 스텝당 GPU당 몇 개의 토큰이 필요합니까? 그 활성화값들이 카드에 들어가며, FSDP가 매 마이크로배치마다 가중치를 다시 모을 때는 왜 그레이디언트 누적이 도움이 되지 않습니까?
  2. [extended] 옵티마이저 상태 샤딩. ● optax.adam 과 함께 train_step(13.6절)에서 출발하여 ZeRO 1단계 (Rajbhandari 기타 2020년) 를 선언적으로 구현하십시오. 모델 매개변수는 복제(P()) 상태로 유지하고 nnx.state(opt) 의 리프들을 fsdp_sharding 으로 배치하십시오.
    1. 필요한 경우 jax.sharding.reshard 를 통해 train_step 끝에서 매개변수가 복제 상태로 유지되도록 보장하고, 다중 스텝 매개변수 업데이트가 복제 Adam과 일치함을 검증하십시오.
    2. collective_megabytes 로 컴파일된 스텝을 검사하고, \(k = 2\) 및 \(k = 4\) 에서의 집합 통신과 상주/피크 메모리를 표 13.7.1 의 수치와 비교하십시오.
  3. [code] 텐서 병렬화 대 데이터 병렬화. ● \(k\) 개 장치에 걸친 MLP 블록 \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\)(\(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\))를 생각해 보십시오. 텐서 병렬화(그림 13.5.1, (Shoeybi 기타 2019년))는 \(\mathbf{W}_1\) 을 열 방향(P(None, 'data'))으로, \(\mathbf{W}_2\) 를 행 방향(P('data', None))으로 분할합니다.
    1. 각 장치가 통신 없이 부분 \(n \times d\) 출력을 계산할 수 있고 \(k\) 개 부분 출력의 합이 \(\mathbf{Y}\) 가 됨을 보이십시오. 순전파에는 어떤 집합 통신이 필요하며, 역전파에서 \(\nabla_{\mathbf{X}}\) 를 구할 때는 어떤 집합 통신이 필요합니까?
    2. 텐서 병렬화와 데이터 병렬화에서 장치당 스텝당 전송되는 값의 개수를 비교하고, 텐서 병렬화가 더 적은 데이터를 보내는 토큰 수 \(n\) 의 조건을 구하십시오. 그럼에도 텐서 병렬화가 빠른 노드 내 NVLink 도메인으로 제한되는 이유는 무엇입니까?
    3. Auto 메시 위에 \(\mathbf{W}_1\) 을 P(None, 'data'), \(\mathbf{W}_2\) 를 P('data', None), \(\mathbf{X}\) 를 복제 상태로 배치하여 순전파와 역전파를 JIT 컴파일하고 생성된 집합 통신을 확인하십시오.
  4. 다음 블록 프리페칭. FSDP 순전파에서 한 블록의 올개더 시간을 \(g\), 연산 시간을 \(c\) 라 합시다. 중첩이 없으면 \(L\) 개 블록에 \(L(g + c)\) 가 걸리지만, 프리페칭(사전 인출)은 블록 \(l\) 이 계산하는 동안 블록 \(l + 1\) 의 올개더를 미리 발행합니다.
    1. 프리페칭이 순전파 시간을 \(g + (L-1)\max(g, c) + c\) 로 줄여 줌을 보이고, 왜 어떤 스케줄도 \(L\max(g, c)\) 보다 더 나을 수 없는지 설명하십시오.
    2. 36블록 GPT의 단일 블록(매개변수 \(50\)M개, GPU당 2,048토큰, 83 TFLOP/s)에 대해 실험용 PCIe 링크와 NVLink 5(900 GB/s)에서 \(g\) 와 \(c\) 를 계산하고, 각 인터커넥트에서 프리페칭이 얼마나 시간을 절약하는지 서술하십시오.

토론