13.7  Sharding the Training State

In Section 13.4, we saw that training with Adam in fp32 stores 16 bytes per parameter—four bytes each for the weight, its gradient, and Adam’s two moment estimates. For our 18-block, 1B-parameter GPT, that fixed state fills 15.1 GiB of a 24 GiB card before reading a single token, and data parallelism (Section 13.5, Section 13.6) replicates all 16 bytes on every GPU. If we double the depth of our GPT to 36 blocks (1.92B parameters, 28.6 GiB of state), data parallelism on four 24 GiB GPUs cannot train it any more than one GPU can.

Can \(k\) GPUs train a model that no single card can hold? They can, because a GPU needs the full weights of a block only while computing that block’s forward or backward pass, and it never needs the full gradient or full optimizer state at all. Each of the \(k\) GPUs can therefore store \(1/k\) of the weights, gradients, and optimizer moments, gather each block’s weights on the fly just before the block runs, and reduce-scatter each block’s gradients as soon as they are produced.

# 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

We first verify on a meta/shape-only device that the 36-block GPT’s \(16N\) bytes of training state exceed the 24 GiB capacity of a single RTX 4090:

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 Partitioning the Optimizer State, Gradients, and Weights

In standard data parallelism, all \(k\) GPUs hold identical copies of Adam’s moment estimates and perform identical optimizer updates. The ZeRO (Zero Redundancy Optimizer) family (Rajbhandari et al. 2020) eliminates this redundancy in three cumulative stages (Table 13.7.1):

  • ZeRO Stage 1 partitions only the optimizer state: each GPU holds Adam’s two moments for \(1/k\) of the parameters (\(8 + 8/k\) bytes/parameter). Instead of an allreduce (\(=\text{reduce-scatter} + \text{all-gather}\), Section 13.5.3), the GPUs reduce-scatter the gradients so each GPU receives the summed gradient for its \(1/k\) shard, updates its own parameters, and all-gathers the updated weights—moving the exact same bytes as data parallelism.
  • ZeRO Stage 2 also partitions the gradients (\(4 + 12/k\) bytes/parameter): as each gradient bucket fills during the backward pass, it is immediately reduce-scattered and the non-owned \(1 - 1/k\) gradient shards are freed, again at zero extra byte cost over data parallelism.
  • ZeRO Stage 3, or Fully Sharded Data Parallelism (FSDP) (Zhao et al. 2023), shards the weights as well (\(16/k\) bytes/parameter). Before a block runs in the forward or backward pass, an all-gather assembles its full weights; immediately after the block finishes, the non-owned weight shards are freed, and the block’s gradients are reduce-scattered (Figure 13.7.1).
Table 13.7.1: Training state per GPU at the end of the backward pass, with Adam in fp32 on \(k\) GPUs, and for the GPT with 36 blocks and 1.92 billion parameters on \(k = 2\).
each GPU holds weights gradients Adam state bytes per parameter GPT, \(k = 2\)
data parallelism all all all 16 28.6 GiB
ZeRO stage 1 all all \(1/k\) \(8 + 8/k\) 21.4 GiB
ZeRO stage 2 all \(1/k\) \(1/k\) \(4 + 12/k\) 17.9 GiB
ZeRO stage 3 (FSDP) \(1/k\) \(1/k\) \(1/k\) \(16/k\) 14.3 GiB
Figure 13.7.1: The life of one block’s weights under FSDP on one GPU. Between uses the block is sharded, and each GPU holds \(1/k\) of it; the other blocks stay sharded throughout. An all-gather assembles the whole block for its forward pass, after which it is released. A second all-gather assembles it for the backward pass, after which it is released again, and a reduce-scatter leaves each GPU with its share of the gradients.

Because FSDP performs two all-gathers (forward and backward) and one reduce-scatter of \(S = 4N\) bytes per step—three collective phases where a ring allreduce performs two—it moves \(1.5\times\) the communication volume of data parallelism. Table 13.7.2 summarizes the four primary collectives used across parallel training, and Figure 13.7.2 shows what each one moves between two GPUs.

