# AMD GPU

[AMD Instinct](https://www.amd.com/en/products/accelerators/instinct.html)（MI200、MI300、MI350 シリーズ）および [Radeon](https://www.amd.com/en/products/graphics/desktops/radeon.html) GPU は、AMD の GPU ソフトウェアスタックである [ROCm](https://rocm.docs.amd.com/) を通じて PyTorch を実行します。PyTorch の ROCm ビルドは、AMD の CUDA に類似したプログラミングインターフェースである [HIP](https://rocm.docs.amd.com/projects/HIP/en/latest/what_is_hip.html) を使用し、`torch.cuda` API 経由で AMD GPU を公開します。デバイス文字列は `cuda` であるため、NVIDIA GPU 向けに書かれたコードは変更なしで実行できます。Transformers は実行時に `torch.version.hip` をチェックして両者を区別し、アテンションや Hub カーネルを AMD 固有のビルドにルーティングします。

## インストール

[huggingface/transformers-pytorch-amd-gpu](https://hub.docker.com/r/huggingface/transformers-pytorch-amd-gpu) Docker イメージから ROCm をインストールしてください。このイメージには、PyTorch の ROCm ビルド、MI300 および MI350 GPU（`gfx942` および `gfx950`）向けの `flash-attn` ビルド、そしてソースからインストールされた Transformers が含まれています。

```bash
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](https://github.com/huggingface/kernels) をインストールして、[Hub kernels を使用](#use-hub-kernels) します。

```bash
pip install "transformers[kernels]"
```

代わりにご自身のシステムにインストールする場合は、[PyTorch install selector](https://pytorch.org/get-started/locally/)でROCmを選択し、お使いのドライバーが対応しているROCmバージョンのwheelであることを確認してください。

PyTorchがAMD GPUを認識していることを確認します。

```py
import torch

print(torch.version.hip, torch.cuda.is_available(), torch.cuda.device_count())
print(torch.cuda.get_device_properties(0).gcnArchName)
```

```txt
7.2.53211 True 2
gfx942:sramecc+:xnack-
```

PyTorch の CUDA ビルドでは、`torch.version.hip` は `None` になります。`gcnArchName` は GPU アーキテクチャを報告します。例えば、MI300 なら `gfx942`、MI350 なら `gfx950`、Ryzen AI Max (Strix Halo) なら `gfx1151` となります。

## GPUの選択と順序付け

`HIP_VISIBLE_DEVICES` を使用して GPU を選択し、その順序を設定します。実行と同じコマンドラインで設定してください。

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

PyTorch は GPU 0 と 2 のみを認識し、これらはそれぞれ `cuda:0` と `cuda:1` にマッピングされます。`ROCR_VISIBLE_DEVICES` はスタックのより低いレベルで GPU をフィルタリングし、クラスタスケジューラによって設定されることが一般的です。両方が設定されている場合、`HIP_VISIBLE_DEVICES` は `ROCR_VISIBLE_DEVICES` によって可視化された GPU に対してインデックス付けを行います。

`rocm-smi`または`amd-smi`を使用して、GPUとそのインデックスをリスト表示します。

## 推論を実行する

[Pipeline](/docs/transformers/main/ja/main_classes/pipelines#transformers.Pipeline)と`device_map="auto"`はAMD GPUを検出し、モデルを自動的に`cuda`に配置します。明示的に`device_map="cuda"`または`device_map="cuda:1"`を渡すこともできます。

```py
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))
```

```txt
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`でアテンションバックエンドを設定すると、推論と学習の両方に適用されます。SDPAがデフォルトであり、PyTorchがサポートするすべてのAMD GPUで動作します。また、FlashAttentionのオプションも2つ利用可能です。

| `attn_implementation` | 必要 | 注記 |
|---|---|---|
| `"sdpa"` | – | デフォルト。 |
| `"flash_attention_2"` | ROCm向けに構築された[flash-attn](https://github.com/Dao-AILab/flash-attention#amd-rocm-support)、または[kernels](https://github.com/huggingface/kernels) | インストールされている場合、`flash-attn`パッケージを使用します。そのデフォルトのComposable Kernel (CK)バックエンドは、MI200、MI300、MI355、およびRDNA 3/4 GPUをサポートし、[Dockerイメージ](#installation)にはMI300またはMI350で同梱されています。それ以外の場合は、Hubから[amd/aiter-flash-attn](https://huggingface.co/kernels/amd/aiter-flash-attn)を読み込みます。 |
| `"flash_attention_3"` | [カーネル](https://github.com/huggingface/kernels) | AMDの[AITER](https://github.com/ROCm/aiter)ライブラリから、事前ビルド済みのFlashAttentionカーネルである[amd/aiter-flash-attn](https://huggingface.co/kernels/amd/aiter-flash-attn)を読み込みます。コンパイルは不要です。 |

```py
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` がインストールされている場合にも表示されます。

```txt
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](./attention_interface) を参照してください。

