> For the complete documentation index, see [llms.txt](https://unsloth.ai/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://unsloth.ai/docs/jp/ji-chu/embedding-finetuning.md).

# Unsloth ガイドによる埋め込みモデルのファインチューニング

Unsloth で埋め込みモデルを簡単にファインチューニングする方法を学びます。

埋め込みモデルをファインチューニングすると、特定のタスクでの検索およびRAGの性能を大幅に向上できます。モデルのベクトルをあなたのドメインと、ユースケースで重要な「類似性」の種類に合わせることで、データ上の検索、RAG、クラスタリング、レコメンドが改善されます。

例: 見出し「GoogleがPixel 10を発表」と「QwenがQwen3をリリース」は、両方を単に「テック」とラベル付けするだけなら似ていると埋め込まれるかもしれませんが、意味検索を行うなら異なる事柄について述べているため似ていません。ファインチューニングは、モデルがあなたのユースケースにとって「適切な」種類の類似性を捉えるのを助け、誤りを減らして結果を改善します。

[**Unsloth**](https://github.com/unslothai/unsloth) 現在、埋め込みの学習をサポートしています、 **分類器**, **BERT**, **リランカー** モデル [**約1.8〜3.3倍高速**](#unsloth-benchmarks) 他のFlash Attention 2実装よりメモリ使用量が20%少なく、コンテキスト長は2倍長いにもかかわらず、精度低下はありません。EmbeddingGemma-300Mはわずか **3GBのVRAM**。学習済みの **モデルをどこでも**：transformers、LangChain、Ollama、vLLM、llama.cpp など。

Unsloth は [SentenceTransformers](https://github.com/huggingface/sentence-transformers) Qwen3-Embedding、BERT などの互換モデルをサポートするために。 **ノートブックやアップロードがなくても、まだサポートされています。**

**3つの主なユースケースに対応した無料のファインチューニング用ノートブックを作成しました：**

| [EmbeddingGemma (300M)](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/EmbeddingGemma_\(300M\).ipynb) | [Qwen3-Embedding 4B](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_Embedding_\(4B\).ipynb) • [0.6B](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/Qwen3_Embedding_\(0_6B\).ipynb) | [BGE M3](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/BGE_M3.ipynb)                        |
| -------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| [ModernBERT](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/bert_classification.ipynb) - 分類           | [All-MiniLM-L6-v2](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/All_MiniLM_L6_v2.ipynb)                                                                                                                            | [ModernBERT-large](https://colab.research.google.com/github/unslothai/notebooks/blob/main/nb/bert_classification.ipynb) |

* `All-MiniLM-L6-v2`：独自データで調整された、意味検索・検索・クラスタリング向けのコンパクトなドメイン特化文埋め込みを生成します。
* `tomaarsen/miriad-4.4M-split`：医療に関する質問と生物医学論文を埋め込み、高品質な医療向け意味検索とRAGを実現します。
* `electroglyph/technical`：技術文書（ドキュメント、仕様書、エンジニアリング議論）における意味と意味的類似性をより適切に捉えます。

アップロード済みモデルの残りは次で確認できます： [こちらのコレクションでご覧ください](https://huggingface.co/collections/unsloth/embedding-models).

> Unslothコントリビューターに心から感謝します [**electroglyph**](https://github.com/unslothai/unsloth/pull/3719)、この機能を支えるうえで重要な役割を果たした方です。electroglyphのカスタムモデルはHugging Faceで確認できます [ここ](https://huggingface.co/electroglyph).

### 🦥 Unslothの機能

* パイプラインを書き直すことなく、埋め込みのためのLoRA/QLoRAまたはフルファインチューニングが可能です
* エンコーダー専用モデルの最良のサポート `SentenceTransformer` モデル（ `modules.json`)
* クロスエンコーダーモデルは、フォールバック経路でも正しく学習できることが確認されています
* このリリースでは、次もサポートします `transformers v5`

以下を持たないモデルには限定的なサポートがあります `modules.json` （デフォルトを自動割り当てします `SentenceTransformers` プーリングモジュール）。カスタム処理（カスタムヘッド、非標準のプーリング）をしている場合は、プールされた埋め込みの挙動などの出力を再確認してください。

MPNetやDistilBERTのようにカスタム追加が必要だった一部のモデルは、勾配チェックポイントを次にパッチ適用することで有効になりました `transformers` モデル。

### 🛠️ ファインチューニングのワークフロー

新しいファインチューニングの流れは次を中心にしています `FastSentenceTransformer`.

主な保存/プッシュ方法：

* `save_pretrained()` 保存します **LoRAアダプターを** ローカルフォルダに
* `save_pretrained_merged()` 保存します **マージ済みモデルを** ローカルフォルダに
* `push_to_hub()` プッシュします **LoRAアダプターを** Hugging Faceへ
* `push_to_hub_merged()` プッシュします **マージ済みモデルを** Hugging Faceへ

**そして非常に重要な点が1つあります：推論時の読み込みには `for_inference=True`**

`from_pretrained()` は、Lackerの他の高速クラスに似ていますが、 **1つ例外があります**:

* モデルを読み込んで **推論** を使用して `FastSentenceTransformer`、あなたは **するには** 次を渡す必要があります： `for_inference=True`

したがって、推論時の読み込みは次のようになります：

```python
model = FastSentenceTransformer.from_pretrained(
    "sentence-transformers/all-MiniLM-L6-v2",
    for_inference=True,
)
```

Hugging Faceの認証については、次を実行すると：

```
hf auth login
```

ハブメソッドを呼び出す前に同じ仮想環境内で実行すると、次のようになります：

* `push_to_hub()` そして `push_to_hub_merged()` **トークン引数は不要です**.

### ✅ 推論もデプロイもどこでも！ <a href="#docs-internal-guid-c10bfa80-7fff-446e-714d-732eebcd72d6" id="docs-internal-guid-c10bfa80-7fff-446e-714d-732eebcd72d6"></a>

ファインチューニングしたUnslothモデルは、主要なツールすべてで利用・デプロイできます：transformers、LangChain、Weaviate、sentence-transformers、Text Embeddings Inference（TEI）、vLLM、llama.cpp、独自の埋め込みAPI、pgvector、FAISS/ベクトルデータベース、そしてあらゆるRAGフレームワーク。

ファインチューニングしたモデルは後から自分の端末にローカルでダウンロードできるため、ロックインはありません。

```python
# 1. 事前学習済みのSentence Transformerモデルを読み込む
model = SentenceTransformer("<your-unsloth-finetuned-model")

query = "赤い惑星として知られている惑星はどれですか？"
documents = [
    "金星は、その大きさが似ていて地球に近いため、しばしば地球の双子と呼ばれます。",
    "赤みがかった外観で知られる火星は、しばしば赤い惑星と呼ばれます。",
    "太陽系最大の惑星である木星には、目立つ赤い斑点があります。",
    "輪で有名な土星は、赤い惑星と間違われることがあります。"
]

# 2. 必要に応じて、encode_query と encode_document を使ってエンコードし、適切なプロンプトを自動で使用する
query_embedding = model.encode_query(query)
document_embedding = model.encode_document(documents)
print(query_embedding.shape, document_embedding.shape)

# 3. 類似度を計算する。たとえば、組み込みの similarity ヘルパー関数を使う
similarity = model.similarity(query_embedding, document_embedding)
print(similarity)
```

### 📊 Unslothのベンチマーク

Unslothの利点には、埋め込みファインチューニングの速度があります！私たちは一貫して **1.8〜3.3倍高速であることを示しています** さまざまな埋め込みモデルと、128から2048以上までの異なるシーケンス長で。

EmbeddingGemma-300MのQLoRAはわずか **3GBのVRAM** で動作し、LoRAは6GB VRAMで動作します。

以下は、ヒートマップで示したUnslothのベンチマークです。比較対象は `SentenceTransformers` + 4bit QLoRA向けのFlash Attention 2（FA2）です。 **4bit QLoRAでは、Unslothは1.8倍〜2.6倍高速です：**

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FQqagyYR6DebgX768A0HV%2Foutput(16).png?alt=media&amp;token=e3ea6510-b129-401a-83ae-301d01865547" alt=""><figcaption></figcaption></figure>

以下は、ヒートマップで示したUnslothのベンチマークです。比較対象は `SentenceTransformers` + 16bit LoRA向けのFlash Attention 2（FA2）です。 **16bit LoRAでは、Unslothは1.2倍〜3.3倍高速です：**

<figure><img src="https://735611837-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FxhOjnexMCB3dmuQFQ2Zq%2Fuploads%2FTl12zuBg68ZPSyOC9hUe%2Foutput(15).png?alt=media&amp;token=47d7cade-7eac-4366-8011-7034de087431" alt=""><figcaption></figcaption></figure>

### 🔮 モデル対応

Unslothがサポートする人気の埋め込みモデルをいくつか紹介します（ここにすべてのモデルは載っていません）：

```
Alibaba-NLP/gte-modernbert-base
BAAI/bge-large-en-v1.5
BAAI/bge-m3
BAAI/bge-reranker-v2-m3
Qwen/Qwen3-Embedding-0.6B
answerdotai/ModernBERT-base
answerdotai/ModernBERT-large
google/embeddinggemma-300m
intfloat/e5-large-v2
intfloat/multilingual-e5-large-instruct
mixedbread-ai/mxbai-embed-large-v1
sentence-transformers/all-MiniLM-L6-v2
sentence-transformers/all-mpnet-base-v2
Snowflake/snowflake-arctic-embed-l-v2.0
```

ほとんどの [一般的なモデル](https://huggingface.co/models?library=sentence-transformers) はすでにサポートされています。エンコーダー専用でサポートされていないモデルが必要なら、遠慮なく次を開いてください： [GitHub の issue](https://github.com/unslothai/unsloth/issues) 要望を送ってください。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://unsloth.ai/docs/jp/ji-chu/embedding-finetuning.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
