GPUs, Devices, and Memory

Dive into Deep Learning · §5.7

GPUs, Devices, and Memory Budgets
device placement · PCIe copy bottlenecks · async command queues · 3 memory views · O(\sqrt{K}) activation checkpointing

Why Device Placement and Memory Budgets Govern Scale

Hardware Throughput vs. HBM Capacity

  • Dedicated onboard memory (HBM): An 8B model fits on a 24 GB GPU for bf16 inference (16 GB weights), yet fp32 Adam training requires 128 GB of static state before storing a single activation.
  • Co-location requirement: Cross-device PCIe transfers are 3\text{--}6\times slower than matrix multiplication; all inputs, weights, and buffers must reside on the same device.
  • Asynchronous command queues: Python enqueues GPU kernels and returns immediately; per-step host scalar readouts stall the pipeline.

Querying Hardware Devices with Graceful CPU Fallback

Device Abstraction

Every tensor lives on a specific device (cpu(), gpu(i)). Our try_gpu(i) helper selects GPU i when available and falls back cleanly to CPU so notebooks run unmodified anywhere:

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)])

Operations Reject Operands on Mismatched Devices

No Silent Cross-Device Copies

  • Placing X on GPU 0 and Y on GPU 1 (or CPU) and evaluating X + Y raises an immediate runtime error so implicit PCIe copies never stall training loops:
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

Explicit Device Transfers: Copy Once at the Boundary

Moving Tensors Between Devices

To combine tensors from different devices, copy X explicitly onto Y’s device:

Z = X.to(try_gpu(1))
(Y + Z).device
device(type='cuda', index=1)
  • Transfer discipline: Move data once at the boundary of your loop and keep every inner-loop operation on a single device.

Placing an Entire Model Tree on a Target Device

Co-Locating Parameters and Inputs

  • Move or initialize the model on its target GPU before constructing the optimizer (so Adam moments allocate on GPU), and allocate new tensors inside forward on X.device:
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>)

Asynchronous GPU Execution: The Command Queue

How Python Drives a GPU

Python does not wait for B = A @ A: it pushes a kernel launch onto the GPU’s execution queue and moves on:

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
  • Queueing vs. computing: Enqueueing 32 products of 4096 \times 4096 matrices takes a few milliseconds on the CPU, whereas the GPU takes dozens of milliseconds to drain the queue.

Synchronization Points Stall the CPU–GPU Pipeline

Don’t Break the Pipeline

  • What triggers a synchronization stall: Calling loss.item(), float(loss), print(tensor), .numpy(), or branching on a tensor value (if loss < best:) forces the CPU to block until the GPU finishes all queued work, leaving the GPU idle while Python catches up.
  • Systems best practice: Accumulate per-step losses inside an on-device tensor and convert to a Python float only at the end of the epoch.

Four Rules for Accurate GPU Benchmarking

Timing Asynchronous Kernels

  • Warmup + Dual Sync: Run warmup iterations, synchronize before starting perf_counter(), and synchronize before stopping the clock.

A Benchmark Helper That Follows the Rules

Timing Asynchronous Kernels

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'

4096×4096 Matmul vs. PCIe Host-to-Device Copy

Compute Throughput vs. Memory Bandwidth

Timing a 4096 \times 4096 matrix multiplication on CPU (fp32), on GPU (tf32 and 16-bit), and a CPU-to-GPU copy reveals the fundamental hardware bottleneck of deep learning:

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
  • Compute is 100\text{--}1000\times faster on GPU: Tensor Cores finish 4096^3 \approx 6.9 \times 10^{10} multiply-adds in under 2 ms (and 16-bit precision halves that time again).
  • PCIe copies take 3\text{--}6\times longer than matmul: Copying 4096^2 \times 4\text{ B} = 64\text{ MiB} over PCIe takes longer than performing 4096 multiply-adds per element once on the GPU.

Three Nested Views of GPU Memory

Live Tensors vs. Caching Allocator vs. CUDA Driver

Asking how much GPU memory a process uses yields three different answers depending on which layer of the memory hierarchy you query:

after creating big:  1192.1 MiB allocated,  1302.0 MiB reserved
after deleting it :   168.1 MiB allocated,  1302.0 MiB reserved
  • Why del big leaves nvidia-smi unchanged: Frameworks use a caching allocator that keeps freed GPU slabs in a reserved pool for instant reuse without slow CUDA driver calls.

Dissecting Memory Across One Training Step

Weights + Activations + Gradients + Optimizer Moments

Tracing live GPU memory across one training step of a 3-hidden-layer MLP (1024 \to 4096 \to 4096 \to 4096 \to 10, 4N \approx 144\text{ MiB} weights, batch size B = 4096) reveals how the four memory components arrive:

weights              160.2 MiB
+ activations        353.4 MiB
+ gradients          313.6 MiB
+ optimizer state    602.0 MiB
  • Activations exceed weights (+192\text{ MiB}): The three 4096 \times 4096 hidden outputs (3 \times 64\text{ MiB} = 192\text{ MiB}) sit in memory during forward and are freed during backward as gradients (+144\text{ MiB}) and Adam moments (+288\text{ MiB}) materialize.

Will the 8B Model Fit on a 24 GB or 80 GB GPU?

Static vs. Dynamic Memory Budgets

  • Inference (16 GB in bf16 vs. 32 GB in fp32): bf16 fits on a single 24 GB GPU with 8 GB left for KV cache/activations.
  • Training (38.3 GB head-only vs. 128 GB full fp32 Adam): Head-only fine-tuning fits on one 80 GB GPU; full fp32 Adam requires \ge 2 GPUs.
  • Activation OOMs (O(K \cdot B \cdot T \cdot d)): Halve micro-batch size B first, then enable activation checkpointing.

Activation Checkpointing: O(√K) Memory for 1 Extra Pass

Trading Compute for Activation Memory

Activation checkpointing (Chen et al., 2016) stores only segment boundaries and recomputes the rest during backward:

  • O(K) \to O(\sqrt{K}) peak activations: Partitioning K layers into segments of size s holds K/s boundary tensors plus s live interior tensors (K/s + s total, minimized at s = \sqrt{K} with 2\sqrt{K} tensors).
  • Bounded compute overhead: Recomputing each segment adds one extra forward pass (roughly 20\text{--}30\% extra step time).

Implementing Per-Segment Activation Checkpointing

Checkpointing a Stack of Residual Blocks

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 X
  • Grouping ResidualBlock modules into segments of segment_size = 4 and wrapping each segment in the framework’s checkpoint wrapper produces exact gradients in O(\sqrt{K}) memory.

Checkpointed Gradients Match Ordinary Backpropagation

Checkpointing a Stack of Residual Blocks

  • Recomputing activations must never alter the math: on an eight-block stack split into two segments, every gradient matches 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

Measured: >50% Less Step Memory for ~25% More Time

16 Residual Blocks on a GPU

On a 16-block residual stack (d = 1024, batch size B = 8192, four-block segments), activation checkpointing cuts peak step memory from \sim 1.1\text{ GiB} down to \sim 0.45\text{--}0.5\text{ GiB}:

checkpointing=False  step memory  1096 MiB,  25.5 ms per step
checkpointing=True   step memory   452 MiB,  32.3 ms per step

Wiring Automatic Device Placement Into d2l.Trainer

The Device-Aware 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')

def prepare_batch(self, batch):
    if self.gpus:
        batch = [d2l.to(a, self.gpus[0]) for a in batch]
    return batch

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))
  • d2l.Trainer moves the model to self.gpus[0] in prepare_model and each minibatch in prepare_batch, falling back to CPU without a GPU.

Timing the Device-Aware Trainer on CPU and GPU

The Device-Aware Trainer

num_gpus=0: 2.9 sec per epoch
num_gpus=1: 1.1 sec per epoch
  • Why tiny models see modest GPU speedups: On a 256-wide Fashion-MNIST MLP, matrices are at most 784 \times 256, so data loading and Python kernel-launch latency dominate; GPUs deliver 100\times speedups once wide layers, convolutions, and attention dominate compute.

Concept Check: Asynchronous Queues & Activation Memory

Concept Check

Test your systems intuition on these three scenarios:

  1. A training loop executes if loss < best_loss: best_loss = loss on every minibatch step on a GPU. Why does this single if statement hurt GPU utilization, and how should you rewrite it?
  2. A deep transformer stacks K = 36 identical blocks. How many block-input activation tensors are held at peak during the backward pass without checkpointing (s = 36), with every-block checkpointing (s = 1), and with optimal segment size s = \sqrt{36} = 6?
  3. When you delete a 2 GiB GPU tensor, the framework’s allocated-memory counter drops by 2 GiB, but nvidia-smi shows zero change. Why?

Answers:

  1. Evaluating a Python bool (loss < best_loss) forces a CPU–GPU synchronization on every step, draining the command queue. Fix: update best_loss = minimum(best_loss, loss) on-device and read it back once per epoch.
  2. Peak stored block activations (K/s + s): Uncheckpointed holds 36; s = 1 holds 36/1 + 1 = 37; optimal s = 6 holds only 36/6 + 6 = 12 (3\times reduction).
  3. The caching allocator keeps freed slabs in its reserved pool for future tensors without returning them to the CUDA driver (nvidia-smi).

Summary: GPUs, Devices, and Memory Budgets

Key Takeaways

  • Co-location & async queues: Move the model to GPU before constructing the optimizer, transfer each batch once at the boundary, and avoid per-step host synchronization stalls.
  • Benchmarking & memory views: Always warmup and synchronize around GPU timers; distinguish live allocated bytes from the caching allocator pool and nvidia-smi.
  • Activation checkpointing: Segmenting K layers by s = \sqrt{K} cuts activation memory from O(K) to O(\sqrt{K}) for \sim 25\text{--}33\% extra compute.