# Intel Gaudi

Intel Gaudi 加速器在 [Intel Gaudi](https://docs.habana.ai/en/latest/index.html) 软件栈上运行 PyTorch，设备字符串为 `hpu`。Gaudi 默认以 eager 模式运行 PyTorch。Eager 模式会在每次调用操作时立即执行，与 PyTorch 在 CPU 或 GPU 上的运行方式相同，因此 Transformers 模型可以在 Gaudi 上运行，无需进行 Gaudi 特定的修改。若要改为将模型捕获为图，请使用 `torch.compile` 对其进行 [编译](#compile-the-model)。

## 安装

请按照[Intel Gaudi 安装指南](https://docs.habana.ai/en/latest/Installation_Guide/index.html)安装 Intel Gaudi 软件及其 PyTorch 包（`habana-torch-plugin`，导入名为 `habana_frameworks`），并安装 [Accelerate](https://huggingface.co/docs/accelerate/index) 1.5.0 或更高版本。

Transformers 使用 int64 张量来表示 token ID，因此需要在 Gaudi 上启用 int64 支持。Transformers 的 Gaudi CI 也使用相同的设置运行。

```bash
export PT_ENABLE_INT64_SUPPORT=1
```

检查 Transformers 是否能看到该设备。

```py
from transformers import is_torch_hpu_available

print(is_torch_hpu_available())
```

当 Gaudi 准备就绪时，它会打印 `True`；如果 Accelerate 版本低于 1.5.0，即使存在 Gaudi 设备，也会打印 `False`。

## 选择设备

在启动 Docker 容器时，选择该容器可以使用的 Gaudi 设备。将 `HABANA_VISIBLE_MODULES` 设置为模块 ID，这些 ID 在重启和重新安装驱动程序后保持不变；或者将 `HABANA_VISIBLE_DEVICES` 设置为设备索引，这些索引可能会发生变化。如果两者都未设置，PyTorch 将使用服务器上任何可用的 Gaudi 设备。

```bash
docker run --runtime=habana -e HABANA_VISIBLE_MODULES=0,1,2,3 ...
```

运行 `hl-smi -Q index,module_id -f csv` 以将设备索引映射到模块 ID。对于在服务器部分上运行的分布式工作负载，Intel 仅支持 2 设备和 4 设备组。有关支持的模块 ID 组合，请参阅 [每个 Docker 包含单个工作负载的多个 Docker](https://docs.habana.ai/en/latest/Orchestration/Multiple_Tenants_on_HPU/Multiple_Dockers_each_with_Single_Workload.html)。

## 运行推理

将 `device_map="hpu"` 传递给 [from_pretrained()](/docs/transformers/main/zh/main_classes/model#transformers.PreTrainedModel.from_pretrained)。如果不传递 `device`，[pipeline()](/docs/transformers/main/zh/main_classes/pipelines#transformers.pipeline) 会自动选择 Gaudi。

```py
from transformers import AutoModelForCausalLM, AutoTokenizer

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

inputs = tokenizer("Intel Gaudi is", return_tensors="pt").to(model.device)
output = model.generate(**inputs, max_new_tokens=50, do_sample=False)
print(tokenizer.decode(output[0], skip_special_tokens=True))
```

## 量化模型

[bitsandbytes](./quantization/bitsandbytes) 在 Gaudi 2 和 Gaudi 3 上将模型量化为 4 位或 8 位。如果不传入 `device_map`，它会将模型放置在当前的 Gaudi 设备上。

要微调无法装入单个设备的模型，请使用 bitsandbytes 以 4 位加载该模型，并使用 [PEFT](./peft) 训练 LoRA 适配器。

## 使用 Trainer 进行训练

[TrainingArguments](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments) 会检测 Gaudi 并将设备设置为 `hpu`，因此 `Trainer` 无需任何设备设置即可在其上进行训练。所有 Gaudi 代际均支持 bf16。

```py
from transformers import TrainingArguments

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

当 `Trainer` 将在 Gaudi 上进行训练时，它会打印一个 `hpu` 设备。

## 编译模型

Transformers 在 Gaudi 上对 `torch.compile` 进行了封装，因此任何使用 `hpu_backend` 或 `eager` 以外后端的调用（包括建模代码中的 `@torch.compile` 装饰器）都会切换到 `hpu_backend` 并记录一条警告。该封装适用于所有 `torch.compile` 调用，无论是用于推理还是训练。

要编译模型以进行训练，请在 [TrainingArguments](/docs/transformers/main/zh/main_classes/trainer#transformers.TrainingArguments) 中设置 `torch_compile=True`，这会将 `torch_compile_backend` 设置为 `"hpu_backend"`。

```py
from transformers import TrainingArguments

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

### 分布式训练

分布式训练使用 [HCCL](https://docs.habana.ai/en/latest/API_Reference_Guides/HCCL_APIs/index.html) 集合通信后端。Transformers 在 Gaudi 上会自动选择该后端，你也可以通过 `ddp_backend="hccl"` 显式指定。

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

在[选择设备](#select-devices)后，使用`torchrun`或`accelerate launch`为每个 Gaudi 设备启动一个进程。当未传入`--num_processes`时，`accelerate launch`会将进程数设置为 Gaudi 设备的数量。

```bash
accelerate launch train.py
```

## 后续步骤

- 阅读[Intel Gaudi 文档](https://docs.habana.ai/en/latest/index.html)以了解硬件详情、软件栈以及[Gaudi 架构](https://docs.habana.ai/en/latest/Gaudi_Overview/Gaudi_Architecture.html)。
- 请尝试使用 [Optimum for Intel Gaudi](https://huggingface.co/docs/optimum-habana/index)，它提供了针对 Gaudi 优化的模型实现，适用于训练和推理。

