You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacOS M1 Max运行Hugging Face Transformers示例遇Bus Error求助

解决Apple Silicon(M1 Max)上Hugging Face Transformers的Bus Error问题

问题场景

环境配置:

  • MacOS Sonoma 14.7,Apple M1 Max芯片
  • Python 3.11.5
  • pip安装了transformers、datasets、evaluate、accelerate、tf-keras

运行代码:

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("We are very happy to show you the 🤗 Transformers library.")
print(result)

报错信息:

未指定模型,默认使用distilbert/distilbert-base-uncased-finetuned-sst-2-english及其版本714eb0f。
生产环境使用pipeline不指定模型名称和版本不被推荐。[1]

92883 bus error python main.py


解决思路

  • 强制使用PyTorch后端:Apple Silicon对PyTorch的Metal适配更稳定,当前环境安装了tf-keras可能导致pipeline默认调用TensorFlow版本模型引发冲突。修改代码指定后端:

    classifier = pipeline("sentiment-analysis", framework="pt")
    

    同时确保安装Apple Silicon版本的PyTorch:

    pip3 install torch torchvision torchaudio
    
  • 升级Transformers及依赖库:旧版本可能存在Apple Silicon兼容性bug,执行升级命令:

    pip install --upgrade transformers accelerate
    
  • 禁用模型内存映射:Apple Silicon的内存映射机制可能与部分模型文件不兼容,手动加载模型并关闭内存映射:

    from transformers import AutoTokenizer, AutoModelForSequenceClassification
    
    tokenizer = AutoTokenizer.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english", use_fast=False)
    model = AutoModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english", use_memory_map=False)
    classifier = pipeline("sentiment-analysis", model=model, tokenizer=tokenizer)
    result = classifier("We are very happy to show you the 🤗 Transformers library.")
    print(result)
    
  • 验证Python架构:确保使用的是原生arm64架构的Python,而非Rosetta转译的x86版本。执行命令验证:

    python -c "import platform; print(platform.machine())"
    

    输出应为arm64,若为x86_64,建议重新安装Apple Silicon版本的Python(如官网arm64安装包或Homebrew安装)。

  • 清理模型缓存:缓存的模型文件可能损坏,删除~/.cache/huggingface/hub目录后重新运行代码,让模型重新下载。

内容的提问来源于stack exchange,提问作者Roy Ca

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 10:44:57