langchain使用jina-embeddings构建Chroma向量库,解决加载模型初始化失败

摘要

使用 {"trust_remote_code":True} 传递给 langchain_community.embeddings 的 SentenceTransformerEmbeddings ,逐步解析 jinaai/jina-embeddings-v2-base-en 编码模型初始化加载异常的问题。

背景

首先先说一下,最近的研究方向,想构建一个向量数据库,做一些RAG和相似文本筛选方面的实验。

接下来,我们来看看 LangChain 官方给的示例代码。

https://python.langchain.com/v0.2/docs/integrations/vectorstores/chroma/

python 复制代码
# import
from langchain_chroma import Chroma
from langchain_community.document_loaders import TextLoader
from langchain_community.embeddings.sentence_transformer import (
    SentenceTransformerEmbeddings,
)
from langchain_text_splitters import CharacterTextSplitter

# load the document and split it into chunks
loader = TextLoader("../../how_to/state_of_the_union.txt")
documents = loader.load()

# split it into chunks
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)

# create the open-source embedding function
embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")

# load it into Chroma
db = Chroma.from_documents(docs, embedding_function)

# query it
query = "What did the president say about Ketanji Brown Jackson"
docs = db.similarity_search(query)

# print results
print(docs[0].page_content)

官方使用的是 all-MiniLM-L6-v2 编码模型。笔者并不想用这个模型,在https://huggingface.co/models?sort=trending&search=embedding上搜索"embedding"关键词。

jina-embeddings-v2-base-en 排在第一位,有182k的下载量,故笔者想使用这个模型作为向量编码模型。

加载模型:

python 复制代码
# create the open-source embedding function
embedding_function = SentenceTransformerEmbeddings(model_name="jinaai/jina-embeddings-v2-base-en")

Output:

python 复制代码
No sentence-transformers model found with name jinaai/jina-embeddings-v2-base-en. Creating a new one with mean pooling.
Some weights of BertModel were not initialized from the model checkpoint at jinaai/jina-embeddings-v2-base-en and are newly initialized: ['embeddings.position_embeddings.weight', 'encoder.layer.0.intermediate.dense.bias', 'encoder.layer.0.intermediate.dense.weight', 'encoder.layer.0.output.LayerNorm.bias', 'encoder.layer.0.output.LayerNorm.weight', 'encoder.layer.0.output.dense.bias', 'encoder.layer.0.output.dense.weight', 'encoder.layer.1.intermediate.dense.bias', 'encoder.layer.1.intermediate.dense.weight',       
                                             ......                                         'encoder.layer.8.output.dense.bias', 'encoder.layer.8.output.dense.weight', 'encoder.layer.9.intermediate.dense.bias', 'encoder.layer.9.intermediate.dense.weight', 'encoder.layer.9.output.LayerNorm.bias', 'encoder.layer.9.output.LayerNorm.weight', 'encoder.layer.9.output.dense.bias', 'encoder.layer.9.output.dense.weight']
You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.

在加载jinaai/jina-embeddings-v2-base-en模型的时候,提醒我们很多层的权重,重新初始化了,必须要引起重视。如果你忽视了这个报错,你会得到的错误的结果。

Tips:

其实一开始我也没有重视,忽视了这个报错,因为我自认为参考LangChain官方的代码,可以不用理会这个报错。

后果就是,模型每次重新初始化,权重都会变化,导致得到的编码向量不一致,这才让我引起重视,不得不解决这个问题。

那么笔者是如何解决这个问题的呢?

通过浏览 https://huggingface.co/jinaai/jina-embeddings-v2-base-en 的说明文档,发现在文档中早有说明了。

通过浏览上述的说明,解决方法就是在加载模型时,传入 trust_remote_code=True

可以看到 LangChain 的 SentenceTransformerEmbeddings 接收一个 model_kwargs 字典参数。我都不用看源码,就能想到 model_kwargs 会传递给模型进行初始化。

python 复制代码
# create the open-source embedding function
embedding_function = SentenceTransformerEmbeddings(
    model_name="jinaai/jina-embeddings-v2-base-en",
    model_kwargs={"trust_remote_code":True}
    )

运行上述代码,传入{"trust_remote_code":True} 就不会报警告了。

接下来的部分,大家就可以浏览 LangChain 上的教程,进行进一步的学习了。

附录

若无法连接 huggingface,可尝试使用 proxy:

只需运行下述代码,与huggingface的连接,就会走proxy

python 复制代码
import os
os.environ['HTTP_PROXY'] = 'http://127.0.0.1:7890'
os.environ['HTTPS_PROXY'] = 'http://127.0.0.1:7890'

参考资料

相关推荐
老周聊大模型12 小时前
LangChain已死?不,是时候重新思考AI工程范式了
人工智能·langchain·mcp
数据智能老司机14 小时前
基础图谱增强检索生成(GraphRAG)——智能代理式 RAG
langchain·llm·aigc
deephub1 天前
AI代理性能提升实战:LangChain+LangGraph内存管理与上下文优化完整指南
人工智能·深度学习·神经网络·langchain·大语言模型·rag
都叫我大帅哥1 天前
LangChain分层记忆解决方案:完整案例
python·langchain
alex1002 天前
AI Agent开发学习系列 - langchain之LCEL(5):如何创建一个Agent?
人工智能·python·语言模型·langchain·prompt·向量数据库·ai agent
青Cheng序员石头2 天前
Prompt Engineering vs Vibe Coding vs Context Engineering
langchain·llm·aigc
数据智能老司机2 天前
构建由 LLM 驱动的 Neo4j 应用程序——使用 Neo4j 和 Haystack 实现强大搜索功能
langchain·llm·aigc
都叫我大帅哥2 天前
🚀 LangGraph终极指南:从入门到生产级AI工作流编排
python·langchain
showyoui2 天前
LangChain vs LangGraph:从困惑到清晰的认知之路(扫盲篇)
langchain·ai编程
_一条咸鱼_3 天前
LangChain记忆序列化与持久化方案源码级分析(37)
人工智能·面试·langchain