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

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

例: 「Google launches Pixel 10」と「Qwen releases Qwen3」という見出しは、両方を単に「Tech」とラベル付けするだけなら類似として埋め込みできますが、意味検索をしている場合は、別の内容について述べているため類似ではありません。ファインチューニングは、ユースケースにとって「正しい」種類の類似性をモデルに学習させ、エラーを減らし、結果を改善します。

[**Unsloth**](https://github.com/unslothai/unsloth) は現在、埋め込み、 **分類器**, **BERT**, **リランカー** モデルの学習を [**約1.8〜3.3倍高速に**](#unsloth-benchmarks) 対応しています。メモリ使用量は20%少なく、他のFlash Attention 2実装よりコンテキスト長は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)に心から感謝します。このサポートには彼の仕事が非常に重要でした。Hugging Face 上の electroglyph のカスタムモデルは [こちら](https://huggingface.co/electroglyph).

### 🦥 Unslothの機能

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

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

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

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

新しいファインチューニングの流れは `FastSentenceTransformer`.

を中心にしています。主な保存/Hubへの公開メソッド:

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

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

`が必要です。` from\_pretrained() **と似ていますが、**:

* モデルを **推論用に** 読み込むには `FastSentenceTransformer`、 **必ず** 次を渡してください: `for_inference=True`

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

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

Hugging Face の認証については、次を実行する場合:

```
hf auth login
```

Hubメソッドを呼び出す前に同じ仮想環境内で実行すると、

* `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` + Flash Attention 2 (FA2) を4bit QLoRAで使用した場合との比較です。 **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&#x26;token=e3ea6510-b129-401a-83ae-301d01865547" alt=""><figcaption></figcaption></figure>

以下は、ヒートマップで比較した Unsloth のベンチマークです。 `SentenceTransformers` + Flash Attention 2 (FA2) を16bit LoRAで使用した場合との比較です。 **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&#x26;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: Querying This Documentation

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

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

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

The question should be specific, self-contained, and written in natural language.
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.
