Jina AI 通过 Hugging Face 发布了其最先进的开源德英和中英双语嵌入模型。


在本教程中,我们将介绍一个非常简单的安装和使用案例,包括:
- 从 Hugging Face 下载 Jina Embedding 模型。
- 使用模型获取德语和英语文本的编码。
- 构建一个基于嵌入的简单跨语言神经搜索引擎。
我们将向您展示如何使用 Jina Embeddings 编写英语查询来检索匹配的德语文本,反之亦然。
此教程同样适用于中文模型。只需按照标题为Querying in Chinese的章节(在文末)中的说明获取中英双语模型和中文示例文档即可。


tag双语嵌入模型
双语嵌入模型是一个将两种语言的文本(本教程中为德语和英语,中文模型则为中文和英语)映射到同一嵌入空间的模型。并且,它以这样一种方式工作:如果一个德语文本和一个英语文本表达相同的含义,它们对应的嵌入向量将非常接近。
这类模型非常适合跨语言信息检索应用,我们将在本教程中演示这一点。它们也可以作为基于 RAG 的聊天机器人、多语言文本分类、摘要、情感分析以及任何使用嵌入的其他应用的基础。通过使用这些模型,您可以将两种语言的文本视为用同一种语言编写的文本。
尽管许多大型语言模型声称支持多种不同的语言,但它们对所有语言的支持并不均衡。关于互联网上英语主导地位导致的偏见以及由于机器翻译文本的广泛在线发布导致的输入源失真的问题日益增多。通过专注于两种语言,我们可以更好地控制两种语言的嵌入质量,最大限度地减少偏见,同时生成更小的模型,其性能与声称可以处理几十种语言的巨型模型相似或更高。
Jina Embeddings v2 双语模型支持 8,192 个输入上下文 token,使其不仅可以支持两种语言,而且与同类模型相比,还可以支持相对较大的文本段落。这使它们非常适合需要将更多文本信息处理成嵌入的复杂用例。
tag在 Google Colab 上跟随学习
本教程有一个配套笔记本,您可以在 Google Colab 上运行,或在您自己的系统上本地运行。

tag安装先决条件
确保当前环境已安装相关库。您需要最新版本的 transformers
,即使它已经安装,也请运行:
pip install -U transformers
本教程将使用 Meta 的 FAISS 库进行向量搜索和比较。要安装它,请运行:
pip install faiss-cpu
我们还将使用 Beautiful Soup 来处理本教程中的输入数据,请确保安装:
pip install bs4
tag访问 Hugging Face
您需要访问 Hugging Face,具体来说是一个账户和访问令牌来下载模型。
如果您没有 Hugging Face 账户:
访问 https://huggingface.co/,您应该能在页面右上角看到一个"Sign Up"按钮。点击它并按照说明创建新账户。

登录账户后:
按照 Hugging Face 网站上的说明获取访问令牌。
HF_TOKEN
. 如果你正在使用 notebook (比如在 Google Colab 上),或者在 Python 程序内部设置它,使用以下 Python 代码:
import os
os.environ['HF_TOKEN'] = "<your token here>"
在你的 shell 中,使用相应的语法来设置环境变量。在 bash
中:
export HF_TOKEN="<your token here>"
## 下载用于德语和英语的 Jina Embeddings v2
一旦设置好你的 token,你就可以使用 transformers
库下载 Jina Embeddings 德语-英语双语模型:
from transformers import AutoModel
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-de', trust_remote_code=True)
第一次下载时可能需要几分钟时间,但之后模型会被本地缓存,所以如果你之后重新启动本教程不用担心。
## 下载英语数据
对于本教程,我们将获取 Pro Git: Everything You Need to Know About Git 的英语版本。这本书也有中文和德语版本,我们稍后会在本教程中使用。
要下载 EPUB 版本,运行以下命令:
wget -O progit-en.epub https://open.umn.edu/opentextbooks/formats/3437
这会将该书复制到本地目录中名为 progit-en.epub
的文件中。

