hung-phan/ml-skills/embeddings
Claude Code and agent skill by hung-phan/ml-skills
- community
Checking that the SKILL.md file is still in the repository.
Embedding models for retrieval and similarity — sentence-transformers, BGE, E5, OpenAI/Voyage APIs, plus rerankers and cross-modal (CLIP) matching. Use when building RAG retrieval, semantic search, deduplication, or any pipeline that maps unstructured data to dense vectors.
Install
npx vskill@latest install hung-phan/ml-skills/embeddingsSKILL.md
The same SKILL.md was published earlier as hung-phan/ml-skills/embeddings.
Embeddings
1. Why This Exists
Text, images, and code are variable-length unstructured data. You can't compute "distance" between two paragraphs or sort images by similarity without a shared numeric representation.
Embeddings solve this by mapping inputs to fixed-size dense vectors (typically 384–4096 dimensions) where geometric proximity encodes semantic similarity. This enables:
- Retrieval: find the 10 most relevant documents for a query in <10ms over millions of vectors
- Clustering: group similar items without labels
- Classification: use vectors as features for downstream models
- Deduplication: detect near-duplicates via cosine threshold
- Cross-modal search: match text queries to images (CLIP/SigLIP)
| Without Embeddings | With Embeddings | |
|---|---|---|
| BM25 keyword match (misses synonyms) | Semantic similarity captures meaning | |
| O(N) pairwise comparison | ANN index: O(log N) or sublinear | |
| Modality-locked (text↔text only) | Cross-modal (text↔image↔code) |
2. Text Embeddings
Bi-Encoder vs Cross-Encoder
| Property | Bi-Encoder | Cross-Encoder | |
|---|---|---|---|
| Architecture | Encode query & doc independently | Joint attention over (query, doc) pair | |
| Speed | O(1) per doc (precompute) | O(N) -- must score every pair | |
| Quality | Good (MTEB ~65-70) | Best (MTEB ~72-75) | |
| Use case | First-stage retrieval | Reranking top-K | |
| Scalability | Millions of docs | Top 20-100 candidates |
Training Objectives
Contrastive Loss (InfoNCE):
sim= cosine similarityτ= temperature (typically 0.05-0.1)d+= positive,di= in-batch negatives + hard negatives
Hard Negative Mining: Random negatives are too easy. Mine hard negatives from:
- BM25 top-K that aren't relevant (lexical overlap, wrong semantics)
- Previous model's top-K false positives
- Cross-encoder scores to find borderline cases
Matryoshka Representation Learning (MRL): Train with loss applied at multiple dimension prefixes (e.g., 64, 128, 256, 768). At inference, truncate to smaller dims with minimal quality loss -- saves storage and speeds search.
3. Code Examples
Sentence-Transformers Encode + Cosine
FAISS Index (CPU, Flat + IVF)
Milvus Insert + Search
Cross-Encoder Reranking
4. Model Comparison
| Model | Dims | MTEB Avg | Max Tokens | Notes | |
|---|---|---|---|---|---|
| BAAI/bge-base-en-v1.5 | 768 | 63.6 | 512 | Best open-source base size | |
| BAAI/bge-large-en-v1.5 | 1024 | 64.2 | 512 | Slightly better, 2x compute | |
| intfloat/e5-large-v2 | 1024 | 62.0 | 512 | Strong zero-shot | |
| Alibaba-NLP/gte-large-en-v1.5 | 1024 | 65.4 | 8192 | Long context, high quality | |
| nomic-embed-text-v1.5 | 768 | 62.3 | 8192 | MRL-trained, truncatable to 256d | |
| text-embedding-3-large (OpenAI) | 3072 | 64.6 | 8191 | API-only, MRL (truncate to 256/1024) | |
| embed-v4.0 (Cohere) | 1536 | -- | 128000 | API-only, multimodal (text+image+PDF), MRL dims 256/512/1024/1536, input_type parameter | |
| embed-english-v3.0 (Cohere) | 1024 | 64.5 | 512 | API-only, input_type parameter (legacy, superseded by embed-v4.0) | |
| voyage-3-large (Voyage AI) | 1024 | -- | 32000 | Top general API model, MRL to 256/512/2048; voyage-large-2 now legacy | |
| voyage-code-3 (Voyage AI) | 1024 | -- | 32000 | Best API model for code retrieval |
Choosing a model:
- Budget-constrained, self-hosted → BGE-base (768d, 110M params)
- Quality-first, self-hosted → GTE-large or BGE-large
- Long documents (>512 tokens) → GTE or Nomic (8K context)
- API acceptable → Voyage or OpenAI text-embedding-3-large
- Need dim reduction → Nomic or OpenAI (MRL-trained)
5. Fine-Tuning Embeddings
Sentence-Transformers Trainer
Hard Negative Mining During Training
When to Fine-Tune
| Scenario | Action | |
|---|---|---|
| Domain vocab differs (legal, medical) | Fine-tune on domain pairs | |
| Short queries → long docs | Fine-tune with asymmetric pairs | |
| Performance plateau on your eval set | Mine hard negatives, retrain | |
| Need smaller dims for cost | Train with Matryoshka loss | |
| General English retrieval | Use pretrained BGE/GTE (already strong) |
6. Image & Cross-Modal Embeddings
CLIP / SigLIP
Map images and text to the same vector space. A text query finds relevant images (and vice versa).
| Model | Image Dims | Text Dims | Training | Best For | |
|---|---|---|---|---|---|
| openai/clip-vit-large-patch14 | 768 | 768 | Contrastive (softmax) | General cross-modal | |
| google/siglip-base-patch16-224 | 768 | 768 | Sigmoid (per-pair) | Fine-grained, batch-flexible | |
| laion/CLIP-ViT-bigG-14-laion2B | 1280 | 1280 | Contrastive on 2B pairs | Highest quality open |
SigLIP vs CLIP: SigLIP uses sigmoid loss (independent per pair) instead of softmax (requires all pairs in batch). This means SigLIP works with any batch size and handles fine-grained distinctions better.
7. Retrieval Patterns
Bi-Encoder → Cross-Encoder Pipeline
This is the standard production pattern. Bi-encoder handles scale; cross-encoder handles quality.
Hybrid Search (Sparse + Dense)
Combine BM25 (exact keyword match) with dense embeddings (semantic match):
When to Use Hybrid
| Signal | Use Dense Only | Use Hybrid | |
|---|---|---|---|
| Queries have entity names (product IDs, codes) | ❌ | ✅ | |
| Pure semantic ("things like X") | ✅ | ✅ (no harm) | |
| Domain with specialized vocab | ❌ | ✅ | |
| Cold start (no training data) | ✅ | ✅ | |
| Latency budget <5ms | ✅ | ❌ (2 searches) |
8. Gotchas
- Always normalize embeddings before cosine similarity. Without normalization, dot product ≠ cosine. Most models have
normalize_embeddings=Trueflag. - Prefix instructions matter: BGE models expect
"Represent this sentence: "prefix for docs,"Represent this sentence for searching: "for queries. E5 uses"query: "/"passage: ". Check model card. - Dimension mismatch: You cannot mix 768d and 1024d vectors in the same index. Pick one model and stick with it (or retrain with MRL for flexibility).
- Batching: Encode in batches of 256-1024 for GPU utilization. Single-item encode wastes 90%+ of GPU compute.
- Token truncation: Most models silently truncate at 512 tokens. For long docs, chunk into overlapping windows (256 tokens, 64 overlap) and store per-chunk vectors.
- Index type matters: FLAT = exact, IVF = fast approximate, HNSW = best recall/speed tradeoff for <10M vectors, DiskANN = billion-scale.
- Don't fine-tune on <1K pairs: Contrastive learning needs diversity. Under 1K pairs, you'll overfit. Use pretrained or augment with LLM-generated pairs.
9. References
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/ml-review/references/ml-architectures/embeddings/SKILL.md
Popularity
- Repository stars
- 4
- 7-day trend score
- 0
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/hung-phan/ml-skills/embeddings)