Transformers documentation

Apple Silicon

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

Apple Silicon

Apple Silicon(M 系列)芯片通过 Metal Performance Shaders (MPS) 后端运行 PyTorch,设备字符串为 mps。CPU 和 GPU 共享一个统一内存池。

MPS 与标准的 torch 安装兼容。当前适用于 Apple Silicon 的 PyTorch 版本要求 macOS 14 或更高版本。请检查 PyTorch 是否已针对 MPS 构建,并且能够检测到 GPU。

import torch

print(torch.backends.mps.is_available())

当 MPS 准备就绪时,它会打印 True。

选择注意力后端

在加载模型时,通过 attn_implementation 设置注意力后端,该设置同时适用于推理和训练。模型默认使用 SDPA。在 PyTorch 2.13 或更高版本中,MPS 上的 SDPA 可以直接处理分组查询注意力,无需先重复键和值头。

使用 SDPA 进行训练。

  • kernels-community/metal-flash-sdpa 仅支持变长输入,例如打包序列或注意力掩码中包含填充的批次。对于无填充的批次(例如单个提示),会引发错误。它不会为 query、key 和 value 投影计算梯度。当你在 MPS 上请求 flash attention 时,gpt-oss 会自动切换到该内核。
  • 当安装了 kernels 时,ggml-org/ggml-attn 是 transformers serve 和 GGUF 模型的默认选项。

安装 kernels 附加组件以使用任一内核。它会安装 Transformers 支持的版本。

pip install "transformers[kernels]"

运行推理

将 device_map="mps" 传递给 from_pretrained()。如果未传递 device,pipeline() 会自动选择 MPS。

from transformers import AutoModelForCausalLM, AutoTokenizer

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

inputs = tokenizer("Apple Silicon is", return_tensors="pt")
output = model.generate(**inputs, max_new_tokens=50, do_sample=False)
print(tokenizer.decode(output[0], skip_special_tokens=True))

使用针对 MPS 的 device_map 时,Transformers 会将 safetensors 权重直接加载到 MPS 设备上。

部署模型

transformers serve 会启动一个兼容 OpenAI 的服务器。其 --device 选项的默认值为 auto,因此无需额外参数即可在 MPS 上加载模型。请安装服务依赖项并启动服务器。

pip install "transformers[serving]"
transformers serve

服务器会在首次收到指定该模型的请求时加载模型。向 http://localhost:8000 发送一个聊天请求。

curl http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "Qwen/Qwen2.5-0.5B-Instruct",
    "messages": [{"role": "user", "content": "What is Apple Silicon? Answer in one sentence."}],
    "max_tokens": 64,
    "temperature": 0
  }'
{"id":"b48e84c1-b3c6-484d-b781-4c9ce8022dff","choices":[{"finish_reason":"stop","index":0,"message":{"content":"Apple Silicon is a type of processor technology developed and manufactured by Apple Inc., designed to offer faster performance and lower power consumption compared to traditional silicon-based processors. This technology allows for the creation of more efficient and energy-efficient devices, such as high-performance computers, smartphones, and other Apple products.","role":"assistant"}}],"created":1791843839,"model":"Qwen/Qwen2.5-0.5B-Instruct@main","object":"chat.completion","usage":{"completion_tokens":59,"prompt_tokens":39,"total_tokens":98}}

当 kernels 已安装时,transformers serve 在 MPS 上默认使用 ggml-org/ggml-attn,并在启动时记录一条警告。如需改用 SDPA,请传入 --attn-implementation sdpa。

量化模型

模型权重与 macOS 及 Mac 上运行的其他所有内容共享统一内存,因此对其进行量化可以让更大的模型适配推理或微调。Metal 在加载模型时对其进行量化,而 GGUF 则运行已经量化的检查点。两者均仅支持推理。

  • Metal 使用来自 Hub 的 Metal 内核进行 2、4 或 8 位量化。
  • 当 ggml-org/ggml-quantization 内核可用时,GGUF 会在 MPS 上保持权重以打包形式存储。
  • bitsandbytes 使用原生 MPS 内核进行 4 位量化。

若要微调无法装入内存的模型,请以 4-bit 精度使用 bitsandbytes 加载该模型,并使用 PEFT 训练 LoRA 适配器。

使用 Trainer 进行训练

TrainingArguments 会检测 MPS 并将设备设置为 mps,因此 Trainer 无需任何设备设置即可在其上训练。bf16 和 fp16 混合精度均可正常工作。请使用默认的 SDPA 注意力加载模型,因为 metal-flash-sdpa 不会计算注意力投影的梯度。

from transformers import TrainingArguments

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

当 Trainer 将在 GPU 上进行训练时,它会打印 mps。

在 macOS 上,Python 默认使用 spawn 来启动工作进程,这会重新导入你的脚本,并要求数据集和 collate_fn 可被 pickle 序列化。当 dataloader_num_workers 大于 1 时,TrainingArguments 会在 MPS 上设置 dataloader_multiprocessing_context="fork",从而让工作进程从训练进程的副本中启动。如果数据源不支持 fork,请将其设置为 "spawn"。

限制图缓存的增长

MPS 会为遇到的每个张量形状编译一个 Metal 内核,并将它们保存在一个永不淘汰的图缓存中。使用变长输入进行训练时,每出现一个新形状就会增加一个内核,这可能导致统一内存耗尽。

使用 DataCollatorWithPadding 的 pad_to_multiple_of 参数,将每个批次填充为固定长度的整数倍,从而减少形状的数量。

from transformers import AutoTokenizer, DataCollatorWithPadding

tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-0.6B")
data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=64)

将其与 data_collator=data_collator 一起传递给 Trainer。

局限性

  • device_map="auto" 无法将层卸载到 CPU,因为 MPS 和 CPU 共享同一内存。溢出部分会被写入磁盘。
  • compressed-tensors FP8 检查点可以在 MPS 上加载,但其权重会在第一次前向传播时被解压,因此无法在推理期间减少内存占用。
  • 由于 Mac 只有一个设备,因此不支持张量并行。
  • 部分 PyTorch 操作目前尚无 MPS 实现。设置 PYTORCH_ENABLE_MPS_FALLBACK=1 可在 CPU 上运行这些操作,而不是抛出错误。

后续步骤

  • 阅读 PyTorch MPS 后端 的说明,了解受支持的操作和已知问题。
  • 阅读 Attention backends 指南,了解 attn_implementation 如何选择注意力函数。
  • 在 量化概览 中查看 Metal 列,以查找所有可在 MPS 上运行的量化方法。
Update on GitHub