13.6  データ並列の実践

13.5 節 で手書きしたデータ並列(data parallelism)ループでは、2 基の GPU で LeNet がかえって遅くなった。その理由は 2 つある。単一の Python スレッドが両方の GPU へカーネルを逐次的にディスパッチしていたこと、そして出力に近い層の勾配はずっと早い段階で揃っていたにもかかわらず、逆伝播全体が完了するまでオールリデュースが待機していたことである。

実用データ並列ツールは、これら両方のボトルネックを解消する。GPU ごとに 1 つのホストプロセスを実行するか、全 GPU にまたがる単一のシャーディングされたプログラムをコンパイルし、さらに勾配をバケットにまとめて逆伝播中に各バケットが埋まり次第そのオールリデュースを開始するのである。逆伝播の計算の背後に勾配交換をどれだけ隠蔽できるかを検証するため、ここでは LeNet から \(64 \times 64\) の Fashion-MNIST 画像に対する ResNet-18 へと対象を移す(画像 1 枚あたり 22 億回の積和演算、45 MB の勾配 1 バイトあたり約 300 訓練 FLOPs を要し、画像 256 枚の 1 ステップあたり 1 基の RTX 4090 を約 100 ms 稼働させ続ける)。並列ステップが何を計算しているかを 1 ステップチェックで検証したうえで、1、2、4 基の GPU にわたる弱スケーリング(weak scaling)と強スケーリング(strong scaling)を計測し、コストモデルと比較する。

# 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 os
import random
import sys
import json
import re
import subprocess
import sys
from jax.sharding import NamedSharding, PartitionSpec as P

13.6.1 実用データ並列

13.6.1.1 実行モデル

現代のあらゆるフレームワークは、次の 2 種類の単一プログラム複数データ(single program, multiple data、SPMD)設計のいずれかを用いて \(k\) 基の GPU を駆動する。

  1. マルチプロセス(\(k\) 個の複製+集団通信ライブラリ):ランチャが \(k\) 個の独立した Python プロセス(GPU ごとに 1 つ、それぞれが \(\{0, \ldots, k-1\}\) の固有のランクと専用の CPU スレッドを持つ)を起動し、NCCL を介して勾配を同期する。各プロセスの内部では任意の Python コードを実行できる。
  2. コンパイラ分割型の単一プログラム:単一デバイス向けのステップを記述し、デバイスメッシュ上での入力のシャーディングを注釈として指定すると、コンパイラが計算を分割し、集団通信演算(collective operations)を自動的に挿入・スケジューリングする (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)。

図 13.6.1: 上:オールリデュースが逆伝播全体の完了を待つ場合。下:勾配をバケットにまとめ、逆伝播が各バケットの勾配を生成し終え次第、そのオールリデュースを開始する場合。逆伝播の終了後に実行されるのは最後のバケットのみであり、それより前のバケットが隠蔽されるのは、逆伝播がまだ実行されている間に各オールリデュースが完了する場合に限られる。

バケットサイズは、呼び出しごとのレイテンシ \(\alpha\) とオーバーラップのトレードオフを決める。極小のバケットでは \(\alpha\) を何度も支払うことになり、単一の巨大なバケットでは逆伝播が完了するまで通信を開始できない。理想的なオーバーラップのバケットモデルのもとでは(すなわち、次のバケットが埋まる前に各バケットの通信を終えられるほど GPU 間リンクが高速であり、かつ通信が同時実行中の逆伝播カーネルを減速させないと仮定すると)、最後のバケットを除くすべてのバケットが逆伝播の背後に隠蔽される。

DDP は最初のバケットを 1 MiB で閉じ、それ以降のバケットを 25 MiB(bucket_cap_mb)で閉じる。ResNet-18 の 45 MB の勾配に対し、DDP は約 9、26、9 MB の 3 つのバケットを形成する(最後の 9 MB のバケットには、最も遅く計算される入力側の層が入る)。

XLA は 30 MiB のしきい値(--xla_gpu_all_reduce_combine_threshold_bytes)まで勾配のオールリデュースを結合し、ResNet-18 の 45 MB の勾配を、逆伝播計算と並行してスケジュールされる 2 組の非同期 all-reduce-start / all-reduce-done ペアにまとめる。

13.6.1.3 訓練ステップ

