在Llama Index加载Hugging Face嵌入模型及重排器时遇Torch属性错误求助
问题解决:AttributeError: module 'torch._subclasses' has no attribute 'functional_tensor'
问题场景
在Google Colab中使用LlamaIndex加载嵌入模型和重排器时触发以下错误:
AttributeError: module 'torch._subclasses' has no attribute 'functional_tensor'
后续引发 RuntimeError:无法导入transformers.models.bert.modeling_bert
触发错误的代码
加载嵌入模型:
from llama_index.embeddings.huggingface import HuggingFaceEmbedding from llama_index.core import Settings Settings.embed_model = HuggingFaceEmbedding( model_name="BAAI/bge-small-en-v1.5" )
加载重排器:
from llama_index.core.postprocessor import SentenceTransformerRerank rerank = SentenceTransformerRerank( model="cross-encoder/ms-marco-MiniLM-L-12-v2", top_n=3 )
已尝试重装升级llama-index、torch和transformers,但问题未解决。
解决步骤
卸载现有Torch依赖
执行以下命令清理当前环境中的Torch相关包:!pip uninstall -y torch torchvision torchaudio安装兼容版本的Torch(CUDA 11.8版本)
Colab环境默认支持CUDA 11.8,安装对应版本的Torch确保兼容性:!pip install torch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 --index-url https://download.pytorch.org/whl/cu118重新安装LlamaIndex及相关扩展
确保安装与Torch兼容的LlamaIndex组件:!pip install --upgrade llama-index llama-index-embeddings-huggingface llama-index-postprocessor-sentence-transformers重启Colab内核
点击Colab界面上方的「Runtime」→「Restart runtime」,确保新安装的包生效。验证环境(可选)
重启后运行以下代码确认Torch版本和CUDA可用性:import torch print(f"Torch版本: {torch.__version__}") print(f"CUDA可用: {torch.cuda.is_available()}")输出应显示Torch版本为2.1.0且CUDA可用。
重新运行业务代码
再次执行加载嵌入模型和重排器的代码,问题应已解决。
内容的提问来源于stack exchange,提问作者Rahul_51
相关产品推荐
相关产品推荐

