Jina AI は Hugging Face を通じて最先端のオープンソース二言語埋め込みモデルを ドイツ語-英語と中国語-英語の言語ペアでリリースしました。


このチュートリアルでは、最小限のインストールとユースケースについて説明します。内容は以下の通りです:
- Hugging Face から Jina Embedding モデルをダウンロードする。
- モデルを使用してドイツ語と英語のテキストからエンコーディングを取得する。
- クロス言語クエリのための基本的な埋め込みベースのニューラル検索エンジンを構築する。
このチュートリアルでは、英語のクエリを使用してドイツ語のテキストを検索し、その逆も可能な方法を Jina Embeddings を使って示します。
このチュートリアルは中国語モデルでも同様に機能します。Querying in Chinese というタイトルの節(最後の方)の指示に従って、中国語-英語二言語モデルと中国語の例文を取得してください。


tag二言語埋め込みモデル
二言語埋め込みモデルは、2つの言語のテキスト(このチュートリアルではドイツ語と英語、中国語モデルでは中国語と英語)を同じ埋め込み空間にマッピングするモデルです。ドイツ語のテキストと英語のテキストが同じ意味を持つ場合、それらに対応する埋め込みベクトルが近くなるような方法でマッピングを行います。
このようなモデルは、このチュートリアルで示すクロス言語情報検索アプリケーションに非常に適していますが、RAG ベースのチャットボット、多言語テキスト分類、要約、感情分析、その他の埋め込みを使用するアプリケーションの基礎としても機能します。これらのモデルを使用することで、両方の言語のテキストを同じ言語で書かれているかのように扱うことができます。
多くの巨大言語モデルが多くの異なる言語をサポートすると主張していますが、すべての言語を同等にサポートしているわけではありません。インターネット上の英語の優位性によるバイアスや、機械翻訳されたテキストのオンライン公開が広がることによる入力ソースの歪みについて、懸念が高まっています。2つの言語に焦点を当てることで、両言語の埋め込み品質をより良くコントロールでき、バイアスを最小限に抑えながら、数十の言語を扱うと主張する巨大モデルと同等以上のパフォーマンスを持つ、はるかに小さなモデルを生成することができます。
Jina Embeddings v2 二言語モデルは 8,192 入力コンテキストトークンをサポートしており、2つの言語をサポートするだけでなく、同様のモデルと比較してより大きなテキストセグメントをサポートすることができます。これにより、より多くのテキスト情報を埋め込みに処理する必要がある、より複雑なユースケースに最適です。
tagGoogle Colab で一緒に進める
このチュートリアルには、付属のノートブックがあり、Google Colab またはローカルシステムで実行できます。

tag前提条件のインストール
現在の環境に関連ライブラリがインストールされていることを確認してください。最新バージョンの transformers
が必要なので、すでにインストールされている場合でも、以下を実行してください:
pip install -U transformers
このチュートリアルでは、Meta の FAISS ライブラリを使用してベクトル検索と比較を行います。インストールするには、以下を実行してください:
pip install faiss-cpu
また、このチュートリアルでは入力データの処理に Beautiful Soup を使用するので、以下をインストールしてください:
pip install bs4
tagHugging Face へのアクセス
モデルをダウンロードするには、Hugging Face へのアクセス、特にアカウントとアクセストークンが必要です。
Hugging Face のアカウントをお持ちでない場合:
https://huggingface.co/ にアクセスし、ページ右上の「Sign Up」ボタンが表示されるはずです。クリックして、新しいアカウントを作成するための指示に従ってください。

アカウントにログインした後:
アクセストークンを取得するには、Hugging Face のウェブサイトの指示に従ってください。
HF_TOKEN
という環境変数にコピーする必要があります。ノートブック(例えば Google Colab)で作業している場合や、Python プログラム内で直接設定する場合は、以下の Python コードを使用してください:
import os
os.environ['HF_TOKEN'] = "<your token here>"
シェルでは、環境変数を設定するための適切な構文を使用してください。bash
の場合:
export HF_TOKEN="<your token here>"
## ドイツ語と英語用の Jina Embeddings v2 のダウンロード
トークンを設定したら、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 トークンの入力を受け付けることができ、この本のような場合、さらなるテキストの分割や、セクションがトークン制限を超えていないかチェックする必要はありません。本の最も長いセクションでも約12,000文字であり、通常の英語テキストであれば8kトークンの制限をはるかに下回ります。
単一のエンベッディングを生成するには、ダウンロードしたモデルの 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
は GPU なしの無料枠の Google Colab で動作し、エンベッディングの全セットを生成するのに約1時間かかりました。
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.
ご自身のドイツ語の質問で試してみて、どの程度うまく機能するか確認してください。テキスト情報検索を扱う際の一般的な実践として、1つだけでなく3〜5つの応答を求めるべきです。最適な回答は必ずしも最初の回答ではありません。
tag役割の逆転:英語でドイツ語文書を検索する
『Pro Git: Everything You Need to Know About 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.
このセクションのタイトルは「What is version control?」という意味なので、これは良い応答と言えます。
tag中国語での検索
これらの例は、Jina Embeddings v2 を使用すれば中国語と英語でも全く同じように機能します。代わりに中国語モデルを使用するには、以下を実行するだけです:
from transformers import AutoModel
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True)
そして『Pro Git: Everything You Need to Know About 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、Sagemaker で使用するための AWS マーケットプレイス、および Jina Embeddings Web API から利用できます。多くの AI プロセスフレームワークとベクターデータベースに完全に統合されています。
詳細についてはJina Embeddings のウェブサイトをご覧いただくか、Jina AI の製品があなたのビジネスプロセスにどのように適合するかについて、お気軽にお問い合わせください。
