import time
from torch.utils.checkpoint import checkpoint5.7 GPU, 장치 및 메모리
2.4절 이후 Trainer는 num_gpus 인자를 받아 놓고는 정중히 무시해 왔습니다. 앞 장들의 초소형 모델에서는 CPU 훈련도 몇 초면 끝났기에 별문제가 되지 않았습니다. 그러나 모델 규모가 커지면 장치 배치가 수 초와 수 시간의 차이를 가릅니다. 최신 데스크톱 GPU는 두 개의 \(4096 \times 4096\) 행렬 곱셈을 2밀리초 미만으로 끝내지만 CPU는 0.1초 이상 걸립니다(5.7.2.1절 에서 직접 벤치마킹합니다). 이 압도적인 속도에는 엄격한 하드웨어 제약이 따릅니다. GPU는 전용 메모리(예: 데스크톱 카드의 24 GB)를 따로 갖추고 있으며, 연산 대상인 모든 텐서가 그 메모리 위에 올라와 있어야 합니다.
목표 모델이 과연 메모리에 들어갈까요? 이 장의 예제인 매개변수 80억 개 모델은 bf16 가중치에 16 GB가 들므로 추론용으로는 여유 있게 들어갑니다. 그러나 fp32와 Adam으로 훈련하려면 활성화값을 단 하나도 저장하기 전에 정적 상태만으로 128 GB(5.2절 참조)가 필요해 단일 24 GB나 80 GB 카드로는 턱없이 부족합니다. 모델이 장치에 수용되는지, 그리고 GPU가 쉴 새 없이 연산에 매진하는지 아니면 데이터를 기다리며 멈춰 서는지는 결국 모든 텐서가 어디에 위치하고 몇 바이트를 소비하느냐로 귀결됩니다.
이 절에서는 세 가지 핵심 질문에 답합니다. 텐서와 모델을 CPU와 GPU에 어떻게 배치하고 복사하는지, 비동기 GPU 실행은 어떻게 작동하며 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 장치 객체
모든 텐서는 특정 장치(device), 즉 호스트 RAM과 짝지어진 CPU 또는 전용 온보드 메모리와 짝지어진 개별 GPU 위에 상주합니다. 터미널에서 nvidia-smi를 실행하면 시스템에 장착된 모든 NVIDIA GPU와 전체·사용 중 메모리, 활성 프로세스 목록을 볼 수 있습니다. 네 프레임워크마다 장치를 부르는 이름은 조금씩 다르지만 모두 한 가지 대원칙을 따릅니다. 연산은 단일 장치에서 실행되므로 모든 피연산자가 동일한 장치 위에 있어야 합니다.
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라 불렀음).
책의 나머지 부분에서 임포트해 쓸 수 있도록 장치 조회를 세 개의 작은 보조 함수(CPU용, GPU \(i\) 용, 사용 가능한 GPU 개수 확인용)로 감쌉니다.
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로 대체하는 유연 배치(soft placement)를 사용합니다.
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()(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를 첫 번째 GPU에, Y를 두 번째 GPU에 배치하고(GPU가 두 개 미만이면 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)
이제 덧셈이 정상 실행되어 결과도 두 피연산자와 함께 두 번째 GPU에 놓입니다. 실무 규칙은 단순합니다. 계산의 경계에서 데이터를 단 한 번 전송하고(이미 해당 장치에 있는 텐서를 같은 장치로 옮기는 호출은 사실상 아무 작업도 하지 않는 no-op입니다), 내부 루프의 모든 연산은 그 단일 장치 위에서만 수행합니다.
이러한 이동에 쓰는 메서드는 to_device이며, 배열이 이미 목표 장치에 있으면 배열 자신을 그대로 반환합니다(반면 copyto는 항상 새로 복사합니다).
5.7.1.4 장치 위의 모델
순전파는 입력과 모델 매개변수를 결합하므로 모델 전체가 미니배치와 같은 장치에 상주해야 합니다. 5.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))
입력과 매개변수가 같은 장치에 함께 놓이면 순전파가 그 장치에서 실행되고 출력 역시 같은 장치 위에 반환됩니다.
두 가지 배치 원칙을 기억해야 합니다. 옵티마이저를 생성하기 전에 모델을 목표 장치로 옮기거나 초기화하고(그래야 옵티마이저 모멘트도 같은 장치에 할당됨), forward 내부에서 새로 생성하는 모든 텐서는 CPU 기본값이 아니라 X.device에 할당합니다.
5.7.2 비동기 실행
5.7.2.1 실행 큐
GPU는 Python이 연산을 호출할 때 동기적으로 실행하지 않습니다. 대신 Python이 각 커널 실행 명령을 장치의 명령 큐에 넣고 즉시 반환하면, GPU가 큐의 작업을 순서대로 처리하는 동안 CPU는 다음 작업을 미리 준비합니다. 이 파이프라이닝은 Python 오버헤드를 숨겨 주지만 시간 측정에서 결정적인 함정을 만듭니다. Python 루프가 걸린 시간을 재면 실제 실행 시간이 아니라 큐 등록 시간만 측정되기 때문입니다. 아래에서는 \(4096 \times 4096\) 행렬 곱셈 32개를 큐에 등록하며 벽시계 시간을 두 번 확인합니다. 한 번은 Python이 큐 등록을 마친 직후이고, 다른 한 번은 장치가 실제 계산을 끝낸 직후입니다.
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 문에서의 텐서 조건 분기처럼 호스트에서 구체적인 값을 돌려받아야 할 때뿐입니다. 이러한 모든 동기화 지점(synchronization point)은 GPU가 해당 값까지 큐를 비울 때까지 Python을 멈춰 세우고, 다시 Python이 뒤따라잡는 동안 GPU를 유휴 상태로 놀게 만듭니다(그림 5.7.2 참조). 매 미니배치마다 손실을 Python 숫자로 기록하면 매 스텝마다 동기화 거품(bubble)이 끼어드는 셈이며, 바로 이 때문에 Trainer는 손실을 장치 위의 d2l.Averager 안에 유지하다가 에포크당 한 번만 Python 부동소수점으로 변환합니다(2.4절 참조).
비동기 디스패치는 신뢰할 수 있는 GPU 벤치마크를 위한 네 가지 규칙도 규정합니다. (1) 일회성 메모리 할당, 라이브러리 초기화, JIT 컴파일을 배제하기 위해 먼저 웜업 호출을 실행하고, (2) 타이머 시작 직전과 종료 직전 양쪽에서 장치를 동기화하며, (3) 여러 번 반복해 평균을 내고, (4) 밀리초 미만의 해상도를 위해 time.perf_counter를 사용합니다. (위 시연 셀도 웜업과 동기화를 거쳤으나 32회 곱셈의 합계를 출력했으며, 아래 Benchmark 보조 클래스는 이 장과 뒷장들을 위해 네 규칙을 모두 자동화합니다.)
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는 마지막 호출의 반환값이 준비될 때까지 대기합니다.
앞서 언급한 두 가지 주장, 즉 대규모 행렬 곱셈에서 GPU가 CPU보다 얼마나 빠른지와 호스트→장치 전송이 연산에 비해 얼마나 비싼지를 Benchmark로 즉시 검증해 봅시다. 아래에서는 CPU(fp32)와 GPU(tf32(5.5절 참조) 및 16비트 정밀도)에서의 \(4096 \times 4096\) 행렬 곱셈 시간과 단일 \(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를 사용합니다. 행렬 곱이 bf16을 지원하지 않으므로 여기서는 동일한 텐서 코어에서 같은 속도로 실행되는 fp16으로 16비트 곱셈을 측정합니다.
최신 GPU에서 \(4096 \times 4096\) 행렬 곱셈은 2 ms 미만으로 끝나는 반면 CPU는 약 100 ms~2 s가 걸립니다(CPU 코어 수에 따라 약 \(100\times\) 에서 \(1000\times\) 속도 향상). 16비트 정밀도로 낮추면 GPU 시간이 다시 절반가량 줄어들어 5.5절 에서 약속한 텐서 코어 가속을 그대로 보여 줍니다.
마지막 줄에 특히 주목해 봅시다. 복사된 원소 하나당 4096번의 곱셈-덧셈을 수행함에도, 행렬을 CPU 메모리에서 GPU로 단순히 복사하는 데 걸리는 시간이 도착 후 행렬을 곱하는 시간보다 오히려 3~6배 더 오래 걸립니다. 일반 호스트 복사는 GPU의 DMA 엔진이 직접 끌어갈 수 있도록 데이터를 먼저 고정(pinned, 페이지 잠금) 호스트 메모리에 임시 복사하는 단계를 거치는데, 배치를 미리 고정 메모리에 올려 두면 이 추가 복사가 사라지고 데이터 전송과 연산을 중첩할 수 있습니다(13.2절 참조).
5.7.3 GPU 메모리
5.7.3.1 메모리의 세 가지 뷰
훈련 스크립트가 GPU 메모리를 얼마나 쓰는지 물으면 스택의 어느 계층에 질의하느냐에 따라 세 가지 서로 다른 숫자를 얻게 됩니다. CUDA 드라이버에 직접 메모리를 요청하는 작업은 느리므로, 프레임워크는 드라이버로부터 큰 메모리 블록(slab)들을 미리 받아 텐서에 나누어 주고 해제된 블록도 즉시 반납하지 않고 재사용을 위해 붙들고 있는 내부 캐싱 할당자(caching allocator)를 운용합니다. 이로 인해 세 겹으로 중첩된 메모리 뷰(그림 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 이상을 내줄 수 없으므로 엄격한 메모리 부족(OOM) 한계선을 결정합니다. 반면 작성한 코드 내부에서 메모리가 어디로 가는지 진단하려면 활성 바이트 카운터, 특히 스텝의 성공과 메모리 부족(OOM) 충돌을 가르는 호출 중 피크(peak) 메모리를 살펴보아야 합니다.
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절 에서는 매개변수가 \(N\) 개일 때 fp32 Adam 훈련의 정적 메모리 하한이 \(16N\) 바이트(가중치 \(4N\), 그레이디언트 \(4N\), Adam 모멘트 \(8N\))임을 확인했습니다. 실제 훈련 스텝이 시작되면 여기에 네 번째 항인 활성화값이 합류합니다. 역전파는 순전파의 중간 출력을 역전파가 소비할 때까지 보관해야 하며, 정적인 \(16N\) 과 달리 활성화 메모리는 미니배치 크기와 층 너비에 선형으로 비례해 커집니다. 측정 전에 미리 계산해 볼 수도 있습니다. 미니배치 크기 4096에서 1024차원 입력을 받는 너비 4096의 은닉층 세 개짜리 MLP(\(N \approx 3.8 \times 10^7\) 개 매개변수이므로 \(4N \approx 144\) MiB)를 생각해 봅시다. 세 은닉층의 출력은 각각 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의 두 모멘트(\(8N\))를 할당합니다. 그림 5.7.4 에서는 16 MiB 입력 배치를 제외한 네 단계를 보여 줍니다. 두 번째 스텝부터는 매 스텝 안에서 메모리가 오르내립니다. 순전파가 가중치와 Adam 모멘트 위에 활성화값을 쌓고, 역전파가 이를 그레이디언트로 교체합니다. 피크 사용량은 최대 정적 \(16N\) 더하기 활성화값이며, 다음 순전파 전에 이전 그레이디언트를 먼저 해제하는 루프에서는 최대 \(4N\) 만큼 더 낮아집니다. 활성화값 때문에 메모리가 한계를 넘을 때 가장 빠른 지렛대는 아키텍처를 건드리지 않고 활성화 메모리 사용량을 줄여 주는 미니배치 크기 축소입니다. 반대로 메모리가 스텝을 거듭할수록 꾸준히 치솟는다면 이전 계산 그래프를 살아 있게 붙잡아 두는 메모리 누수를 의심해야 하며, 대표적인 원인은 손실 텐서를 분리(detach)하지 않은 채 Python 리스트에 그대로 추가하는 실수입니다.
optimizer.zero_grad()는 기본적으로 그레이디언트 메모리를 해제하므로(set_to_none=True), 순전파 전에 이를 호출하는 루프는 활성화값이 저장되는 동안 \(16N\) 바이트가 아니라 \(12N\) 바이트를 보유합니다.
5.7.3.3 활성화 체크포인팅
활성화 메모리를 줄이는 두 번째 아키텍처적 지렛대도 있습니다. 표준 역전파는 역전파 시 단 한 번 읽을 목적으로 모든 층의 중간 출력을 저장해 둡니다. 활성화 체크포인팅(activation checkpointing, 그레이디언트 체크포인팅(gradient checkpointing) 또는 재실체화(rematerialization)라고도 함, (Chen 기타 2016년))은 순전파 중 대부분의 중간 활성화값을 버리고 선택된 세그먼트 경계의 입력만 남겨 둔 뒤, 역전파 도중 각 세그먼트 내부의 활성화값을 즉석에서 다시 계산합니다. (이름에 같은 단어가 들어가지만 이 메모리 내 기법은 5.6절 의 디스크 체크포인트와는 무관합니다.)
\(K\) 개의 균일한 층을 층 \(s\) 개짜리 세그먼트들로 나누면 \(K/s\) 개의 세그먼트 경계와 현재 활성 세그먼트 내부의 활성 텐서 \(s\) 개(\(K\) 개 대신 약 \(K/s + s\) 개의 텐서)만 저장하면 됩니다. \(s = \sqrt{K}\) 로 택하면 피크 활성화 메모리가 \(O(K)\) 에서 \(O(\sqrt{K})\) 로 줄어듭니다. 그 대가는 역전파 중 세그먼트마다 수행하는 추가 순전파 한 번입니다(그림 5.7.5 참조). 선형 층의 역전파는 두 번의 행렬 곱(입력 그레이디언트와 가중치 그레이디언트)을 계산하고 순전파는 한 번을 계산하므로, 순전파를 한 번 더 수행하면 스텝 전체 연산량이 순전파 환산 약 3회에서 4회로 늘어나 하드웨어와 층 구성에 따라 대략 33% 수준의 상한 오버헤드가 발생합니다.
활성화 체크포인팅은 앞선 잔차 MLP(5.1절 참조)나 현대 트랜스포머처럼 동일한 블록을 깊게 쌓은 구조에서 진가를 발휘합니다. 아래에서는 \(\mathcal{N}(0, 0.01^2)\) 가중치와 영편향을 가진 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 내부의 중간 활성화값을 버리고 RNG 상태를 저장·복원하여(드롭아웃 일관성 유지) backward() 중에 segment를 다시 실행합니다.
tf.recompute_grad(segment)로 segment를 감싸면 GradientTape가 세그먼트 경계 입력만 유지하고 역전파 시 내부 활성화값을 다시 계산합니다.
jax.checkpoint(또는 jax.remat)는 (nnx.split으로 얻은) 순수 함수를 변환하여 jax.grad가 세그먼트 경계 입력만 저장하고 역전파 중 내부 활성화값을 재실체화하게 합니다.
MXNet은 Python에서 세그먼트별 체크포인팅 API를 제공하지 않으므로(하이브리드 그래프용 프로세스 전역 플래그 MXNET_BACKWARD_DO_MIRROR=1만 있음) 이 소절에는 MXNet 코드가 없습니다.
먼저 정합성부터 점검합니다. 활성화값을 재계산하더라도 수학적 결과가 절대 달라져서는 안 됩니다. 두 개의 체크포인팅 세그먼트로 나눈 8블록 스택에서 모든 그레이디언트가 표준 역전파와 일치하는지 확인합니다.
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
이 정확성 점검은 어디서나 실행되지만, 메모리–연산 트레이드오프를 측정하기 위해 4블록 세그먼트로 묶은 더 깊은 16블록 스택(너비 1024, 배치 크기 8192)을 GPU로 옮겨 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블록 세그먼트로 묶으면 네 개의 세그먼트 경계와 활성 세그먼트 하나만 유지하여 약 25%의 추가 연산 시간만으로(어림잡은 33% 상한 이내) 스텝 메모리를 약 1.1 GiB에서 0.4~0.5 GiB로 절반 이상 줄입니다. 이 유리한 교환비 덕분에 활성화 체크포인팅은 대규모 트랜스포머와 깊은 비전 모델 훈련의 표준 기법으로 쓰입니다.
5.7.4 장치 인식 Trainer
이제 마침내 num_gpus를 d2l.Trainer에 연결할 수 있습니다. 앞서 세운 원칙을 적용하는 일은 단 두 단계면 됩니다. 훈련이 시작되기 전에 모델 매개변수를 목표 장치에 배치하고, 매 스텝이 시작될 때마다 각 미니배치를 해당 장치로 옮기는 것입니다.
@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 디스패치, 그리고 작은 층들이 함께 섞여 있습니다. 아래에서는 \(\mathcal{N}(0, 0.01^2)\) 가중치와 영편향을 가진 너비 256짜리 잔차 블록 두 개(5.7.3.3절 참조)로 구성된 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)\) 에서 추출합니다.
num_gpus=0과 num_gpus=1에서 웜업 이후 Fashion-MNIST 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보다 기껏해야 몇 배 빠른 수준으로, \(4096 \times 4096\) 행렬 곱셈에서 본 \(100\times\) 이득에는 근처에도 미치지 못합니다. 여기서는 가장 큰 행렬이 \(784 \times 256\) 에 불과해 GPU 연산 유닛 대부분이 놀고 있는 반면 데이터 적재와 커널 실행 오버헤드가 전체 시간을 지배하기 때문입니다. GPU는 다음 장부터 등장하는 대규모 합성곱, 어텐션 헤드, 넓은 선형 층이 작업량을 지배할 때 비로소 제 위력을 발휘합니다.
메모리 관점에서 이 소형 SGD 모델은 수 기가바이트의 여유를 남기며 거뜬히 들어갑니다. 하지만 매개변수 80억 개 모델로 다시 돌아가 봅시다. 배치 크기를 줄이고 활성화 체크포인팅을 켜면 활성화 메모리는 길들일 수 있지만 fp32 가중치, 그레이디언트, Adam 모멘트가 만드는 128 GB 정적 하한은 조금도 줄어들지 않으며, Trainer는 OOM에 부딪히기 전에 미리 경고해 줄 수 없습니다. 어림셈으로라도 메모리 예산을 미리 산정하는 습관은 언제나 필수적이며, 단일 장치 메모리를 넘어서는 확장은 13장 의 다중 GPU 병렬화로 이어집니다.
5.7.5 요약
모든 텐서와 모델 매개변수는 특정 장치에 상주하며 모든 연산은 피연산자들이 같은 장치에 있을 것을 요구합니다. 호스트–장치 간 전송은 GPU 연산보다 훨씬 느리므로 모델은 시작 시 한 번만 배치하고 배치는 스텝 경계에서 전송하며 내부 루프는 장치 위에서만 실행합니다. GPU는 명령 큐에서 비동기로 실행되므로 Python은 (스칼라의 Python 부동소수점 변환이나 NumPy 변환 같은) 동기화 지점에서만 대기하며, 신뢰할 수 있는 벤치마크에는 웜업, 명시적 동기화, 반복 측정이 필수적입니다. 훈련 메모리는 정적 모델·옵티마이저 상태에 배치 의존적 활성화값이 더해진 크기이며, 활성화 체크포인팅은 추가 순전파 약 1회를 대가로 활성화 메모리를 \(O(K)\) 에서 \(O(\sqrt{K})\) 로 줄여 줍니다. 마지막으로 장치 인식 Trainer는 단일 GPU 배치를 자동화하는 동시에 GPU가 없을 때 CPU로 깔끔하게 대체 실행됩니다.
5.7.6 연습 문제
[code] 피크 메모리. 5.7.3.2절 에서와 같이 너비가 1024, 4096, 4096, 4096이고 출력이 10개인 4층 MLP를 Adam으로 훈련한다고 합시다. 해당 소절의 산정 방식을 사용해 가중치, 그레이디언트, 옵티마이저 상태 및 역전파가 보관하는 활성화값을 모두 세어 배치 크기 64, 256, 1024에서 단일 훈련 스텝의 피크 메모리를 예측하십시오. 그런 다음 GPU에서 실제 피크 메모리를 측정하십시오. 예측은 어디서 어긋나며 무엇을 빠뜨렸습니까?
체크포인팅 산술. 배치 크기 8192에서 너비 1024인
ResidualBlock16개를 쌓은 스택에 대해 그림 5.7.5 의 스케줄을 종이 위에서 직접 계산해 보십시오.- 단일 블록 내부에서 역전파가 보관해야 하는 배열들의 이름을 적고 각각의 원소 개수를 세십시오.
- 체크포인팅을 쓰지 않을 때와 블록 1개, 2개, 4개, 8개 단위 세그먼트를 쓸 때 역전파 정점에서 보유하는 활성화 메모리를 각각 계산하고, 각 스케줄이 순전파 연산을 얼마나 반복하는지 밝히십시오.
- 이 조건에서는 어떤 세그먼트 크기를 선택하겠습니까? 이는 5.7.3.3절 에서 다룬 약 \(\sqrt{K}\) 개 층 단위 세그먼트 규칙과 어떻게 연결됩니까?
[code] 비동기 디스패치. ● 두 문항 모두 5.7.2.1절 의 시간 측정 규칙을 적용하십시오.
- \(n\) 을 256부터 8192까지 변화시키며 \(n \times n\) 행렬을 CPU에서 GPU로 보냈다가 다시 돌려받는 왕복 시간과 장치에서의 \(n \times n\) 행렬 곱셈 1회 시간을 각각 측정하십시오. 두 시간이 같아지는 \(n\) 을 찾되, 이 범위 안에서 교차하지 않으면 각 시간이 \(n\) 에 따라 커지는 추세를 외삽하여 구하십시오. 사용 중인 GPU의 공인 호스트→장치 대역폭과 행렬 곱 처리량으로부터 이 교차점을 이론적으로 예측하고 측정값과의 차이를 설명하십시오.
- GPU가 두 장 이상 있다면 두 개의 \(4096 \times 4096\) 행렬 곱셈 1000회를 단일 GPU에서 실행한 시간과, 동일한 루프에서 두 GPU에 각각 500회씩 발행한 시간을 측정하십시오. 확장 효율을 측정하고 비동기 디스패치가 어떻게 Python으로 하여금 두 장치에 동시에 작업을 발행하게 하는지 설명한 뒤, 선형 확장에서 벗어나는 원인을 찾으십시오. 실험 코드는
num_gpus() >= 2조건으로 보호하십시오.
[code] 동기화 지점. ● 5.7.4절 의
ResMLPClassifier를 GPU에서 훈련하는 과정을 살펴봅시다.- 모델 코드뿐 아니라
Trainer.fit_epoch,Trainer.prepare_batch,Averager를 읽고 단일 훈련 스텝에 존재하는 모든 동기화 지점을 나열하십시오. 각각을 올바른 루프 동작에 불가피한 동기화와 피할 수 있는 계측 부산물로 분류하고 그 근거를 제시하십시오. - 루프가 매 스텝 직후 손실을 Python 부동소수점으로 읽어 들인다고 가정합시다. 작성한 목록을 바탕으로 이 읽기가 기본
ResMLPClassifier와ResMLPClassifier(num_hiddens=2048, num_blocks=8)을 얼마나 느리게 만들지 예측하십시오. 이어서 각 모델에 대해 읽기 유무별 1에포크 시간을 측정하고 네 측정값을 설명하십시오.
PyTorch 공식 문서 CUDA semantics에서 발췌·수정.
- 모델 코드뿐 아니라