Figure 13.7.2: The four collectives as data movement between two GPUs, before and after. GPU 0 starts with the chunks \(a_0, a_1\) and GPU 1 with \(b_0, b_1\); for all-gather, GPU \(g\) starts with only its own shard, chunk \(g\). Raw chunks are blue and sums are green.
Table 13.7.2: The collective operations behind data-parallel and sharded training.
collective what every GPU ends with where it appears
allreduce the full sum gradients in data parallelism
reduce-scatter one \(1/k\) shard of the sum gradients in ZeRO and FSDP
all-gather every shard, concatenated weights in ZeRO and FSDP
all-to-all a distinct slice from each GPU token routing in mixtures of experts (Section 11.7)

13.7.2 Memory and Communication

Let us predict the peak memory and step time of our 36-block GPT under FSDP on \(k = 2\) GPUs, with 2 sequences of 1,024 tokens per GPU and per-block activation checkpointing (Section 13.4.3).

  • Memory: The sharded training state takes \(16N/2 = 14.3\) GiB per GPU. Checkpointed activations take ~1 MiB/token (~2 GiB for 2,048 tokens), and one or two currently gathered blocks (~0.2 GB each) bring peak memory to at most ~17 GiB per GPU—comfortably below 24 GiB.

  • Communication: Each of the three collective phases sends \((k-1)S/k\) bytes per GPU, giving a total communication time of

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

    Notice the key scaling property of FSDP: adding more GPUs divides the state memory per GPU by \(k\), but the bytes each GPU sends per step grow from \(1.5S\) (at \(k = 2\)) toward \(3S\) (at large \(k\)). Only processing more tokens per GPU or using a faster interconnect reduces the communication share of a step.

We first measure \(\beta_\textrm{link}\) for an all-gather of 256 MiB across \(k = 2\) GPUs:

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)

