|
| 1 | +{ |
| 2 | + "cells": [ |
| 3 | + { |
| 4 | + "cell_type": "markdown", |
| 5 | + "metadata": {}, |
| 6 | + "source": [ |
| 7 | + "# Quickstart: Ridge Mapping\n", |
| 8 | + "\n", |
| 9 | + "**Use case:** You have a vector database embedded with an \"old\" model and want to use a \"new\" model. isotrieve learns a linear mapping between the two spaces so you can transform existing vectors without re-embedding your entire corpus.\n", |
| 10 | + "\n", |
| 11 | + "**When you'd reach for this:** Any time you want to migrate to a better embedding model but re-embedding is expensive or slow.\n", |
| 12 | + "\n", |
| 13 | + "**What you need installed:** `isotrieve`, `numpy`, `scikit-learn` (all included in the base install).\n", |
| 14 | + "\n", |
| 15 | + "**Estimated runtime:** ~1 minute." |
| 16 | + ] |
| 17 | + }, |
| 18 | + { |
| 19 | + "cell_type": "markdown", |
| 20 | + "metadata": {}, |
| 21 | + "source": [ |
| 22 | + "[](https://colab.research.google.com/github/krish1925/AECP/blob/main/isotrieve-python/notebooks/01_quickstart_ridge_mapping.ipynb)" |
| 23 | + ] |
| 24 | + }, |
| 25 | + { |
| 26 | + "cell_type": "code", |
| 27 | + "execution_count": null, |
| 28 | + "metadata": {}, |
| 29 | + "outputs": [], |
| 30 | + "source": [ |
| 31 | + "# Install isotrieve (no-op if already installed)\n", |
| 32 | + "!pip install -q isotrieve numpy scikit-learn" |
| 33 | + ] |
| 34 | + }, |
| 35 | + { |
| 36 | + "cell_type": "code", |
| 37 | + "execution_count": null, |
| 38 | + "metadata": {}, |
| 39 | + "outputs": [], |
| 40 | + "source": [ |
| 41 | + "import numpy as np\n", |
| 42 | + "from isotrieve import RidgeMapping\n", |
| 43 | + "from isotrieve.quality.gate import QualityGate\n", |
| 44 | + "\n", |
| 45 | + "print(\"isotrieve imported successfully\")" |
| 46 | + ] |
| 47 | + }, |
| 48 | + { |
| 49 | + "cell_type": "markdown", |
| 50 | + "metadata": {}, |
| 51 | + "source": [ |
| 52 | + "## 1. Generate synthetic embedding spaces\n", |
| 53 | + "\n", |
| 54 | + "We create two embedding spaces (old: 384-dim, new: 768-dim) that share a latent structure. This simulates what happens when two different embedding models encode the same texts — their vectors live in different dimensionalities but capture overlapping semantic content." |
| 55 | + ] |
| 56 | + }, |
| 57 | + { |
| 58 | + "cell_type": "code", |
| 59 | + "execution_count": null, |
| 60 | + "metadata": {}, |
| 61 | + "outputs": [], |
| 62 | + "source": [ |
| 63 | + "rng = np.random.default_rng(42)\n", |
| 64 | + "\n", |
| 65 | + "N = 2000 # number of calibration texts\n", |
| 66 | + "D_OLD = 384 # old model dimension\n", |
| 67 | + "D_NEW = 768 # new model dimension\n", |
| 68 | + "LATENT = 64 # shared latent dimension\n", |
| 69 | + "\n", |
| 70 | + "# Shared latent representation (what both models \"see\" about the text)\n", |
| 71 | + "latent = rng.normal(size=(N, LATENT))\n", |
| 72 | + "\n", |
| 73 | + "# Each model projects the latent representation into its own space\n", |
| 74 | + "W_old = rng.normal(size=(LATENT, D_OLD)) / np.sqrt(LATENT)\n", |
| 75 | + "W_new = rng.normal(size=(LATENT, D_NEW)) / np.sqrt(LATENT)\n", |
| 76 | + "\n", |
| 77 | + "X_old = latent @ W_old # (N, 384) — old model embeddings\n", |
| 78 | + "Y_new = latent @ W_new # (N, 768) — new model embeddings\n", |
| 79 | + "\n", |
| 80 | + "# L2-normalize (as real embedding models do)\n", |
| 81 | + "X_old = X_old / np.linalg.norm(X_old, axis=1, keepdims=True)\n", |
| 82 | + "Y_new = Y_new / np.linalg.norm(Y_new, axis=1, keepdims=True)\n", |
| 83 | + "\n", |
| 84 | + "print(f\"Old model vectors: {X_old.shape}\")\n", |
| 85 | + "print(f\"New model vectors: {Y_new.shape}\")" |
| 86 | + ] |
| 87 | + }, |
| 88 | + { |
| 89 | + "cell_type": "markdown", |
| 90 | + "metadata": {}, |
| 91 | + "source": [ |
| 92 | + "## 2. Split into calibration and evaluation sets\n", |
| 93 | + "\n", |
| 94 | + "The calibration set is what isotrieve uses to learn the mapping. The evaluation set is fresh data the mapping has never seen — this is what the quality gate checks." |
| 95 | + ] |
| 96 | + }, |
| 97 | + { |
| 98 | + "cell_type": "code", |
| 99 | + "execution_count": null, |
| 100 | + "metadata": {}, |
| 101 | + "outputs": [], |
| 102 | + "source": [ |
| 103 | + "split = 1500\n", |
| 104 | + "X_cal, X_eval = X_old[:split], X_old[split:]\n", |
| 105 | + "Y_cal, Y_eval = Y_new[:split], Y_new[split:]\n", |
| 106 | + "\n", |
| 107 | + "print(f\"Calibration: {X_cal.shape[0]} pairs\")\n", |
| 108 | + "print(f\"Evaluation: {X_eval.shape[0]} pairs\")" |
| 109 | + ] |
| 110 | + }, |
| 111 | + { |
| 112 | + "cell_type": "markdown", |
| 113 | + "metadata": {}, |
| 114 | + "source": [ |
| 115 | + "## 3. Fit the Ridge mapping\n", |
| 116 | + "\n", |
| 117 | + "isotrieve learns a linear transformation `Y ≈ X W` (with optional bias term) using Ridge regression. Alpha is selected automatically via generalized cross-validation." |
| 118 | + ] |
| 119 | + }, |
| 120 | + { |
| 121 | + "cell_type": "code", |
| 122 | + "execution_count": null, |
| 123 | + "metadata": {}, |
| 124 | + "outputs": [], |
| 125 | + "source": [ |
| 126 | + "mapping = RidgeMapping(alpha=\"auto\", seed=0)\n", |
| 127 | + "mapping.fit(X_cal, Y_cal)\n", |
| 128 | + "\n", |
| 129 | + "report = mapping.validation_report()\n", |
| 130 | + "print(f\"Chosen alpha: {report.alpha:.4f}\")\n", |
| 131 | + "print(f\"Train size: {report.n_train}, Holdout size: {report.n_holdout}\")\n", |
| 132 | + "print(f\"Holdout cosine mean: {report.holdout_cosine_mean:.4f}\")\n", |
| 133 | + "print(f\"Top-1 retention: {report.top1_retention:.4f}\")\n", |
| 134 | + "print(f\"Top-10 retention: {report.top10_retention:.4f}\")" |
| 135 | + ] |
| 136 | + }, |
| 137 | + { |
| 138 | + "cell_type": "markdown", |
| 139 | + "metadata": {}, |
| 140 | + "source": [ |
| 141 | + "## 4. Transform old vectors to new space\n", |
| 142 | + "\n", |
| 143 | + "Now we can take any old-model vector and map it into the new model's space." |
| 144 | + ] |
| 145 | + }, |
| 146 | + { |
| 147 | + "cell_type": "code", |
| 148 | + "execution_count": null, |
| 149 | + "metadata": {}, |
| 150 | + "outputs": [], |
| 151 | + "source": [ |
| 152 | + "# Transform a batch of old vectors to new space\n", |
| 153 | + "X_mapped = mapping.transform(X_eval)\n", |
| 154 | + "\n", |
| 155 | + "print(f\"Input shape: {X_eval.shape} (old model space)\")\n", |
| 156 | + "print(f\"Output shape: {X_mapped.shape} (new model space)\")\n", |
| 157 | + "\n", |
| 158 | + "# How close are mapped vectors to the true new-model vectors?\n", |
| 159 | + "cosine_sim = np.sum(X_mapped * Y_eval, axis=1) # cosine since both are L2-normed\n", |
| 160 | + "print(f\"\\nCosine similarity (mapped vs true new):\")\n", |
| 161 | + "print(f\" Mean: {cosine_sim.mean():.4f}\")\n", |
| 162 | + "print(f\" Median: {np.median(cosine_sim):.4f}\")\n", |
| 163 | + "print(f\" P5: {np.percentile(cosine_sim, 5):.4f}\")" |
| 164 | + ] |
| 165 | + }, |
| 166 | + { |
| 167 | + "cell_type": "markdown", |
| 168 | + "metadata": {}, |
| 169 | + "source": [ |
| 170 | + "## 5. Run the quality gate\n", |
| 171 | + "\n", |
| 172 | + "The quality gate predicts retrieval retention from proxy metrics (cosine similarity, rank correlation) without needing a full benchmark run. It returns PASS, WARN, or FAIL." |
| 173 | + ] |
| 174 | + }, |
| 175 | + { |
| 176 | + "cell_type": "code", |
| 177 | + "execution_count": null, |
| 178 | + "metadata": {}, |
| 179 | + "outputs": [], |
| 180 | + "source": [ |
| 181 | + "gate = QualityGate()\n", |
| 182 | + "gate_report = gate.evaluate(mapping, X_eval, Y_eval)\n", |
| 183 | + "\n", |
| 184 | + "print(f\"Verdict: {gate_report.verdict.value}\")\n", |
| 185 | + "print(f\"Predicted retention: {gate_report.predicted_retention:.3f}\")\n", |
| 186 | + "print(f\"Prediction interval: {gate_report.prediction_interval}\")\n", |
| 187 | + "print(f\"Cosine mean: {gate_report.cosine_mean:.4f}\")\n", |
| 188 | + "print(f\"Top-1 retention: {gate_report.top1_retention:.4f}\")\n", |
| 189 | + "print(f\"Top-10 retention: {gate_report.top10_retention:.4f}\")\n", |
| 190 | + "print(f\"Holdout rank corr: {gate_report.holdout_rank_corr:.4f}\")\n", |
| 191 | + "print(f\"\\nRationale: {gate_report.rationale}\")" |
| 192 | + ] |
| 193 | + }, |
| 194 | + { |
| 195 | + "cell_type": "markdown", |
| 196 | + "metadata": {}, |
| 197 | + "source": [ |
| 198 | + "## 6. Save and load\n", |
| 199 | + "\n", |
| 200 | + "The mapping is persisted as a single `.isotrieve` binary file containing the weight matrices and metadata." |
| 201 | + ] |
| 202 | + }, |
| 203 | + { |
| 204 | + "cell_type": "code", |
| 205 | + "execution_count": null, |
| 206 | + "metadata": {}, |
| 207 | + "outputs": [], |
| 208 | + "source": [ |
| 209 | + "mapping.save(\"demo_mapping.isotrieve\")\n", |
| 210 | + "\n", |
| 211 | + "# Load it back\n", |
| 212 | + "loaded = RidgeMapping.load(\"demo_mapping.isotrieve\")\n", |
| 213 | + "print(f\"Loaded mapping: {loaded.d_src} -> {loaded.d_tgt}\")\n", |
| 214 | + "print(f\"Fitted: {loaded.is_fitted}\")\n", |
| 215 | + "\n", |
| 216 | + "# Verify it produces the same output\n", |
| 217 | + "X_loaded = loaded.transform(X_eval[:5])\n", |
| 218 | + "print(f\"Max diff from original: {np.max(np.abs(X_loaded - X_mapped[:5])):.2e}\")" |
| 219 | + ] |
| 220 | + }, |
| 221 | + { |
| 222 | + "cell_type": "markdown", |
| 223 | + "metadata": {}, |
| 224 | + "source": [ |
| 225 | + "## What just happened\n", |
| 226 | + "\n", |
| 227 | + "In plain English:\n", |
| 228 | + "\n", |
| 229 | + "1. You had vectors embedded with an old model (384 dimensions).\n", |
| 230 | + "2. You collected a small calibration set (~1500 texts) and embedded them with both old and new models.\n", |
| 231 | + "3. isotrieve learned a linear transformation that maps old-space vectors into new-space vectors.\n", |
| 232 | + "4. The quality gate checked that the mapping is good enough to use (PASS = safe to deploy).\n", |
| 233 | + "5. You saved the mapping to a file. From now on, any old vector can be transformed to the new space instantly — no re-embedding needed.\n", |
| 234 | + "\n", |
| 235 | + "**Key insight:** The mapping is tiny (a single matrix multiply), runs in microseconds per vector, and preserves retrieval quality. The calibration cost is O(K) embeddings instead of O(corpus_size) embeddings." |
| 236 | + ] |
| 237 | + }, |
| 238 | + { |
| 239 | + "cell_type": "markdown", |
| 240 | + "metadata": {}, |
| 241 | + "source": [ |
| 242 | + "## Try it yourself\n", |
| 243 | + "\n", |
| 244 | + "Change `LATENT` from 64 to 16 (making the two spaces more dissimilar). Does the gate verdict change? What about the cosine similarity?\n", |
| 245 | + "\n", |
| 246 | + "```python\n", |
| 247 | + "LATENT = 16 # try this\n", |
| 248 | + "```" |
| 249 | + ] |
| 250 | + } |
| 251 | + ], |
| 252 | + "metadata": { |
| 253 | + "kernelspec": { |
| 254 | + "display_name": "Python 3", |
| 255 | + "language": "python", |
| 256 | + "name": "python3" |
| 257 | + }, |
| 258 | + "language_info": { |
| 259 | + "name": "python", |
| 260 | + "version": "3.14.3" |
| 261 | + } |
| 262 | + }, |
| 263 | + "nbformat": 4, |
| 264 | + "nbformat_minor": 4 |
| 265 | +} |
0 commit comments