GPU, 장치 및 메모리

Dive into Deep Learning · §5.7

GPU, 장치 및 메모리 예산
장치 배치 · PCIe 복사 병목 · 비동기 명령 큐 · 3단계 메모리 뷰 · O(\sqrt{K}) 활성화 체크포인팅

장치 배치와 메모리 예산이 모델 규모를 좌우하는 이유

하드웨어 처리량 대 HBM 용량

  • 전용 온보드 메모리(HBM): 8B 모델은 bf16 추론(16 GB 가중치) 시 24 GB GPU에 들어가지만, fp32 Adam 훈련에는 활성화값 저장 전에 정적 상태만으로 128 GB가 필요하다.
  • 동일 장치 상주 요건: 장치 간 PCIe 전송은 행렬 곱셈보다 3\text{--}6\times 느리므로 모든 입력, 가중치, 버퍼가 같은 장치에 있어야 한다.
  • 비동기 명령 큐: Python은 GPU 커널을 큐에 넣고 즉시 반환하며, 매 스텝 호스트 스칼라를 읽으면 파이프라인이 멈춘다.

자동 CPU 대체 기능을 갖춘 하드웨어 장치 조회

장치 추상화

모든 텐서는 특정 장치(cpu(), gpu(i))에 상주한다. try_gpu(i) 보조 함수는 GPU i가 있으면 선택하고 없으면 깔끔하게 CPU로 대체해 어디서든 노트북이 그대로 실행되게 한다:

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

연산은 장치가 어긋난 피연산자를 즉시 거부한다

암묵적 장치 간 복사 금지

  • X를 GPU 0에, Y를 GPU 1(또는 CPU)에 두고 X + Y를 계산하면 암묵적 PCIe 복사로 훈련 루프가 느려지지 않도록 즉시 런타임 오류가 발생한다:
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

명시적 장치 전송: 경계에서 단 한 번만 복사하라

장치 간 텐서 이동

서로 다른 장치의 텐서를 결합하려면 먼저 X를 Y의 장치로 명시적으로 복사한다:

Z = X.to(try_gpu(1))
(Y + Z).device
device(type='cuda', index=1)
  • 전송 원칙: 루프 경계에서 데이터를 단 한 번 옮기고 내부 루프의 모든 연산은 단일 장치 위에서 유지한다.

모델 트리 전체를 목표 장치에 배치하기

매개변수와 입력의 동일 장치 배치

  • 옵티마이저를 생성하기 전에 모델을 목표 GPU로 이동·초기화하고(그래야 Adam 모멘트도 GPU에 할당됨), forward 내부의 새 텐서는 X.device에 할당한다:
net = nn.Sequential(nn.Linear(3, 1))
net = net.to(device=try_gpu())
net(X)
tensor([[-0.2254],
        [-0.2254]], device='cuda:0', grad_fn=<AddmmBackward0>)

비동기 GPU 실행: 명령 큐

Python이 GPU를 구동하는 방식

Python은 B = A @ A가 끝나기를 기다리지 않고 GPU의 실행 큐에 커널 실행을 밀어 넣은 뒤 곧바로 다음 줄로 넘어간다:

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
  • 큐 등록 대 실제 연산: 4096 \times 4096 행렬 곱셈 32개를 큐에 넣는 데는 CPU에서 수 밀리초면 끝나지만, GPU가 큐를 비우는 데는 수십 밀리초가 걸린다.

동기화 지점은 CPU–GPU 파이프라인을 멈춰 세운다

파이프라인을 끊지 마라

  • 동기화 정체를 유발하는 호출: loss.item(), float(loss), print(tensor), .numpy(), 텐서 조건 분기(if loss < best:)는 큐의 작업이 모두 끝날 때까지 CPU를 멈추고 GPU를 유휴 상태로 만든다.
  • 시스템 모범 관례: 스텝별 손실은 장치 위 텐서에 누적하고 에포크 끝에서 한 번만 Python 부동소수점으로 변환한다.

정확한 GPU 벤치마킹을 위한 네 가지 규칙

비동기 커널 시간 측정

  • 웜업 + 이중 동기화: 웜업 반복을 먼저 수행하고, perf_counter() 시작 직전과 종료 직전 모두 장치를 동기화한다.

네 가지 규칙을 지키는 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'

4096×4096 행렬 곱셈 대 PCIe 호스트→장치 복사

연산 처리량 대 메모리 대역폭

CPU(fp32)와 GPU(tf32 및 16비트)에서의 4096 \times 4096 행렬 곱셈과 CPU→GPU 복사의 시간을 비교하면 딥러닝 하드웨어의 근본적인 병목이 드러난다:

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
  • 연산은 GPU가 100\text{--}1000\times 빠름: Tensor Core는 4096^3 \approx 6.9 \times 10^{10} 회의 곱셈-덧셈을 2 ms 미만에 끝낸다(16비트 정밀도는 이를 다시 절반으로 단축).
  • PCIe 복사가 행렬 곱보다 3\text{--}6\times 더 걸림: PCIe로 4096^2 \times 4\text{ B} = 64\text{ MiB} 를 복사하는 시간이 GPU에서 원소당 4096 회 곱셈-덧셈을 수행하는 시간보다 길다.

