콘텐츠로 이동

6. CUDA에서 이전하기

GPU에서 도는 PyTorch 코드는 대부분 cuda를 기준으로 작성되어 있습니다. 이 장은 cuda 코드를 lpu로 옮길 때 바꿔야 할 것과 그대로 두어도 되는 것을 정리합니다.

Contents

Section Objective
6.1 이름 대응 CUDA API와 대응하는 LPU API
6.2 코드를 바꿔야 하는 차이 계산 경로, 커버리지, 텐서 생성, 동기화 등 수정이 필요한 영역
6.3 바꾸지 않아도 되는 것 그대로 동작하는 PyTorch 사용 패턴
6.4 이전 절차 이전 작업의 권장 순서
6.5 예제 같은 코드의 CUDA판과 LPU판 비교

6.1 이름 대응

CUDA LPU
torch.device("cuda") torch.device("lpu")
tensor.cuda() tensor.to("lpu")
torch.cuda.is_available() torch.accelerator.is_available()
torch.cuda.set_device(i) torch.accelerator.set_device_index(i)
torch.cuda.device_count() torch.accelerator.device_count()
torch.cuda.device(i) torch.accelerator.device_index(i)
torch.compile(model) torch.compile(model, backend="legato", options={"legato.device": "bertha"})
torch.autocast("cuda") 명시적 캐스팅(.to(torch.bfloat16)). §6.2 참조
dist.init_process_group("nccl") dist.init_process_group("lccl")
torch.cuda.synchronize() torch.accelerator.synchronize() 또는 값 읽기. §6.2 참조
torch.cuda.Stream / Event PyTorch에서는 기본 스트림(torch.accelerator.current_stream())만 씀. torch.Stream("lpu")와 torch.Event는 아직 없음
torch.cuda.memory_allocated() torch.accelerator.memory_allocated()
import torch 동일. import torch_ha는 필요하지 않습니다

6.2 코드를 바꿔야 하는 차이

영역 CUDA LPU
모델 계산 경로 eager로 모두 실행 torch.compile(backend="legato")로 컴파일해야 디바이스에서 실행됨. 기본 백엔드(inductor)는 lpu 커널을 만들지 못해 실패. 연산
연산 커버리지 사실상 ATen 전체 torch.compile 경로의 legato resolver가 결정. eager 계산은 bfloat16의 add, sub, mul, mm 네 연산만 실험적으로 지원
등록되지 않은 연산 드묾 lpu 백엔드를 언급하는 디스패치 에러
텐서 생성 torch.randn(..., device="cuda") 값 팩토리는 device="lpu"(현재 디바이스)나 명시적 인덱스로 동작. 난수 텐서는 CPU에서 만든 뒤 .to("lpu")
명시적 동기화 torch.cuda.synchronize() 값을 읽어 동기화(.cpu(), .item()) 또는 torch.accelerator.synchronize()
한 프로세스에서 여러 디바이스 torch.cuda.set_device(i) 지원. torch.accelerator.set_device_index(i). 분산 §4.2
Autocast 연산 dtype을 바꿈 torch.autocast("lpu") 안의 연산은 NotImplementedError를 냄. 명시적 캐스팅(.to(torch.bfloat16))
집합 연산 범위 모든 NCCL 연산과 리덕션 LCCL이 구현한 연산과 리덕션만. reduce, gather, scatter, all_to_all은 쓸 수 없음. LCCL 매트릭스
학습 지원 추론 전용

6.3 바꾸지 않아도 되는 것

다음은 CUDA에서와 같이 동작합니다.

  • 텐서와 모듈의 .to("lpu"), 그리고 .cpu()로 호스트에 가져오기
  • LPU 텐서의 torch.save / torch.load (map_location="cpu" 로드는 디바이스 시맨틱 §2.5 참조)
  • 표준 환경 변수와 torchrun을 쓰는 torch.distributed
  • 랭크마다 디바이스를 먼저 고르고 이후에는 인덱스 없이 할당하는 방식
  • LPU 텐서의 view, 슬라이싱, reshape (디바이스 계산이 그대로 받는 슬라이스에는 조건이 있습니다. 디바이스 시맨틱 §슬라이싱을 보십시오)
  • bfloat16 모듈 캐스트(float16은 저장 용도)

6.4 이전 절차

  1. 디바이스 문자열 교체. cuda → lpu, nccl → lccl.
  2. 난수 텐서 생성을 디바이스 밖으로 옮기기. 값 팩토리(zeros, full 등)는 device="lpu"(현재 디바이스)나 명시적 인덱스로 동작합니다. torch.randn(..., device=dev)는 CPU 생성 후 .to(dev)로 바꿉니다.
  3. CPU에서 legato dry-run으로 모델을 확인하십시오. 방법은 연산 §3.3에 있습니다. 이전할 수 있는지가 이 단계에서 정해지므로, 나머지 단계보다 먼저 하십시오.
  4. 모델 계산을 torch.compile(backend="legato")로 컴파일하십시오. 기본 백엔드(inductor)는 lpu 커널을 만들지 못합니다. Compile PyTorch Model with Legato를 보십시오.
  5. 스트림 코드는 걷어내고, 메모리 통계는 torch.accelerator로 바꾸십시오. 연산은 기본 스트림에서 실행되므로, 스트림 코드를 걷어내도 동작에 영향이 없습니다.
  6. torch.cuda.synchronize()를 교체하십시오. 완료를 기다려야 하는 지점에서 out.cpu()나 torch.accelerator.synchronize()를 호출하십시오.
  7. 집합 연산과 리덕션은 설계하기 전에 LCCL 매트릭스에서 지원 여부를 확인하십시오.
  8. autocast에 의존하지 말고 명시적으로 캐스팅하십시오.

성능 가정은 옮기지 마십시오

커널 사이의 상대 비용이 GPU와 다르므로, GPU에서 빨랐던 구현이 LPU에서도 빠르다고 볼 수 없습니다. haprof로 측정하십시오.

6.5 예제

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import torch
import torch.distributed as dist

dist.init_process_group("nccl")
torch.cuda.set_device(rank)

model = MyModel().cuda().half()
x = torch.randn(B, S, D, device="cuda", dtype=torch.float16)

with torch.autocast("cuda", dtype=torch.float16):
    out = model(x)

dist.all_reduce(out, op=dist.ReduceOp.SUM)
torch.cuda.synchronize()
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import os

import torch
import torch.distributed as dist

# 백엔드는 랭크 r을 lpu:<r>에 바인딩합니다.
# 텐서도 같은 디바이스에 두도록 먼저 선택하십시오.
local_rank = int(os.environ["LOCAL_RANK"])
torch.accelerator.set_device_index(local_rank)

dist.init_process_group("lccl")

# autocast에 의존하지 않고 명시적으로 캐스팅합니다.
model = MyModel().to("lpu").to(torch.bfloat16)
model = torch.compile(model, backend="legato",
                      options={"legato.device": "bertha"})
x = torch.randn(B, S, D, dtype=torch.bfloat16).to("lpu")

out = model(x)

dist.all_reduce(out, op=dist.ReduceOp.SUM)
out = out.cpu()          # 여기가 동기화 지점입니다

다음 단계