Post-Market Monitoring
Post-Market Monitoring
The activity of continuously monitoring the performance and safety of an AI system after its release. An obligation for high-risk AI.
Post-Market Monitoring
The activity of continuously monitoring the performance and safety of an AI system after its release. An obligation for high-risk AI.
Post-Market Monitoring (PMM) is the activity of continuously monitoring the performance, safety, and regulatory compliance status of an AI system after it has been placed on the market. Article 72 of the EU AI Act makes it mandatory for providers of high-risk AI to establish a post-market monitoring system.
The core purpose of PMM is to detect problems that arise after deployment at an early stage. It monitors the difference between the data distribution at training time and at operation time (Data Drift), model performance degradation (Model Degradation), the emergence of unexpected bias, cases of misuse, and the like. When a serious risk is discovered, it must be reported to the authorities immediately.
Article 72 of the EU AI Act requires the active and systematic collection, analysis, and recording of relevant data for PMM systems throughout the entire operational lifecycle. Providers must take corrective action when necessary and report serious incidents to the Market Surveillance Authority.
Technically, PMM is implemented through real-time inference logging, performance metric dashboards, drift detection alerts, user feedback collection systems, and the like. It must be integrated into the MLOps pipeline so that automated monitoring and alerting take place.
# 사후 시장 모니터링 시스템 구현 예제
from dataclasses import dataclass
from datetime import datetime
from typing import Dict, List, Optional
from enum import Enum
import numpy as np
class AlertSeverity(Enum):
INFO = "info"
WARNING = "warning"
CRITICAL = "critical"
@dataclass
class MonitoringAlert:
"""모니터링 알림"""
alert_id: str
severity: AlertSeverity
metric_name: str
current_value: float
threshold: float
message: str
timestamp: datetime
requires_authority_report: bool = False
class PostMarketMonitor:
"""EU AI Act 제72조 준수 사후 시장 모니터링 시스템"""
def __init__(self, model_id: str, baseline_metrics: Dict):
self.model_id = model_id
self.baseline_metrics = baseline_metrics
self.alerts: List[MonitoringAlert] = []
self.inference_logs: List[Dict] = []
def log_inference(self, input_data: Dict, output: Dict,
latency_ms: float, user_feedback: Optional[str] = None):
"""추론 로깅 (제72조: 관련 데이터의 능동적 수집)"""
log_entry = {
"timestamp": datetime.now().isoformat(),
"model_id": self.model_id,
"input_hash": hash(str(input_data)), # 개인정보 보호
"output": output,
"latency_ms": latency_ms,
"user_feedback": user_feedback
}
self.inference_logs.append(log_entry)
def detect_data_drift(self, recent_inputs: np.ndarray,
baseline_inputs: np.ndarray,
drift_threshold: float = 0.1) -> Optional[MonitoringAlert]:
"""데이터 드리프트 탐지"""
# 간단한 통계적 드리프트 측정 (실제로는 KS test 등 사용)
recent_mean = np.mean(recent_inputs, axis=0)
baseline_mean = np.mean(baseline_inputs, axis=0)
drift_score = np.mean(np.abs(recent_mean - baseline_mean))
if drift_score > drift_threshold:
alert = MonitoringAlert(
alert_id=f"DRIFT-{datetime.now().strftime('%Y%m%d%H%M%S')}",
severity=AlertSeverity.WARNING,
metric_name="data_drift",
current_value=drift_score,
threshold=drift_threshold,
message=f"입력 데이터 분포 변화 감지: {drift_score:.4f}",
timestamp=datetime.now()
)
self.alerts.append(alert)
return alert
return None
def monitor_performance(self, recent_accuracy: float,
degradation_threshold: float = 0.1) -> Optional[MonitoringAlert]:
"""성능 저하 모니터링"""
baseline_accuracy = self.baseline_metrics.get("accuracy", 0.9)
degradation = baseline_accuracy - recent_accuracy
if degradation > degradation_threshold:
severity = AlertSeverity.CRITICAL if degradation > 0.2 else AlertSeverity.WARNING
alert = MonitoringAlert(
alert_id=f"PERF-{datetime.now().strftime('%Y%m%d%H%M%S')}",
severity=severity,
metric_name="accuracy_degradation",
current_value=recent_accuracy,
threshold=baseline_accuracy - degradation_threshold,
message=f"모델 성능 저하: {baseline_accuracy:.2%} -> {recent_accuracy:.2%}",
timestamp=datetime.now(),
requires_authority_report=severity == AlertSeverity.CRITICAL
)
self.alerts.append(alert)
return alert
return None
def monitor_fairness(self, group_metrics: Dict[str, float],
disparity_threshold: float = 0.15) -> Optional[MonitoringAlert]:
"""공정성 모니터링 (그룹 간 성능 격차)"""
if len(group_metrics) < 2:
return None
max_disparity = max(group_metrics.values()) - min(group_metrics.values())
if max_disparity > disparity_threshold:
alert = MonitoringAlert(
alert_id=f"FAIR-{datetime.now().strftime('%Y%m%d%H%M%S')}",
severity=AlertSeverity.WARNING,
metric_name="fairness_disparity",
current_value=max_disparity,
threshold=disparity_threshold,
message=f"그룹 간 성능 격차 증가: {max_disparity:.2%}",
timestamp=datetime.now()
)
self.alerts.append(alert)
return alert
return None
def report_serious_incident(self, incident_description: str) -> Dict:
"""심각한 사고 보고서 생성 (제72조: 당국 보고 의무)"""
report = {
"report_type": "EU_AI_Act_Article_72_Serious_Incident",
"model_id": self.model_id,
"incident_timestamp": datetime.now().isoformat(),
"description": incident_description,
"related_alerts": [
{
"alert_id": a.alert_id,
"severity": a.severity.value,
"metric": a.metric_name,
"value": a.current_value
} for a in self.alerts if a.requires_authority_report
],
"corrective_actions_planned": [],
"status": "pending_authority_notification"
}
return report
def generate_periodic_report(self, period_days: int = 30) -> Dict:
"""정기 모니터링 보고서"""
return {
"report_period": f"Last {period_days} days",
"model_id": self.model_id,
"generated_at": datetime.now().isoformat(),
"total_inferences": len(self.inference_logs),
"alerts_summary": {
"total": len(self.alerts),
"critical": sum(1 for a in self.alerts if a.severity == AlertSeverity.CRITICAL),
"warning": sum(1 for a in self.alerts if a.severity == AlertSeverity.WARNING)
},
"compliance_status": "compliant" if not any(
a.severity == AlertSeverity.CRITICAL for a in self.alerts
) else "requires_attention"
}
# 사용 예시
monitor = PostMarketMonitor(
model_id="CREDIT-MODEL-v2",
baseline_metrics={"accuracy": 0.92, "f1": 0.89}
)
# 일별 모니터링
monitor.monitor_performance(recent_accuracy=0.88)
monitor.monitor_fairness({"male": 0.90, "female": 0.85})
# 정기 보고서 생성
report = monitor.generate_periodic_report()
print(f"준수 상태: {report['compliance_status']}")
PM: How are you monitoring models after deployment?
ML Engineer: We only look at basic latency and error rate.
Senior: Article 72 of the EU AI Act makes post-market monitoring mandatory. You need to monitor performance metrics, data drift, and even fairness metrics. There is also an obligation to report serious issues to the authorities when they are discovered.
Interviewer: How do you detect performance degradation of an AI model in operation?
Candidate: I monitor along three axes. First, I detect changes in the input distribution through data drift detection. Second, once Ground Truth is available, I measure actual performance, and third, I analyze user feedback and complaints. All metrics can be checked in real time on a Grafana dashboard, and a Slack alert is sent when a threshold is exceeded.
Senior: There's no inference logging. It's essential for PMM.
Junior: Are there no personal data issues?
Senior: Good question. Store only hashes of the input data, and keep only the aggregated information needed for statistical analysis. Also specify the retention period.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free