Transformers documentation

AMD GPU

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v5.22.2).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

AMD GPU

AMD Instinct(MI200, MI300, MI350 시리즈) 및 Radeon GPU는 AMD의 GPU 소프트웨어 스택인 ROCm를 통해 PyTorch를 실행합니다. PyTorch의 ROCm 빌드는 AMD의 CUDA 유사 프로그래밍 인터페이스인 HIP를 사용하여 torch.cuda API를 통해 AMD GPU를 노출합니다. 디바이스 문자열은 cuda이므로 NVIDIA GPU용으로 작성된 코드는 변경 없이 실행됩니다. Transformers는 런타임에 torch.version.hip를 확인하여 두 환경을 구분하고, attention 및 Hub 커널을 AMD 전용 빌드로 라우팅합니다.

설치

huggingface/transformers-pytorch-amd-gpu Docker 이미지에서 ROCm을 설치합니다. 해당 이미지는 PyTorch의 ROCm 빌드, MI300 및 MI350 GPU(gfx942 및 gfx950)용 flash-attn 빌드, 그리고 소스에서 설치된 Transformers를 제공합니다.

docker run -it --device=/dev/kfd --device=/dev/dri --group-add video \
    --ipc=host --shm-size 16G \
    huggingface/transformers-pytorch-amd-gpu

--device=/dev/kfd 및 --device=/dev/dri는 컨테이너에 AMD GPU를 노출합니다. 컨테이너 내부에 kernels를 설치하여 Hub kernels를 사용하세요.

pip install "transformers[kernels]"

대신 자체 시스템에 설치하려면 PyTorch install selector에서 ROCm을 선택하고, 해당 wheel의 ROCm 버전이 드라이버에서 지원되는지 확인하세요.

PyTorch가 AMD GPU를 인식하는지 확인하세요.

import torch

print(torch.version.hip, torch.cuda.is_available(), torch.cuda.device_count())
print(torch.cuda.get_device_properties(0).gcnArchName)
7.2.53211 True 2
gfx942:sramecc+:xnack-

CUDA 빌드의 PyTorch에서 torch.version.hip은 None입니다. gcnArchName은 GPU 아키텍처를 보고하며, 예를 들어 MI300의 경우 gfx942, MI350의 경우 gfx950, Ryzen AI Max (Strix Halo)의 경우 gfx1151입니다.

GPU 선택 및 순서 지정

HIP_VISIBLE_DEVICES를 사용하여 GPU를 선택하고 순서를 설정합니다. 실행과 동일한 명령줄에서 설정하세요.

HIP_VISIBLE_DEVICES=0,2 torchrun trainer-program.py ...

PyTorch는 cuda:0 및 cuda:1에 매핑된 GPU 0과 2만 인식합니다. ROCR_VISIBLE_DEVICES는 스택의 더 낮은 수준에서 GPU를 필터링하며, 일반적으로 클러스터 스케줄러에 의해 설정됩니다. 두 변수가 모두 설정된 경우, HIP_VISIBLE_DEVICES는 ROCR_VISIBLE_DEVICES에 의해 가시적으로 유지되는 GPU에 대해 인덱싱합니다.

rocm-smi 또는 amd-smi를 사용하여 GPU 목록과 해당 인덱스를 확인하세요.

추론 실행

Pipeline와 device_map="auto"는 AMD GPU를 감지하여 모델을 자동으로 cuda에 배치합니다. device_map="cuda" 또는 device_map="cuda:1"를 명시적으로 전달할 수도 있습니다.

from transformers import AutoModelForCausalLM, AutoTokenizer

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B", dtype="bfloat16", device_map="auto"
)

inputs = tokenizer("The French Bread Law states", return_tensors="pt").to(model.device)
output = model.generate(**inputs, do_sample=False, max_new_tokens=50)
print(tokenizer.decode(output[0], skip_special_tokens=True))
The French Bread Law states that the French government must provide a certain amount of bread for the citizens of the country. The law is passed by the French parliament. The French parliament is a body of the French government. The French government is a body of the French state. The

어텐션 백엔드 선택

모델을 로드할 때 attn_implementation으로 attention backends를 설정하면 추론과 학습 모두에 적용됩니다. SDPA가 기본값이며 PyTorch가 지원하는 모든 AMD GPU에서 작동합니다. 두 가지 FlashAttention 옵션도 사용할 수 있습니다.