세 겹으로 중첩된 GPU 메모리 뷰

활성 텐서 대 캐싱 할당자 대 CUDA 드라이버

프로세스의 GPU 메모리 사용량은 메모리 계층의 어느 단계에 질의하느냐에 따라 세 가지 다른 답을 내놓는다:

after creating big:  1192.1 MiB allocated,  1302.0 MiB reserved
after deleting it :   168.1 MiB allocated,  1302.0 MiB reserved
  • del big 후에도 nvidia-smi가 그대로인 이유: 프레임워크의 캐싱 할당자가 느린 CUDA 드라이버 호출 없이 즉시 재사용하려고 해제된 GPU 블록을 예약 풀에 보관하기 때문이다.

단일 훈련 스텝의 메모리 변화 해부하기

가중치 + 활성화값 + 그레이디언트 + 옵티마이저 모멘트

3은닉층 MLP(1024 \to 4096 \to 4096 \to 4096 \to 10, 가중치 4N \approx 144\text{ MiB}, 배치 크기 B = 4096)의 단일 훈련 스텝에서 활성 GPU 메모리를 추적하면 네 메모리 요소가 등장하는 순서가 그대로 드러난다:

weights              160.2 MiB
+ activations        353.4 MiB
+ gradients          313.6 MiB
+ optimizer state    602.0 MiB
  • 가중치를 넘어서는 활성화값(+192\text{ MiB}): 세 개의 4096 \times 4096 은닉 출력(3 \times 64\text{ MiB} = 192\text{ MiB})이 forward 중 메모리에 머물다가 backward에서 해제되면서 그레이디언트(+144\text{ MiB})와 Adam 모멘트(+288\text{ MiB})가 실체화된다.

8B 모델은 24 GB 또는 80 GB GPU에 들어갈까?

정적 예산 대 동적 메모리 예산

  • 추론(bf16 16 GB 대 fp32 32 GB): bf16은 단일 24 GB GPU에 들어가며 KV 캐시·활성화값용으로 8 GB가 남는다.
  • 훈련(헤드 전용 38.3 GB 대 전체 fp32 Adam 128 GB): 헤드 전용 미세 조정은 80 GB GPU 한 장에 들어가지만 전체 fp32 Adam에는 \ge 2 개의 GPU가 필요하다.
  • 활성화 OOM(O(K \cdot B \cdot T \cdot d)): 먼저 마이크로배치 크기 B 를 절반으로 줄이고, 이어서 활성화 체크포인팅을 켠다.

활성화 체크포인팅: 추가 순전파 1회로 O(√K) 메모리 달성

연산량과 활성화 메모리의 맞교환

활성화 체크포인팅(Chen et al., 2016)은 세그먼트 경계만 저장하고 나머지는 backward 중에 재계산한다:

  • O(K) \to O(\sqrt{K}) 피크 활성화: K 개 층을 크기 s 인 세그먼트로 나누면 경계 텐서 K/s 개와 활성 내부 텐서 s 개를 보유한다(총 K/s + s 개, s = \sqrt{K} 에서 2\sqrt{K} 개로 최소).
  • 유계된 연산 오버헤드: 각 세그먼트 재계산은 순전파를 한 번 추가할 뿐이다(스텝 시간 약 20\text{--}30\% 증가).

세그먼트별 활성화 체크포인팅 구현하기

잔차 블록 스택 체크포인팅

class ResidualBlock(nn.Module):
    def __init__(self, num_hiddens):
        super().__init__()
        self.body = nn.Sequential(
            nn.Linear(num_hiddens, num_hiddens), nn.ReLU(),
            nn.Linear(num_hiddens, num_hiddens))
        for layer in self.body[0], self.body[2]:
            nn.init.normal_(layer.weight, std=0.01)
            nn.init.zeros_(layer.bias)

    def forward(self, X):
        return X + self.body(X)

def run_stack(blocks, X, use_checkpoint=False, segment_size=4):
    for start in range(0, len(blocks), segment_size):
        stop = min(start + segment_size, len(blocks))
        # Bind this segment's range now: the backward pass calls segment
        # again after the loop has moved on
        def segment(X, start=start, stop=stop):
            for i in range(start, stop):
                X = blocks[i](X)
            return X
        X = checkpoint(segment, X, use_reentrant=False) \
            if use_checkpoint else segment(X)
    return X
  • ResidualBlock 모듈들을 segment_size = 4 단위로 묶어 프레임워크 체크포인트 래퍼로 감싸면 O(\sqrt{K}) 메모리로 정확한 그레이디언트를 얻는다.

체크포인팅 그레이디언트는 일반 역전파와 정확히 일치한다

잔차 블록 스택 체크포인팅

  • 활성화 재계산이 수학적 결과를 바꿔서는 안 된다. 두 세그먼트로 나눈 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

