File size: 8,956 Bytes
c3efd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
"""Anomaly detection for training monitoring."""
import numpy as np
from typing import List, Dict, Optional, Callable
from collections import deque
import logging

logger = logging.getLogger(__name__)


class AnomalyDetector:
    """
    Detects anomalies during training.
    
    Monitors for reward collapse, gradient explosion, and other issues.
    """
    
    def __init__(
        self,
        window_size: int = 10,
        alert_callback: Optional[Callable] = None
    ):
        """
        Initialize anomaly detector.
        
        Args:
            window_size: Size of sliding window for detection
            alert_callback: Optional callback function for alerts
        """
        self.window_size = window_size
        self.alert_callback = alert_callback or self._default_alert
        
        # Sliding windows for metrics
        self.reward_window = deque(maxlen=window_size)
        self.loss_window = deque(maxlen=window_size)
        self.gradient_window = deque(maxlen=window_size)
        
        # Alert history
        self.alerts = []
        
        logger.info(f"AnomalyDetector initialized: window_size={window_size}")
    
    def _default_alert(self, alert_type: str, message: str, severity: str) -> None:
        """
        Default alert handler.
        
        Args:
            alert_type: Type of alert
            message: Alert message
            severity: Severity level
        """
        log_func = {
            'critical': logger.critical,
            'warning': logger.warning,
            'info': logger.info
        }.get(severity, logger.warning)
        
        log_func(f"[{alert_type}] {message}")
    
    def update(
        self,
        reward: Optional[float] = None,
        loss: Optional[float] = None,
        gradient_norm: Optional[float] = None
    ) -> List[Dict[str, str]]:
        """
        Update detector with new metrics and check for anomalies.
        
        Args:
            reward: Current reward value
            loss: Current loss value
            gradient_norm: Current gradient norm
        
        Returns:
            List of detected anomalies
        """
        anomalies = []
        
        # Update windows
        if reward is not None:
            self.reward_window.append(reward)
        if loss is not None:
            self.loss_window.append(loss)
        if gradient_norm is not None:
            self.gradient_window.append(gradient_norm)
        
        # Check for anomalies
        if len(self.reward_window) >= self.window_size:
            reward_anomaly = self.detect_reward_collapse()
            if reward_anomaly:
                anomalies.append(reward_anomaly)
        
        if len(self.gradient_window) >= 3:  # Need fewer samples for gradient check
            gradient_anomaly = self.detect_gradient_explosion()
            if gradient_anomaly:
                anomalies.append(gradient_anomaly)
        
        if len(self.loss_window) >= self.window_size:
            loss_anomaly = self.detect_loss_divergence()
            if loss_anomaly:
                anomalies.append(loss_anomaly)
        
        # Store and alert
        for anomaly in anomalies:
            self.alerts.append(anomaly)
            self.alert_callback(
                anomaly['type'],
                anomaly['message'],
                anomaly['severity']
            )
        
        return anomalies
    
    def detect_reward_collapse(self) -> Optional[Dict[str, str]]:
        """
        Detect reward collapse (rewards stop changing).
        
        Returns:
            Anomaly dictionary if detected, None otherwise
        """
        if len(self.reward_window) < self.window_size:
            return None
        
        rewards = list(self.reward_window)
        
        # Check if variance is very low
        variance = np.var(rewards)
        if variance < 1e-6:
            return {
                'type': 'reward_collapse',
                'message': f'Reward collapse detected: variance={variance:.2e}',
                'severity': 'critical',
                'details': {
                    'variance': variance,
                    'mean_reward': np.mean(rewards)
                }
            }
        
        # Check if rewards are consistently decreasing
        if len(rewards) >= 5:
            recent_trend = np.polyfit(range(len(rewards)), rewards, 1)[0]
            if recent_trend < -0.01:  # Significant negative trend
                return {
                    'type': 'reward_decline',
                    'message': f'Reward declining: trend={recent_trend:.4f}',
                    'severity': 'warning',
                    'details': {
                        'trend': recent_trend,
                        'mean_reward': np.mean(rewards)
                    }
                }
        
        return None
    
    def detect_gradient_explosion(self) -> Optional[Dict[str, str]]:
        """
        Detect gradient explosion (very large gradients).
        
        Returns:
            Anomaly dictionary if detected, None otherwise
        """
        if len(self.gradient_window) < 3:
            return None
        
        gradients = list(self.gradient_window)
        latest_gradient = gradients[-1]
        
        # Check for very large gradient
        if latest_gradient > 100.0:
            return {
                'type': 'gradient_explosion',
                'message': f'Gradient explosion detected: norm={latest_gradient:.2f}',
                'severity': 'critical',
                'details': {
                    'gradient_norm': latest_gradient,
                    'mean_gradient': np.mean(gradients)
                }
            }
        
        # Check for rapidly increasing gradients
        if len(gradients) >= 3:
            gradient_growth = gradients[-1] / (gradients[-3] + 1e-8)
            if gradient_growth > 10.0:
                return {
                    'type': 'gradient_growth',
                    'message': f'Rapid gradient growth: {gradient_growth:.2f}x',
                    'severity': 'warning',
                    'details': {
                        'growth_factor': gradient_growth,
                        'current_gradient': latest_gradient
                    }
                }
        
        return None
    
    def detect_loss_divergence(self) -> Optional[Dict[str, str]]:
        """
        Detect loss divergence (loss increasing or becoming NaN/Inf).
        
        Returns:
            Anomaly dictionary if detected, None otherwise
        """
        if len(self.loss_window) < self.window_size:
            return None
        
        losses = list(self.loss_window)
        latest_loss = losses[-1]
        
        # Check for NaN or Inf
        if np.isnan(latest_loss) or np.isinf(latest_loss):
            return {
                'type': 'loss_invalid',
                'message': f'Invalid loss detected: {latest_loss}',
                'severity': 'critical',
                'details': {
                    'loss_value': str(latest_loss)
                }
            }
        
        # Check for consistently increasing loss
        if len(losses) >= 5:
            loss_trend = np.polyfit(range(len(losses)), losses, 1)[0]
            if loss_trend > 0.1:  # Significant positive trend
                return {
                    'type': 'loss_divergence',
                    'message': f'Loss diverging: trend={loss_trend:.4f}',
                    'severity': 'warning',
                    'details': {
                        'trend': loss_trend,
                        'current_loss': latest_loss,
                        'mean_loss': np.mean(losses)
                    }
                }
        
        return None
    
    def get_alerts(self) -> List[Dict[str, str]]:
        """
        Get all alerts.
        
        Returns:
            List of alert dictionaries
        """
        return self.alerts
    
    def get_recent_alerts(self, n: int = 10) -> List[Dict[str, str]]:
        """
        Get most recent alerts.
        
        Args:
            n: Number of recent alerts to return
        
        Returns:
            List of recent alert dictionaries
        """
        return self.alerts[-n:]
    
    def clear_alerts(self) -> None:
        """Clear all alerts."""
        self.alerts.clear()
        logger.info("Alerts cleared")
    
    def get_summary(self) -> Dict[str, any]:
        """
        Get summary of detected anomalies.
        
        Returns:
            Summary dictionary
        """
        alert_types = {}
        for alert in self.alerts:
            alert_type = alert['type']
            alert_types[alert_type] = alert_types.get(alert_type, 0) + 1
        
        return {
            'total_alerts': len(self.alerts),
            'alert_types': alert_types,
            'recent_alerts': self.get_recent_alerts(5)
        }