← Back to Pull requests

Add embedding_sft algorithm for contrastive embedding fine-tuning #139

Merged
Maxusmusti merged 6 files (555 lines) on Sep 04, 2026 15:56 UTC
View on GitHub
Maxusmusti Maxusmusti commented on Aug 02, 2026 21:12 UTC
Author

Summary

  • New embedding_sft algorithm for fine-tuning sentence embedding models using contrastive losses

  • Designed for the semantic routing project (vSR) but applicable to any embedding classification task

  • Wraps sentence-transformers library via SentenceTransformersBackend
  • Details

    Algorithm: embedding_sft()

    Fine-tunes embedding models (e.g. all-MiniLM-L6-v2, 23M params) so that inputs with the same label cluster together in embedding space. Supports three loss functions:

    | Loss | Description | Best for |
    |------|-------------|----------|
    | batch_all_triplet | Mines all valid triplets per batch | Default — exhaustive boundary learning |
    | batch_hard_triplet | Mines hardest triplet per anchor | Focused on worst-case boundaries |
    | mnrl | Multiple Negatives Ranking Loss | General semantic similarity |

    Key features:

  • GROUP_BY_LABEL batch sampling ensures every batch has all classes (required for triplet mining)

  • Auto-converts label datasets to (anchor, positive) pairs for MNRL

  • Custom loss_fn callable support for extensibility

  • Saves in standard sentence-transformers format
  • Usage

    from training_hub import embedding_sft
    
    result = embedding_sft(
        model_path="sentence-transformers/all-MiniLM-L6-v2",
        data_path="routing_train.jsonl",    # {"text": "...", "label": 0}
        ckpt_output_dir="./routing_model",
        loss_type="batch_all_triplet",
        num_epochs=20,
        batch_size=32,
        learning_rate=2e-5,
    )
    

    Files

  • src/training_hub/algorithms/embedding_sft.py — Algorithm, Backend, convenience function

  • src/training_hub/__init__.py — exports

  • pyproject.toml — [embedding] extra: sentence-transformers>=5.0

  • examples/embedding_sft_semantic_routing.py — full POC reproducer (data gen → train → eval)

  • examples/notebooks/routing_demo.ipynb — interactive walkthrough notebook (data gen → fine-tune → router runtime → eval), with rendered outputs

  • tests/test_embedding_sft.py — unit tests for validation and data helpers

  • docs/algorithms/embedding_sft.md, docs/api/{functions,classes,backends}/embedding_sft.md — algorithm docs

  • docs/README.md, docs/_sidebar.md, docs/api/README.md, docs/examples/README.md — support matrix, nav, and examples entries
  • Test plan

  • Tested batch_all_triplet loss — PASS

  • Tested batch_hard_triplet loss — PASS

  • Tested mnrl loss (with auto pair conversion) — PASS

  • Verified model saves in sentence-transformers format and reloads correctly

  • Ran full semantic routing example end-to-end

  • tests/test_embedding_sft.py — 17 unit tests passing

  • Re-executed routing_demo.ipynb end-to-end against the reviewed source (baseline 64.17% → fine-tuned 100%, live demo 10/10)
  • 🤖 Generated with Claude Code

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

    New Features
    Added embedding model fine-tuning with triplet and multiple-negative-ranking losses.
    Supports common training data formats, configurable sampling, evaluation data, checkpoints, and custom loss functions.
    Added public APIs for configuring and running embedding fine-tuning.
    Added a semantic-routing example with generated datasets and baseline versus fine-tuned accuracy, F1, and misrouting metrics.
    Added configurable model, output, training, and reproducibility options for the example.

    Documentation
    * Added installation guidance, usage examples, and API reference documentation for embedding fine-tuning.
    <!-- end of auto-generated comment: release notes by CodeRabbit -->

    <!-- This is an auto-generated comment: release notes by coderabbit.ai -->

    Summary by CodeRabbit

  • New Features

  • - Added embedding fine-tuning for sentence-transformer models with contrastive, triplet, and custom losses.
    - Added configurable data loading, evaluation, sampling, checkpointing, and structured training results.
    - Added semantic-routing example with baseline and fine-tuned accuracy metrics.
    - Added optional embedding support and public API access.

  • Documentation

  • - Added comprehensive guides, API references, installation instructions, and quick-start examples.

  • Tests

  • - Added coverage for dataset loading, validation, pair conversion, custom losses, and deterministic sampling.

    <!-- end of auto-generated comment: release notes by coderabbit.ai -->

    Diff: 555 lines (+416 / -139) across 6 files Reviewer: None requested Review duration: 47204m
    All Vouch review confidence checks passed
    Residual risk 0.34 = Change Risk (0.60) × (1 − Review Confidence (0.44)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.60 · 555 lines diff across 6 files
    0.60
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 10%
    44%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.378
    Shallow Review Depth shallow_review_depth
    0.344
    No Reviewer Assigned no_reviewer_assigned
    0.120
    Real PR Conversation Timeline
    1 comments
    "Review active on #139"
    general weight: 0.35
    Reviewers
    None requested
    Assignees
    Maxusmusti Maxusmusti
    Labels
    risk: low confidence: 44.2% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 60.1% (MEDIUM) · Higher = larger blast radius
    60.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 44.2% · Lower = rushed or shallow review
    44.2%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 33.6% · Safe to merge
    33.6%