🤖 AI/ML

Model Monitoring

Model Monitoring

Continuous oversight of deployed model performance. Drift and anomaly detection.

📖 Detailed Explanation

Model Monitoring is the process of continuously monitoring the performance, data quality, and system health of ML models deployed in production environments. Its key goal is to detect and respond early to "model drift," the phenomenon in which a model's performance degrades over time.

Monitoring is broadly divided into three areas: 1) Data drift - detecting changes in the distribution of input data, 2) Concept drift - detecting changes in the relationship between inputs and outputs, 3) Model performance - tracking real-time metrics such as accuracy and latency. Statistical tests and thresholds suited to each area are set.

An effective monitoring system includes alerting and automated response. Drift is detected using PSI (Population Stability Index), the KS test, the chi-square test, and so on, and the team is notified when a threshold is exceeded. In severe cases, a Circuit Breaker pattern that automatically switches traffic back to the previous model is also applied.

The Ground Truth (actual label) delay problem is also important. When actual outcomes are confirmed only months later, as with loan default prediction, performance is monitored indirectly using proxy metrics or A/B tests. Recently, new challenges such as monitoring the quality of LLM responses have also emerged.

💻 Code Example

This is an example implementation of data drift detection and a monitoring dashboard:

import numpy as np
from scipy import stats
from datetime import datetime
import json

class ModelMonitor:
    def __init__(self, reference_data, model_name):
        self.reference_data = reference_data
        self.model_name = model_name
        self.alerts = []
        self.metrics_history = []

    def compute_psi(self, expected, actual, buckets=10):
        """Population Stability Index 계산"""
        breakpoints = np.percentile(expected,
                                    np.linspace(0, 100, buckets + 1))
        expected_counts = np.histogram(expected, breakpoints)[0]
        actual_counts = np.histogram(actual, breakpoints)[0]

        expected_pct = expected_counts / len(expected) + 1e-10
        actual_pct = actual_counts / len(actual) + 1e-10

        psi = np.sum((actual_pct - expected_pct) *
                     np.log(actual_pct / expected_pct))
        return psi

    def detect_drift(self, current_data, threshold_psi=0.1):
        """데이터 드리프트 감지"""
        results = {}
        for feature in self.reference_data.keys():
            ref = self.reference_data[feature]
            curr = current_data.get(feature, [])

            # PSI 계산
            psi = self.compute_psi(ref, curr)

            # KS 테스트
            ks_stat, p_value = stats.ks_2samp(ref, curr)

            drift_detected = psi > threshold_psi or p_value < 0.05

            results[feature] = {
                "psi": round(psi, 4),
                "ks_statistic": round(ks_stat, 4),
                "p_value": round(p_value, 4),
                "drift_detected": drift_detected
            }

            if drift_detected:
                self.create_alert(feature, psi, "data_drift")

        return results

    def monitor_performance(self, predictions, actuals,
                           accuracy_threshold=0.85):
        """모델 성능 모니터링"""
        accuracy = np.mean(np.array(predictions) == np.array(actuals))

        metrics = {
            "timestamp": datetime.now().isoformat(),
            "accuracy": round(accuracy, 4),
            "sample_size": len(predictions)
        }
        self.metrics_history.append(metrics)

        if accuracy < accuracy_threshold:
            self.create_alert("accuracy", accuracy, "performance_degradation")

        return metrics

    def create_alert(self, feature, value, alert_type):
        """알림 생성"""
        alert = {
            "timestamp": datetime.now().isoformat(),
            "model": self.model_name,
            "type": alert_type,
            "feature": feature,
            "value": value,
            "severity": "high" if alert_type == "performance_degradation" else "medium"
        }
        self.alerts.append(alert)
        print(f"🚨 ALERT: {alert_type} detected in {feature}: {value}")
        return alert

# 사용 예시
reference = {"age": np.random.normal(35, 10, 1000),
             "income": np.random.lognormal(10, 0.5, 1000)}

monitor = ModelMonitor(reference, "loan-approval-v2")

# 드리프트가 있는 새 데이터
current = {"age": np.random.normal(40, 12, 500),  # 분포 변화
           "income": np.random.lognormal(10, 0.5, 500)}

drift_results = monitor.detect_drift(current)
print(json.dumps(drift_results, indent=2))

📊 Performance & Cost

Monitoring Tool Monthly Cost Key features Ease of Integration
Evidently AI (OSS) Free Drift Report High (Python)
WhyLabs $500~ Automatic Drift Detection Medium
Arize AI $1,000~ LLM Support, Tracing High
AWS SageMaker Monitor Inference-Based Billing SageMaker Integration High on AWS only
Custom (Prometheus+Grafana) Infrastructure Cost Full Customization Low (Development Required)

🗣️ Say It Like This in Practice

"Data drift has been detected in the input features since last week. It looks like retraining is needed."
Used when reporting the need for a model update based on monitoring results.

"The P99 latency exceeded the SLA threshold and triggered an alert. Please check the infrastructure."
An expression used to request an immediate response when system performance degradation is detected.

"Collecting Ground Truth takes two weeks, so let's monitor with proxy metrics in the meantime."
Used when discussing a monitoring strategy in a label-delay situation.

⚠️ Common Mistakes & Cautions

1. Excessive alert settings: Setting thresholds too sensitively increases alert fatigue. Classify alerts by severity, and set only the critical ones as immediate alerts.

2. Ignoring seasonality: Natural distribution changes due to holidays, seasons, and the like can be falsely detected as drift. Update the baseline data periodically or use dynamic thresholds.

3. Exploding monitoring costs: Storing every feature and sample causes costs to surge. Establish a sampling strategy and monitor only the important features in detail.

4. No response process: Alerts without response procedures are useless. Write a runbook and define an automatic rollback policy in advance.

🔗 Related Terms

  • Data Drift: The phenomenon in which the statistical distribution of input data changes over time
  • Concept Drift: The phenomenon in which the relationship between inputs and the target changes
  • Model Registry: A repository that manages model versions and supports rollback
  • A/B Testing: An experimental methodology for comparing performance between models
  • Shadow Deployment: Runs a new model in parallel and compares performance

📚 Learn More