Monitoring Embedding Drift in Production Scikit-LLM Pipelines A tutorial published on embedding drift detection outlines three techniques for monitoring production large language model pipelines: model-based detection via a binary domain classifier, centroid distance using cosine similarity, and dimensionality reduction with UMAP or PCA combined with Kolmogorov-Smirnov statistical tests. The implementation demonstrates the domain classifier and centroid distance methods on simulated 384-dimensional embeddings generated with scikit-learn, using 500 samples with the production set's mean shifted from 0.0 to 0.3, then applies the same techniques to real text embeddings from a SentenceTransformer model via the Scikit-LLM library. In this article, you will learn what embedding drift is, why it matters for production large language models, and how to implement two practical techniques to detect it. Topics we will cover include: - The key approaches for detecting embedding drift in production machine learning systems, including model-based detection, centroid distance, and dimensionality reduction combined with statistical tests. - How to implement a domain classifier and a centroid distance method using scikit-learn on simulated 384-dimensional embeddings. - How to apply these same drift detection techniques to real text embeddings generated with a SentenceTransformer model via Scikit-LLM. Introduction When a large language model LLM hits production, the story is far from over. User behavior inevitably evolves in the real world, and so does the data consumed by the model, typically encoded into numerical text representations called embeddings for its internal processing. Therefore, it is crucial to track so-called embedding drifts to ascertain when a deployed model needs an update. However, traditional drift detection metrics designed for tabular data often fail when applied to high-dimensional embeddings. This article starts by providing a brief outline of top techniques for detecting embedding drift, followed by an illustrative implementation of two of them, both simulation-based and in conjunction with the Scikit-LLM library for embedding generation. Techniques for Effective Embedding Drift Detection Below we list three key approaches for accurately identifying embedding drift that have been remarkably put into practice in production LLMs: - Model-based detection: This consists of training a domain-specific classifier, usually a binary classifier that has learned to distinguish between baseline data and new drifted production data. A model capable of easily telling them apart will be able to signal drifts when they occur. - Centroid distance : Following classical anomaly detection algorithms, this strategy boils down to calculating the distance often cosine for embedding data between the center of mass of your baseline embedding vectors and that of new, incoming embedding vectors. - Combining dimensionality reduction and statistical tests: This method entails compressing the embeddings to a lower dimension using UMAP or PCA, after which we apply standard drift tests such as Kolmogorov-Smirnov. Interested in exploring further how they work? Let’s examine how to implement the core logic behind two of these techniques based on an open-source stack. Illustrating Drift Detection on Simulated Embeddings Let’s build a mathematical foundation for two of the listed techniques using standard scikit-learn and simulated embeddings first. We generate an initial, random set of embeddings, after which we create another synthetic set — this time containing “production embeddings” that shift from the original embeddings’ mean to simulate the existence of data drift. python import numpy as np Simulating 384-dimensional embeddings e.g. standard sentence-transformers output n samples = 500 n features = 384 1. Referencing Embeddings Baseline / Training Data Imagine this is the data your LLM/Vector DB was originally populated with np.random.seed 42 X reference = np.random.normal loc=0.0, scale=1.0, size= n samples, n features 2. Production Embeddings New Data The original mean is shifted to loc=0.3 to simulate data drift e.g. new topic emerging X production = np.random.normal loc=0.3, scale=1.0, size= n samples, n features 1234567891011121314 import numpy as np Simulating 384-dimensional embeddings e.g. standard sentence-transformers output n samples = 500n features = 384 1. Referencing Embeddings Baseline / Training Data Imagine this is the data your LLM/Vector DB was originally populated withnp.random.seed 42 X reference = np.random.normal loc=0.0, scale=1.0, size= n samples, n features 2. Production Embeddings New Data The original mean is shifted to loc=0.3 to simulate data drift e.g. new topic emerging X production = np.random.normal loc=0.3, scale=1.0, size= n samples, n features Next, we train a domain classifier based on random forests to separate baseline data labeled 0 from new, production data labeled 1 . If the accuracy metric — for instance, ROC-AUC — signals a high value, e.g. above 0.65, the classifier will trigger a drift alert. python from sklearn.ensemble import RandomForestClassifier from sklearn.model selection import train test split from sklearn.metrics import roc auc score 1. Assigning labels: 0 for reference, baseline embeddings; 1 for production embeddings y reference = np.zeros n samples y production = np.ones n samples 2. Combining into a single dataset X combined = np.vstack X reference, X production y combined = np.hstack y reference, y production 3. Randomly splitting into train and test sets for the drift detector X train, X test, y train, y test = train test split X combined, y combined, test size=0.3, random state=42 4. Training a lightweight Random Forest classifier drift classifier = RandomForestClassifier n estimators=50, max depth=5, random state=42 drift classifier.fit X train, y train 5. Evaluating the classifier using ROC-AUC y pred proba = drift classifier.predict proba X test :, 1 roc auc = roc auc score y test, y pred proba print f"Domain Classifier ROC-AUC Score: {roc auc:.3f}" 6. Alerting Logic If the metric score is around 0.5 it means the model can't tell the datasets apart no drift detected . Meanwhile, a score closer to 1.0 means they are easily distinguishable high drift . if roc auc 0.65: print "ALERT: Significant embedding drift detected Trigger retraining/review pipeline." else: print "System stable: Distributions are sufficiently similar." 12345678910111213141516171819202122232425262728293031323334 from sklearn.ensemble import RandomForestClassifierfrom sklearn.model selection import train test splitfrom sklearn.metrics import roc auc score 1. Assigning labels: 0 for reference, baseline embeddings; 1 for production embeddingsy reference = np.zeros n samples y production = np.ones n samples 2. Combining into a single datasetX combined = np.vstack X reference, X production y combined = np.hstack y reference, y production 3. Randomly splitting into train and test sets for the drift detectorX train, X test, y train, y test = train test split X combined, y combined, test size=0.3, random state=42 4. Training a lightweight Random Forest classifierdrift classifier = RandomForestClassifier n estimators=50, max depth=5, random state=42 drift classifier.fit X train, y train 5. Evaluating the classifier using ROC-AUCy pred proba = drift classifier.predict proba X test :, 1 roc auc = roc auc score y test, y pred proba print f"Domain Classifier ROC-AUC Score: {roc auc:.3f}" 6. Alerting Logic If the metric score is around 0.5 it means the model can't tell the datasets apart no drift detected . Meanwhile, a score closer to 1.0 means they are easily distinguishable high drift .if roc auc 0.65: print "ALERT: Significant embedding drift detected Trigger retraining/review pipeline." else: print "System stable: Distributions are sufficiently similar." Output: Domain Classifier ROC-AUC Score: 0.970 ALERT: Significant embedding drift detected Trigger retraining/review pipeline. 12 Domain Classifier ROC-AUC Score: 0.970ALERT: Significant embedding drift detected Trigger retraining/review pipeline. Alternatively, we can resort to the centroid calculation technique, also known as the “center of mass” method, measuring the distance between two centroids: one stemming from the baseline embeddings and one associated with the new, production embeddings. This method is computationally cheaper than the classifier method, but it incurs a loss of nuance valuable information : after all, aggregating high-dimensional vectors into a single central point throws away complex distribution shapes, masking important patterns like multi-modal shifts or structural changes in the data. python from sklearn.metrics.pairwise import cosine distances 1. Calculating the centroid mean vector for both batches axis=0 calculates the mean across all samples, resulting in a single 384-d vector centroid ref = np.mean X reference, axis=0 .reshape 1, -1 centroid prod = np.mean X production, axis=0 .reshape 1, -1 2. Calculating the distance 1 - Cosine Similarity between the two centroids A distance of 0 means identical direction; higher means they are drifting apart distance = cosine distances centroid ref, centroid prod 0 0 print f"Centroid Cosine Distance: {distance:.4f}" 3. Alerting Logic Determining the exact threshold requires tuning in accordance with your specific model and baseline variance threshold = 0.05 if distance threshold: print "ALERT: Centroid distance exceeded threshold System drifting." else: print "System stable: Centroids are aligned." 1234567891011121314151617181920 from sklearn.metrics.pairwise import cosine distances 1. Calculating the centroid mean vector for both batches axis=0 calculates the mean across all samples, resulting in a single 384-d vectorcentroid ref = np.mean X reference, axis=0 .reshape 1, -1 centroid prod = np.mean X production, axis=0 .reshape 1, -1 2. Calculating the distance 1 - Cosine Similarity between the two centroids A distance of 0 means identical direction; higher means they are drifting apartdistance = cosine distances centroid ref, centroid prod 0 0 print f"Centroid Cosine Distance: {distance:.4f}" 3. Alerting Logic Determining the exact threshold requires tuning in accordance with your specific model and baseline variancethreshold = 0.05 if distance threshold: print "ALERT: Centroid distance exceeded threshold System drifting." else: print "System stable: Centroids are aligned." Output: Centroid Cosine Distance: 0.9811 ALERT: Centroid distance exceeded threshold System drifting. 12 Centroid Cosine Distance: 0.9811ALERT: Centroid distance exceeded threshold System drifting. No doubt the cosine distance value looks a bit exaggerated, due to a combination of the orthogonal nature of the distance metric used and the fact that the baseline data were generated randomly. A more realistic dataset would normally yield high distances in the presence of topic-driven data drifts, but not so extreme in the majority of cases. Let’s find out with a final example that uses Scikit-LLM to generate embeddings from real text. Drift Detection on Generated Embeddings with Scikit-LLM The last code example uses Scikit-LLM as a wrapper for a Groq LLM specialized in embedding generation. It has been run on Google Colab, with an API key obtained from Groq a free LLM repository and stored in the “My Secrets” section of the left-hand side menu. python from sentence transformers import SentenceTransformer from google.colab import userdata from skllm.config import SKLLMConfig Securely extract the Groq API Key you may have previously stored in Colab secrets groq api key = userdata.get 'GROQ API KEY' Redirecting scikit-LLM to Groq using API compatibility: SKLLMConfig.set openai key groq api key SKLLMConfig.set gpt url "https://api.groq.com/openai/v1/" Since Groq does not have an embeddings API, we can use a free and very lightweight local model vectorizer = SentenceTransformer 'all-MiniLM-L6-v2' Baseline raw texts and production texts, clearly with a drastic topic shift texts reference = "How do I reset my password?", "Where is the billing menu?" 100 We multiply to simulate a larger dataset texts production = "The new cryptocurrency system is failing", "How to mint an NFT on the platform?" 100 Converting text to embeddings X reference = vectorizer.encode texts reference X production = vectorizer.encode texts production Implementing Embedding Drift Detection Logic Assign labels: 0 for reference, 1 for production y reference = np.zeros len X reference y production = np.ones len X production Combining datasets X combined = np.vstack X reference, X production y combined = np.hstack y reference, y production Training the domain classifier X train, X test, y train, y test = train test split X combined, y combined, test size=0.3, random state=42 clf = RandomForestClassifier n estimators=50, max depth=5 .fit X train, y train Calculating drift using ROC-AUC roc auc = roc auc score y test, clf.predict proba X test :, 1 print f"ROC-AUC Score: {roc auc:.3f}" if roc auc 0.65: print "DRIFT DETECTED User queries have changed topic." else: print "System stable: Embeddings are consistent." 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 from sentence transformers import SentenceTransformerfrom google.colab import userdatafrom skllm.config import SKLLMConfig Securely extract the Groq API Key you may have previously stored in Colab secretsgroq api key = userdata.get 'GROQ API KEY' Redirecting scikit-LLM to Groq using API compatibility:SKLLMConfig.set openai key groq api key SKLLMConfig.set gpt url "https://api.groq.com/openai/v1/" Since Groq does not have an embeddings API, we can use a free and very lightweight local modelvectorizer = SentenceTransformer 'all-MiniLM-L6-v2' Baseline raw texts and production texts, clearly with a drastic topic shifttexts reference = "How do I reset my password?", "Where is the billing menu?" 100 We multiply to simulate a larger dataset texts production = "The new cryptocurrency system is failing", "How to mint an NFT on the platform?" 100 Converting text to embeddingsX reference = vectorizer.encode texts reference X production = vectorizer.encode texts production Implementing Embedding Drift Detection Logic Assign labels: 0 for reference, 1 for productiony reference = np.zeros len X reference y production = np.ones len X production Combining datasetsX combined = np.vstack X reference, X production y combined = np.hstack y reference, y production Training the domain classifierX train, X test, y train, y test = train test split X combined, y combined, test size=0.3, random state=42 clf = RandomForestClassifier n estimators=50, max depth=5 .fit X train, y train Calculating drift using ROC-AUCroc auc = roc auc score y test, clf.predict proba X test :, 1 print f"ROC-AUC Score: {roc auc:.3f}" if roc auc 0.65: print "DRIFT DETECTED User queries have changed topic." else: print "System stable: Embeddings are consistent." The process is similar to what we saw earlier. The main difference lies in the data used, which are now embeddings generated from real text examples. Due to the intentionally drastic topic difference between the two datasets, the classifier can perfectly distinguish between baseline and production embeddings: ROC-AUC Score: 1.000 DRIFT DETECTED User queries have changed topic. 12 ROC-AUC Score: 1.000DRIFT DETECTED User queries have changed topic. Let’s also try the centroid method one more time: python from sklearn.metrics.pairwise import cosine distances import numpy as np Centroid Distance for SentenceTransformer embeddings Calculate centroids centroid ref st = np.mean X reference, axis=0 .reshape 1, -1 centroid prod st = np.mean X production, axis=0 .reshape 1, -1 Calculate cosine distance distance st = cosine distances centroid ref st, centroid prod st 0 0 print f"Centroid Cosine Distance SentenceTransformer Embeddings : {distance st:.4f}" Alerting Logic threshold st = 0.05 Adjust threshold as needed if distance st threshold st: print "ALERT: Centroid distance exceeded threshold System drifting SentenceTransformer Embeddings ." else: print "System stable: Centroids are aligned SentenceTransformer Embeddings ." 1234567891011121314151617181920 from sklearn.metrics.pairwise import cosine distancesimport numpy as np Centroid Distance for SentenceTransformer embeddings Calculate centroidscentroid ref st = np.mean X reference, axis=0 .reshape 1, -1 centroid prod st = np.mean X production, axis=0 .reshape 1, -1 Calculate cosine distancedistance st = cosine distances centroid ref st, centroid prod st 0 0 print f"Centroid Cosine Distance SentenceTransformer Embeddings : {distance st:.4f}" Alerting Logicthreshold st = 0.05 Adjust threshold as neededif distance st threshold st: print "ALERT: Centroid distance exceeded threshold System drifting SentenceTransformer Embeddings ." else: print "System stable: Centroids are aligned SentenceTransformer Embeddings ." Output: Centroid Cosine Distance SentenceTransformer Embeddings : 0.8719 ALERT: Centroid distance exceeded threshold System drifting SentenceTransformer Embeddings . 12 Centroid Cosine Distance SentenceTransformer Embeddings : 0.8719ALERT: Centroid distance exceeded threshold System drifting SentenceTransformer Embeddings . As we can see, financial/crypto topics and basic IT support can be far apart in the embedding space managed by our chosen model, all-MiniLM-L6-v2 , which still yields a high cosine distance — although not nearly as high as in the purely random data scenario. Wrapping Up This article introduced some common techniques used in production machine learning systems to monitor and detect drifts in data represented as vector embeddings. Two of these techniques, namely model-based detection and the centroid distance method, have been illustrated through code examples, aided by Scikit-LLM for embedding generation.