页面简介
正文摘录
从 2.4 节 开始,我们的 Trainer 一直接收 num_gpus 参数却客气地忽略了它。在前面几章的小模型上这无关紧要,因为 CPU 训练几秒钟就能跑完。然而一旦模型规模扩大,设备放置就会决定训练耗时是几秒还是几小时:一块现代桌面级 GPU 只需不到 2 毫秒就能完成两个 \(4096 \times 4096\) 矩阵相乘,而 CPU 需要十分之一秒甚至更久(我们将在 5.7.2.1 节 中实测对比)。这种澎湃算力伴随着一条严格的硬件约束:GPU 拥有独立板载显存(例如桌面显卡上的 24 GB),它所操作的每一个张量都必须驻留其中。 目标模型究竟装得下吗?贯穿本章的 80 亿参数模型在 bf16 下权重占用 16 GB,推理时轻松装入。但如果用 Adam 以 fp32 训练它,在存放任何一份激活值之前就需要 128 GB 的静态状态(5.2 节),远超任何单张 24 GB 或 80 GB 显卡。模型能否装入设备,以及 GPU 是持续满载计算还是停滞等待数据,都取决于每个张量驻留在何处以及消耗多少字节。 本节回答三个核心问题:张量和模型如何放置到 CPU 和 GPU 上并在两者间拷贝;异步 GPU 执行如何运作(以及如何准确评测 GPU 内核耗时);训练期间究竟是什么填满了 GPU 显存,包括激活检查点如何用额外计算换取大幅显存节省。随后我们将这一切接入全书余下部分使用的设备感知 Trainer。前面 5.2 节 和 5.5 节 核算了每个参数和每个数值的字节数,这里我们将这些字节落到真实硬件上(多 GPU 训练留待 第 13 章)。若当前没有可用 GPU,每个代码单元格都会优雅地回退到 CPU,即便耗时测量需要 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 设备与放置 5.7.1.1 设备对象 每个张量都驻留在特定的设备上:要么是搭配主机内存的 CPU,要么是搭配板载显存的某块 GPU。在终端运行 nvidia-smi 可以列出机器上的每一块 NVIDIA GPU、其总显存与已用显存以及活动进程。尽管四个框架对设备的命名略有差异,但都遵循同一条基本原则:一次运算只在单个设备上执行,因此它的所有操作数都必须位于该设备上。 PyTorchTensorFlowJAXMXNet torch.device('cpu') 和 torch.device(f'cuda:{i}') 分别表示 CPU 和第 \(i\) 块 GPU。 tf.device('/CPU:0') 和 tf.device(f'/GPU:{i}') 创建设备放置作用域。 jax.devices('cpu')[0] 和 jax.devices('gpu')[i] 返回硬件设备句柄。 npx.cpu() 和 npx.gpu(i) 分别表示 CPU 和第 \(i\) 块 GPU(在 MXNet 2.0 之前称为 ctx)。 我们将设备查询封装为全书后续章节都会导入的三个小辅助函数:一个返回 CPU,一个返回第 \(i\) 块 GPU,还有一个统计可用 GPU 数量。 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 构造设备对象总是会成功;只有当张量被放置到该设备上时,框架才会检查硬件是否存在。 默认情况下,TensorFlow 采用软放置(soft placement),如果请求的 GPU 作用域不存在,会静默回退到 CPU。 jax.devices('gpu') 会立即查询真实硬件,若没有 GPU 则直接报错。 构造设备对象总是会成功;只有当张量被放置到该设备上时,框架才会检查硬件是否存在。 基于 num_gpus,我们定义两个回退辅助函数:有 GPU 时选择 GPU,否则回退到 CPU,使同一份笔记本代码无需修改就能在笔记本电脑和 GPU 服务器上运行。 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)]) 其他加速器(如 Apple Silicon GPU mps 和 Google TPU)有各自的设备标识符,但下文介绍的放置原则对它们同样适用。全书以 CPU 和 CUDA GPU 为主。 5.7.1.2 设备上的数组 每个张量都通过 device 属性暴露其所在位置: PyTorchTensorFlowJAXMXNet 除非传入 device=,PyTorch 张量默认位于 CPU。 有可用 GPU 时,TensorFlow 张量默认位于第一块 GPU(也可通过 with tf.device(...): 显式指定)。 有可用 GPU 时,JAX 数组默认位于第一块 GPU(也可通过 jax.device_put 显式指定)。 除非传入 device=,MXNet 张量默认位于 CPU。 直接在目标设备上分配张量可以避免一次额外的 CPU 到 GPU 拷贝。下面将 X 放在第一块 GPU 上、将 Y 放在第二块 GPU 上(不足两块 GPU 时回退到 CPU),并尝试将它们相加: 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 对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。 在显式设备作用域之外,TensorFlow 会静默地将不匹配的操作数拷贝到默认设备上(除非启用 tf.config.experimental.set_device_policy('explicit'))。 对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。 对位于不同设备上的张量执行加法会立即报错,防止意外触发跨设备传输。 5.7.1.3 在设备间拷贝 在设备间搬运张量比在设备上计算慢得多(5.7.2.1 节 将实测这一差距),因此静默拷贝不匹配的操作数会掩盖严重的性能缺陷。相反,我们在相加前先将 X 显式拷贝到 Y 所在的设备上(图 5.7.1)。 图 5.7.1: X 位于 GPU 0,Y 位于 GPU 1。将 X 拷贝为位于 GPU 1 的 Z(虚线)后,Y + Z 即可完全在 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) 现在加法顺利执行,结果与两个操作数一同落在第二块 GPU 上。实践准则很简单:在计算边界一次性传输数据(把张量移动到它已经驻留的设备上基本是空操作),并让内层循环的每一步运算都留在同一设备上。 MXNet 执行此类移动的方法是 to_device,当数组已在目标设备上时它直接返回数组本身;而 copyto 总是执行拷贝。 5.7.1.4 设备上的模型 由于前向传播需要将输入与模型参数结合,整个模型必须与小批量数据位于同一设备上。得益于 5.1 节 中的模块树,每个框架都能通过一次调用移动或初始化全部参数。 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]], dtype=float32)> net = nnx.Sequential(nnx.Linear(3, 1, rngs=nnx.Rngs(d2l.get_key()))) nnx.update(net, jax.device_put(nnx.state(net), try_gpu())) net(X) Array([[0.8409575], [0.8409575]], dtype=float32) net = nn.Sequential() net.add(nn.Dense(1, in_units=3)) net.initialize(device=try_gpu()) net(X) array([[-0.01747404], [-0.01747404]], device=gpu(0)) 输入与参数同驻一处后,前向传播在该设备上执行,输出也返回在同一设备上。 牢记两条放置规则:在构造优化器之前将模型移动到目标设备或在其上初始化(使优化器矩估计分配在同一设备上),并在 forward 内部创建任何新张量时将其分配在 X.device 上,而非默认留在 CPU 上。 5.7.2 异步执行 5.7.2.1 执行队列 Python 调用 GPU 运算时,GPU 并非同步执行。相反,Python 只是将每次内核启动压入设备的命令队列便立即返回,让 CPU 在 GPU 顺序消化队列的同时继续准备后续工作。这种流水线机制隐藏了 Python 开销,却带来一个关键的计时陷阱:直接测量 Python 循环耗时测到的是入队时间,而非执行时间。下面我们连续入队 32 次 \(4096 \times 4096\) 矩阵乘法,并两次读取挂钟时间:一次在 Python 刚完成入队时,一次在设备完成计算后。 PyTorchTensorFlowJAXMXNet 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 if num_gpus() > 0: with gpu(): A = tf.random.normal((4096, 4096)) A @ A tf.test.experimental.sync_devices() # Warm up and wait t = time.perf_counter() with gpu(): for _ in range(32): B = A @ A print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec') tf.test.experimental.sync_devices() print(f'time until they all finished: {time.perf_counter() - t:.4f} sec') else: print('No GPU: eager operations on the CPU run synchronously.') time to queue 32 matrix products: 0.0025 sec time until they all finished: 0.0536 sec A = jax.random.normal(d2l.get_key(), (4096, 4096)) (A @ A).block_until_ready() # 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') B.block_until_ready() # The device runs the products in order print(f'time until they all finished: {time.perf_counter() - t:.4f} sec') time to queue 32 matrix products: 0.0020 sec time until they all finished: 0.0517 sec A = mnp.random.normal(size=(4096, 4096), device=try_gpu()) mnp.dot(A, A) npx.waitall() # Warm up and wait t = time.perf_counter() for _ in range(32): B = mnp.dot(A, A) print(f'time to queue 32 matrix products: {time.perf_counter() - t:.4f} sec') npx.waitall() print(f'time until they all finished: {time.perf_counter() - t:.4f} sec') time to queue 32 matrix products: 0.0023 sec time until they all finished: 0.0545 sec PyTorchTensorFlowJAXMXNet GPU 内核异步运行,而 CPU 运算同步运行;torch.cuda.synchronize() 会等待所有已入队的 GPU 工作完成。 GPU 内核异步运行,而 CPU 运算同步运行;tf.test.experimental.sync_devices() 会等待所有已入队的 GPU 工作完成。 JAX 在 CPU 和 GPU 上都采用异步派发;B.block_until_ready() 会阻塞直到计算完成。 MXNet 在 CPU 和 GPU 上都采用异步派发;npx.waitall() 会阻塞直到计算完成。 Python 仅用实际计算时间的一小部分就把全部 32 次矩阵乘法送入了队列。CPU 究竟何时才会阻塞等待?仅当 Python 需要在主机端拿到具体数值时——例如打印张量、将标量转为 Python 浮点数、转换为 NumPy 数组,或在 if 语句中根据张量值分支。每一个这样的同步点都会让 Python 停等 GPU 把队列排空到该值为止,而在 Python 赶上进度前 GPU 则处于空闲状态(图 5.7.2)。在每个小批量后都将损失记录为 Python 数值,相当于每步都插入一个同步气泡;正因如此,我们的 Trainer 将损失留在设备端的 d2l.Averager 中累加,每轮仅转换一次为 Python 浮点数(2.4 节)。 图 5.7.2: Python 将运算 op1