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

使用LLaMA-2时出现无法从huggingface_hub导入指定函数的错误求助

解决LLaMA-2导入时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中不存在。

解决步骤

  1. 安装兼容版本组合
    在代码开头执行以下命令,安装经过验证的适配LLaMA-2 4bit加载的依赖版本:

    pip install --upgrade transformers==4.35.2 huggingface_hub==0.17.3 accelerate==0.24.1 bitsandbytes==0.41.1
    
  2. 重启运行时
    执行安装命令后,必须重启Colab/Kaggle的运行时(Colab:Runtime -> Restart runtime;Kaggle:Session -> Restart session),确保新安装的包生效。

  3. 验证版本匹配
    重启后执行以下代码确认版本:

    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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:05:09