drift-detection
БесплатноБез исполняемых скриптовНе проверенDetecting distributional drift in production embeddings. Metrics (KL, PSI, MMD, cosine-to-centroid), alerting thresholds, query-vs-corpus divergence…
от claude-dev-suite★ 51 звезда на GitHubОб этом скилле
Embedding Drift Detection
What Drifts
| Source | Symptom | Impact |
|---|---|---|
| Query topic shift (user behavior change) | Query embedding distribution moves | Recall drops for old corpus |
| Corpus freshness (new docs indexed) | Corpus centroid shifts | Old gold set no longer representative |
| Upstream model update | Mean cosine between re-encoded docs < 0.99 | Silent index corruption |
| Tokenizer / preprocessing change | Mean token count changes | Chunks map to different embeddings |
| Language mix shift | Language-detection histogram drifts | Monolingual model hit by new languages |
Drift is not inherently bad — it is a trigger for evaluation, retraining, or re-indexing.
Reference Windows
Keep two rolling distributions:
- Reference: embeddings collected during a known-good period (e.g. last full month before deploy). Freeze this.
- Current: last 24h / 7d of production embeddings.
Compare current against reference at a fixed cadence.
PSI (Population Stability Index)
Industry-standard drift metric — cheap and interpretable.
import numpy as np
def psi(reference: np.ndarray, current: np.ndarray, bins: int = 10) -> float:
"""Compute PSI on a single scalar signal (e.g., one embedding dim or a projection)."""
eps = 1e-6
qs = np.quantile(reference, np.linspace(0, 1, bins + 1))
qs[0], qs[-1] = -np.inf, np.inf
ref_hist, _ = np.histogram(reference, bins=qs)
cur_hist, _ = np.histogram(current, bins=qs)
ref_pct = ref_hist / (ref_hist.sum() + eps) + eps
cur_pct = cur_hist / (cur_hist.sum() + eps) + eps
return float(np.sum((cur_pct - ref_pct) * np.log(cur_pct / ref_pct)))
# Thresholds (conventional):
# PSI < 0.1 -> stable
# 0.1 - 0.25 -> moderate drift, investigate
# > 0.25 -> significant drift, act
def embedding_psi(ref: np.ndarray, cur: np.ndarray) -> float:
"""Average PSI across dims — crude but robust."""
dims = ref.shape[1]
return float(np.mean([psi(ref[:, d], cur[:, d]) for d in range(dims)]))
Don't run PSI on raw 1536-dim vectors in alerting — it's noisy. Project to 8-16 dims via PCA fit on the reference set, then compute PSI on each projection.
KL Divergence via Binning
from scipy.stats import entropy
def kl_div(reference: np.ndarray, current: np.ndarray, bins: int = 20) -> float:
qs = np.quantile(reference, np.linspace(0, 1, bins + 1))
qs[0], qs[-1] = -np.inf, np.inf
p, _ = np.histogram(reference, bins=qs, density=True)
q, _ = np.histogram(current, bins=qs, density=True)
return float(entropy(p + 1e-9, q + 1e-9))
Maximum Mean Discrepancy (MMD)
Kernel-based two-sample test; detects multivariate drift without binning.
import torch
def mmd_rbf(X: torch.Tensor, Y: torch.Tensor, sigma: float = 1.0) -> float:
XX = torch.cdist(X, X).pow(2)
YY = torch.cdist(Y, Y).pow(2)
XY = torch.cdist(X, Y).pow(2)
k_xx = torch.exp(-XX / (2 * sigma ** 2)).mean()
k_yy = torch.exp(-YY / (2 * sigma ** 2)).mean()
k_xy = torch.exp(-XY / (2 * sigma ** 2)).mean()
return float(k_xx + k_yy - 2 * k_xy)
# Use on a random sample of 1-5k reference vs current embeddings; anything
# above permutation-test p=0.01 threshold is significant.
Cosine-to-Centroid Drift (Cheapest Signal)
def centroid_drift(ref: np.ndarray, cur: np.ndarray) -> float:
ref_c = ref.mean(0); ref_c /= np.linalg.norm(ref_c)
cur_c = cur.mean(0); cur_c /= np.linalg.norm(cur_c)
return float(1 - np.dot(ref_c, cur_c))
# Works well for fast dashboards; misses shape changes with stable mean.
Query vs Corpus Gap
def query_corpus_gap(query_embs: np.ndarray, corpus_embs: np.ndarray, k: int = 10):
"""Average cosine of nearest corpus neighbor per query."""
q = query_embs / np.linalg.norm(query_embs, axis=1, keepdims=True)
c = corpus_embs / np.linalg.norm(corpus_embs, axis=1, keepdims=True)
sims = q @ c.T
top = np.partition(sims, -k, axis=1)[:, -k:]
return float(top.mean())
# Track this daily — a falling value indicates queries are drifting away from corpus.
Streaming Drift with River / scikit-multiflow
from river.drift import ADWIN
detector = ADWIN(delta=0.002)
warned = []
for i, vec in enumerate(production_embeddings_stream):
proj = float(pca.transform(vec.reshape(1, -1))[0, 0]) # 1st principal component
detector.update(proj)
if detector.drift_detected:
warned.append(i)
print(f"drift at index {i}")
Alert Thresholds
| Metric | Warn | Alert |
|---|---|---|
| PSI (projected) | 0.10 | 0.25 |
| KL (binned, per projection) | 0.10 | 0.25 |
| MMD permutation p-value | 0.05 | 0.01 |
| Centroid cosine gap | 0.02 | 0.05 |
| Query-corpus top-k cosine drop | 2% relative | 5% relative |
Calibrate on historical data before paging on-call.
Root-Cause Playbook
When drift fires, check in order:
- Deployment diff — did embedding model, tokenizer, or preprocessing change?
Установить drift-detection в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
ReadGrepGlobWriteEditFAQ
Что делает скилл drift-detection?
Detecting distributional drift in production embeddings. Metrics (KL, PSI, MMD, cosine-to-centroid), alerting thresholds, query-vs-corpus divergence, root-cause analysis, and embedding observability tooling (Arize, Fiddler). USE WHEN: user mentions "embedding drift", "distribution shift", "PSI", "KL divergence", "MMD", "embedding monitoring", "embedding observability", "model staleness", "production embedding quality" DO NOT USE FOR: evaluation of answer quality - use `rag-evaluation`; retraining embeddings - use `embedding-fine-tuning`; general model drift on tabular features - use an ML monitoring skill
Как установить скилл drift-detection?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл drift-detection запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic