翻篇收录说明
翻篇网页快照

5.7 GPUs, Devices, and Memory – Dive into Deep Learning

https://d2l.ai/chapter_builders-guide/gpus-devices-memory.html

最近抓取:2026-12-04 14:16:14(北京时间)

最近内容变化:2026-12-01 22:48:28(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

正文摘录

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 \(4096 \times 4096\) 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. TensorFlow # Silence TensorFlow's C++ info and warning messages. TensorFlow reads this # variable when it is first imported, so this cell runs before the imports. import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' PyTorchTensorFlowJAXMXNet import time from torch.utils.checkpoint import checkpoint import time import time import time PyTorch torch.set_float32_matmul_precision('high') # allow tf32 in fp32 matmuls 5.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. PyTorchTensorFlowJAXMXNet torch.device('cpu') and torch.device(f'cuda:{i}') denote the CPU and GPU \(i\). tf.device('/CPU:0') and tf.device(f'/GPU:{i}') create device placement scopes. jax.devices('cpu')[0] and jax.devices('gpu')[i] return hardware device handles. npx.cpu() and npx.gpu(i) denote the CPU and GPU \(i\) (called ctx prior to MXNet 2.0). We wrap device lookup in three small helpers that the rest of the book imports: one for CPU, one for GPU \(i\), and one that counts available GPUs. PyTorchTensorFlowJAXMXNet 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() def cpu(): """Get the CPU device.""" return tf.device('/CPU:0') def gpu(i=0): """Get a GPU device.""" return tf.device(f'/GPU:{i}') def num_gpus(): """Get the number of available GPUs.""" return len(tf.config.experimental.list_physical_devices('GPU')) def cpu(): """Get the CPU device.""" return jax.devices('cpu')[0] def gpu(i=0): """Get a GPU device.""" return jax.devices('gpu')[i] def num_gpus(): """Get the number of available GPUs.""" try: return jax.device_count('gpu') except: return 0 # No GPU backend found def cpu(): """Get the CPU device.""" return npx.cpu() def gpu(i=0): """Get a GPU device.""" return npx.gpu(i) def num_gpus(): """Get the number of available GPUs.""" return npx.num_gpus() PyTorchTensorFlowJAXMXNet Constructing a device object always succeeds; hardware existence is checked only when a tensor is placed on it. By default, TensorFlow uses soft placement, silently falling back to the CPU if a requested GPU scope does not exist. jax.devices('gpu') queries live hardware immediately and raises an error when no GPU is present. 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() PyTorchTensorFlowJAXMXNet (device(type='cuda', index=0), device(type='cpu'), [device(type='cuda', index=0), device(type='cuda', index=1)]) (<tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c173d80>, <tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7ce0a180>, [<tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c22f080>, <tensorflow.python.eager.context._EagerDeviceContext at 0x70ea7c22d4c0>]) (CudaDevice(id=0), CpuDevice(id=0), [CudaDevice(id=0), CudaDevice(id=1)]) (gpu(0), cpu(0), [gpu(0), gpu(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: PyTorchTensorFlowJAXMXNet PyTorch tensors default to the CPU unless device= is passed. TensorFlow tensors default to the first GPU when one is available (or can be placed explicitly via with tf.device(...):). JAX arrays default to the first GPU when one is available (or can be placed explicitly via jax.device_put). MXNet 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: PyTorchTensorFlowJAXMXNet 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 with try_gpu(): X = tf.ones((2, 3)) with try_gpu(1): Y = tf.random.uniform((2, 3)) print((X + Y).device) /job:localhost/replica:0/task:0/device:GPU:0 X = jax.device_put(jnp.ones((2, 3)), try_gpu()) Y = jax.device_put(jax.random.uniform(d2l.get_key(), (2, 3)), try_gpu(1)) try: print(X + Y) except ValueError as e: print(str(e).split('. ')[0]) # The first sentence names the problem Received incompatible devices for jitted computation X = mnp.ones((2, 3), device=try_gpu()) Y = mnp.random.uniform(size=(2, 3), device=try_gpu(1)) try: print(X + Y) except Exception as e: print(str(e).splitlines()[0]) operands for add must be on the same device/context, got gpu(0) and gpu(1) PyTorchTensorFlowJAXMXNet Adding tensors on different devices raises an error immediately, preventing accidental cross-device transfers. Outside an explicit device scope, TensorFlow silently copies mismatched operands onto the default device (unless tf.config.experimental.set_device_policy('explicit') is enabled). Adding tensors on different devices raises an error immediately, preventing accidental cross-device transfers. 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. Figure 5.7.1: 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. PyTorchTensorFlowJAXMXNet Z = X.to(try_gpu(1)) (Y + Z).device device(type='cuda', index=1) with try_gpu(1): Z = tf.identity(X) # The explicit copy: tf.identity in the target's scope print((Y + Z).device) # The scope, not the operands, decides the device /job:localhost/replica:0/task:0/device:GPU:1 Z = jax.device_put(X, try_gpu(1)) (Y + Z).device CudaDevice(id=1) Z = X.copyto(try_gpu(1)) (Y + Z).device gpu(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. MXNet The method for such a move is to_device, which returns the array itself when it is already there; copyto always copies. 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. PyTorchTensorFlowJAXMXNet 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>) net = tf.keras.Sequential([tf.keras.layers.Dense(1)]) with try_gpu(): Y_hat = net(X) # The first call creates the variables inside the scope Y_hat <tf.Tensor: shape=(2, 1), dtype=float32, numpy= array([[-2.197855], [-2.197855]], dt