M2芯片Mac运行HuggingFace模型时Jupyter内核崩溃求助
解决M2 Mac Jupyter加载HuggingFace模型内核崩溃问题
问题描述
在搭载M2芯片、32GB内存的全新Mac上,使用Jupyter Notebook运行HuggingFace的ML模型时,执行模型加载步骤内核反复崩溃,已尝试多个模型均出现相同问题,且内存并未占满。
运行代码
import torch from transformers import AutoTokenizer, AutoModelForTokenClassification, pipeline # Step 1: Choose a pre-trained NER model from Hugging Face's Model Hub # Here we use "dbmdz/bert-large-cased-finetuned-conll03-english", which is a common NER model fine-tuned on the CoNLL-2003 dataset model_name = "dbmdz/bert-large-cased-finetuned-conll03-english" # Step 2: Load the model and tokenizer tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForTokenClassification.from_pretrained(model_name)
报错信息
Kernel Restarting
The kernel forappears to have died. It will restart automatically.
解决方法
强制使用CPU加载模型
M系列芯片的PyTorch默认可能尝试启用Metal加速,但部分模型存在兼容性问题,强制CPU加载可避免内核崩溃。修改模型加载代码:model = AutoModelForTokenClassification.from_pretrained(model_name, device_map="cpu")更新依赖库到最新版本
旧版本的PyTorch和Transformers对M系列芯片支持不完善,执行以下命令更新:pip install --upgrade torch transformers调整Jupyter内核内存限制
即使系统内存未占满,Jupyter内核可能存在默认内存上限,可修改配置调整:- 生成Jupyter配置文件(未生成过的话执行):
jupyter notebook --generate-config - 打开配置文件,找到
c.NotebookApp.max_buffer_size,取消注释并设置更大值,例如:c.NotebookApp.max_buffer_size = 16*1024*1024*1024 # 16GB
- 生成Jupyter配置文件(未生成过的话执行):
用
accelerate库优化模型加载
HuggingFace的accelerate库可更好适配M系列芯片的内存管理,安装后调整加载逻辑:pip install acceleratefrom accelerate import Accelerator accelerator = Accelerator() model = AutoModelForTokenClassification.from_pretrained(model_name) model = accelerator.prepare(model)
内容的提问来源于stack exchange,提问作者taga
相关产品推荐
相关产品推荐