측정 결과: ~25% 추가 시간으로 스텝 메모리 50% 이상 절감

GPU 위의 16개 잔차 블록

16블록 잔차 스택(d = 1024, 배치 크기 B = 8192, 4블록 세그먼트)에서 활성화 체크포인팅은 피크 스텝 메모리를 \sim 1.1\text{ GiB} 에서 \sim 0.45\text{--}0.5\text{ GiB} 로 줄인다:

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

d2l.Trainer에 자동 장치 배치 연결하기

장치 인식 Trainer

def __init__(self, max_epochs, num_gpus=0, gradient_clip_val=0):
    self.save_hyperparameters()
    self.gpus = [d2l.gpu(i) for i in range(min(num_gpus, d2l.num_gpus()))]
    self.board = d2l.ProgressBoard(xlabel='epoch', ylabel='loss')

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

def prepare_model(self, model):
    self.model = model
    if self.gpus:
        model.to(self.gpus[0])
        # Pick convolution algorithms by timing, unless determinism is wanted
        torch.backends.cudnn.benchmark = not (
            torch.are_deterministic_algorithms_enabled()
            or torch.backends.cudnn.deterministic)
    # Lazy parameters get their shapes from a dry pass on the device, then
    # the model's weight_init, if it has one, before the optimizer exists
    if any(isinstance(p, nn.parameter.UninitializedParameter)
           for p in model.parameters()):
        loader = (self.train_dataloader if self.train_dataloader is not None
                  else self.val_dataloader)  # `evaluate` has no training data
        batch = self.prepare_batch(next(iter(loader)))
        model.apply_init(batch[:-1], getattr(model, 'weight_init', None))
  • d2l.Trainer는 prepare_model에서 모델을, prepare_batch에서 각 미니배치를 self.gpus[0]로 옮기며 GPU가 없으면 CPU로 대체한다.

CPU와 GPU에서 장치 인식 Trainer 시간 측정하기

장치 인식 Trainer

num_gpus=0: 2.9 sec per epoch
num_gpus=1: 1.1 sec per epoch
  • 초소형 모델의 GPU 가속이 제한적인 이유: 너비 256인 Fashion-MNIST MLP에서는 행렬이 기껏해야 784 \times 256 이므로 데이터 적재와 Python 커널 실행 지연 시간이 지배적이며, 넓은 층·합성곱·어텐션이 연산을 지배할 때 100\times 가속이 달성된다.

개념 확인: 비동기 큐와 활성화 메모리

개념 확인

다음 세 가지 시나리오로 시스템 직관을 점검해 보자:

  1. GPU 훈련 루프가 매 미니배치 스텝마다 if loss < best_loss: best_loss = loss를 실행한다. 이 단 한 줄의 if 문이 GPU 활용률을 떨어뜨리는 이유는 무엇이며 어떻게 고쳐야 하는가?
  2. 깊은 트랜스포머가 동일한 블록 K = 36 개를 쌓는다. 역전파 피크 시점에 보유하는 블록 입력 활성화 텐서 개수는 체크포인팅 미적용(s = 36), 매 블록 체크포인팅(s = 1), 최적 세그먼트 크기 s = \sqrt{36} = 6 일 때 각각 몇 개인가?
  3. 2 GiB GPU 텐서를 삭제하면 프레임워크의 할당 메모리 카운터는 2 GiB 줄어들지만 nvidia-smi는 전혀 변하지 않는다. 왜 그런가?

정답:

  1. Python bool 평가(loss < best_loss)가 매 스텝 CPU–GPU 동기화를 강제하여 명령 큐를 비우기 때문이다. 해결책: 장치 위에서 best_loss = minimum(best_loss, loss)로 갱신하고 에포크당 한 번만 읽는다.
  2. 피크 저장 블록 활성화 수(K/s + s): 미적용 시 36 개, s = 1 은 36/1 + 1 = 37 개, 최적 s = 6 은 36/6 + 6 = 12 개만 보유한다(3\times 절감).
  3. 캐싱 할당자가 해제된 블록을 예약 풀에 그대로 유지하여 CUDA 드라이버(nvidia-smi)에 반납하지 않고 다음 텐서에 재사용하기 때문이다.

요약: GPU, 장치 및 메모리 예산

핵심 정리

  • 동일 장치 배치와 비동기 큐: 옵티마이저 생성 전에 모델을 GPU로 옮기고 배치는 경계에서 한 번만 전송하며 매 스텝 호스트 동기화 정체를 피한다.
  • 벤치마킹과 메모리 뷰: GPU 타이머 전후로 반드시 웜업과 동기화를 수행하며, 활성 할당 바이트를 캐싱 할당자 풀 및 nvidia-smi와 구분한다.
  • 활성화 체크포인팅: K 개 층을 s = \sqrt{K} 단위로 분할하면 \sim 25\text{--}33\% 추가 연산으로 활성화 메모리가 O(K) 에서 O(\sqrt{K}) 로 줄어든다.