使用LLaMA-2时出现无法从huggingface_hub导入指定函数的错误求助
split_torch_state_dict_into_shards导入错误的问题 问题详情
此前运行正常的LLaMA-2加载代码,今日突然抛出如下错误:
RuntimeError: Failed to import transformers.models.llama.modeling_llama because of the following error (look up to see its traceback):
Failed to import transformers.generation.utils because of the following error (look up to see its traceback):
cannot import name 'split_torch_state_dict_into_shards' from 'huggingface_hub' (/opt/conda/lib/python3.10/site-packages/huggingface_hub/init.py)
已尝试重新生成Hugging Face Token,问题未解决,运行环境为Google Colab和Kaggle Notebook。加载代码如下:
from transformers import AutoModelForCausalLM, AutoTokenizer device = torch.device("cuda") tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf", token="token_key", torch_dtype="auto") model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-chat-hf", token="token_key", torch_dtype="auto", load_in_4bit=True)
核心原因
该错误由transformers与huggingface_hub版本不兼容导致:split_torch_state_dict_into_shards是huggingface_hub特定版本的接口,当前环境中transformers版本依赖的该接口在已安装的huggingface_hub中不存在。
解决步骤
安装兼容版本组合
在代码开头执行以下命令,安装经过验证的适配LLaMA-2 4bit加载的依赖版本:pip install --upgrade transformers==4.35.2 huggingface_hub==0.17.3 accelerate==0.24.1 bitsandbytes==0.41.1重启运行时
执行安装命令后,必须重启Colab/Kaggle的运行时(Colab:Runtime -> Restart runtime;Kaggle:Session -> Restart session),确保新安装的包生效。验证版本匹配
重启后执行以下代码确认版本:import transformers import huggingface_hub print(f"transformers版本: {transformers.__version__}") print(f"huggingface_hub版本: {huggingface_hub.__version__}")确认版本与安装命令中的一致后,再重新运行LLaMA-2加载代码。
额外提示
- Google Colab和Kaggle会定期更新预装依赖,容易破坏原本兼容的版本组合,建议每次运行前都执行上述版本固定的安装命令。
- 避免单独升级单个依赖包,防止出现版本不匹配问题,优先使用经过验证的版本组合。
内容的提问来源于stack exchange,提问作者lucasa.lisboa

