近期项目用到了 Transformers。然而,配置过程中发生了不少问题,好在通过查阅各种论坛(CSDN,Github Issues, Huggingface Discuss, StackOverflow ...),最后都解决了。

在这里将问题记录一下,方便后面大家配置。

1. OSError: Unable to load weights from pytorch checkpoint file

这个问题,是最最难解决的。

我解决这个问题主要经过了三个过程:

1.1 网络连接问题

直接使用 Transformers 提供的方法,很容易发生这个问题。

  • 例如,通过下列代码加载模型:

  • from transformers import AutoTokenizer, AutoModelForQuestionAnswering
    tokenizer = AutoTokenizer.from_pretrained("uer/roberta-base-chinese-extractive-qa")
    model = AutoModelForQuestionAnswering.from_pretrained("uer/roberta-base-chinese-extractive-qa")

解决方案:

  • 选择 git lfs 下载模型文件:

  • git lfs install
    git clone https://huggingface.co/uer/roberta-base-chinese-extractive-qa
  • 下载后,将模型路径修改为本地文件路径。

  • from transformers import AutoTokenizer, AutoModelForQuestionAnswering
    tokenizer = AutoTokenizer.from_pretrained("./model/roberta-base-chinese-extractive-qa")
    model = AutoModelForQuestionAnswering.from_pretrained("./model/roberta-base-chinese-extractive-qa")

1.2 缓存问题

上面的步骤完成后,问题仍然无法得到解决。这时,我们就要清理一下缓存,然后再进入下一步。

缓存的位置在 ~/.cache/pytorch 以及 ~/.cache/transformers 中。删除缓存即可。如果缓存内没有其他内容,可以直接删除文件夹。

1.3 Pytorch 版本问题

最后,需要检查 PyTorch 版本。Transformers 加载模型需要 PyTorch 版本在 1.6 以上。如果版本没有达到,需要更新 PyTorch。

经过这一步,问题基本可以解决。

pip install --upgrade pytorch torchvision

# 如果无法更新,可以先卸载再重新下载
pip uninstall torch
pip install pytorch

参考内容

  1. OSError: Unable to load weights from pytorch checkpoint file

  2. Pytorch如何更新版本与卸载,使用pip,conda更新卸载Pytorch

  3. Unable to load weights from pytorch checkpoint file