embedding-fine-tuning
БесплатноБез исполняемых скриптовНе проверенFine-tuning sentence embedding models with sentence-transformers. Contrastive objectives (MultipleNegativesRankingLoss, TripletLoss, CoSENT), domain…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Embedding Fine-Tuning
When to Fine-Tune
| Signal | Action |
|---|---|
| Domain vocabulary very different from web (legal, medical, code) | Fine-tune |
| Generic model recall@10 above 0.85 on eval | Do not fine-tune; tune retrieval |
| No labelled (query, doc) pairs available | Start with GPL synthetic queries |
| Fewer than 500 real pairs | Use synthetic + in-batch negatives |
| 10k+ labelled pairs with hard negatives | Expect 5-15% nDCG lift |
Contrastive Loss Choices
| Loss | Inputs | When to use |
|---|---|---|
| MultipleNegativesRankingLoss (MNR) | (anchor, positive) | Default — uses in-batch negatives, no labels needed |
| MultipleNegativesSymmetricRankingLoss | (anchor, positive) | Symmetric tasks (STS-like) |
| TripletLoss | (anchor, positive, negative) | When hard negatives are curated |
| CachedMultipleNegativesRankingLoss | (anchor, positive) | Large batch sizes on small GPUs |
| CoSENT / AnglE | labelled similarity scores | STS regression tasks |
| Matryoshka2dLoss wrapper | any base loss | Train MRL-truncatable model |
Minimal Training Loop (sentence-transformers v3+)
from sentence_transformers import (
SentenceTransformer, SentenceTransformerTrainer,
SentenceTransformerTrainingArguments,
)
from sentence_transformers.losses import MultipleNegativesRankingLoss
from sentence_transformers.training_args import BatchSamplers
from sentence_transformers.evaluation import InformationRetrievalEvaluator
from datasets import Dataset
model = SentenceTransformer("BAAI/bge-base-en-v1.5")
# Dataset: two columns named exactly "anchor" and "positive"
train_ds = Dataset.from_dict({
"anchor": ["how do I reset my password?", "what is OAuth 2.0?"],
"positive": ["Go to Settings > Security > Reset Password.",
"OAuth 2.0 is an authorization framework for delegated access."],
})
loss = MultipleNegativesRankingLoss(model)
args = SentenceTransformerTrainingArguments(
output_dir="models/my-domain-embedder",
num_train_epochs=3,
per_device_train_batch_size=64,
learning_rate=2e-5,
warmup_ratio=0.1,
fp16=True,
batch_sampler=BatchSamplers.NO_DUPLICATES, # critical for MNR
eval_strategy="steps",
eval_steps=200,
save_strategy="steps",
save_steps=200,
logging_steps=50,
run_name="bge-domain-v1",
)
trainer = SentenceTransformerTrainer(
model=model,
args=args,
train_dataset=train_ds,
loss=loss,
)
trainer.train()
model.save_pretrained("models/my-domain-embedder/final")
Triplet Loss with Hard Negatives
from sentence_transformers.losses import TripletLoss, TripletDistanceMetric
from datasets import Dataset
triplet_ds = Dataset.from_dict({
"anchor": ["revoke OAuth token"],
"positive": ["Call POST /oauth/revoke with the token parameter."],
"negative": ["Register a new OAuth client in the developer console."], # topically similar but wrong
})
loss = TripletLoss(
model=model,
distance_metric=TripletDistanceMetric.COSINE,
triplet_margin=0.3,
)
Hard Negative Mining
Random negatives are too easy; mine negatives that a pretrained model ranks highly but are NOT the ground-truth positive.
from sentence_transformers import SentenceTransformer, util
miner = SentenceTransformer("BAAI/bge-base-en-v1.5")
corpus = [...] # all candidate docs
corpus_emb = miner.encode(corpus, convert_to_tensor=True, normalize_embeddings=True)
def mine_hard_negatives(query: str, positive_idx: int, k: int = 3, top_n: int = 50):
q_emb = miner.encode(query, convert_to_tensor=True, normalize_embeddings=True)
hits = util.semantic_search(q_emb, corpus_emb, top_k=top_n)[0]
# Skip true positive; take next ranked items
negatives = [corpus[h["corpus_id"]] for h in hits if h["corpus_id"] != positive_idx][:k]
return negatives
# Filter out false negatives with a cross-encoder or teacher model before using.
False-negative filtering is critical — if a mined "negative" is actually relevant,
you teach the model the opposite of what you want. Use a strong cross-encoder
(BAAI/bge-reranker-large) to filter out candidates with rerank score above a
threshold.
Synthetic Query Generation (GPL-style)
When you have documents but no queries:
# Step 1: Generate queries per document using an LLM
from openai import OpenAI
client = OpenAI()
PROMPT = """Generate exactly 3 distinct search queries a user would type to find
this passage. Return one query per line, no numbering.
Passage:
{doc}"""
def generate_queries(doc: str) -> list[str]:
resp = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": PROMPT.format(doc=doc)}],
temperature=0.7,
)
return [q.strip() for q in resp.choices[0].message.content.splitlines() if q.strip()]
# Step 2: Mine hard negatives with a pretrained embedder
# Step 3: Score (query, pos, neg) triplets with a cross-encoder teacher to get
Установить embedding-fine-tuning в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл embedding-fine-tuning?
Fine-tuning sentence embedding models with sentence-transformers. Contrastive objectives (MultipleNegativesRankingLoss, TripletLoss, CoSENT), domain adaptation, synthetic query generation (GPL), hard negative mining, and downstream retrieval evaluation. USE WHEN: user mentions "fine-tune embeddings", "domain adaptation", "sentence-transformers training", "contrastive loss", "hard negatives", "GPL", "synthetic queries", "MNR loss", "triplet loss" DO NOT USE FOR: picking a pretrained model - use `embedding-models`; MRL truncation - use `matryoshka-embeddings`; reranker training - out of scope
Как установить скилл embedding-fine-tuning?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл embedding-fine-tuning запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
theme-factory
Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with…
от Anthropicaccess
Manage Discord channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropicconfigure
Set up the Discord channel — save the bot token and review access policy. Use when the user pastes a Discord bot token, asks to configure Discord, asks "how…
от Anthropicaccess
Manage iMessage channel access — approve pairings, edit allowlists, set DM/group policy. Use when the user asks to pair, approve someone, check who's allowed…
от Anthropic