13.6  توازي البيانات في الممارسة العملية

في القسم 13.5 أبطأت حلقة توازي البيانات التي كتبناها يدويًا شبكة LeNet على وحدتي GPU لسببين: خيط Python واحد كان يرسل النوى إلى الوحدتين بالتتابع، وعملية allreduce كانت تنتظر حتى ينتهي التمرير الخلفي كله، مع أن تدرجات الطبقات الأخيرة كانت جاهزة قبل ذلك بكثير.

تزيل أدوات توازي البيانات المستخدمة في بيئة الإنتاج عنقي الزجاجة كليهما: فهي إما تشغل عملية واحدة على المضيف لكل وحدة GPU، وإما تصرّف برنامجًا واحدًا مقسمًا إلى حصص على وحدات GPU كلها، وهي تجمع التدرجات في سلال (buckets) تبدأ عملية allreduce لكل سلة منها فور امتلائها أثناء التمرير الخلفي. ولنختبر كم من تبادل التدرجات يمكن إخفاؤه خلف حساب التمرير الخلفي، ننتقل من شبكة LeNet إلى شبكة ResNet-18 على صور Fashion-MNIST بحجم \(64 \times 64\) (2.2 مليار عملية ضرب وجمع للصورة الواحدة، ونحو 300 عملية FLOP في التدريب لكل بايت من تدرجها البالغ 45 MB، وهو ما يشغل بطاقة RTX 4090 واحدة نحو 100 ms في كل خطوة من 256 صورة). نتحقق مما تحسبه الخطوة المتوازية بفحص لخطوة واحدة، ونقيس التناسب الضعيف والتناسب القوي على وحدة GPU واحدة ووحدتين وأربع وحدات، ونقارنهما بنموذج الكلفة.

# 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 نموذج التنفيذ

يقود كل إطار عمل حديث \(k\) وحدة GPU بأحد تصميمين من نوع برنامج واحد وبيانات متعددة (single program, multiple data, SPMD):

  1. تعدد العمليات (\(k\) نسخة + مكتبة عمليات جماعية): يشغل برنامج إطلاق \(k\) عملية Python مستقلة، واحدة لكل وحدة GPU، ولكل منها رتبتها (rank) في \(\{0, \ldots, k-1\}\) وخيطها الخاص على وحدة CPU، وتزامن هذه العمليات التدرجات عبر مكتبة NCCL. ويمكن تشغيل أي شيفرة Python داخل كل عملية.
  2. برنامج واحد يقسمه المصرِّف: يكتب المستخدم خطوة لجهاز واحد ويصرّح بتقسيم مدخلاتها إلى حصص على شبكة أجهزة؛ فيقسم المصرِّف الحساب ويدرج العمليات الجماعية ويجدولها تلقائيًا (Xu وآخرون 2021).

تستخدم مكتبة PyTorch تصميم تعدد العمليات: يطلق البرنامج torchrun عمليات عددها \(k\) ويغلف الصنف DistributedDataParallel (DDP) النموذج. ولأن الدفتر عملية واحدة، تكتب دالتنا المساعدة torchrun برنامجًا مكتفيًا بذاته في ملف مؤقت، وتشغل الأمر torchrun --standalone --nproc-per-node=k، وتحلل مخرجات JSON لكل رتبة.

تستخدم مكتبة JAX التصميم الذي يقسم فيه المصرِّف البرنامج: يصرّف المزخرف nnx.jit خطوة تدريب مكتوبة لجهاز واحد، ووضع معلَمات منسوخة (P()) إلى جانب مدخلات مقسمة إلى حصص على بُعد الدفعة (P('data')) يجعل مقسِّم Shardy/GSPMD يدرج عملية allreduce للتدرجات تلقائيًا.

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 تراكب الاتصال مع التمرير الخلفي

تحزم أطر العمل المستخدمة في بيئة الإنتاج التدرجات في سلال حجم كل منها بضع عشرات من الميغابايت، بالترتيب العكسي للطبقات (وهو الترتيب الذي ينتجها به الانتشار العكسي)، وتطلق عملية allreduce غير المتزامنة لكل سلة فور جاهزية آخر تدرج فيها (Li وآخرون 2020) (الشكل 13.6.1).

