5.7 GPUs, Devices, and Memory
Since Section 2.4, our Trainer has accepted a num_gpus argument
and politely ignored it. For the tiny models of earlier chapters that hardly
mattered, since CPU training finished in seconds. Once models scale up,
however, device placement makes the difference between seconds and hours: a
modern desktop GPU multiplies two matrices in under 2
milliseconds, whereas a CPU needs a tenth of a second or more (as we benchmark
in Section 5.7.2.1). That raw speed comes with a strict hardware
constraint: the GPU has its own dedicated memory (say 24 GB on a desktop card), and
every tensor it operates on must reside there.
Will a target model even fit? Our running 8-billion-parameter model needs 16 GB for its weights in bf16, which fits easily for inference. Training it with Adam in fp32, however, requires 128 GB of static state (Section 5.2) before storing a single activation, far more than any single 24 GB or 80 GB card. Whether a model fits on a device, and whether the GPU stays busy computing or stalls waiting for data, comes down to where every tensor lives and how many bytes it consumes.
In this section, we answer three core questions: how tensors and models are
placed on and copied between CPUs and GPUs; how asynchronous GPU execution
works (and how to benchmark GPU kernels accurately); and what actually fills GPU
memory during training, including how activation checkpointing trades extra
compute for dramatic memory savings. We then wire everything into the
device-aware Trainer used throughout the rest of the book. Whereas
Section 5.2 and Section 5.5 accounted for bytes per
parameter and per number, here we put those bytes onto real hardware (deferring
multi-GPU training to Chapter 13). Every code cell degrades
gracefully to CPU if no GPU is available, confirming correctness even if timings
require a GPU.
import time
from torch.utils.checkpoint import checkpointtorch.set_float32_matmul_precision('high') # allow tf32 in fp32 matmuls5.7.1 Devices and Placement#
5.7.1.1 Device Objects#
Every tensor lives on a specific device: either the CPU paired with host RAM,
or an individual GPU paired with its onboard memory. Running nvidia-smi in a
terminal lists every NVIDIA GPU on your machine, its total and occupied memory,
and active processes. While each framework names devices slightly differently,
all four follow one governing principle: an operation executes on a single
device, so all of its operands must live on that device.
torch.device('cpu') and torch.device(f'cuda:{i}') denote the CPU and GPU .
We wrap device lookup in three small helpers that the rest of the book imports: one for CPU, one for GPU , and one that counts available GPUs.
def cpu():
"""Get the CPU device."""
return torch.device('cpu')
def gpu(i=0):
"""Get a GPU device."""
return torch.device(f'cuda:{i}')
def num_gpus():
"""Get the number of available GPUs."""
return torch.cuda.device_count()Constructing a device object always succeeds; hardware existence is checked only when a tensor is placed on it.
Building on num_gpus, we define two fallback helpers that select a GPU when
present and fall back to CPU otherwise, allowing identical notebook code to run
unchanged on both laptops and GPU servers.
def try_gpu(i=0):
"""Return gpu(i) if exists, otherwise return cpu()."""
if num_gpus() >= i + 1:
return gpu(i)
return cpu()
def try_all_gpus():
"""Return all available GPUs, or [cpu(),] if no GPU exists."""
devices = [gpu(i) for i in range(num_gpus())]
return devices if devices else [cpu()]
try_gpu(), try_gpu(10), try_all_gpus()(device(type='cuda', index=0),
device(type='cpu'),
[device(type='cuda', index=0), device(type='cuda', index=1)])
Other accelerators, such as Apple-silicon GPUs (mps) and Google TPUs, use their
own device identifiers, though the placement principles below apply equally to
all of them. Throughout this book we focus on CPUs and CUDA GPUs.
5.7.1.2 Arrays on Devices#
Every tensor exposes its location via its device attribute:
PyTorch tensors default to the CPU unless device= is passed.
Allocating directly on the target device avoids an extra CPU-to-GPU copy.
Below we place X on the first GPU and Y on the second GPU (falling back to CPU
when fewer than two GPUs are present) and try adding them:
X = torch.ones(2, 3, device=try_gpu())
Y = torch.rand(2, 3, device=try_gpu(1))
try:
print(X + Y)
except RuntimeError as e:
print(str(e).split(', but')[0])Expected all tensors to be on the same device
Adding tensors on different devices raises an error immediately, preventing accidental cross-device transfers.
5.7.1.3 Copying Between Devices#
Moving tensors across devices is vastly slower than computing on them
(Section 5.7.2.1 measures the gap), so silently copying
mismatched operands would hide severe performance bugs. Instead, we copy X
explicitly onto Y's device (Figure 5.7.1) before adding them.
X lives on GPU 0 and Y on GPU 1. The copy Z of X on GPU 1 (dashed) lets Y + Z run entirely on GPU 1.
Z = X.to(try_gpu(1))
(Y + Z).devicedevice(type='cuda', index=1)
Now the sum runs and lands on the second GPU alongside both operands. The practical rule is simple: transfer data once at the boundary of your computation (moving a tensor to a device it already occupies is essentially a no-op) and keep every inner-loop operation on that single device.
5.7.1.4 Models on a Device#
Because a forward pass combines inputs with model parameters, the entire model must live on the same device as its minibatches. Thanks to the module tree from Section 5.1, every framework moves or initializes all parameters in one call.
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())
net(X)tensor([[-0.2254],
[-0.2254]], device='cuda:0', grad_fn=<AddmmBackward0>)
With inputs and parameters colocated on the same device, the forward pass runs there and returns its output on that device as well.
Keep two placement rules in mind: move or initialize the model on its target
device before constructing the optimizer (so optimizer moments are allocated
on the same device), and allocate any new tensors created inside forward on
X.device rather than defaulting to the CPU.
5.7.2 Asynchronous Execution#
5.7.2.1 The Execution Queue#
A GPU does not execute operations synchronously when Python invokes them. Instead, Python enqueues each kernel launch onto the device's command queue and returns immediately, letting the CPU prepare subsequent work while the GPU crunches through its queue in order. This pipelining hides Python overhead, but it comes with a crucial timing catch: measuring how long a Python loop takes measures enqueueing, not execution. Below we enqueue 32 products of matrices and check the wall clock twice: right after Python finishes queuing them, and again once the device finishes computing them.
if torch.cuda.is_available():
A = torch.randn(4096, 4096, device=gpu())
A @ A
torch.cuda.synchronize() # Warm up and wait
t = time.perf_counter()
for _ in range(32):
B = A @ A
print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec')
torch.cuda.synchronize()
print(f'time until they all finished: {time.perf_counter() - t:.4f} sec')
else:
print('No CUDA device: operations on the CPU run synchronously.')time to queue 32 matrix products: 0.0010 sec
time until they all finished: 0.0535 sec
GPU kernels run asynchronously while CPU operations run synchronously; torch.cuda.synchronize() waits for all queued GPU work to finish.
Python finishes enqueuing all 32 matrix multiplications in a tiny fraction of
the actual compute time. When does the CPU actually block and wait? Only when
Python needs a concrete value back on the host—printing a tensor, converting
a scalar to a Python float, converting to NumPy, or branching on a tensor in an if statement.
Every such synchronization point stalls Python until the GPU drains its queue
up to that value, leaving the GPU idle while Python catches up
(Figure 5.7.2). Logging the loss as a Python number after every minibatch
inserts a synchronization bubble on every step, which is why our Trainer keeps
losses on-device inside a d2l.Averager and converts them to Python floats only
once per epoch (Section 2.4).
Python queues operations op1 through op4 and continues while the GPU runs them in order. Reading the loss as a Python number is a synchronization point: the CPU blocks until the GPU has drained its queue; Python then resumes, and the GPU idles until it receives more work.
Asynchronous dispatch also dictates four rules for trustworthy GPU benchmarks:
(1) run warm-up calls first to exclude one-time allocation, library setup, and
JIT compilation; (2) synchronize the device both immediately before starting
the timer and immediately before stopping it; (3) average over multiple
repetitions; and (4) use time.perf_counter for sub-millisecond resolution.
(The demonstration cell above warmed up and synchronized but reported the
32-product total; our Benchmark helper below automates all four rules for this
and later chapters.)
class Benchmark:
"""Time a callable: warmup, then device-synchronized average seconds.
`devices` lists the GPUs to wait for, by default the current one."""
def __init__(self, f, warmup=3, repeats=10, desc='time', devices=None):
def wait(): # CUDA runs asynchronously; the CPU does not
if torch.cuda.is_available():
for device in devices or [None]:
torch.cuda.synchronize(device)
self.desc = desc
for _ in range(warmup):
f()
wait()
t0 = time.perf_counter()
for _ in range(repeats):
f()
wait()
self.time = (time.perf_counter() - t0) / repeats
def __repr__(self):
return f'{self.desc}: {1000 * self.time:.2f} ms/call'We put Benchmark to work immediately on two claims from earlier: how much
faster a GPU is than a CPU on large matrix multiplications, and how expensive
host-to-device transfers are relative to compute. Below we time a
product on CPU (fp32), on GPU in tf32 (Section 5.5)
and 16-bit precision, alongside copying a single matrix from
CPU RAM to the GPU.
if torch.cuda.is_available():
A_cpu = A.cpu() # The same matrix in main memory
A16 = A.bfloat16()
print(Benchmark(lambda: A_cpu @ A_cpu, warmup=1, repeats=3,
desc='product on the CPU, fp32'))
print(Benchmark(lambda: A @ A, desc='product on the GPU, tf32'))
print(Benchmark(lambda: A16 @ A16, desc='product on the GPU, bf16'))
print(Benchmark(lambda: A_cpu.to(gpu()),
desc='copy from CPU to the GPU'))
else:
print('No CUDA device: there is nothing to compare the CPU with.')product on the CPU, fp32: 1423.37 ms/call
product on the GPU, tf32: 1.68 ms/call
product on the GPU, bf16: 0.91 ms/call
copy from CPU to the GPU: 5.32 ms/call
On a modern GPU, the product finishes in under 2 ms, whereas the CPU requires about 100 ms to 2 s (roughly a to speedup depending on CPU core count). Dropping to 16-bit precision cuts GPU time roughly in half again, delivering the tensor-core speedup promised in Section 5.5.
Pay special attention to the final line: merely copying the matrix from CPU memory to the GPU takes three to six times longer than multiplying it once it arrives, even though the multiplication executes 4096 multiply-adds per copied element. Standard host copies first stage data through pinned (page-locked) host memory so the GPU's DMA engine can pull it directly; pre-pinning batches eliminates that extra copy and allows transfers to overlap with compute (Section 13.2).
5.7.3 GPU Memory#
5.7.3.1 Three Views of Memory#
Ask how much GPU memory a training script uses and you can get three different
numbers, depending on which layer of the stack you query. Requesting memory
directly from the CUDA driver is slow, so frameworks run an internal caching
allocator that grabs large slabs from the driver and sub-allocates them to
tensors, retaining freed slabs for reuse rather than releasing them immediately.
This creates three nested memory views (Figure 5.7.3): the bytes
currently occupied by live tensors, the larger pool reserved by the framework's
allocator, and the total memory assigned by the CUDA driver to the process (the
figure displayed by nvidia-smi).
The three memory views nest: the driver's allocation to the process, which nvidia-smi reports, contains the allocator's reserved blocks, which contain the live arrays.
torch.cuda.memory_allocated() reports live tensor bytes, while torch.cuda.memory_reserved() reports the caching allocator's pool.
We allocate a 1 GiB float32 tensor and immediately delete it to watch these counters respond:
if torch.cuda.is_available():
def report(tag):
print(f'{tag}: {torch.cuda.memory_allocated() / 2**20:7.1f} MiB '
f'allocated, {torch.cuda.memory_reserved() / 2**20:7.1f} MiB '
'reserved')
big = torch.zeros(256, 1024, 1024, device=gpu()) # 1 GiB of float32
report('after creating big')
del big
report('after deleting it ')
else:
print('No CUDA device: both counters read 0 on the CPU.')after creating big: 1192.1 MiB allocated, 1302.0 MiB reserved
after deleting it : 168.1 MiB allocated, 1302.0 MiB reserved
Deleting big frees 1 GiB of live tensors, yet the framework's caching
allocator retains the freed 1 GiB slab in its reserved pool so nvidia-smi
does not budge. (Never force slabs back to the CUDA driver inside a training
loop, as this adds slow driver allocations on every step.)
The outermost driver view sets the hard out-of-memory ceiling, since the driver
cannot hand out more RAM than the card physically holds. To diagnose where
memory goes inside our code, we inspect live-byte counters, especially the peak
memory reached during a call, which determines whether a step succeeds or
crashes with out-of-memory (OOM).
torch.cuda.reset_peak_memory_stats() and torch.cuda.max_memory_allocated() measure the exact peak live memory delta of any call:
def peak_memory(f, *args):
"""Extra peak GPU memory allocated by f(*args), in bytes."""
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
base = torch.cuda.memory_allocated()
f(*args)
torch.cuda.synchronize()
return torch.cuda.max_memory_allocated() - base5.7.3.2 Memory During Training#
In Section 5.2, we established the static memory floor for fp32 Adam training: bytes for parameters ( weights, gradients, and Adam moments). During an actual training step, a fourth term joins them: activations. Backpropagation must retain intermediate forward-pass outputs until the backward pass consumes them, and unlike the static , activation memory scales linearly with minibatch size and layer width. We can calculate it before measuring: consider a three-hidden-layer MLP of width 4096 taking 1024-dimensional inputs ( parameters, so MiB) at minibatch size 4096. The three hidden-layer outputs are each fp32 tensors of 64 MiB (192 MiB in total), already a third larger than the weights themselves.
if torch.cuda.is_available():
start = torch.cuda.memory_allocated()
def allocated(): # Memory in use beyond that at the start of the cell
return f'{(torch.cuda.memory_allocated() - start) / 2**20:7.1f} MiB'
net = nn.Sequential(nn.Linear(1024, 4096), nn.ReLU(),
nn.Linear(4096, 4096), nn.ReLU(),
nn.Linear(4096, 4096), nn.ReLU(),
nn.Linear(4096, 10)).to(gpu())
optimizer = torch.optim.Adam(net.parameters())
X = torch.randn(4096, 1024, device=gpu())
y = torch.randint(0, 10, (4096,), device=gpu())
print('weights ', allocated())
loss = F.cross_entropy(net(X), y)
print('+ activations ', allocated())
loss.backward()
print('+ gradients ', allocated())
optimizer.step()
print('+ optimizer state ', allocated())
else:
print('No CUDA device: run this cell on a GPU to see the four readings.')weights 160.2 MiB
+ activations 353.4 MiB
+ gradients 313.6 MiB
+ optimizer state 602.0 MiB
The readings trace the exact lifecycle of a training step: weights ( bytes) plus inputs sit in memory first; the forward pass adds the stored activations (~192 MiB, exceeding the weights); the backward pass consumes and frees those activations while materializing gradients (); and the first optimizer step allocates Adam's two moments (). Figure 5.7.4 draws the four stages without the 16 MiB input batch. From step two onward, memory rises and falls within every step: the forward pass stores the activations on top of the weights and Adam's moments, and the backward pass replaces them with gradients. The peak is at most the static plus the activations. It is lower, by up to , when the loop frees the old gradients before the next forward pass. Shrinking the minibatch size is the quickest lever when activations push memory over the edge, since it cuts activation footprint without altering the architecture. By contrast, if memory climbs steadily from step to step, look for a leak keeping old computation graphs alive, the classic culprit being appending raw loss tensors to a Python list without detaching them first.
optimizer.zero_grad() frees the gradients by default (set_to_none=True), so a loop that calls it before the forward pass holds bytes, not , while the activations are stored.
Memory in use after each stage of the first training step, for the MLP of width 4096 at minibatch size 4096. The input batch is not counted. The forward pass adds the three stored activations to the weights (). The backward pass frees the activations and leaves the gradients (). The optimizer step adds Adam's two moments ().
5.7.3.3 Activation Checkpointing#
There is a second, architectural lever for activation memory. Standard backpropagation stores every layer's intermediate output only to read it once on the backward sweep. Activation checkpointing (also called gradient checkpointing or rematerialization, (Chen et al., 2016)) discards most intermediate activations during the forward pass, retaining only the inputs at the boundaries of chosen segments, and recomputes each segment's internal activations on the fly during the backward pass. (Despite the shared word, this in-memory technique is unrelated to the disk checkpoints of Section 5.6.)
Partitioning uniform layers into segments of layers stores only segment boundaries plus live activations inside the active segment (about tensors instead of ). Choosing drops peak activation memory from down to . The trade-off is one extra forward pass per segment during backpropagation (Figure 5.7.5). Since a linear layer's backward pass computes two matrix products (input gradient and weight gradient) while its forward pass computes one, adding an extra forward pass increases total step compute from roughly 3 forward-pass equivalents to 4: about a 33% rough upper bound, depending on hardware and layer mix.
(a) Standard backpropagation stores the activations of every layer. (b) Checkpointing stores only the inputs of the segments (filled) and recomputes the activations inside each segment (open) during the backward pass. With layers in segments of layers, stored activations fall from to at the cost of one extra forward pass.
Activation checkpointing shines on deep stacks of identical blocks, such as our
residual MLP (Section 5.1) and modern transformers. Below
we define ResidualBlock with weights and zero biases,
along with a run_stack helper that groups blocks into
segments with optional checkpointing.
class ResidualBlock(nn.Module):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential(
nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
nn.Linear(num_hiddens, num_hiddens))
for layer in self.body[0], self.body[2]:
nn.init.normal_(layer.weight, std=0.01)
nn.init.zeros_(layer.bias)
def forward(self, X):
return X + self.body(X)
def run_stack(blocks, X, use_checkpoint=False, segment_size=4):
for start in range(0, len(blocks), segment_size):
stop = min(start + segment_size, len(blocks))
# Bind this segment's range now: the backward pass calls segment
# again after the loop has moved on
def segment(X, start=start, stop=stop):
for i in range(start, stop):
X = blocks[i](X)
return X
X = checkpoint(segment, X, use_reentrant=False) \
if use_checkpoint else segment(X)
return Xtorch.utils.checkpoint.checkpoint(segment, X, use_reentrant=False) discards intermediate activations inside segment, saves and restores RNG state (keeping dropout consistent), and reruns segment during backward().
First, a sanity check: recomputing activations must never alter the math. We verify on an eight-block stack split into two checkpointed segments that all gradients match standard backpropagation.
blocks = nn.Sequential(*[ResidualBlock(64) for _ in range(8)])
X = torch.randn(32, 64)
def stack_grads(use_checkpoint):
blocks.zero_grad(set_to_none=True)
run_stack(blocks, X, use_checkpoint).sum().backward()
return [p.grad.clone() for p in blocks.parameters()]
for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
assert torch.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')checkpointed gradients match the ordinary ones
That correctness check runs anywhere; to measure the memory–compute trade-off,
we move to a GPU with a deeper stack of 16 blocks (width 1024, batch size 8192)
grouped into four-block segments, reporting both step memory (peak memory
beyond parameters and inputs) and wall-clock time via Benchmark.
if torch.cuda.is_available():
blocks = nn.Sequential(*[ResidualBlock(1024) for _ in range(16)]).to(gpu())
X = torch.randn(8192, 1024, device=gpu())
def step(use_checkpoint):
blocks.zero_grad(set_to_none=True)
run_stack(blocks, X, use_checkpoint).sum().backward()
for use_checkpoint in (False, True):
timing = Benchmark(lambda: step(use_checkpoint))
blocks.zero_grad(set_to_none=True) # Gradients count as step memory
peak = peak_memory(step, use_checkpoint)
print(f'checkpointing={use_checkpoint!s:5} step memory '
f'{peak / 2**20:5.0f} MiB, {timing.time * 1e3:5.1f} ms per step')
else:
print('No CUDA device: the peak-memory comparison needs a GPU.')checkpointing=False step memory 1096 MiB, 25.5 ms per step
checkpointing=True step memory 452 MiB, 32.3 ms per step
Without checkpointing, the backward pass holds activations for all 16 blocks at once; grouping into four-block segments keeps only four segment boundaries plus one active segment, cutting step memory from roughly 1.1 GiB down to 0.4–0.5 GiB for roughly a quarter more compute time (within our back-of-the-envelope 33% bound). That favorable exchange makes activation checkpointing standard practice when training large transformers and deep vision models.
5.7.4 Device-Aware Trainer#
Now we can finally wire num_gpus into d2l.Trainer. Putting our rules into
practice takes just two steps: place the model parameters on the target device
before training begins, and move each minibatch to that device at the start of
every step.
@d2l.add_to_class(d2l.Trainer)
def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
self.save_hyperparameters()
self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')
@d2l.add_to_class(d2l.Trainer)
def prepare_batch(self, batch):
if self.gpus:
batch = [d2l.to(a, self.gpus[0]) for a in batch]
return batch
@d2l.add_to_class(d2l.Trainer)
def prepare_model(self, model):
self.model = model
if self.gpus:
model.to(self.gpus[0])
# Pick convolution algorithms by timing, unless determinism is wanted
torch.backends.cudnn.benchmark = not (
torch.are_deterministic_algorithms_enabled()
or torch.backends.cudnn.deterministic)
# Lazy parameters get their shapes from a dry pass on the device, then
# the model's weight_init, if it has one, before the optimizer exists
if any(isinstance(p, nn.parameter.UninitializedParameter)
for p in model.parameters()):
loader = (self.train_dataloader if self.train_dataloader is not None
else self.val_dataloader) # `evaluate` has no training data
batch = self.prepare_batch(next(iter(loader)))
model.apply_init(batch[:-1], getattr(model, 'weight_init', None))Using min(num_gpus, d2l.num_gpus()) treats num_gpus as an upper bound rather
than a hard requirement: on CPU-only machines, self.gpus is empty and training
runs seamlessly on the CPU, the exact fallback behind every Trainer(num_gpus=1)
call throughout the rest of the book.
How much faster does a GPU actually train a small model? While our matrix product sped up by roughly or more, an end-to-end training loop includes data loading, Python dispatch, and smaller layers. Below we measure a Fashion-MNIST classifier built from two 256-wide residual blocks (Section 5.7.3.3) with weights and zero biases.
class ResMLPClassifier(d2l.Classifier):
def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(
nn.Flatten(), nn.Linear(784, num_hiddens), nn.ReLU(),
*[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
nn.Linear(num_hiddens, 10))
for layer in self.net[1], self.net[-1]: # The blocks set their own
nn.init.normal_(layer.weight, std=0.01)
nn.init.zeros_(layer.bias)We compare one post-warmup epoch on Fashion-MNIST with num_gpus=0 versus
num_gpus=1:
data = d2l.FashionMNIST(batch_size=256)
def epoch_time(num_gpus):
model = ResMLPClassifier()
trainer = d2l.Trainer(max_epochs=1, num_gpus=num_gpus)
trainer.board.display = False
trainer.fit(model, data) # The first epoch warms up
return Benchmark(trainer.fit_epoch, warmup=0, repeats=1).time
for gpus in (0, 1):
print(f'num_gpus={gpus}: {epoch_time(num_gpus=gpus):.1f} sec per epoch')num_gpus=0: 2.9 sec per epoch
num_gpus=1: 1.1 sec per epoch
The speedup is a useful reality check: on this tiny Fashion-MNIST network, a GPU epoch runs at most a few times faster than CPU, nowhere near the gain on matrix multiplies. Here the largest matrix is only , leaving the GPU vastly underutilized while data loading and kernel-launch overhead dominate the clock. GPUs pay off once large convolutions, attention heads, and wide linear layers dominate the workload, as they do starting in the next chapter.
From a memory perspective, this small SGD model fits comfortably with gigabytes
to spare. Return to our 8-billion-parameter model, however: shrinking batch size
and enabling activation checkpointing tame activation memory, yet the 128 GB
static floor of fp32 weights, gradients, and Adam moments remains untouched, and
remember that Trainer cannot warn you ahead of time before hitting OOM.
Back-of-the-envelope memory budgeting remains essential, and scaling past a
single device's memory brings us to multi-GPU parallelism in
Chapter 13.
5.7.5 Summary#
Every tensor and model parameter resides on a specific device, and every
operation requires its operands on the same device. Because host–device
transfers are far slower than GPU compute, place models once upfront, transfer
batches at step boundaries, and keep inner loops on-device. GPUs execute
asynchronously from a command queue, meaning Python stalls only at
synchronization points (such as converting a scalar to a Python float, or NumPy
conversions) and reliable
benchmarks require warm-up, explicit synchronization, and repeated trials.
Training memory consists of static model/optimizer state plus batch-dependent
activations; activation checkpointing cuts activation memory from to
at the cost of roughly one extra forward pass. Finally, our
device-aware Trainer automates single-GPU placement while falling back cleanly
to CPU when no GPU is present.
5.7.6 Exercises#
-
[code] Peak memory. Take a four-layer MLP with widths 1024, 4096, 4096, 4096 and 10 outputs, trained with Adam, as in Section 5.7.3.2. Using the accounting of that subsection, predict the peak memory of one training step at batch sizes 64, 256, and 1024, counting weights, gradients, optimizer state, and the activations the backward pass keeps. Then measure the peak on a GPU. Where does the prediction break down, and what did it omit?
-
Checkpointing arithmetic. Work out the schedule of Figure 5.7.5 on paper for a stack of sixteen
ResidualBlocks of width 1024 at batch size 8192.- Name the arrays inside one block that the backward pass must keep, and count their entries.
- Compute the activation memory held at the peak of the backward pass without checkpointing and with segments of one, two, four, and eight blocks. State how much forward computation each schedule repeats.
- Which segment size would you choose here, and how does it relate to the rule of segments of about layers in Section 5.7.3.3?
-
[code] Asynchronous dispatch. ● Use the timing rules of Section 5.7.2.1 for both parts.
- For from 256 to 8192, time a round trip of an matrix from CPU to GPU and back, and time one matrix product on the device. Find the at which the two times are equal, extrapolating from how each time grows with if they do not cross in this range. Predict this crossover from your GPU's published host-to-device bandwidth and matrix-product throughput, and explain any gap between prediction and measurement.
- If you have two GPUs, time 1000 matrix products of two
matrices executed on one GPU, then 500 on each of
two GPUs issued from the same loop. Measure the scaling, explain how
asynchronous dispatch lets Python issue work to both devices, and
identify sources of deviation from linear scaling. Guard the
experiment with
num_gpus() >= 2.
-
[code] Synchronization points. ● Consider the training run of
ResMLPClassifierin Section 5.7.4 on a GPU.- List every synchronization point in one training step, reading
Trainer.fit_epoch,Trainer.prepare_batch, andAverageras well as the model code. Classify each as unavoidable for a correct loop or as an avoidable instrumentation artifact, and justify each classification. - Suppose the loop reads the loss into a Python float after every
step. Predict from your list how much this readout slows down the
default
ResMLPClassifierandResMLPClassifier(num_hiddens=2048, num_blocks=8). Then time one epoch of each model with and without the readout, and explain the four timings.
Adapted from the PyTorch documentation CUDA semantics.
- List every synchronization point in one training step, reading