Component · L2
Embedding Trainer
github.com/juanmmm21/contrastive-embedding-trainer
Contrastive training of text embeddings with PyTorch and Siamese networks using a triplet cosine loss.
- Lines
- 540
- Files
- 8
- Test files
- 1
- Commits
- 9
- Started
- 25 Jun 2026
- Last commit
- 6 Jul 2026
- Python 100%
● Where it sits
Layer 2 of AI Core — representation & retrieval.
L1 Data & input
L2 Representation & retrieval
L3 Inference & control
L4 Agents
L5 MLOps & quality
↳ Flagship
Fed by
BPE TokenizerFeeds into
Vector DBREADME · 2 min read
Commits per day
Custom PyTorch pipeline for training text embeddings using a siamese network architecture and Triplet Cosine Loss. This project enables fine-tuning of Transformer-based encoders for semantic search, clustering, and retrieval-augmented generation (RAG) tasks.
Architecture and Theoretical Foundations
The system uses a single base Transformer encoder (default distilbert-base-uncased) whose weights are shared in a siamese structure. During training, we process three texts in parallel (the triplet):
- Anchor: The reference text.
- Positive: A text that is semantically similar or related to the Anchor.
- Negative: A text that is semantically dissimilar or unrelated to the Anchor.
Each text generates its dense representation through the same encoder.
1. Mean Pooling over Hidden States
Instead of relying solely on the special [CLS] token (which often suffers from information bottlenecks in sentence-similarity tasks), this pipeline performs an arithmetic average (Mean Pooling) of the Transformer's last-layer hidden states across all tokens in the sentence, weighted and filtered using the attention mask (attention_mask) to ignore padding tokens.
Mathematically, for a sequence of token embeddings and a binary attention mask :
Finally, normalization is applied to the resulting vector to simplify cosine similarity to a dot product:
2. Triplet Cosine Loss
The loss function optimizes the vector space by forcing the cosine distance between the Anchor () and the Positive () to be smaller than the distance between the Anchor and the Negative () by an established margin.
Cosine distance is defined from cosine similarity:
The loss formula for a triplet is:
where is the penalty margin (default 0.3). Optimization seeks to minimize by reducing and increasing .
3. AdamW Optimization with Regularization
Training is performed using the AdamW optimizer, which decouples weight decay from the first- and second-moment gradient updates:
Where is the learning rate, is the weight decay coefficient, and is the bias-corrected gradient.
Export Directory Structure (model_output/)
After fine-tuning completes, the model is exported in a format compatible with Hugging Face Transformers:
pytorch_model.binormodel.safetensors: The fine-tuned encoder's weights.config.json: Structural metadata of the base model.vocab.txtortokenizer.json: The original vocabulary.tokenizer_config.json: WordPiece tokenizer configuration.
Installation Requirements
- Python 3.10 or higher
- PyTorch
- Transformers (Hugging Face)
- Numpy
To install the specified dependencies, run:
pip install -r requirements.txt
Execution and Verification Guide
1. Run Unit Tests
Verifies random weight initialization, pooling layer dimensions, and gradient flow:
python3 -m unittest test_trainer.py
2. Run the Demo Fine-Tuning
python3 example.py
The script will download the base model, run 4 fine-tuning epochs, and compare the resulting cosine similarity before and after training for specific triplets (cooking, astronomy, and programming).
Connectivity within the ai-core-infra Ecosystem
- semantic-chunking-engine: The generated semantic chunks can be vectorized using the siamese model trained here.
- nano-vector-db: The output embeddings are indexed directly into the HNSW index for K-nearest-neighbor (K-NN) searches.
- hybrid-search-retrieval-pipeline: Provides the high-fidelity embeddings required for the dense branch.