import time
from torch.utils.checkpoint import checkpoint5.7 GPU、デバイス、メモリ
2.4 節 以降、Trainer は num_gpus 引数を受け取りつつも、それを黙って無視してきた。これまでの章で扱った小さなモデルでは、CPU での訓練が数秒で終わるため、それでもほとんど問題にならなかった。しかし、モデルが大規模になると、デバイス配置(device placement)が数秒で済むか数時間かかるかの違いを生む。現代のデスクトップ GPU は 2 つの \(4096 \times 4096\) 行列の積を 2 ms 未満で計算するが、CPU では 0.1 秒以上かかるからである(5.7.2.1 節 でベンチマークする)。この圧倒的な計算速度には、厳しいハードウェア上の制約が伴う。GPU は専用のメモリ(たとえばデスクトップ向けカードなら 24 GB)を備えており、GPU が演算するすべてのテンソルはそのメモリ上に置かれていなければならない。
そもそも目的のモデルはメモリに収まるのだろうか。ここまで例に挙げてきた 80 億パラメータのモデルは、bf16 の重みに 16 GB を必要とするため、推論であれば余裕をもって収まる。しかし、このモデルを fp32 の Adam で訓練するには、活性化値(activation)を 1 つ保存する前でも 128 GB の静的な状態が必要となり(5.2 節)、単一の 24 GB や 80 GB のカードの容量をはるかに超えてしまう。モデルがデバイスに収まるかどうか、そして GPU が休みなく計算を続けられるかデータ待ちで停止してしまうかは、すべてのテンソルがどこに存在し、何バイトを消費するかに帰着する。
本節では、3 つの中心的な問いに答える。すなわち、テンソルとモデルをどのように CPU や GPU 上に配置し、デバイス間でコピーするか、GPU の非同期実行(asynchronous execution)はどのように動作するか(また GPU カーネルを正確にベンチマークするにはどうすればよいか)、そして訓練中に実際何が GPU メモリを占めるのか(余分な計算と引き換えにメモリ使用量を劇的に削減する活性化チェックポイント(activation checkpointing)の仕組みを含む)である。そのうえで、これらすべてを本書の残りの章で用いるデバイス対応の Trainer に組み込む。5.2 節 と 5.5 節 ではパラメータあたり・数値あたりのバイト数を数えたが、本節ではそれらのバイトを実際のハードウェア上に載せる(マルチ GPU 訓練は 第 13 章 に譲る)。すべてのコードセルは、GPU が利用できない環境でも CPU へスムーズにフォールバックし、実行時間の計測には GPU が必要であっても動作の正しさは確認できるようになっている。
# 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'import timeimport timeimport timetorch.set_float32_matmul_precision('high') # allow tf32 in fp32 matmuls5.7.1 デバイスと配置
5.7.1.1 デバイスオブジェクト
すべてのテンソルは特定のデバイス上に存在する。すなわち、ホスト RAM と対になった CPU か、オンボードメモリと対になった個々の GPU のいずれかである。ターミナルで nvidia-smi を実行すると、マシン上のすべての NVIDIA GPU、その総メモリ量と使用中メモリ量、および実行中のプロセスが一覧表示される。デバイスの命名法はフレームワークごとに多少異なるものの、4 つのフレームワークはすべて 1 つの基本原則に従っている。それは、演算は単一のデバイス上で実行されるため、そのオペランドはすべて同じデバイス上に存在しなければならないという原則である。
torch.device('cpu') と torch.device(f'cuda:{i}') は、それぞれ CPU と GPU \(i\) を表す。
tf.device('/CPU:0') と tf.device(f'/GPU:{i}') は、デバイス配置のスコープを作成する。
jax.devices('cpu')[0] と jax.devices('gpu')[i] は、ハードウェアデバイスのハンドルを返す。
npx.cpu() と npx.gpu(i) は、それぞれ CPU と GPU \(i\) を表す(MXNet 2.0 より前は ctx と呼ばれていた)。
デバイスの取得処理を、本書の以降の章でインポートする 3 つの小さなヘルパ関数にまとめておこう。CPU 用のもの、GPU \(i\) 用のもの、そして利用可能な GPU の数を数えるものの 3 つである。
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 founddef 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()デバイスオブジェクトの構築は常に成功し、ハードウェアが存在するかどうかはテンソルをその上に配置した時点で初めて確認される。
デフォルトでは、TensorFlow はソフトプレースメントを使用し、指定された GPU スコープが存在しない場合は暗黙的に CPU へフォールバックする。
jax.devices('gpu') は実機のハードウェアを即座に照会し、GPU が存在しない場合はエラーを送出する。
デバイスオブジェクトの構築は常に成功し、ハードウェアが存在するかどうかはテンソルをその上に配置した時点で初めて確認される。
num_gpus を土台として、GPU があればそれを選択し、なければ CPU にフォールバックする 2 つのヘルパ関数を定義する。これにより、ノート PC でも 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()(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 シリコンの GPU(mps)や Google TPU などの他のアクセラレータも独自のデバイス識別子を用いるが、以下で述べる配置の原則はそれらすべてに等しく当てはまる。本書全体を通して、CPU と CUDA GPU に焦点を当てる。
5.7.1.2 デバイス上の配列
すべてのテンソルは、device 属性を通じて自身の配置先を公開している。
PyTorch のテンソルは、device= を渡さない限りデフォルトで CPU に配置される。
TensorFlow のテンソルは、GPU が利用可能であればデフォルトで最初の GPU に配置される(または with tf.device(...): で明示的に配置できる)。
JAX の配列は、GPU が利用可能であればデフォルトで最初の GPU に配置される(または jax.device_put で明示的に配置できる)。
MXNet のテンソルは、device= を渡さない限りデフォルトで CPU に配置される。
目的のデバイス上に直接メモリを確保すれば、CPU から GPU への余分なコピーを避けられる。以下では、X を 1 番目の GPU に、Y を 2 番目の GPU に配置し(GPU が 2 基未満の場合は CPU にフォールバックする)、両者の加算を試みる。
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 problemReceived 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)
異なるデバイス上のテンソル同士を加算しようとすると即座にエラーが送出され、意図しないデバイス間転送を防ぐ。
明示的なデバイススコープの外では、TensorFlow は異なるデバイス上のオペランドを暗黙的にデフォルトデバイスへコピーする(ただし tf.config.experimental.set_device_policy('explicit') を有効にした場合を除く)。
異なるデバイス上のテンソル同士を加算しようとすると即座にエラーが送出され、意図しないデバイス間転送を防ぐ。
異なるデバイス上のテンソル同士を加算しようとすると即座にエラーが送出され、意図しないデバイス間転送を防ぐ。
5.7.1.3 デバイス間のコピー
デバイス間でテンソルを移動する処理は、デバイス上での計算よりはるかに遅いため(この差は 5.7.2.1 節 で計測する)、異なるデバイス上のオペランドを暗黙的にコピーしてしまうと深刻な速度低下のバグが隠れてしまう。そこで、X を Y のデバイス上へ明示的にコピーしてから(図 5.7.1)加算する。
Z = X.to(try_gpu(1))
(Y + Z).devicedevice(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).deviceCudaDevice(id=1)
Z = X.copyto(try_gpu(1))
(Y + Z).devicegpu(1)
これで加算が実行され、結果も両オペランドと同じ 2 番目の GPU 上に置かれる。実践上の原則は単純である。計算の境界で一度だけデータを転送し(すでにそのデバイス上にあるテンソルの移動は実質的に何もしない操作である)、内側ループの演算はすべてその単一のデバイス上に留めることである。
このような移動に使うメソッドは to_device であり、配列がすでに移動先にある場合はその配列自身を返す。一方、copyto は常にコピーを作成する。
5.7.1.4 デバイス上のモデル
順伝播(forward pass)では入力とモデルパラメータを組み合わせるため、モデル全体がミニバッチと同じデバイス上に存在しなければならない。5.1 節 で見たモジュールツリーのおかげで、どのフレームワークでも 1 回の呼び出しですべてのパラメータを移動または初期化できる。
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))
入力とパラメータが同じデバイス上に揃っていれば、順伝播はそのデバイス上で実行され、出力も同じデバイス上に返される。
配置に関する 2 つの原則を心に留めておこう。1 つ目は、オプティマイザを構築する前にモデルを目的のデバイス上へ移動または初期化すること(これによりオプティマイザのモーメントも同じデバイス上に確保される)、2 つ目は、forward 内で新たに生成するテンソルをデフォルトの CPU ではなく X.device 上に確保することである。
5.7.2 非同期実行
5.7.2.1 実行キュー
GPU は、Python から演算が呼び出された瞬間にそれを同期的に実行するわけではない。その代わり、Python は各カーネル起動(kernel launch)をデバイスのコマンドキューに追加して即座に制御を返し、GPU がキュー内の処理を順番にこなしている間に CPU が後続の処理を準備できるようにする。このパイプライン化によって Python のオーバーヘッドは隠蔽されるが、時間計測においては重要な落とし穴がある。Python ループの所要時間を測っても、計測されるのは実行ではなくキューへの投入にかかる時間なのである。以下では、\(4096 \times 4096\) 行列の積を 32 回キューに投入し、実時間(ウォールクロック時間)を 2 回確認する。Python がキューへの投入を終えた直後と、デバイスが計算を終えた直後の 2 回である。
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
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 の浮動小数点数への変換、NumPy への変換、あるいは if 文でのテンソル値に基づく分岐など、Python がホスト側で具体的な値を必要とするときだけである。このような同期ポイント(synchronization point)のたびに、GPU がその値までのキューを消化し終えるまで Python は停止し、その後 Python が追いつくまでの間、今度は GPU がアイドル状態になる(図 5.7.2)。ミニバッチごとに損失を Python の数値として記録すると、毎ステップ同期の空白時間(バブル)が生じてしまう。Trainer が d2l.Averager 内で損失をデバイス上に保持し、エポックごとに 1 回だけ Python の浮動小数点数に変換しているのはこのためである(2.4 節)。
非同期ディスパッチの仕組みから、信頼できる GPU ベンチマークのための 4 つの原則も導かれる。(1)初回限りのメモリ確保、ライブラリの初期化、JIT コンパイルを除外するため、最初にウォームアップ呼び出しを実行すること、(2)タイマの開始直前と停止直前の両方でデバイスを同期すること、(3)複数回の反復にわたって平均をとること、(4)サブミリ秒の分解能を得るために time.perf_counter を使用することである。(上の実演セルではウォームアップと同期は実施したものの、32 回の積の合計時間を報告していた。以下で定義する Benchmark ヘルパは、本章および以降の章のためにこれら 4 つの原則をすべて自動化する。)
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'class Benchmark:
"""Time a callable: warmup, then device-synchronized average seconds."""
def __init__(self, f, warmup=3, repeats=10, desc='time'):
self.desc = desc
for _ in range(warmup):
f()
tf.test.experimental.sync_devices()
t0 = time.perf_counter()
for _ in range(repeats):
f()
tf.test.experimental.sync_devices()
self.time = (time.perf_counter() - t0) / repeats
def __repr__(self):
return f'{self.desc}: {1000 * self.time:.2f} ms/call'class Benchmark:
"""Time a callable: warmup, then device-synchronized average seconds."""
def __init__(self, f, warmup=3, repeats=10, desc='time'):
self.desc, out = desc, None
for _ in range(warmup):
out = f()
jax.block_until_ready(out)
t0 = time.perf_counter()
for _ in range(repeats):
out = f()
jax.block_until_ready(out)
self.time = (time.perf_counter() - t0) / repeats
def __repr__(self):
return f'{self.desc}: {1000 * self.time:.2f} ms/call'class Benchmark:
"""Time a callable: warmup, then device-synchronized average seconds."""
def __init__(self, f, warmup=3, repeats=10, desc='time'):
self.desc = desc
for _ in range(warmup):
f()
npx.waitall()
t0 = time.perf_counter()
for _ in range(repeats):
f()
npx.waitall()
self.time = (time.perf_counter() - t0) / repeats
def __repr__(self):
return f'{self.desc}: {1000 * self.time:.2f} ms/call'JAX はデバイス全体ではなく特定の配列の完了を待機するため、計測対象の関数は計算結果を返す必要があり、Benchmark は最後の呼び出しが返した値の完了を待機する。
さっそく Benchmark を使って、先ほどの 2 つの主張を検証しよう。すなわち、大規模な行列積において GPU が CPU よりどれだけ高速か、そして計算に比べてホストからデバイスへの転送がいかに高コストかである。以下では、\(4096 \times 4096\) 行列の積を CPU(fp32)、GPU の tf32(5.5 節)および 16 ビット精度で計測し、あわせて単一の \(4096 \times 4096\) 行列を CPU RAM から 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
if num_gpus() > 0:
with cpu():
A_cpu = tf.identity(A) # The same matrix in main memory
A16 = tf.cast(A, tf.bfloat16)
def cpu_product():
with cpu():
return A_cpu @ A_cpu
@tf.function # Eager mode would reuse a cached copy of A_cpu on the GPU
def copy_to_gpu():
with gpu():
return tf.identity(A_cpu)
print(Benchmark(cpu_product, 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(copy_to_gpu, desc='copy from CPU to the GPU'))
else:
print('No GPU: there is nothing to compare the CPU with.')product on the CPU, fp32: 1696.38 ms/call
product on the GPU, tf32: 1.69 ms/call
product on the GPU, bf16: 0.92 ms/call
copy from CPU to the GPU: 7.75 ms/call
if num_gpus() > 0:
A_cpu = jax.device_put(A, cpu()) # The same matrix in main memory
A16 = A.astype(jnp.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'))
# Wait for each copy, so that the copies are timed one at a time
print(Benchmark(lambda: jax.device_put(A_cpu, gpu()).block_until_ready(),
desc='copy from CPU to the GPU'))
else:
print('No GPU: there is nothing to compare the CPU with.')product on the CPU, fp32: 136.53 ms/call
product on the GPU, tf32: 1.61 ms/call
product on the GPU, bf16: 0.86 ms/call
copy from CPU to the GPU: 8.55 ms/call
if num_gpus() > 0:
A_cpu = A.copyto(cpu()) # The same matrix in main memory
A16 = A.astype('float16') # MXNet's matrix product rejects bf16
print(Benchmark(lambda: mnp.dot(A_cpu, A_cpu), warmup=1, repeats=3,
desc='product on the CPU, fp32'))
print(Benchmark(lambda: mnp.dot(A, A), desc='product on the GPU, tf32'))
print(Benchmark(lambda: mnp.dot(A16, A16),
desc='product on the GPU, fp16'))
print(Benchmark(lambda: A_cpu.copyto(gpu()),
desc='copy from CPU to the GPU'))
else:
print('No GPU: there is nothing to compare the CPU with.')product on the CPU, fp32: 277.79 ms/call
product on the GPU, tf32: 1.72 ms/call
product on the GPU, fp16: 0.88 ms/call
copy from CPU to the GPU: 6.45 ms/call
TensorFlow はデフォルトで fp32 の行列積に tf32 を使用する。
JAX のデフォルトの行列積の精度設定では、この GPU 上で tf32 が選択される。
MXNet はデフォルトで fp32 の行列積に tf32 を使用する。MXNet の行列積は bf16 を受け付けないため、ここでの 16 ビットの積には fp16 を用いているが、同じテンソルコア上で同じ速度で実行される。
現代の GPU では、\(4096 \times 4096\) の積は 2 ms 未満で完了するのに対し、CPU では約 100 ms から 2 s を要する(CPU のコア数に応じて約 \(100\times\) から \(1000\times\) の高速化である)。16 ビット精度に落とすと GPU の計算時間はさらにほぼ半減し、5.5 節 で予告したテンソルコアによる高速化が実現される。
最後の行に特に注目してほしい。行列の積ではコピーされた要素 1 つあたり 4096 回の積和演算が実行されるにもかかわらず、CPU メモリから GPU へ行列を単にコピーするだけで、到着後に積を計算するよりも 3〜6 倍長くかかっている。通常のホストからのコピーでは、GPU の DMA エンジンが直接データを引き出せるよう、まずピン留め(pinned、ページロック)ホストメモリにデータを中継する。バッチをあらかじめピン留めしておけば、この余分なコピーが不要になり、データ転送と計算をオーバーラップさせることができる(13.2 節)。
5.7.3 GPU メモリ
5.7.3.1 メモリの 3 つのビュー
訓練スクリプトがどれだけの GPU メモリを使用しているかを尋ねると、ソフトウェアスタックのどの層に問い合わせるかによって 3 つの異なる数値が返ってくる。CUDA ドライバにメモリを直接要求する処理は遅いため、各フレームワークは内部でキャッシングアロケータを動かし、ドライバから大きなメモリ領域(スラブ)をまとめて取得してテンソルへ細分化して割り当て、解放されたスラブも即座に返却せず再利用のために保持する。これにより、入れ子になった 3 つのメモリビューが生じる(図 5.7.3)。すなわち、生存中のテンソルが現在占有しているバイト数、フレームワークのアロケータが予約しているより大きなプール、そして CUDA ドライバがそのプロセスに割り当てた総メモリ量(nvidia-smi に表示される数値)である。
torch.cuda.memory_allocated() は生存中のテンソルのバイト数を報告し、torch.cuda.memory_reserved() はキャッシングアロケータのプール量を報告する。
tf.config.experimental.get_memory_info('GPU:0') は、TensorFlow の GPU アロケータ内における生存バイト数の現在値('current')とピーク値('peak')を報告する。
gpu().memory_stats() は、JAX が事前確保した GPU プール内での使用中バイト数('bytes_in_use')とピーク使用バイト数('peak_bytes_in_use')を報告する。
npx.gpu_memory_info(0) は、gpu().empty_cache() の実行後に CUDA ドライバからデバイス全体の空きバイト数と総バイト数を取得する。
1 GiB の float32 テンソルを確保して直ちに削除し、これらのカウンタがどう反応するか見てみよう。
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
if num_gpus() > 0:
def report(tag):
info = tf.config.experimental.get_memory_info('GPU:0')
print(f'{tag}: {info["current"] / 2**20:7.1f} MiB in use, '
f'{info["peak"] / 2**20:7.1f} MiB peak')
with gpu():
big = tf.zeros((256, 1024, 1024)) # 1 GiB of float32
report('after creating big')
del big
report('after deleting it ')
else:
print('No GPU: get_memory_info() tracks only GPU and TPU allocators.')after creating big: 1184.0 MiB in use, 1184.0 MiB peak
after deleting it : 160.0 MiB in use, 1184.0 MiB peak
if num_gpus() > 0:
def report(tag):
s = gpu().memory_stats()
print(f'{tag}: {s["bytes_in_use"] / 2**20:7.1f} MiB in use, '
f'{s["peak_bytes_in_use"] / 2**20:7.1f} MiB peak')
big = jnp.zeros((256, 1024, 1024)) # 1 GiB of float32
big.block_until_ready()
report('after creating big')
del big
report('after deleting it ')
else:
print('No GPU: memory_stats() returns None on the CPU backend.')after creating big: 1184.0 MiB in use, 1184.0 MiB peak
after deleting it : 160.0 MiB in use, 1184.0 MiB peak
if num_gpus() > 0:
gpu().empty_cache()
npx.waitall()
free_start, _ = npx.gpu_memory_info(0)
def report(tag):
npx.waitall()
free, _ = npx.gpu_memory_info(0)
print(f'{tag}: {(free_start - free) / 2**20:7.1f} MiB more used')
big = mnp.zeros((256, 1024, 1024), device=gpu()) # 1 GiB of float32
report('after creating big')
del big
report('after deleting it ')
gpu().empty_cache()
report('after empty_cache ')
else:
print('No GPU: gpu_memory_info() queries the CUDA driver.')after creating big: 1024.0 MiB more used
after deleting it : 1024.0 MiB more used
after empty_cache : 0.0 MiB more used
MXNet はドライバレベルの使用量のみを報告するため、empty_cache() がスラブを返却した時点で数値が下がる。
big を削除すると生存中のテンソル 1 GiB 分が解放されるが、フレームワークのキャッシングアロケータは解放された 1 GiB のスラブを予約プール内に保持し続けるため、nvidia-smi の表示はピクリとも動かない。(訓練ループの内部でスラブを強制的に CUDA ドライバへ返却してはならない。毎ステップ低速なドライバ割り当てが発生してしまうからである。)最も外側のドライバビューは、メモリ不足の絶対的な上限を定める。ドライバはカードが物理的に搭載している以上の RAM を貸し出せないためである。コード内のどこにメモリが使われているかを診断するには、生存バイト数のカウンタ、とりわけ呼び出し中に達したピークメモリを調べる。このピーク値が、ステップが成功するかメモリ不足(out-of-memory、OOM)でクラッシュするかを決定する。
torch.cuda.reset_peak_memory_stats() と torch.cuda.max_memory_allocated() を使えば、任意の呼び出しにおける生存メモリの正確なピーク増分を計測できる。
XLA はコンパイル済み関数のメモリを静的に計画するため、compiled.memory_analysis().temp_size_in_bytes によって入出力以外に必要な一時ワークスペース・活性化メモリのバイト数が報告される。
MXNet の C++ キャッシングアロケータは生存テンソル数やピークバイト数のカウンタを Python に公開していないため、デバイスメモリの調査には nvidia-smi またはフレームワークのプロファイラを使用する。
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() - basedef peak_memory(f, *args):
"""Temporary memory that XLA reserves to run jax.jit(f) on args, in
bytes."""
compiled = jax.jit(f).lower(*args).compile()
return compiled.memory_analysis().temp_size_in_bytes5.7.3.2 訓練時のメモリ
5.2 節 では、fp32 の Adam 訓練における静的メモリの下限を \(16N\) バイト(パラメータ数を \(N\) として、重みに \(4N\)、勾配に \(4N\)、Adam のモーメントに \(8N\))と導出した。実際の訓練ステップでは、ここに 4 つ目の項として活性化値が加わる。誤差逆伝播法(backpropagation)では、順伝播の中間出力を逆伝播(backward pass)で消費するまで保持しなければならず、静的な \(16N\) とは異なり、活性化メモリはミニバッチサイズと層の幅に比例して増大する。実測する前に計算してみよう。1024 次元の入力を受け取る幅 4096・隠れ層 3 層の MLP(パラメータ数は \(N \approx 3.8 \times 10^7\)、したがって重みは \(4N \approx 144\) MiB)を、ミニバッチサイズ 4096 で動かすとする。3 つの隠れ層の出力はそれぞれ 64 MiB の \(4096 \times 4096\) fp32 テンソル(合計 192 MiB)となり、この時点ですでに重み自体より 3 分の 1 大きい。
MXNet はステップごとの生存バイト数を取得するアロケータのカウンタを Python に公開していないため、本項には MXNet のコードはないが、以下で述べる \(16N\) プラス活性化値という解析的なメモリ見積もりはそのまま当てはまる。
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
if num_gpus() > 0:
start = tf.config.experimental.get_memory_info('GPU:0')['current']
def in_use(): # Memory in use beyond that at the start of the cell
info = tf.config.experimental.get_memory_info('GPU:0')
return f'{(info["current"] - start) / 2**20:7.1f} MiB'
with gpu():
net = tf.keras.Sequential(
[tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dense(4096, activation='relu'),
tf.keras.layers.Dense(10)])
X = tf.random.normal((4096, 1024))
y = tf.random.uniform((4096,), 0, 10, dtype=tf.int32)
net(X) # The first call creates the variables
optimizer = tf.keras.optimizers.Adam()
loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
print('weights ', in_use())
with tf.GradientTape() as tape:
loss = loss_fn(y, net(X, training=True))
print('+ activations ', in_use())
grads = tape.gradient(loss, net.trainable_variables)
print('+ gradients ', in_use())
optimizer.apply_gradients(zip(grads, net.trainable_variables))
print('+ optimizer state ', in_use())
else:
print('No GPU: run this cell on a GPU to see the four readings.')weights 160.2 MiB
+ activations 352.5 MiB
+ gradients 304.4 MiB
+ optimizer state 592.8 MiB
if num_gpus() > 0:
start = gpu().memory_stats()['bytes_in_use']
def in_use(): # Memory in use beyond that at the start of the cell
s = gpu().memory_stats()
return f'{(s["bytes_in_use"] - start) / 2**20:7.1f} MiB'
rngs = nnx.Rngs(d2l.get_key())
net = nnx.Sequential(nnx.Linear(1024, 4096, rngs=rngs), nnx.relu,
nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,
nnx.Linear(4096, 4096, rngs=rngs), nnx.relu,
nnx.Linear(4096, 10, rngs=rngs))
key1, key2 = jax.random.split(d2l.get_key())
X = jax.random.normal(key1, (4096, 1024))
y = jax.random.randint(key2, (4096,), 0, 10)
def loss(model):
logits = model(X)
return optax.softmax_cross_entropy_with_integer_labels(
logits, y).mean()
jax.block_until_ready(nnx.state(net))
print('weights ', in_use())
grads = jax.block_until_ready(nnx.grad(loss)(net))
print('+ gradients ', in_use())
optimizer = nnx.Optimizer(net, optax.adam(1e-3), wrt=nnx.Param)
jax.block_until_ready(optimizer.opt_state)
print('+ optimizer state ', in_use())
graphdef, params = nnx.split(net)
grad_fn = jax.grad(lambda params: loss(nnx.merge(graphdef, params)))
planned = peak_memory(grad_fn, params)
print(f'activations (planned) {planned / 2**20:7.1f} MiB')
else:
print('No GPU: run this cell on a GPU to see the terms arrive.')weights 160.2 MiB
+ gradients 304.4 MiB
+ optimizer state 593.0 MiB
activations (planned) 192.0 MiB
出力された数値は、訓練ステップのライフサイクルを正確にたどっている。まず重み(\(4N\) バイト)と入力がメモリ上に置かれ、順伝播によって保存された活性化値(約 192 MiB、重みを上回る)が加わり、逆伝播がその活性化値を消費・解放しつつ勾配(\(4N\))を実体化し、最初のオプティマイザステップが Adam の 2 つのモーメント(\(8N\))を確保する。図 5.7.4 は、16 MiB の入力バッチを除いたこれら 4 つの段階を示したものである。2 ステップ目以降は、毎ステップの中でメモリが増減する。順伝播で重みと Adam のモーメントの上に活性化値が保存され、逆伝播でそれが勾配に置き換わる。ピーク使用量は高々、静的な \(16N\) に活性化値を加えた量であり、次の順伝播の前に古い勾配を解放するループでは最大 \(4N\) だけ低くなる。活性化値が原因でメモリ上限を超えてしまう場合、アーキテクチャを変えずに活性化メモリを削減できるミニバッチサイズの縮小が最も手軽な対策となる。対照的に、メモリがステップを追うごとに着実に増え続ける場合は、古い計算グラフを生かし続けているメモリリークを疑うべきである。典型的な原因は、生の損失テンソルを切り離さずそのまま Python のリストに追加してしまうことである。
optimizer.zero_grad() はデフォルト(set_to_none=True)で勾配を解放するため、順伝播の前にこれを呼び出すループでは、活性化値を保持している間のパラメータ関連メモリは \(12N\) バイト(\(16N\) ではなく)にとどまる。
5.7.3.3 活性化チェックポイント
活性化メモリを抑えるには、アーキテクチャ面での 2 つ目の手段がある。通常の誤差逆伝播法は、逆方向の計算で一度読み出すためだけに、すべての層の中間出力を保存している。活性化チェックポイント(勾配チェックポイント(gradient checkpointing)や再実体化(rematerialization)とも呼ばれる (Chen ほか 2016年))は、順伝播中に大半の中間活性化値を破棄して選択したセグメントの境界にある入力だけを保持し、逆伝播中に各セグメント内部の活性化値をその場で再計算する。(同じ「チェックポイント」という語を含むが、このメモリ上の手法は 5.6 節 で扱ったディスクへのチェックポイント保存とは無関係である。)
均一な \(K\) 個の層を \(s\) 層ずつのセグメントに分割すると、保持されるのは \(K/s\) 個のセグメント境界と、処理中のセグメント内部で生存している \(s\) 個の活性化値のみとなる(約 \(K/s + s\) 個のテンソルであり、\(K\) 個すべてではない)。\(s = \sqrt{K}\) と選べば、ピークの活性化メモリは \(O(K)\) から \(O(\sqrt{K})\) へと減少する。その代償は、誤差逆伝播法におけるセグメントあたり 1 回分の追加の順伝播である(図 5.7.5)。線形層の逆伝播が 2 回の行列積(入力勾配と重み勾配)を計算するのに対し、順伝播は 1 回の行列積で済むため、順伝播が 1 回増えてもステップ全体の計算量は順伝播換算で約 3 回分から 4 回分に増えるだけであり、ハードウェアや層の構成にもよるが大まかな上限として約 33% の増加にとどまる。
活性化チェックポイントが真価を発揮するのは、5.1 節 の残差 MLP や現代の Transformer のように、同一構造のブロックを深く積み重ねたモデルである。以下では、重みを \(\mathcal{N}(0, 0.01^2)\)、バイアスを 0 で初期化した ResidualBlock と、ブロックをセグメントにまとめて任意でチェックポイントを適用する run_stack ヘルパを定義する。
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 Xclass ResidualBlock(tf.keras.layers.Layer):
def __init__(self, num_hiddens, **kwargs):
super().__init__(**kwargs)
normal = tf.keras.initializers.RandomNormal # One instance per layer
self.body = tf.keras.Sequential([
tf.keras.layers.Dense(num_hiddens, activation='relu',
kernel_initializer=normal(stddev=0.01)),
tf.keras.layers.Dense(num_hiddens,
kernel_initializer=normal(stddev=0.01))])
def call(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):
# Bind this segment's blocks now: the backward pass calls segment
# again after the loop has moved on
def segment(X, segment_blocks=blocks[start:start + segment_size]):
for blk in segment_blocks:
X = blk(X)
return X
f = tf.recompute_grad(segment) if use_checkpoint else segment
X = f(X)
return Xclass ResidualBlock(nnx.Module):
def __init__(self, num_hiddens, *, rngs):
normal = nnx.initializers.normal(0.01)
self.body = nnx.Sequential(
nnx.Linear(num_hiddens, num_hiddens, kernel_init=normal,
rngs=rngs), nnx.relu,
nnx.Linear(num_hiddens, num_hiddens, kernel_init=normal,
rngs=rngs))
def __call__(self, X):
return X + self.body(X)
def run_stack(graphdef, states, X, use_checkpoint=False, segment_size=4):
def segment(segment_states, X):
for state in segment_states:
X = nnx.merge(graphdef, state)(X)
return X
f = jax.checkpoint(segment) if use_checkpoint else segment
for start in range(0, len(states), segment_size):
X = f(states[start:start + segment_size], X)
return Xtorch.utils.checkpoint.checkpoint(segment, X, use_reentrant=False) は segment 内部の中間活性化値を破棄し、乱数生成器の状態を保存・復元して(ドロップアウトの一貫性を保ちつつ)、segment を backward() の実行中に再実行する。
tf.recompute_grad(segment) は segment をラップし、GradientTape がセグメント境界の入力のみを保持して逆方向の計算時に内部の活性化値を再計算するようにする。
jax.checkpoint(または jax.remat)は(nnx.split で得られる)純粋関数を変換し、jax.grad がセグメント境界の入力のみを保存して誤差逆伝播法の実行中に内部の活性化値を再実体化するようにする。
MXNet には Python から利用できるセグメント単位のチェックポイント API がないため(ハイブリッド化されたグラフに対するプロセス全体のフラグ MXNET_BACKWARD_DO_MIRROR=1 のみ)、本項には MXNet のコードはない。
まず健全性チェックとして、活性化値の再計算によって数学的な計算結果が一切変わらないことを確認しておこう。8 ブロックのスタックを 2 つのチェックポイント付きセグメントに分割し、すべての勾配が通常の誤差逆伝播法と一致することを検証する。
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
blocks = [ResidualBlock(64) for _ in range(8)]
X = tf.random.normal((32, 64))
def stack_grads(use_checkpoint):
with tf.GradientTape() as tape:
loss = tf.reduce_sum(run_stack(blocks, X, use_checkpoint))
params = [v for blk in blocks for v in blk.trainable_variables]
return tape.gradient(loss, params)
for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
assert np.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')checkpointed gradients match the ordinary ones
X = jax.random.normal(d2l.get_key(), (32, 64))
blocks = [ResidualBlock(64, rngs=nnx.Rngs(d2l.get_key())) for _ in range(8)]
split_blocks = [nnx.split(block) for block in blocks]
graphdef = split_blocks[0][0]
states = [state for _, state in split_blocks]
def stack_grads(use_checkpoint):
loss = lambda states: run_stack(graphdef, states, X,
use_checkpoint).sum()
return jax.tree_util.tree_leaves(jax.grad(loss)(states))
for g, g_ckpt in zip(stack_grads(False), stack_grads(True)):
assert jnp.allclose(g, g_ckpt)
print('checkpointed gradients match the ordinary ones')checkpointed gradients match the ordinary ones
この正しさの確認はどの環境でも実行できるが、メモリと計算量のトレードオフを実測するため、次は GPU 上でより深い 16 ブロックのスタック(幅 1024、バッチサイズ 8192)を 4 ブロックずつのセグメントにまとめ、ステップメモリ(パラメータと入力を除いたピークメモリ)と 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
if num_gpus() > 0:
with gpu():
blocks = [ResidualBlock(1024) for _ in range(16)]
X = tf.random.normal((8192, 1024))
run_stack(blocks, X) # Create the variables
params = [v for blk in blocks for v in blk.trainable_variables]
@tf.function # One graph for each value of use_checkpoint
def step(use_checkpoint):
with tf.GradientTape() as tape:
loss = tf.reduce_sum(run_stack(blocks, X, use_checkpoint))
return tape.gradient(loss, params)
for use_checkpoint in (False, True):
step(use_checkpoint) # Trace and warm up
tf.test.experimental.sync_devices()
start = tf.config.experimental.get_memory_info('GPU:0')['current']
tf.config.experimental.reset_memory_stats('GPU:0')
timing = Benchmark(lambda: step(use_checkpoint), warmup=0)
peak = tf.config.experimental.get_memory_info('GPU:0')['peak'] - start
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 GPU: the peak-memory comparison needs a GPU.')checkpointing=False step memory 1152 MiB, 24.4 ms per step
checkpointing=True step memory 512 MiB, 30.0 ms per step
if num_gpus() > 0:
X = jax.random.normal(d2l.get_key(), (8192, 1024))
blocks = [ResidualBlock(1024, rngs=nnx.Rngs(d2l.get_key()))
for _ in range(16)]
split_blocks = [nnx.split(block) for block in blocks]
graphdef = split_blocks[0][0]
states = [state for _, state in split_blocks]
for use_checkpoint in (False, True):
step = jax.jit(jax.grad(lambda states: run_stack(
graphdef, states, X, use_checkpoint).sum()))
plan = step.lower(states).compile().memory_analysis()
timing = Benchmark(lambda: step(states))
peak = plan.temp_size_in_bytes + plan.output_size_in_bytes
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 GPU: the peak-memory comparison needs a GPU.')checkpointing=False step memory 1152 MiB, 22.7 ms per step
checkpointing=True step memory 512 MiB, 27.6 ms per step
時間を計測する他のすべての TensorFlow コードと同様に、このステップも tf.function でコンパイルしている。
ここでのステップメモリとは、コンパイルされたステップが入力以外に使用する計画のメモリ、すなわち一時配列(主に活性化値)とその出力である勾配の合計である。JAX では peak_bytes_in_use をリセットできず、前のセルの実行ですでに値が上がっているため、この目的には使えない。
チェックポイントなしでは、逆伝播は 16 ブロックすべての活性化値を同時に保持する。4 ブロックずつのセグメントにまとめると、保持されるのは 4 つのセグメント境界と処理中の 1 セグメントのみとなり、計算時間が約 4 分の 1 増える(先ほどの概算による上限 33% の範囲内である)だけで、ステップメモリは約 1.1 GiB から 0.4〜0.5 GiB へと削減される。この有利なトレードオフにより、大規模な Transformer や深い視覚モデルの訓練において、活性化チェックポイントは標準的な手法となっている。
5.7.4 デバイス対応の Trainer
これでようやく num_gpus を d2l.Trainer に組み込むことができる。ここまでの原則を実践に移すには、たった 2 つの手順で済む。訓練が始まる前にモデルパラメータを目的のデバイス上に配置すること、そして毎ステップの冒頭で各ミニバッチをそのデバイスへ移動することである。
@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))@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:
# tf.data.Dataset emits batches on CPU. Re-wrap them inside the
# GPU device context so subsequent ops keep their inputs on-device
# rather than incurring an implicit copy each step.
with self.gpus[0]:
batch = [tf.identity(a) for a in batch]
return batch@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 __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):
# Move to the CPU too: a DataLoader with worker processes delivers its
# minibatches in shared memory, cpu_shared(0), and a hybridized model
# refuses inputs that are not on the device of its parameters, cpu(0)
device = self.gpus[0] if self.gpus else d2l.cpu()
return [a.to_device(device) for a in batch]
@d2l.add_to_class(d2l.Trainer)
def prepare_model(self, model):
self.model = model
if self.gpus:
# Works even while the parameters still wait for their shapes
model.reset_device(self.gpus[0])min(num_gpus, d2l.num_gpus()) を使うことで、num_gpus は必須条件ではなく上限として扱われる。CPU のみのマシンでは self.gpus が空になり、訓練はそのままシームレスに CPU 上で実行される。本書の残りの章におけるすべての Trainer(num_gpus=1) 呼び出しの背後にあるのは、まさにこのフォールバック機構である。
小さなモデルの訓練は、GPU によって実際どれほど速くなるのだろうか。\(4096 \times 4096\) の行列積は約 \(100\times\) 以上高速化されたが、エンドツーエンドの訓練ループにはデータ読み込み、Python のディスパッチ、そしてより小さな層が含まれる。以下では、幅 256 の残差ブロック(5.7.3.3 節)を 2 つ重ね、重みを \(\mathcal{N}(0, 0.01^2)\)、バイアスを 0 で初期化した Fashion-MNIST 分類器で計測してみよう。
class ResidualBlock(nn.Block):
def __init__(self, num_hiddens):
super().__init__()
self.body = nn.Sequential()
self.body.add(nn.Dense(num_hiddens, activation='relu',
in_units=num_hiddens),
nn.Dense(num_hiddens, in_units=num_hiddens))
def forward(self, X):
return X + self.body(X)
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()
self.net.add(nn.Dense(num_hiddens, activation='relu', in_units=784),
*[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
nn.Dense(10, in_units=num_hiddens))
self.net.initialize(init.Normal(sigma=0.01))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)class ResMLPClassifier(d2l.Classifier):
def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1):
super().__init__()
self.save_hyperparameters()
normal = tf.keras.initializers.RandomNormal # One instance per layer
self.net = tf.keras.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(num_hiddens, activation='relu',
kernel_initializer=normal(stddev=0.01)),
*[ResidualBlock(num_hiddens) for _ in range(num_blocks)],
tf.keras.layers.Dense(10, kernel_initializer=normal(stddev=0.01))])class ResMLPClassifier(d2l.Classifier):
def __init__(self, num_hiddens=256, num_blocks=2, lr=0.1, rngs=None):
super().__init__()
self.save_hyperparameters(ignore=['rngs'])
rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
normal = nnx.initializers.normal(0.01)
self.net = nnx.Sequential(
lambda x: x.reshape((x.shape[0], -1)),
nnx.Linear(784, num_hiddens, kernel_init=normal, rngs=rngs),
nnx.relu,
*[ResidualBlock(num_hiddens, rngs=rngs) for _ in range(num_blocks)],
nnx.Linear(num_hiddens, 10, kernel_init=normal, rngs=rngs))上の項には MXNet のチェックポイント用コードがないため、このセルでは 5.1 節 の残差ブロックの Gluon 版を定義している。モデルの initialize はすべての重みを \(\mathcal{N}(0, 0.01^2)\) からサンプリングする。
Fashion-MNIST におけるウォームアップ後の 1 エポックの実行時間を、num_gpus=0 と 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
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
# TensorFlow runs operations on a GPU whenever there is one, and
# num_gpus=0 only keeps the minibatches where they are: the CPU scope
# keeps the whole run on the CPU
with try_gpu() if num_gpus else cpu():
trainer.fit(model, data) # The first epoch warms up and compiles
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.4 sec per epoch
num_gpus=1: 0.7 sec per epoch
data = d2l.FashionMNIST(batch_size=256)
def epoch_time(num_gpus):
# JAX creates the parameters, and runs on the minibatches, on the default
# device, the GPU whenever there is one: num_gpus=0 alone would not move
# the run to the CPU, so we set the default device
with jax.default_device(try_gpu() if num_gpus else cpu()):
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 and compiles
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: 1.3 sec per epoch
num_gpus=1: 0.7 sec per epoch
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.7 sec per epoch
num_gpus=1: 1.0 sec per epoch
この高速化倍率は良い現実確認になる。この小さな Fashion-MNIST ネットワークでは、GPU での 1 エポックは CPU より高々数倍速いだけであり、\(100\times\) の向上(\(4096 \times 4096\) の行列積での倍率)には遠く及ばない。ここでは最大の行列でも \(784 \times 256\) にすぎないため、GPU の計算能力の大部分が遊んでしまい、データの読み込みとカーネル起動のオーバーヘッドが実行時間の大半を占めている。次章以降で扱うように、大きな畳み込み、アテンションヘッド、幅の広い線形層が計算負荷の主役になって初めて、GPU は本領を発揮する。
メモリの観点では、この小さな SGD モデルは数 GB もの余裕を残して楽に収まる。しかし、80 億パラメータのモデルに立ち返ってみよう。バッチサイズを縮小し活性化チェックポイントを有効にすれば活性化メモリは抑えられるものの、fp32 の重み・勾配・Adam のモーメントが占める 128 GB の静的な下限は手つかずのままであり、しかも Trainer は OOM に直面する前に事前警告を出すことはできない。概算によるメモリ見積もりは依然として不可欠であり、単一デバイスのメモリを超えてスケールさせるには 第 13 章 で扱うマルチ GPU の並列性(parallelism)へと進むことになる。
5.7.5 まとめ
すべてのテンソルとモデルパラメータは特定のデバイス上に存在し、あらゆる演算はそのオペランドが同じデバイス上にあることを要求する。ホスト・デバイス間の転送は GPU の計算よりはるかに遅いため、モデルは最初に一度だけ配置し、バッチはステップの境界で転送し、内側ループはデバイス上に留める必要がある。GPU はコマンドキューから非同期に実行するため、Python が停止するのは同期ポイント(スカラーから Python の浮動小数点数への変換や NumPy への変換など)のみであり、信頼できるベンチマークにはウォームアップ、明示的な同期、および反復試行が欠かせない。訓練時のメモリは静的なモデル状態・オプティマイザ状態とバッチ依存の活性化値からなり、活性化チェックポイントは約 1 回分の追加の順伝播をコストとして活性化メモリを \(O(K)\) から \(O(\sqrt{K})\) へと削減する。最後に、デバイス対応の Trainer は単一 GPU への配置を自動化する一方で、GPU がない環境では CPU へとスムーズにフォールバックする。
5.7.6 演習問題
[code] ピークメモリ。幅が 1024、4096、4096、4096 で出力数が 10 の 4 層 MLP を、5.7.3.2 節 と同様に Adam で訓練する場合を考える。同項の計算方法を用いて、重み、勾配、オプティマイザ状態、および逆伝播が保持する活性化値を数え上げ、バッチサイズ 64、256、1024 における 1 訓練ステップのピークメモリを予測せよ。次に、GPU 上で実際のピーク値を計測せよ。この予測はどこで崩れ、何を見落としていたか。
チェックポイントの計算。幅 1024 の
ResidualBlockを 16 個積み重ねたスタックをバッチサイズ 8192 で動かす場合について、図 5.7.5 のスケジュールを紙の上で書き出せ。- 1 つのブロック内部で逆伝播が保持しなければならない配列を挙げ、その要素数を数えよ。
- チェックポイントなしの場合と、セグメントサイズを 1、2、4、8 ブロックとした場合について、逆伝播のピーク時に保持される活性化メモリを計算せよ。また、各スケジュールがどれだけの順伝播計算を繰り返すか述べよ。
- この設定ではどのセグメントサイズを選ぶべきか。また、その選択は 5.7.3.3 節 で述べた約 \(\sqrt{K}\) 層ごとのセグメントという規則とどのように関係するか。
[code] 非同期ディスパッチ。● 以下の両問とも、5.7.2.1 節 の時間計測の原則を用いよ。
- 256 から 8192 までの \(n\) について、\(n \times n\) 行列を CPU から GPU へ送り再び戻す往復時間と、デバイス上での 1 回の \(n \times n\) 行列積の時間を計測せよ。両者の時間が等しくなる \(n\) を求めよ(この範囲内で交差しない場合は、各時間が \(n\) に対してどう増加するかから外挿せよ)。使用している GPU の公称ホスト・デバイス間帯域幅と行列積スループットからこの交差点を予測し、予測値と実測値の間に差があればその理由を説明せよ。
- GPU が 2 基ある場合、2 つの \(4096 \times 4096\) 行列の積を 1 基の GPU 上で 1000 回実行する時間と、同じループから 2 基の GPU にそれぞれ 500 回ずつ発行して実行する時間を計測せよ。スケーリングを計測し、非同期ディスパッチによって Python がどのように両デバイスへ処理を発行できるかを説明したうえで、線形スケーリングから乖離する要因を特定せよ。実験コードは
num_gpus() >= 2でガードせよ。
[code] 同期ポイント。● GPU 上における
ResMLPClassifierの訓練実行(5.7.4 節)を考える。- モデルのコードに加えて
Trainer.fit_epoch、Trainer.prepare_batch、Averagerを読み、1 訓練ステップ内のすべての同期ポイントを列挙せよ。それぞれを「正しいループにとって不可避なもの」か「回避可能な計測・記録上の副産物」かに分類し、その分類の根拠を述べよ。 - ループが毎ステップ後に損失を Python の浮動小数点数へ読み出すとする。作成したリストをもとに、この読み出しによってデフォルトの
ResMLPClassifierとResMLPClassifier(num_hiddens=2048, num_blocks=8)がそれぞれどれだけ遅くなるかを予測せよ。次に、各モデルについて読み出しあり・なしの 1 エポックを計測し、4 つの計測結果を説明せよ。
PyTorch ドキュメントの CUDA semantics に基づき改変。
- モデルのコードに加えて