Embedding Model Customization
Embedding Model Customization
Learn how to fine-tune an embedding model to improve retrieval accuracy for your specific domain.
About
Embedding models convert text into dense vector representations that capture semantic meaning. Fine-tuning these models on your domain data significantly improves retrieval accuracy—in RAG pipelines, this means the LLM receives more relevant context and produces better answers.
What you will achieve with embedding fine-tuning:
- 🎯 Domain specialization: Adapt general embeddings for legal, medical, scientific, or financial content
- 📈 Improved retrieval: Achieve 6-10% better recall on domain-specific benchmarks
- 🔍 Semantic understanding: Teach the model your domain’s vocabulary and relationships
Recall@5 measures the fraction of relevant documents that appear in the top 5 search results.
About the baseline: In retrieval benchmarks like SciDocs, the pretrained model achieves ~0.159 Recall@5. After fine-tuning on scientific paper triplets, you can expect 6-10% improvement (~0.17 Recall@5).
Dataset Format for Embedding Models
Embedding models require triplet format for contrastive learning:
query: The search query or questionpos_doc: A document relevant to the query (positive example)neg_doc: List of hard negatives—documents that share some overlap with the query but are not actually relevant (negative example)
The model learns to maximize similarity between query and positive document while minimizing similarity with negative documents.
Prerequisites
Before starting this tutorial, ensure you have:
- Completed the Quickstart to install and deploy NeMo Platform locally
- Installed the Python SDK (PyPI wrapper:
pip install "nemo-platform[all]"; source checkout: runmake bootstrapfrom the repository root) - HuggingFace token with read access to download the SPECTER dataset (get one at huggingface.co/settings/tokens)
- NGC API key to pull NIM container images from nvcr.io (get one at ngc.nvidia.com → Setup → Generate API Key)
Quick Start
1. Initialize SDK
The SDK needs to know your NeMo Platform server URL. By default, http://localhost:8080 is used in accordance with the Quickstart guide. If NeMo Platform is running at a custom location, you can override the URL by setting the NMP_BASE_URL environment variable:
2. Establish Baseline Performance
Before fine-tuning, establish baseline performance with the pretrained model. Deploy it, run a test query, and observe where it struggles. Following fine-tuning, compare the results.
Scenario: Searching scientific papers by meaning, not keywords.
Demo setup:
- Query: “Conditional Random Fields” (CRFs) - a method for sequence labeling in NLP
- Trap: “Random Forests” shares the word “random” but is an unrelated tree-based algorithm
- Goal: The model should distinguish between them.
3. Prepare Dataset
Use the SPECTER dataset from HuggingFace, a collection of scientific paper triplets where papers that cite each other are considered related.
Dataset structure:
- ~684K scientific paper triplets (this tutorial uses 10%)
- Each triplet: (query paper, positive/related paper, negative/unrelated paper)
- Papers that cite each other are marked as “related”
In this tutorial the following dataset directory structure will be used:
4. Download and Format SPECTER Dataset
The SPECTER dataset requires conversion to the triplet format required for fine-tuning.
5. Create Dataset FileSet and Upload Training Data
6. Secrets Setup
Configure authentication for accessing base models:
- NGC models (
ngc://URIs): Requires NGC API key - HuggingFace models (
hf://URIs): Requires HF token for gated/private models
Get your credentials:
- NGC API Key (Setup → Generate API Key)
- HuggingFace Token (Create token with Read access)
Quick Setup Example
This tutorial fine-tunes nvidia/llama-nemotron-embed-1b-v2, an NVIDIA embedding model optimized for question-answering and retrieval tasks.
7. Create Base Model FileSet and Model Entity
Create a fileset pointing to the nvidia/llama-nemotron-embed-1b-v2 embedding model from HuggingFace, then create a Model Entity that references this fileset. Model downloading will take place at training time.
8. Create Embedding Fine-tuning Job
Create a customization job to fine-tune the embedding model using contrastive learning on the SPECTER dataset.
Submit to the Automodel backend using AutomodelJobInput with split schedule, batch, optimizer, and parallelism sections. Reference the model entity and dataset fileset by workspace/name (not fileset:// URIs).
Key hyperparameters for embedding fine-tuning:
training.training_type:sfttraining.finetuning_type:all_weightsfor full fine-tuning, orlora_mergedfor merged LoRAoptimizer.learning_rate: Lower values (1e-6 to 5e-6) work well for embedding modelsbatch.global_batch_size: Larger batches improve contrastive learning (128-256 recommended)
NOTE:
NeMo Platform does not support unmerged LoRA adapters for embedding models because the embedding NIM requires ONNX format, which cannot represent standalone adapters. This notebook uses all-weights fine-tuning. For merged LoRA, set finetuning_type to lora_merged:
9. Track Training Progress
Interpreting Embedding Training Metrics:
Embedding models use contrastive loss—lower values indicate better separation between similar and dissimilar pairs:
10. Deploy Fine-Tuned Embedding Model
After training completes, deploy the embedding model using the Deployment Management Service:
Track Deployment Status
11. View the Improvement
Run the same query against the fine-tuned model and compare to the baseline from earlier.
Evaluation Best Practices
Manual Evaluation (Recommended)
- Test with real-world queries from your domain
- Compare retrieval rankings before and after fine-tuning
- Check that semantically similar items rank higher than keyword matches
What to look for:
- ✅ Relevant documents consistently rank in top positions
- ✅ Keyword traps (like “Random Forest” vs “Random Fields”) are handled correctly
- ✅ Domain-specific terminology is understood
- ❌ Unrelated documents with matching keywords do not rank high
Benchmark Evaluation
For systematic evaluation, use the NeMo Evaluator service with retrieval benchmarks like SciDocs, BEIR, or MTEB. Refer to the Evaluator documentation for details.
Hyperparameters
For detailed information on all available hyperparameters, recommended values, and tuning guidance, refer to the Hyperparameter Reference.
Embedding-Specific Recommendations:
Troubleshooting
Embeddings do not show improved retrieval:
- Verify dataset quality: triplets should have clear positive/negative distinctions
- Use hard negatives: negatives should share some overlap with the query but not be relevant (easy negatives do not teach the model much)
- Increase dataset size: 10K+ triplets recommended for meaningful improvement
- Try more epochs: embedding models often need multiple passes
- Lower learning rate: embedding models are sensitive to LR
Training loss not decreasing:
- Check triplet format: ensure
neg_docis a list even for single negatives - Verify hard negative quality: negatives should be challenging but clearly non-relevant
- Increase batch size: contrastive learning benefits from larger batches
Deployment fails:
- Ensure you use the correct NIM image for embedding models
- Verify sufficient GPU memory for the model size
- Check deployment status:
client.inference.deployments.retrieve(name=deployment.name, workspace="default")and refer to platform logs for debugging
Next Steps
- Monitor training metrics in detail
- Evaluate your model with retrieval benchmarks
- Integrate the fine-tuned embedding model into your RAG pipeline
- Scale up training with the full SPECTER dataset (~684K triplets) for better results