<section>
标签轻松找到。下面的代码读取 EPUB 文件并使用 EPUB 文件的内部结构和 <section>
标签将其分割,然后将每个章节转换为不带 XHTML 标签的纯文本。它创建一个 Python 字典,其键是指示每个章节在书中位置的字符串集,其值是该章节的纯文本内容。
from zipfile import ZipFile
from bs4 import BeautifulSoup
import copy
def decompose_epub(file_name):
def to_top_text(section):
selected = copy.copy(section)
while next_section := selected.find("section"):
next_section.decompose()
return selected.get_text().strip()
ret = {}
with ZipFile(file_name, 'r') as zip:
for name in zip.namelist():
if name.endswith(".xhtml"):
data = zip.read(name)
doc = BeautifulSoup(data.decode('utf-8'), 'html.parser')
ret[name + ":top"] = to_top_text(doc)
for num, sect in enumerate(doc.find_all("section")):
ret[name + f"::{num}"] = to_top_text(sect)
return ret
然后,对你之前下载的 EPUB 文件运行 decompose_epub
函数:
book_data = decompose_epub("progit-en.epub")
变量 book_data
现在将包含 583 个章节。例如:
print(book_data['EPUB/ch01-getting-started.xhtml::12'])
结果:
The Command Line
There are a lot of different ways to use Git.
There are the original command-line tools, and there are many graphical user interfaces of varying capabilities.
For this book, we will be using Git on the command line.
For one, the command line is the only place you can run all Git commands — most of the GUIs implement only a partial subset of Git functionality for simplicity.
If you know how to run the command-line version, you can probably also figure out how to run the GUI version, while the opposite is not necessarily true.
Also, while your choice of graphical client is a matter of personal taste, all users will have the command-line tools installed and available.
So we will expect you to know how to open Terminal in macOS or Command Prompt or PowerShell in Windows.
If you don't know what we're talking about here, you may need to stop and research that quickly so that you can follow the rest of the examples and descriptions in this book.
## 使用 Jina Embeddings v2 和 FAISS 生成和索引嵌入
对于这 583 个章节中的每一个,我们将生成一个嵌入并将其存储在 FAISS 索引中。Jina Embeddings v2 模型接受最多 8192 个 token 的输入,对于像这样的书来说足够大,我们不需要做任何进一步的文本分段或检查是否有任何章节的 token 太多。这本书中最长的章节大约有 12,000 个字符,对于普通英语来说,应该远低于 8k token 的限制。
要生成单个嵌入,使用我们下载的模型的 encode
方法。例如:
model.encode([book_data['EPUB/ch01-getting-started.xhtml::12']])
这将返回一个包含单个 768 维向量的数组:
array([[ 6.11135997e-02, 1.67829826e-01, -1.94809273e-01,
4.45595086e-02, 3.28837298e-02, -1.33441269e-01,
1.35364473e-01, -1.23119736e-02, 7.51526654e-02,
-4.25386652e-02, -6.91794455e-02, 1.03527725e-01,
-2.90831417e-01, -6.21018047e-03, -2.16205455e-02,
-2.20803712e-02, 1.50471330e-01, -3.31433356e-01,
-1.48741454e-01, -2.10959971e-01, 8.80039856e-02,
....
这就是一个嵌入。
Jina Embeddings 模型设置为允许批处理。最佳批次大小取决于你运行时使用的硬件。批次大小过大可能会耗尽内存。批次大小过小则需要更长的处理时间。
batch_size=5
可以正常工作,生成整个嵌入集大约需要一个小时。
batch_size
。
import faiss
batch_size = 5
vector_data = []
faiss_index = faiss.IndexFlatIP(768)
data = [(key, txt) for key, txt in book_data.items()]
batches = [data[i:i + batch_size] for i in range(0, len(data), batch_size)]
for ind, batch in enumerate(batches):
print(f"Processing batch {ind + 1} of {len(batches)}")
batch_embeddings = model.encode([x[1] for x in batch], normalize_embeddings=True)
vector_data.extend(batch)
faiss_index.add(batch_embeddings)
在生产环境中工作时,Python 字典并不是处理文档和嵌入的充分或高性能的方式。你应该使用专门构建的向量数据库,它会有自己的数据插入指导。
## 用德语查询英语结果
当我们从这组文本中查询内容时,会发生以下情况:
1. Jina Embeddings 德语-英语模型将为查询创建一个嵌入。
2. 我们将使用 FAISS 索引(faiss_index
)来获取与查询嵌入余弦相似度最高的已存储嵌入,并返回其在索引中的位置。
3. 我们将在向量数据数组(vector_data
)中查找相应的文本,并打印出余弦相似度、文本的位置和文本本身。
这就是下面的 query
函数所做的事情。
def query(query_str):
query = model.encode([query_str], normalize_embeddings=True)
cosine, index = faiss_index.search(query, 1)
print(f"Cosine: {cosine[0][0]}")
loc, txt = vector_data[index[0][0]]
print(f"Location: {loc}\\nText:\\n\\n{txt}")
现在让我们试一下。
# Translation: "How do I roll back to a previous version?"
query("Wie kann ich auf eine frühere Version zurücksetzen?")
结果:
Cosine: 0.5202275514602661
Location: EPUB/ch02-git-basics-chapter.xhtml::20
Text:
Undoing things with git restore
Git version 2.23.0 introduced a new command: git restore.
It's basically an alternative to git reset which we just covered.
From Git version 2.23.0 onwards, Git will use git restore instead of git reset for many undo operations.
Let's retrace our steps, and undo things with git restore instead of git reset.
这是一个相当好的回答。让我们再试一个:
# Translation: "What does 'version control' mean?"
query("Was bedeutet 'Versionsverwaltung'?")
结果:
Cosine: 0.5001817941665649
Location: EPUB/ch01-getting-started.xhtml::1
Text:
About Version Control
What is "version control", and why should you care?
Version control is a system that records changes to a file or set of files over time so that you can recall specific versions later.
For the examples in this book, you will use software source code as the files being version controlled, though in reality you can do this with nearly any type of file on a computer.
If you are a graphic or web designer and want to keep every version of an image or layout (which you would most certainly want to), a Version Control System (VCS) is a very wise thing to use.
It allows you to revert selected files back to a previous state, revert the entire project back to a previous state, compare changes over time, see who last modified something that might be causing a problem, who introduced an issue and when, and more.
Using a VCS also generally means that if you screw things up or lose files, you can easily recover.
In addition, you get all this for very little overhead.
试着用你自己的德语问题来看看效果如何。作为一般做法,在处理文本信息检索时,你应该请求三到五个回答而不是只要一个。最好的答案往往不是第一个。
tag角色互换:用英语查询德语文档
Pro Git:关于 Git 你需要知道的一切 这本书也有德语版本。我们可以使用相同的模型来进行语言相反的演示。
下载电子书:
wget -O progit-de.epub https://open.umn.edu/opentextbooks/formats/3454
这会将书籍复制到名为 progit-de.epub
的文件中。然后我们用与英语版本相同的方式处理它:
book_data = decompose_epub("progit-de.epub")
然后像之前一样生成嵌入:
batch_size = 5
vector_data = []
faiss_index = faiss.IndexFlatIP(768)
data = [(key, txt) for key, txt in book_data.items()]
batches = [data[i:i + batch_size] for i in range(0, len(data), batch_size)]
for ind, batch in enumerate(batches):
print(f"Processing batch {ind + 1} of {len(batches)}")
batch_embeddings = model.encode([x[1] for x in batch], normalize_embeddings=True)
vector_data.extend(batch)
faiss_index.add(batch_embeddings)
现在我们可以使用相同的 query
函数用英语搜索德语答案:
query("What is version control?")
结果:
Cosine: 0.6719034910202026
Location: EPUB/ch01-getting-started.xhtml::1
Text:
Was ist Versionsverwaltung?
Was ist „Versionsverwaltung", und warum sollten Sie sich dafür interessieren?
Versionsverwaltung ist ein System, welches die Änderungen an einer oder einer Reihe von Dateien über die Zeit hinweg protokolliert, sodass man später auf eine bestimmte Version zurückgreifen kann.
Die Dateien, die in den Beispielen in diesem Buch unter Versionsverwaltung gestellt werden, enthalten Quelltext von Software, tatsächlich kann in der Praxis nahezu jede Art von Datei per Versionsverwaltung nachverfolgt werden.
Als Grafik- oder Webdesigner möchte man zum Beispiel in der Lage sein, jede Version eines Bildes oder Layouts nachverfolgen zu können. Als solcher wäre es deshalb ratsam, ein Versionsverwaltungssystem (engl. Version Control System, VCS) einzusetzen.
Ein solches System erlaubt es, einzelne Dateien oder auch ein ganzes Projekt in einen früheren Zustand zurückzuversetzen, nachzuvollziehen, wer zuletzt welche Änderungen vorgenommen hat, die möglicherweise Probleme verursachen, herauszufinden wer eine Änderung ursprünglich vorgenommen hat und viele weitere Dinge.
Ein Versionsverwaltungssystem bietet allgemein die Möglichkeit, jederzeit zu einem vorherigen, funktionierenden Zustand zurückzukehren, auch wenn man einmal Mist gebaut oder aus irgendeinem Grund Dateien verloren hat.
All diese Vorteile erhält man für einen nur sehr geringen, zusätzlichen Aufwand.
这一节的标题翻译为"什么是版本控制?",所以这是一个很好的回答。
tag使用中文查询
这些示例用 Jina Embeddings v2 处理中文和英文的方式完全相同。要使用中文模型,只需运行以下代码:
from transformers import AutoModel
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True)
获取Pro Git:关于 Git 你需要知道的一切的中文版:
wget -O progit-zh.epub https://open.umn.edu/opentextbooks/formats/3455
然后,处理中文版本的书籍:
book_data = decompose_epub("progit-zh.epub")
本教程中的所有其他代码都将以相同的方式工作。
tag未来展望:更多语言,包括编程语言
我们将在近期推出更多双语模型,西班牙语和日语模型已经在开发中,还有一个支持英语和几种主要编程语言的模型。这些模型特别适合管理多语言信息的国际企业,可以作为 AI 驱动的信息检索和基于 RAG 的生成语言模型的基石,适用于各种前沿 AI 应用场景。
Jina AI 的模型结构紧凑,性能在同类中名列前茅,展示了无需最大的模型也能获得最佳性能。通过专注于双语性能,我们开发出的模型不仅在这些语言上表现更好,还更容易适应和更具成本效益,相比之下,在未经筛选数据上训练的大型模型就显得逊色了。
Jina Embeddings 可以从 Hugging Face、AWS marketplace(用于 Sagemaker)获取,也可以通过 Jina Embeddings web API 使用。它们已完全集成到许多 AI 处理框架和向量数据库中。
访问 Jina Embeddings 网站了解更多信息,或联系我们讨论 Jina AI 的产品如何融入您的业务流程。