## Hubカーネルを使用する

`use_kernels=True` を [from_pretrained()](/docs/transformers/main/ja/main_classes/model#transformers.PreTrainedModel.from_pretrained) に設定すると、Hub からの最適化されたカーネルでサポートされているレイヤーを置き換えます。Transformers は ROCm を検出し、回転埋め込みには [amd/aiter-rope](https://huggingface.co/kernels/amd/aiter-rope)、RMSNorm には [kernels-community/liger-kernels](https://huggingface.co/kernels/kernels-community/liger-kernels) のように、各レイヤーに対して AMD ビルドを選択します。カスタムの [KernelConfig](/docs/transformers/main/ja/main_classes/kernels#transformers.KernelConfig) を作成する場合は、AMD 固有のマッピングのデバイスキーとして `"rocm"` を使用してください。

```py
from transformers import AutoModelForCausalLM

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

Hubのカーネルは、主にプリフィルと大規模バッチ処理を高速化します。小規模バッチのデコーディングで有効にする前に、ご自身のワークロードでベンチマークを実行してください。完全なマッピングについては、[カーネルの読み込み](./kernel_doc/loading_kernels)を参照してください。

## モデルの量子化

ROCmでサポートされているメソッドには、[AWQ](./quantization/awq)、[GPT-QModel](./quantization/gptq)、[compressed-tensors](./quantization/compressed_tensors)、およびAMDの[Quark](./quantization/quark)が含まれます。[bitsandbytes](./quantization/bitsandbytes)は部分的にサポートされています。MI300以降のGPUはFP8をネイティブでサポートしています。完全なリストについては、[互換性テーブル](./quantization/overview)を参照してください。

## Trainerで学習

[TrainingArguments](/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments)はAMD GPUを検出し、デバイスを自動的に`cuda`に設定します。

```py
from transformers import TrainingArguments

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

### 分散学習

PyTorch の ROCm ビルドには、NCCL API の AMD 実装である RCCL が同梱されているため、`nccl` バックエンド、`torchrun`、[FSDP](./fsdp)、[DeepSpeed](./main_classes/deepspeed)、および Transformers の分散 API は、変更なしで動作します。

```py
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),
)
```

```bash
torchrun --nproc_per_node=8 train.py
```

利用可能なオプションについては、[Tensor parallelism](./tensor_parallelism)、[Expert parallelism](./expert_parallelism)、および[FSDP](./fsdp)を参照してください。

## 制限事項

- `CodeCarbonCallback` は ROCm と互換性がありません。[TrainingArguments](/docs/transformers/main/ja/main_classes/trainer#transformers.TrainingArguments) の `report_to` に `codecarbon` を含めないように設定してください。
- [互換性テーブル](./quantization/overview)でROCmに対して🔴でマークされている量子化手法は、CUDA専用のカーネルに依存しており、AMD GPUでは読み込みに失敗します。

## 次のステップ

- ドライバーおよびPyTorchのセットアップについては、[ROCmのドキュメント](https://rocm.docs.amd.com/)を参照してください。
- [AMD](https://huggingface.co/amd) と [kernels-community](https://huggingface.co/kernels-community) の組織内の ROCm ビルドを参照してください。
- どのレイヤーがどのカーネルに置き換えられるかをカスタマイズするには、[カーネルの読み込み](./kernel_doc/loading_kernels)を参照してください。