attn_implementation필요 사항The input is a single word "Notes". 참고
"sdpa"–기본값.
"flash_attention_2"ROCm용으로 구축된 flash-attn 또는 kernels설치된 경우 flash-attn 패키지를 사용합니다. 기본 Composable Kernel(CK) 백엔드는 MI200, MI300, MI355, RDNA 3/4 GPU를 지원하며, Docker image에는 MI300 또는 MI350에 해당 패키지가 포함되어 있습니다. 그렇지 않으면 Hub에서 amd/aiter-flash-attn를 로드합니다.
"flash_attention_3"커널AMD의 AITER 라이브러리에서 제공되는 사전 빌드된 FlashAttention 커널인 amd/aiter-flash-attn을 로드합니다. 컴파일이 필요하지 않습니다.
from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B",
    dtype="bfloat16",
    device_map="auto",
    attn_implementation="flash_attention_3",
)

ROCm에서 flash_attention_3은 AITER 커널로 해석되며 다음을 기록합니다. Transformers는 현재 kernels-community/aiter-flash-attn 별칭을 사용하며, 이는 amd/aiter-flash-attn로 리디렉션됩니다. 해당 메시지는 FlashAttention-3 패키지를 참조하므로 flash_attention_2가 설치된 경우에도 표시됩니다.

You do not have `flash_attn` installed, using `kernels-community/aiter-flash-attn` from the `kernels` library instead!

attn_implementation="kernels-community/aiter-flash-attn"를 사용하여 커널 저장소를 직접 전달할 수도 있습니다. 백엔드가 선택되는 방법은 Attention backends를 참고하세요.

Hub 커널 사용

use_kernels=True를 from_pretrained()에 설정하면 Hub의 최적화 커널로 지원되는 레이어를 대체합니다. Transformers는 ROCm을 감지하여 각 레이어에 대해 AMD 빌드를 선택하며, 예를 들어 회전 임베딩에는 amd/aiter-rope, RMSNorm에는 kernels-community/liger-kernels를 사용합니다. 사용자 정의 KernelConfig를 작성할 때는 AMD 전용 매핑의 디바이스 키로 "rocm"를 사용하세요.

from transformers import AutoModelForCausalLM

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-0.6B", dtype="bfloat16", device_map="auto", use_kernels=True
)

Hub 커널은 주로 prefill 및 대규모 배치 처리를 가속화합니다. 소규모 배치 디코딩에 활성화하기 전에 자체 워크로드를 벤치마크하세요. 전체 매핑은 커널 로딩을 참조하세요.

모델 양자화

ROCm에서 지원하는 방법은 AWQ, GPT-QModel, compressed-tensors, AMD의 Quark입니다. bitsandbytes는 부분적으로 지원합니다. MI300 및 이후 GPU는 FP8을 네이티브로 지원합니다. 전체 목록은 호환성 표를 참조하세요.

Trainer로 학습

TrainingArguments는 AMD GPU를 감지하여 장치를 자동으로 cuda로 설정합니다.

from transformers import TrainingArguments

training_args = TrainingArguments(
    output_dir="./outputs",
    bf16=True,
)

분산 학습

PyTorch의 ROCm 빌드는 NCCL API의 AMD 구현체인 RCCL을 포함하므로, nccl 백엔드, torchrun, FSDP, DeepSpeed, 그리고 Transformers의 분산 API는 변경 없이 작동합니다.

import torch
from transformers import AutoModelForCausalLM, DistributedConfig

model = AutoModelForCausalLM.from_pretrained(
    "Qwen/Qwen3-1.7B",
    dtype=torch.bfloat16,
    distributed_config=DistributedConfig(tp_size=2, fsdp_size=4),
)
torchrun --nproc_per_node=8 train.py

사용 가능한 옵션은 Tensor parallelism, Expert parallelism, FSDP를 참고하세요.

한계

  • CodeCarbonCallback은 ROCm과 호환되지 않습니다. TrainingArguments의 report_to에 codecarbon을 제외하도록 설정하세요.
  • 호환성 표에서 ROCm에 대해 🔴로 표시된 양자화 방법은 CUDA 전용 커널에 의존하여 AMD GPU에서 로드되지 않습니다.

다음 단계

  • 드라이버 및 PyTorch 설정에 대한 ROCm 문서를 읽어보세요.
  • AMD 및 kernels-community 조직에서 ROCm 빌드를 확인하세요.
  • 어떤 레이어가 어떤 커널로 대체되는지 커스터마이즈하려면 커널 로딩을 읽어보세요.
Update on GitHub