الشكل 13.6.1: في الأعلى: تنتظر عملية allreduce التمرير الخلفي كله. في الأسفل: تُجمع التدرجات في سلال، وتبدأ عملية allreduce لكل سلة فور أن ينتجها التمرير الخلفي. السلة الأخيرة وحدها تعمل بعد انتهاء التمرير الخلفي، ولا تُخفى السلال السابقة إلا إذا انتهت كل عملية allreduce والتمرير الخلفي ما زال جاريًا.

يقايض حجم السلة زمن الاستجابة لكل استدعاء \(\alpha\) بالتراكب: السلال بالغة الصغر تدفع \(\alpha\) مرات كثيرة، أما السلة العملاقة الواحدة فلا تستطيع أن تبدأ قبل أن ينتهي التمرير الخلفي. وفي نموذج السلال (bucket model) المثالي للتراكب، وهو يفترض أن الروابط بين وحدات GPU سريعة بما يكفي لإنهاء كل سلة قبل امتلاء التالية وأن الاتصال لا يبطئ نوى التمرير الخلفي التي تعمل في الوقت نفسه، تُخفى كل سلة ما عدا الأخيرة خلف التمرير الخلفي.

تغلق طريقة DDP السلة الأولى عند 1 MiB والسلال اللاحقة عند 25 MiB (الوسيط bucket_cap_mb). ومن تدرجات شبكة ResNet-18 البالغة 45 MB تنشئ DDP ثلاث سلال أحجامها نحو 9 و 26 و 9 MB (السلة الأخيرة ذات 9 MB تضم الطبقات المبكرة، وهي تُحسب آخرًا).

يدمج المصرِّف XLA عمليات allreduce للتدرجات حتى عتبة مقدارها 30 MiB (الراية --xla_gpu_all_reduce_combine_threshold_bytes)، فيحزم تدرجات شبكة ResNet-18 البالغة 45 MB في زوجين غير متزامنين من العمليتين all-reduce-start و all-reduce-done يُجدولان بالتزامن مع حساب التمرير الخلفي.

13.6.1.3 خطوة التدريب

نعرّف شبكة ResNet-18 للصور الصغيرة الواردة في القسم 7.4 (ونحفظها بالعلامة #@save من أجل الفصل 32 (بالإنجليزية)) ونحصي بايتات تدرجها \(S\) (وهي 45 MB بالصيغة fp32):

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:

نحسب أيضًا سلال التدرجات بالترتيب العكسي، بحدَّي 1 MiB و 25 MiB، في المتغير buckets، وهي السلال التي تحزمها DDP قبل إطلاق عمليات allreduce.

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

نعرّف الآن خطوة التدريب بتوازي البيانات على صور Fashion-MNIST بحجم \(64 \times 64\):

يغلف البرنامج TRAIN_DDP الشبكة resnet18 بالصنف DDP ويقيس زمن train_step في العمليات كلها (مع خيارين هما model.no_sync() وتحليل أداء النوى).

تنسخ الدالة setup النموذج ومجموعة البيانات على الشبكة 'data'، وتنفذ الدالة train_step تحديثًا مصرَّفًا بخوارزمية SGD على فهارس الدفعة المصغرة idx المقسمة إلى حصص.

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 فحص لخطوة واحدة

تحتوي شبكة ResNet-18، بخلاف شبكة LeNet، على تطبيع الدفعات (القسم 7.3)، وهو يطبّع كل قناة بمتوسط دفعتها المصغرة وتباينها. فحين تُقسم دفعة مصغرة من 256 مثالًا على وحدتي GPU، هل تطبّع كل وحدة بإحصاءات حصتها المؤلفة من 128 مثالًا (فتطابق تراكم التدرجات على دفعتين جزئيتين من 128 مثالًا على وحدة GPU واحدة)، أم تزامن الوحدتان إحصاءات شاملة للأمثلة الـ 256 عبر البطاقتين؟ لنختبر تحديث الوحدتين مقابل المرجعين كليهما على وحدة 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

تطبّع طريقة DDP في PyTorch افتراضيًا حصة كل وحدة GPU بإحصاءات محلية خاصة بالحصة، فتطابق النصفين المتراكمين بدقة نحو \(10^{-7}\) وتختلف عن إحصاءات الدفعة الكاملة ببضعة في المئة (التحويل إلى nn.SyncBatchNorm يزامن الإحصاءات الشاملة مقابل عمليات جماعية إضافية؛ التمرين 4).

لأن محور الدفعة مقسم إلى حصص على محور الشبكة 'data' في النمط Auto، يحسب مقسِّم XLA متوسطات تطبيع الدفعات وتبايناته على نحو شامل عبر الدفعة المصغرة كلها، فيطابق الخطوة ذات 256 مثالًا على وحدة GPU واحدة ويدرج عمليات allreduce صغيرة لإحصاءات تطبيع الدفعات الخاصة بكل قناة إلى جانب مخزني التدرجات المؤقتين الكبيرين:

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

تصريف train_step على شبكة الأجهزة متعددة وحدات GPU ثم تطبيق الدالة allreduce_megabytes يكشفان عن عمليتي allreduce كبيرتين للتدرجات (big، مع تسجيل المخزن المؤقت الأخير في last_bucket) إلى جانب عمليات allreduce الصغيرة الخاصة بإحصاءات تطبيع الدفعات لكل قناة:

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

نقيس الآن التناسب الضعيف (256 مثالًا لكل وحدة GPU) والتناسب القوي (512 مثالًا في المجموع) على وحدات GPU عددها \(k \in \{1, 2, 4\}\).

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

نقيس أولًا \(\beta_\textrm{link}\) على عملية allreduce مجردة حجمها 256 MB عبر مكتبة NCCL، ونقارن تنبؤين لزمن الاتصال المكشوف \(t_{\textrm{step}}(k) - t_{\textrm{step}}(1)\) في التناسب الضعيف:

  1. بلا تراكب: عملية allreduce الحلقية كلها، وحجمها \(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، ومنها نحسب exposed[k] لوحدات GPU عددها \(k \in \{2, 4\}\) وفق النموذجين: نموذج انعدام التراكب (\(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)

نقيس الآن أداء التناسب الضعيف عند 256 مثالًا لكل وحدة GPU (بالاستدعاء step_time(k, 256)) على وحدات GPU عددها \(k \in \{1, 2, 4\}\)، ونقارن الإنتاجية المقاسة وكفاءة التناسب والعبء الإضافي المكشوف 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 تستغرق عملية allreduce بلا تراكب حجمها 45 MB نحو 18 ms على وحدتي GPU ونحو 28 ms على أربع. وفي قياساتنا للتناسب الضعيف تحقق أربع وحدات GPU إنتاجية تبلغ \(3.1\text{--}3.3\times\) إنتاجية الوحدة الواحدة (كفاءة تناسب من 77% إلى 83%)، وهذا يطابق تنبؤ انعدام التراكب عن قرب ويقصر كثيرًا عن تنبؤ السلال بالتراكب الكامل.

في التناسب القوي (دفعة كلية ثابتة من 512 مثالًا، فتعالج كل واحدة من وحدات GPU وعددها \(k\) ما مقداره \(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) عملية allreduce لكل سلة تبدأ أثناء التمرير الخلفي، وأن (2) مكتبة NCCL تعمل بمعدلها في قياس الأداء المجرد، وأن (3) نوى حساب التمرير الخلفي لا تتباطأ حين تعمل NCCL إلى جانبها. تحليل أداء وحدة GPU 0 في ثلاثة إعدادات، هي وحدة GPU واحدة ووحدتا GPU بلا اتصال ووحدتا GPU مع الاتصال، يختبر الافتراضات الثلاثة كلها:

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

تشغيل profile_step عند \(b = 256\) مثالًا لكل وحدة GPU في الإعدادات الثلاثة، وهي وحدة GPU واحدة ووحدتا GPU بلا مزامنة للتدرجات ووحدتا GPU مع عملية allreduce، يفصل الزمن الفعلي للخطوة إلى زمن الحساب على الجهاز وزمن نوى 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 بلا اتصال الخطوة بالسرعة نفسها تمامًا التي تنجزها بها وحدة واحدة، وتعمل نوى NCCL من 20 إلى 22 ms (وهو ما يطابق قياس الأداء المجرد البالغ 18 ms). الذي يسقط هو الافتراض الثالث: حين تعمل NCCL بالتزامن مع التمرير الخلفي، تتباطأ نوى الحساب نفسها بمقدار يتراوح من 8 إلى 13 ms. ففي وحدات GPU التي لا تملك وصولًا من نظير إلى نظير (peer-to-peer) تنسخ NCCL البيانات عبر ذاكرة المضيف بنوى خاصة بها تعمل على معالجات SM (streaming multiprocessors) في وحدة GPU، فتشغل هذه النوى من تلك المعالجات ومن عرض نطاق الذاكرة ما كان التمرير الخلفي سيستخدمه لولاها.

تستطيع راية غير موثقة في NCCL (هي NCCL_SHM_USE_CUDA_MEMCPY=1، وتوجد في الإصدارات من NCCL 2.28 إلى NCCL 2.30) أن تحيل عمليات النسخ عبر ذاكرة المضيف إلى محركات النسخ بتقنية DMA في وحدة GPU، وذلك في قياسات الأداء المصغرة المجردة:

توقع الراية نفسها طريقة DDP في حالة جمود (deadlock) حين تتراكب عمليات allreduce فيها مع حساب التمرير الخلفي.

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)

على وحدات GPU في مراكز البيانات الموصولة عبر NVLink (من 450 إلى 900 GB/s في كل اتجاه، القسم 13.2.4.2) تستغرق عملية allreduce لشبكة ResNet-18، وحجمها 45 MB، أقل كثيرًا من ميلي ثانية وتحقق تناسبًا شبه خطي. لكن حتى مع التناسب المثالي يظل توازي البيانات ينسخ على كل بطاقة بايتات المعلَمات وحالة المحسن كلها وعددها \(16N\)؛ أما القسم 13.7 فيقسم هذه الحالة على وحدات GPU.

13.6.3 الملخص

يقود توازي البيانات في بيئة الإنتاج \(k\) وحدة GPU إما بعمليات مستقلة عددها \(k\) تتزامن عبر مكتبة NCCL، وإما ببرنامج واحد يقسمه المصرِّف، ويجمع التدرجات في سلال حجمها من 25 إلى 30 MiB كي تتراكب عمليات allreduce مع التمرير الخلفي. ويكشف فحص لخطوة واحدة مقابل مراجع على وحدة GPU واحدة هل يستخدم تطبيع الدفعات إحصاءات لكل حصة أم إحصاءات شاملة عبر عمليات جماعية إضافية. وعلى بطاقات RTX 4090 الأربع لدينا (وهي تتصل عبر ذاكرة المضيف بعرض نطاق للناقل مقداره 2.4 GB/s) تعطي أربع وحدات GPU إنتاجية تبلغ \(3.1\text{--}3.3\times\) إنتاجية وحدة GPU واحدة في التناسب الضعيف، ويبين تحليل أداء النوى أن التزاحم على معالجات SM الناتج عن نوى NCCL المارة بالمضيف يسترد معظم الزمن الذي يوفره تراكب الاتصال مع حساب التمرير الخلفي.

13.6.4 تمارين

  1. [code] تقسيم البيانات. في TRAIN_DDP تأخذ الرتبة \(r\) الشريحة التي تبدأ عند \((sk + r)b\) في الخطوة \(s\) من تبديل عشوائي مشترك.
    1. احذف rank من هذه الإزاحة كي تأخذ كل عملية الأمثلة نفسها وعددها \(b\). توقع كيف يتصرف step_time عند \(k = 2\) وكيف يتصرف التدرج المتوسط، ثم تحقق بطباعة مجموع اختباري للدفعة المصغرة في كل رتبة.
    2. أعد الإزاحة لكن أعط كل رتبة بذرة عشوائية مختلفة. أي خاصية لتقسيم الدفعة المصغرة تُفقد؟
    3. اقترح تحققًا صريحًا خفيف الكلفة في زمن التنفيذ يكشف حصص البيانات المتطابقة بين الرتب في الخطوة الأولى.
  2. استكمال التناسب الضعيف خارج المدى. افترض أن الخطوة على \(k\) وحدة GPU تستغرق زمن وحدة 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\) دفعة جزئية من 256 مثالًا لكل وحدة GPU (والاتصال في الدفعة الجزئية الأخيرة فقط)، أوجد أصغر \(a\) يرفع \(E(4)\) إلى 95%، واذكر كيف يتغير حجم الدفعة الكلية.
  3. [code] حجم السلة. ● نمذج تراكب السلال (الشكل 13.6.1) بافتراض أن تمريرًا خلفيًا مدته \(t_b\) يُخرج \(n\) سلة متساوية في الأزمنة \(i\,t_b/n\) (حيث \(i = 1, \ldots, n\))، وأن عملية allreduce لكل سلة تستغرق \(\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 من 1 MB إلى 100 MB عند \(k = 2\) وقارن الاتصال المكشوف المقاس بالنموذج.
  4. [code] تطبيع الدفعات المتزامن. ● أظهر الفحص لخطوة واحدة الوارد في القسم 13.6.1 أن طريقة DDP تطبّع كل حصة بإحصاءات محلية افتراضيًا.
    1. حوّل model في CHECK_DDP بالدالة nn.SyncBatchNorm.convert_sync_batchnorm قبل تغليفه بالصنف DDP وأعد الفحص. أي مرجع على وحدة GPU واحدة يطابقه الآن؟
    2. عُدّ العمليات الجماعية الإضافية التي يضيفها SyncBatchNorm في كل خطوة، وقس step_time عند \(k = 2\) و \(k = 4\)، واشرح لماذا يتجاوز زمنها حاصل ضرب حجمها بالبايتات في \(\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. أي قيم حدّية يجب أن تتبادلها وحدات GPU المتجاورة من أجل التفاف \(3 \times 3\)، وأي عملية جماعية تظهر في HLO المصرَّف؟
  2. استكمال التناسب الضعيف خارج المدى. افترض أن الخطوة على \(k\) وحدة GPU تستغرق زمن وحدة 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\) دفعة جزئية من 256 مثالًا لكل وحدة GPU (والاتصال في الدفعة الجزئية الأخيرة فقط)، أوجد أصغر \(a\) يرفع \(E(4)\) إلى 95%، واذكر كيف يتغير حجم الدفعة الكلية.
  3. [code] حجم السلة. ● نمذج تراكب السلال (الشكل 13.6.1) بافتراض أن تمريرًا خلفيًا مدته \(t_b\) يُخرج \(n\) سلة متساوية في الأزمنة \(i\,t_b/n\) (حيث \(i = 1, \ldots, n\))، وأن عملية allreduce لكل سلة تستغرق \(\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 في عمليات جديدة، وعُدّ عمليات allreduce للتدرجات الناتجة، وقارن الاتصال المكشوف المقاس بالنموذج.
  4. [code] إحصاءات تطبيع الدفعات. ● في ظل nnx.jit ومحاور شبكة من النوع Auto يحسب تطبيع الدفعات إحصاءات شاملة عبر وحدات GPU كلها.
    1. فسّر عمليات allreduce الصغيرة الـ 74 في allreduce_megabytes(compiled) انطلاقًا من عدد طبقات BatchNorm في resnet18 ومن التمريرين الأمامي والخلفي.
    2. استدع model.eval() قبل التصريف كي تستخدم BatchNorm المتوسطات المتحركة بدل إحصاءات الدفعة، وتحقق من أن عمليات allreduce الصغيرة تختفي، وقس كم تكلف من زمن الخطوة عند \(k = 1, 2, 4\).

النقاشات