Transformers documentation

CPU

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

CPU

CPU 使用设备字符串 cpu 来运行 Transformers 模型,无需加速器。在 GPU 不可用或希望采用更具成本效益的配置时,CPU 可用于推理和训练。

运行推理

在未传入 device_map 的情况下,模型默认加载到 CPU 上,并且当没有可用加速器时,pipeline() 会使用 CPU。如果机器上同时配备了加速器,请传入 device_map="cpu" 或 device="cpu" 以使用 CPU。

from transformers import pipeline

generator = pipeline("text-generation", model="Qwen/Qwen3-0.6B", device="cpu")
print(generator("CPUs are", max_new_tokens=50, do_sample=False)[0]["generated_text"])

使用 Trainer 进行训练

支持 bf16 的 CPU(例如较新的 Intel 和 AMD 处理器)可以使用 PyTorch 的 AMP 进行 bf16 混合精度训练,从而降低内存占用并加快训练速度。

以下示例涵盖了三种配置,从单 CPU 到多台机器(当单个 CPU 速度过慢时):

  • 单个 CPU
  • 一台机器上的多个进程(每个 CPU 插槽一个)
  • 跨多台机器的多个进程

单节点和多节点示例使用 Intel MPI(Intel oneAPI HPC Toolkit 的一部分)中的 mpirun 来启动进程,并且 Trainer 通过 gloo 后端运行 DDP。

单个 CPU
分布式 CPU(单节点)
分布式 CPU(多节点)

在 TrainingArguments 中设置 bf16=True 和 use_cpu=True,或者向训练脚本传递 --bf16 和 --use_cpu。在 CPU 上,请优先使用 bf16 而非 fp16,因为其数值稳定性更高。

from transformers import TrainingArguments

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

调整 CPU 性能

预加载更快的内存分配器和 Intel 的 OpenMP 运行时,以降低 CPU 训练中的开销。安装 google-perftools(用于 libtcmalloc)和 intel-openmp Python 包(用于 libiomp5),然后在启动训练前将这两个库添加到 LD_PRELOAD 环境变量中。

将 OMP_NUM_THREADS 设置为每个进程可使用的核心数。在具有 CPU 限制的容器或集群作业中,该值应为已分配的 CPU 单元数,因此请预留部分核心供系统进程使用。

后续步骤

Update on GitHub