7.4 節 の小画像向け ResNet-18(第 32 章 (英語版) でも利用するため #@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 loss

13.6.1.4 1 ステップチェック

LeNet とは異なり、ResNet-18 は各チャネルをミニバッチの平均と分散で正規化するバッチ正規化(7.3 節)を含んでいる。256 個の例からなるミニバッチを 2 基の GPU に分割したとき、各 GPU は自身の 128 例のシャード統計量で正規化するのだろうか(これは 1 基の GPU 上で 128 例のマイクロバッチ 2 つにわたって勾配累積した場合と一致する)。それとも、GPU 間で 256 例の大域的な統計量を同期するのだろうか。2 基の GPU による更新を、単一 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 のシャードをシャードごとの局所統計量で正規化する。そのため、2 分割して累積した場合とは約 \(10^{-7}\) の精度で一致する一方、フルバッチ統計量を用いた場合とは数パーセント異なる(nn.SyncBatchNorm に変換すれば、追加の集団通信と引き換えに大域統計量が同期される。演習問題 4)。

バッチ軸が 'data' メッシュ軸に沿って Auto モードでシャーディングされるため、XLA のパーティショナはバッチ正規化の平均と分散をミニバッチ全体にわたって大域的に計算する。これにより、単一 GPU での 256 例のステップと一致し、2 つの大きな勾配バッファに加えてチャネルごとのバッチ正規化統計量に対する小さなオールリデュースが挿入される。

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 を適用すると、2 つの大きな勾配オールリデュース(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 4 基の GPU でのスケーリング

ここでは、\(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}\) を測定し、弱スケーリングのもとでの露出通信時間(exposed communication time)\(t_{\textrm{step}}(k) - t_{\textrm{step}}(1)\) に対する次の 2 つの予測を比較する。

  1. オーバーラップなし:\(S = 45\) MB のリングオールリデュース全体が露出する(\(\frac{2(k-1)}{k} S \beta_\textrm{link}\))。
  2. 完全なバケットオーバーラップ:逆伝播の終了後に最後のバケットまたはバッファ(\(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 が得られる。これを用いて、\(k \in \{2, 4\}\) 基の GPU に対する exposed[k] を、オーバーラップなしモデル(\(2(k-1)S\beta_\textrm{link}/k\))と完全オーバーラップモデル(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.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)

それでは、GPU あたり 256 例(step_time(k, 256))で \(k \in \{1, 2, 4\}\) 基の GPU にわたる弱スケーリングをベンチマークし、実測されたスループット、スケーリング効率、および露出オーバーヘッド 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 基で約 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 が並行して動作しても逆伝播の計算カーネルが減速しないこと、の 3 つを仮定している。GPU 0 を 3 つの構成(1 基の GPU、通信なしの 2 基の GPU、通信ありの 2 基の GPU)にわたってプロファイリングすることで、これら 3 つの仮定すべてを検証できる。

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, comm

GPU あたり \(b = 256\) 例で、単一 GPU、勾配同期なしの 2 基の GPU、オールリデュースありの 2 基の GPU という 3 つの構成にわたって 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

通信なしの 2 基の GPU は単一 GPU と全く同じ速度でステップを実行し、NCCL のカーネルは 20〜22 ms 動作する(18 ms の単体ベンチマークと整合する)。破綻しているのは 3 つ目の仮定である。すなわち、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 ステップチェックを行えば、バッチ正規化がシャードごとの統計量を用いているのか、追加の集団通信を介して大域統計量を用いているのかが明らかになる。ホストメモリ経由で通信する 4 基の RTX 4090(バス帯域幅 2.4 GB/s)では、弱スケーリングのもとで単一 GPU の \(3.1\text{--}3.3\times\) のスループットが得られたが、カーネルプロファイリングの結果、ホスト中継の NCCL カーネルによる SM 競合が、通信と逆伝播計算のオーバーラップで節約された時間の大部分を帳消しにしていることがわかる。

13.6.4 演習問題

  1. [code] データの分割。TRAIN_DDP では、ランク \(r\) は共有されたランダム順列から \((sk + r)b\) を始点とするスライスを各ステップ \(s\) で取得する。
    1. このオフセットから rank を取り除き、すべてのプロセスが同じ \(b\) 個の例を取得するようにせよ。\(k = 2\) における step_time と平均化された勾配がどのように振る舞うかを予測し、各ランクでミニバッチのチェックサムを出力して検証せよ。
    2. オフセットを元に戻したうえで、各ランクに異なる乱数シードを与えよ。ミニバッチ分割のどの性質が失われるか。
    3. 最初のステップでランク間に同一のデータシャードが存在することを検出する、軽量な実行時アサーションを提案せよ。
  2. 弱スケーリングの外挿。\(k\) 基の GPU 上での 1 ステップに、単一 GPU 時間 \(t_1\) と、リング通信量 \(2(k-1)S/k\) に比例する露出通信時間がかかるとする。
    1. 弱スケーリング効率 \(E(k) = t_1 / t_{\textrm{step}}(k)\) を単一の定数を用いて表し、実測された \(E(2)\) でその定数を較正したうえで、\(E(4)\) に対する予測を 13.6.2 節 の実測値と比較せよ。
    2. \(a\) 個のマイクロバッチ(GPU あたり 256 例、最後のマイクロバッチでのみ通信する)にわたって勾配累積を行う場合、整数 \(a\) のうち \(E(4)\) を 95% 以上に引き上げる最小の値を求め、グローバルバッチサイズがどのように変化するか述べよ。
  3. [code] バケットサイズ。 ● バケットオーバーラップ(図 13.6.1)を次の仮定のもとでモデル化せよ。時間 \(t_b\) の逆伝播が等サイズの \(n\) 個のバケットを時刻 \(i\,t_b/n\)(\(i = 1, \ldots, n\))に順次放出し、各バケットのオールリデュースが逐次的に \(\alpha + \tau/n\) を要するものとする(ただし \(\tau = S\,\beta_\textrm{link}\))。
    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}\] さらに、最適な \(n\) を \(\tau < t_b\) の場合と \(\tau > t_b\) の場合のそれぞれについて求めよ。
    2. bucket_cap_mb(DDP の引数)を \(k = 2\) において 1 MB から 100 MB まで変化させ、実測された露出通信時間をこのモデルと比較せよ。
  4. [code] 同期バッチ正規化。 ● 13.6.1 節 の 1 ステップチェックにより、DDP はデフォルトで各シャードを局所統計量によって正規化することがわかった。
    1. model(CHECK_DDP 内)を nn.SyncBatchNorm.convert_sync_batchnorm で変換してから DDP でラップし、同じチェックを繰り返せ。今度はどちらの単一 GPU 参照結果と一致するか。
    2. SyncBatchNorm によって 1 ステップあたりに追加される集団通信の回数を数え、\(k = 2\) および \(k = 4\) での step_time を測定したうえで、その所要時間がバイト数に \(\beta_\textrm{link}\) を掛けた値を上回る理由を説明せよ。
  1. [code] データの分割。minibatches では、インデックスは P('data') で配置されている。
    1. 代わりに P() で配置し、すべての GPU が全インデックスを受け取るようにせよ。コンパイルされた train_step にどの集団通信が含まれるか、また step_time(2, 256) が step_time(1, 256) と比べてどうなるかを予測し、その両方を確認せよ。
    2. P('data') に戻したうえで、train_step の内部で X[idx] を NamedSharding(mesh, P(None, 'data')) に制約し、画像の高さを GPU 間で分割せよ。\(3 \times 3\) 畳み込みのために隣接する GPU 間でどの境界の値を交換する必要があり、コンパイルされた HLO にはどの集団通信が現れるか。
  2. 弱スケーリングの外挿。\(k\) 基の GPU 上での 1 ステップに、単一 GPU 時間 \(t_1\) と、リング通信量 \(2(k-1)S/k\) に比例する露出通信時間がかかるとする。
    1. 弱スケーリング効率 \(E(k) = t_1 / t_{\textrm{step}}(k)\) を単一の定数を用いて表し、実測された \(E(2)\) でその定数を較正したうえで、\(E(4)\) に対する予測を 13.6.2 節 の実測値と比較せよ。
    2. \(a\) 個のマイクロバッチ(GPU あたり 256 例、最後のマイクロバッチでのみ通信する)にわたって勾配累積を行う場合、整数 \(a\) のうち \(E(4)\) を 95% 以上に引き上げる最小の値を求め、グローバルバッチサイズがどのように変化するか述べよ。
  3. [code] バケットサイズ。 ● バケットオーバーラップ(図 13.6.1)を次の仮定のもとでモデル化せよ。時間 \(t_b\) の逆伝播が等サイズの \(n\) 個のバケットを時刻 \(i\,t_b/n\)(\(i = 1, \ldots, n\))に順次放出し、各バケットのオールリデュースが逐次的に \(\alpha + \tau/n\) を要するものとする(ただし \(\tau = S\,\beta_\textrm{link}\))。
    1. 逆伝播終了後の露出通信時間が次の式で与えられることを示せ。 \[t_{\textrm{exposed}}(n) = \max\Bigl(\alpha + \frac{\tau}{n},\; n\alpha + \tau - \frac{n-1}{n}\,t_b\Bigr),\] さらに、最適な \(n\) を \(\tau < t_b\) の場合と \(\tau > t_b\) の場合のそれぞれについて求めよ。
    2. 新規プロセス上で --xla_gpu_all_reduce_combine_threshold_bytes を 1 MB から 100 MB まで変化させ、生成される勾配オールリデュースの回数を数えて、実測された露出通信時間をこのモデルと比較せよ。
  4. [code] バッチ正規化の統計量。 ● nnx.jit と Auto メッシュ軸のもとでは、バッチ正規化はすべての GPU にわたって大域統計量を計算する。
    1. allreduce_megabytes(compiled) に現れる 74 個の小さなオールリデュースの内訳を、BatchNorm 層の数(resnet18 内)ならびに順伝播・逆伝播の構成から説明せよ。
    2. コンパイル前に model.eval() を呼び出して BatchNorm がバッチ統計量の代わりに移動平均を用いるようにし、小さなオールリデュースが消えることを確認したうえで、\(k = 1, 2, 4\) においてそれらがどれだけのステップ時間を要していたかを測定せよ。

ディスカッション