Using the measured \(\beta_\textrm{link}\) and the RTX 4090’s 82.6 TFLOP/s tf32 peak (peak_flops), we can evaluate our paper predictions for per-GPU state memory (\(16N/k\)), communication time (\(3(k-1)S\beta_\textrm{link}/k\)), and checkpointed compute time (\(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

At ~2.2 GB/s bus bandwidth over host memory, moving \(1.5S = 11.5\) GB per step takes ~5 s, whereas the 2,048 tokens of arithmetic take only ~0.4 s. Because 0.4 s of compute cannot hide 5 s of communication, the step should take ~5 s.

13.7.3 Sharded Training on Two GPUs

Now we run the sharded 36-block GPT step on two GPUs, constructing the model so that no single GPU ever materializes the full 28.6 GiB state at once.

In PyTorch, we construct the model on the 'meta' device, wrap each checkpointed block and the top-level model with fully_shard from torch.distributed.fsdp, materialize only this rank’s shards via model.to_empty(device=device), and initialize them in place.

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()
'''

We now launch TRAIN_FSDP across \(k\) processes with d2l.torchrun and collect the peak allocated memory (peak_bytes), step durations (times), and NCCL communication time (comm) from rank 0:

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

In JAX, fsdp_sharding shards each parameter tensor along its first axis divisible by \(k\) (P('data')), and create applies this sharding constraint so each GPU initializes only its own shards of model and 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

Next, we wrap each block in nnx.remat for activation checkpointing, constrain every block’s activation output in loss_fn to stay batch-sharded (data) so XLA emits FSDP’s all-gathers and reduce-scatters automatically, and donate model and opt in train_step so updated state overwrites the old shards in place:

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

Before running the step, we compile train_step on a batch-sharded token batch X of shape \((kb, T)\) and query compiled.memory_analysis() to check the per-GPU footprint of donated state and temporary buffers:

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

To verify that XLA emitted the expected FSDP collectives, collective_megabytes parses the compiled HLO text and totals the result bytes of each collective operation per 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)

Tallying the collectives in compiled confirms that all-gather (twice per step) and reduce-scatter (once per step) move the predicted byte volumes:

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

Now we warm up train_step, time three repetitions, and profile the step to record NCCL communication time (comm) and peak device memory (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']

Finally, we report the measured per-GPU peak memory, median step duration, and time spent in NCCL communication kernels on GPU 0:

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

Both GPUs hold the 36-block model at a peak of ~16 GiB per card (under our 17 GiB bound), and each step takes ~5.5 s, with GPU 0 spending over 90% of the step in NCCL communication kernels—within a sixth of our 5 s paper prediction. Over NVLink 5 (900 GB/s per direction), the same 11.5 GB of collectives takes only ~13 ms, less than a thirtieth of the 0.4 s compute time.

This comparison also shows when to shard: a model whose training state fits on a single GPU alongside a reasonable micro-batch (such as our 18-block GPT) trains much faster with data parallelism and gradient accumulation (which communicates once per global step) than with FSDP over PCIe (which re-gathers the weights twice on every micro-batch).

13.7.4 Summary

Data parallelism replicates all \(16N\) bytes of fp32 Adam state on every GPU. ZeRO partitions this state across \(k\) GPUs: Stage 1 shards the optimizer moments (\(8 + 8/k\) bytes/parameter) and Stage 2 also shards the gradients (\(4 + 12/k\) bytes/parameter), both moving the exact same \(2(k-1)S/k\) bytes per step as a ring allreduce. Stage 3 (FSDP) shards the weights as well (\(16/k\) bytes/parameter), gathering each block’s weights for the forward and backward pass and reduce-scattering gradients at \(1.5\times\) the communication volume of data parallelism (\(3(k-1)S/k\) bytes per GPU). Sharding enables two 24 GiB GPUs to train a 36-block GPT whose 28.6 GiB state fits on neither card alone.

13.7.5 Exercises

  1. Cost of sharding. ● Count communication per GPU and step in units of \(S = 4N\), the bytes of one full set of fp32 weights or gradients.
    1. A variant of ZeRO Stage 3 keeps every gathered block in memory from its forward pass until its backward pass finishes. Which collective does this eliminate, and how much memory saving from Table 13.7.1 does it give up?
    2. Mixed-precision FSDP all-gathers weights in bf16 and reduce-scatters gradients in bf16 while keeping each GPU’s master weight and Adam shards in fp32. Compare its bytes transferred per step with fp32 data parallelism, and its memory per parameter with the last row of Table 13.7.1.
    3. For the 36-block GPT on \(k = 2\) GPUs at the measured \(\beta_\textrm{link}\), how many tokens per GPU would a step need for checkpointed compute (\(8N\) FLOPs/token at 83 TFLOP/s) to match the communication time Equation 13.7.1? Do those activations fit on the card, and why does gradient accumulation not help when FSDP re-gathers weights on every micro-batch?
  2. [extended] Sharded optimizer state. ● Implement ZeRO Stage 1 (Rajbhandari et al. 2020) by hand starting from TRAIN_DDP (Section 13.6) with torch.optim.Adam.
    1. Partition the parameter tensors across ranks so each rank owns roughly \(1/k\) of the parameters and runs Adam only on its owned tensors, then broadcast each updated tensor from its owner with dist.broadcast. Verify that the parameters match full DDP Adam after several steps, and compare with torch.distributed.optim.ZeroRedundancyOptimizer.
    2. Measure allocated and peak GPU memory at \(k = 2\) and \(k = 4\) with and without sharding, and compare the total bytes sent by DDP allreduce plus owner broadcasts against Stage 1’s reduce-scatter plus all-gather.
  3. [code] Tensor versus data parallelism. ● Consider the MLP block \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\) with \(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), and \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\) across \(k\) devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al. 2019)) splits \(\mathbf{W}_1\) column-wise and \(\mathbf{W}_2\) row-wise.
    1. Show that each device can compute a partial \(n \times d\) output without communication and that summing the \(k\) partial outputs gives \(\mathbf{Y}\). Which collective does the forward pass need, and which does the backward pass need for \(\nabla_{\mathbf{X}}\)?
    2. Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count \(n\) below which tensor parallelism sends less data. Why is tensor parallelism nevertheless restricted to fast intra-node NVLink domains?
    3. Using parallelize_module with ColwiseParallel() and RowwiseParallel() on a 1D DeviceMesh, count the forward and backward collectives with CommDebugMode.
  4. Prefetching the next block. In the forward pass under FSDP, let \(g\) be the all-gather time of one block and \(c\) its compute time. Without overlap, \(L\) blocks take \(L(g + c)\); prefetching issues the all-gather of block \(l + 1\) while block \(l\) computes.
    1. Show that prefetching reduces the forward pass time to \(g + (L-1)\max(g, c) + c\), and explain why no schedule can do better than \(L\max(g, c)\).
    2. Evaluate \(g\) and \(c\) for one block of the 36-block GPT (\(50\)M parameters, 2,048 tokens/GPU, 83 TFLOP/s) on our PCIe link versus NVLink 5 (900 GB/s), and state how much prefetching saves on each interconnect.
  1. Cost of sharding. ● Count communication per GPU and step in units of \(S = 4N\), the bytes of one full set of fp32 weights or gradients.
    1. A variant of ZeRO Stage 3 keeps every gathered block in memory from its forward pass until its backward pass finishes. Which collective does this eliminate, and how much memory saving from Table 13.7.1 does it give up?
    2. Mixed-precision FSDP all-gathers weights in bf16 and reduce-scatters gradients in bf16 while keeping each GPU’s master weight and Adam shards in fp32. Compare its bytes transferred per step with fp32 data parallelism, and its memory per parameter with the last row of Table 13.7.1.
    3. For the 36-block GPT on \(k = 2\) GPUs at the measured \(\beta_\textrm{link}\), how many tokens per GPU would a step need for checkpointed compute (\(8N\) FLOPs/token at 83 TFLOP/s) to match the communication time Equation 13.7.1? Do those activations fit on the card, and why does gradient accumulation not help when FSDP re-gathers weights on every micro-batch?
  2. [extended] Sharded optimizer state. ● Implement ZeRO Stage 1 (Rajbhandari et al. 2020) declaratively starting from train_step (Section 13.6) with optax.adam. Keep the model parameters replicated (P()), and place the leaves of nnx.state(opt) with fsdp_sharding.
    1. Ensure parameters remain replicated at the end of train_step via jax.sharding.reshard if needed, and verify that multi-step parameter updates match replicated Adam.
    2. Inspect the compiled step with collective_megabytes and compare its collectives and live/peak memory at \(k = 2\) and \(k = 4\) against Table 13.7.1.
  3. [code] Tensor versus data parallelism. ● Consider the MLP block \(\mathbf{Y} = \phi(\mathbf{X}\mathbf{W}_1)\mathbf{W}_2\) with \(\mathbf{X} \in \mathbb{R}^{n \times d}\), \(\mathbf{W}_1 \in \mathbb{R}^{d \times 4d}\), and \(\mathbf{W}_2 \in \mathbb{R}^{4d \times d}\) across \(k\) devices. Tensor parallelism (Figure 13.5.1, (Shoeybi et al. 2019)) splits \(\mathbf{W}_1\) column-wise (P(None, 'data')) and \(\mathbf{W}_2\) row-wise (P('data', None)).
    1. Show that each device can compute a partial \(n \times d\) output without communication and that summing the \(k\) partial outputs gives \(\mathbf{Y}\). Which collective does the forward pass need, and which does the backward pass need for \(\nabla_{\mathbf{X}}\)?
    2. Compare the values sent per device and step under tensor parallelism versus data parallelism, and find the token count \(n\) below which tensor parallelism sends less data. Why is tensor parallelism nevertheless restricted to fast intra-node NVLink domains?
    3. Place \(\mathbf{W}_1\) with P(None, 'data'), \(\mathbf{W}_2\) with P('data', None), and \(\mathbf{X}\) replicated on an Auto mesh, jit the forward and backward pass, and inspect the emitted collectives.
  4. Prefetching the next block. In the forward pass under FSDP, let \(g\) be the all-gather time of one block and \(c\) its compute time. Without overlap, \(L\) blocks take \(L(g + c)\); prefetching issues the all-gather of block \(l + 1\) while block \(l\) computes.
    1. Show that prefetching reduces the forward pass time to \(g + (L-1)\max(g, c) + c\), and explain why no schedule can do better than \(L\max(g, c)\).
    2. Evaluate \(g\) and \(c\) for one block of the 36-block GPT (\(50\)M parameters, 2,048 tokens/GPU, 83 TFLOP/s) on our PCIe link versus NVLink 5 (900 GB/s), and state how much prefetching saves on each interconnect.

Discussions

Discussions