Skip to main content

trustformers_mobile/
model_debugger.rs

1//! Mobile model debugging and analysis for TrustformeRS
2//!
3//! This module provides comprehensive model debugging capabilities specifically designed for mobile
4//! environments, including inference debugging, model validation, and performance analysis.
5
6use serde::{Deserialize, Serialize};
7use std::collections::{HashMap, VecDeque};
8use std::sync::{Arc, Mutex};
9use std::time::{Duration, SystemTime, UNIX_EPOCH};
10use trustformers_core::error::{CoreError, Result};
11use trustformers_core::Tensor;
12use trustformers_core::TrustformersError;
13
14/// Model debugging configuration
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct ModelDebuggerConfig {
17    /// Enable model debugging
18    pub enabled: bool,
19    /// Maximum number of inference traces to keep
20    pub max_inference_traces: usize,
21    /// Enable detailed tensor analysis
22    pub enable_tensor_analysis: bool,
23    /// Enable gradient analysis (for training models)
24    pub enable_gradient_analysis: bool,
25    /// Enable model structure validation
26    pub enable_structure_validation: bool,
27    /// Enable performance profiling
28    pub enable_performance_profiling: bool,
29    /// Maximum execution time before flagging as slow
30    pub slow_inference_threshold: Duration,
31    /// Enable automatic anomaly detection
32    pub enable_anomaly_detection: bool,
33    /// Tensor value ranges for anomaly detection
34    pub normal_value_range: (f32, f32),
35    /// Enable debugging output generation
36    pub enable_debug_output: bool,
37}
38
39/// Model debugging information
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct ModelDebugInfo {
42    pub model_id: String,
43    pub model_type: String,
44    pub input_shapes: Vec<Vec<usize>>,
45    pub output_shapes: Vec<Vec<usize>>,
46    pub parameter_count: usize,
47    pub memory_usage: usize,
48    pub inference_count: usize,
49    pub average_inference_time: Duration,
50    pub last_inference_time: Duration,
51    pub validation_status: ValidationStatus,
52    pub anomalies_detected: Vec<ModelAnomaly>,
53    pub performance_profile: PerformanceProfile,
54}
55
56/// Model validation status
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub enum ValidationStatus {
59    Valid,
60    Warning(Vec<String>),
61    Error(Vec<String>),
62    NotValidated,
63}
64
65/// Detected model anomaly
66#[derive(Debug, Clone, Serialize, Deserialize)]
67pub struct ModelAnomaly {
68    pub anomaly_type: AnomalyType,
69    pub severity: AnomalySeverity,
70    pub description: String,
71    pub location: String,
72    pub timestamp: u64,
73    pub suggested_action: String,
74    pub tensor_info: Option<TensorDebugInfo>,
75}
76
77/// Types of model anomalies
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79pub enum AnomalyType {
80    NaNValues,
81    InfiniteValues,
82    ExtremeValues,
83    UnexpectedShapes,
84    PerformanceDegradation,
85    MemorySpike,
86    GradientExplosion,
87    GradientVanishing,
88    ModelDivergence,
89    InvalidOperation,
90}
91
92/// Severity levels for anomalies
93#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
94pub enum AnomalySeverity {
95    Info,
96    Warning,
97    Error,
98    Critical,
99}
100
101/// Tensor debugging information
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct TensorDebugInfo {
104    pub name: String,
105    pub shape: Vec<usize>,
106    pub dtype: String,
107    pub min_value: f32,
108    pub max_value: f32,
109    pub mean_value: f32,
110    pub std_dev: f32,
111    pub zero_count: usize,
112    pub nan_count: usize,
113    pub inf_count: usize,
114    pub memory_size: usize,
115    pub sparsity: f32,
116}
117
118/// Performance profiling information
119#[derive(Debug, Clone, Serialize, Deserialize)]
120pub struct PerformanceProfile {
121    pub total_inference_time: Duration,
122    pub preprocessing_time: Duration,
123    pub model_execution_time: Duration,
124    pub postprocessing_time: Duration,
125    pub memory_allocation_time: Duration,
126    pub memory_peak: usize,
127    pub cpu_usage: f32,
128    pub gpu_usage: f32,
129    pub bottlenecks: Vec<PerformanceBottleneck>,
130}
131
132/// Performance bottleneck information
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct PerformanceBottleneck {
135    pub operation_name: String,
136    pub execution_time: Duration,
137    pub percentage_of_total: f32,
138    pub optimization_suggestions: Vec<String>,
139}
140
141/// Inference trace for debugging
142#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct InferenceTrace {
144    pub trace_id: String,
145    pub timestamp: u64,
146    pub input_tensors: Vec<TensorDebugInfo>,
147    pub output_tensors: Vec<TensorDebugInfo>,
148    pub intermediate_tensors: Vec<TensorDebugInfo>,
149    pub execution_time: Duration,
150    pub memory_usage: usize,
151    pub anomalies: Vec<ModelAnomaly>,
152    pub operations: Vec<OperationTrace>,
153}
154
155/// Individual operation trace
156#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct OperationTrace {
158    pub operation_name: String,
159    pub input_shapes: Vec<Vec<usize>>,
160    pub output_shapes: Vec<Vec<usize>>,
161    pub execution_time: Duration,
162    pub memory_delta: i64,
163    pub parameters: HashMap<String, String>,
164}
165
166/// Mobile model debugger
167pub struct MobileModelDebugger {
168    config: ModelDebuggerConfig,
169    model_info: Arc<Mutex<HashMap<String, ModelDebugInfo>>>,
170    inference_traces: Arc<Mutex<VecDeque<InferenceTrace>>>,
171    anomaly_detectors: Arc<Mutex<HashMap<String, AnomalyDetector>>>,
172    performance_history: Arc<Mutex<VecDeque<PerformanceProfile>>>,
173}
174
175/// Anomaly detection state
176#[derive(Debug)]
177struct AnomalyDetector {
178    model_id: String,
179    baseline_stats: TensorStats,
180    recent_stats: VecDeque<TensorStats>,
181    anomaly_threshold: f32,
182    consecutive_anomalies: usize,
183}
184
185/// Statistical information for tensors
186#[derive(Debug, Clone)]
187struct TensorStats {
188    mean: f32,
189    std_dev: f32,
190    min_val: f32,
191    max_val: f32,
192    nan_rate: f32,
193    inf_rate: f32,
194}
195
196impl Default for ModelDebuggerConfig {
197    fn default() -> Self {
198        Self {
199            enabled: true,
200            max_inference_traces: 100,
201            enable_tensor_analysis: true,
202            enable_gradient_analysis: false, // Disabled by default for inference-only models
203            enable_structure_validation: true,
204            enable_performance_profiling: true,
205            slow_inference_threshold: Duration::from_millis(100),
206            enable_anomaly_detection: true,
207            normal_value_range: (-10.0, 10.0),
208            enable_debug_output: false,
209        }
210    }
211}
212
213impl MobileModelDebugger {
214    /// Create a new model debugger
215    pub fn new(config: ModelDebuggerConfig) -> Self {
216        Self {
217            config,
218            model_info: Arc::new(Mutex::new(HashMap::new())),
219            inference_traces: Arc::new(Mutex::new(VecDeque::new())),
220            anomaly_detectors: Arc::new(Mutex::new(HashMap::new())),
221            performance_history: Arc::new(Mutex::new(VecDeque::new())),
222        }
223    }
224
225    /// Register a model for debugging
226    pub fn register_model(
227        &self,
228        model_id: String,
229        model_type: String,
230        input_shapes: Vec<Vec<usize>>,
231        output_shapes: Vec<Vec<usize>>,
232        parameter_count: usize,
233    ) -> Result<()> {
234        if !self.config.enabled {
235            return Ok(());
236        }
237
238        let mut model_info = self
239            .model_info
240            .lock()
241            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
242
243        let debug_info = ModelDebugInfo {
244            model_id: model_id.clone(),
245            model_type,
246            input_shapes,
247            output_shapes,
248            parameter_count,
249            memory_usage: 0,
250            inference_count: 0,
251            average_inference_time: Duration::from_millis(0),
252            last_inference_time: Duration::from_millis(0),
253            validation_status: ValidationStatus::NotValidated,
254            anomalies_detected: Vec::new(),
255            performance_profile: PerformanceProfile::default(),
256        };
257
258        model_info.insert(model_id.clone(), debug_info);
259
260        // Initialize anomaly detector
261        if self.config.enable_anomaly_detection {
262            let mut detectors = self
263                .anomaly_detectors
264                .lock()
265                .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
266
267            detectors.insert(
268                model_id.clone(),
269                AnomalyDetector {
270                    model_id,
271                    baseline_stats: TensorStats::default(),
272                    recent_stats: VecDeque::new(),
273                    anomaly_threshold: 2.0, // 2 standard deviations
274                    consecutive_anomalies: 0,
275                },
276            );
277        }
278
279        Ok(())
280    }
281
282    /// Debug an inference operation
283    pub fn debug_inference(
284        &self,
285        model_id: &str,
286        input_tensors: &[Tensor],
287        output_tensors: &[Tensor],
288        execution_time: Duration,
289        memory_usage: usize,
290    ) -> Result<InferenceTrace> {
291        if !self.config.enabled {
292            return Err(TrustformersError::runtime_error("Debugger not enabled".into()).into());
293        }
294
295        let trace_id = format!(
296            "trace_{}_{}",
297            model_id,
298            SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos()
299        );
300
301        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
302
303        // Analyze input tensors
304        let input_debug_info = if self.config.enable_tensor_analysis {
305            input_tensors
306                .iter()
307                .enumerate()
308                .map(|(i, tensor)| self.analyze_tensor(tensor, &format!("input_{}", i)))
309                .collect::<Result<Vec<_>>>()?
310        } else {
311            Vec::new()
312        };
313
314        // Analyze output tensors
315        let output_debug_info = if self.config.enable_tensor_analysis {
316            output_tensors
317                .iter()
318                .enumerate()
319                .map(|(i, tensor)| self.analyze_tensor(tensor, &format!("output_{}", i)))
320                .collect::<Result<Vec<_>>>()?
321        } else {
322            Vec::new()
323        };
324
325        // Detect anomalies
326        let mut anomalies = Vec::new();
327        if self.config.enable_anomaly_detection {
328            anomalies.extend(self.detect_tensor_anomalies(model_id, &input_debug_info)?);
329            anomalies.extend(self.detect_tensor_anomalies(model_id, &output_debug_info)?);
330            anomalies.extend(self.detect_performance_anomalies(
331                model_id,
332                execution_time,
333                memory_usage,
334            )?);
335        }
336
337        // Create inference trace
338        let trace = InferenceTrace {
339            trace_id: trace_id.clone(),
340            timestamp,
341            input_tensors: input_debug_info,
342            output_tensors: output_debug_info,
343            intermediate_tensors: Vec::new(), // Would be populated by model internals
344            execution_time,
345            memory_usage,
346            anomalies: anomalies.clone(),
347            operations: Vec::new(), // Would be populated by operation tracing
348        };
349
350        // Store trace
351        let mut traces = self
352            .inference_traces
353            .lock()
354            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
355
356        traces.push_back(trace.clone());
357
358        // Keep only recent traces
359        while traces.len() > self.config.max_inference_traces {
360            traces.pop_front();
361        }
362
363        // Update model info
364        self.update_model_info(model_id, execution_time, memory_usage, anomalies)?;
365
366        Ok(trace)
367    }
368
369    /// Validate a model structure
370    pub fn validate_model(&self, model_id: &str) -> Result<ValidationStatus> {
371        if !self.config.enable_structure_validation {
372            return Ok(ValidationStatus::NotValidated);
373        }
374
375        let model_info = self
376            .model_info
377            .lock()
378            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
379
380        let info = model_info
381            .get(model_id)
382            .ok_or_else(|| TrustformersError::runtime_error("Model not registered".into()))?;
383
384        let mut warnings = Vec::new();
385        let errors = Vec::new();
386
387        // Check input/output shape consistency
388        if info.input_shapes.is_empty() {
389            warnings.push("No input shapes defined".to_string());
390        }
391
392        if info.output_shapes.is_empty() {
393            warnings.push("No output shapes defined".to_string());
394        }
395
396        // Check parameter count
397        if info.parameter_count == 0 {
398            warnings.push("Model has no parameters".to_string());
399        }
400
401        // Check for extremely large models (mobile constraint)
402        let estimated_memory = info.parameter_count * 4; // Assume FP32
403        if estimated_memory > 100 * 1024 * 1024 {
404            // 100MB
405            warnings.push("Model may be too large for mobile deployment".to_string());
406        }
407
408        // Check inference performance
409        if info.average_inference_time > Duration::from_millis(500) {
410            warnings.push("Average inference time exceeds mobile-friendly threshold".to_string());
411        }
412
413        // Return validation status
414        if !errors.is_empty() {
415            Ok(ValidationStatus::Error(errors))
416        } else if !warnings.is_empty() {
417            Ok(ValidationStatus::Warning(warnings))
418        } else {
419            Ok(ValidationStatus::Valid)
420        }
421    }
422
423    /// Get debugging information for a model
424    pub fn get_model_debug_info(&self, model_id: &str) -> Result<ModelDebugInfo> {
425        let model_info = self
426            .model_info
427            .lock()
428            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
429
430        model_info
431            .get(model_id)
432            .cloned()
433            .ok_or_else(|| TrustformersError::runtime_error("Model not registered".into()).into())
434    }
435
436    /// Get recent inference traces
437    pub fn get_inference_traces(
438        &self,
439        model_id: Option<&str>,
440        limit: Option<usize>,
441    ) -> Result<Vec<InferenceTrace>> {
442        let traces = self
443            .inference_traces
444            .lock()
445            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
446
447        let filtered_traces: Vec<InferenceTrace> = traces
448            .iter()
449            .filter(|trace| {
450                if let Some(id) = model_id {
451                    // Extract model ID from trace ID (simplified)
452                    trace.trace_id.contains(id)
453                } else {
454                    true
455                }
456            })
457            .cloned()
458            .collect();
459
460        let result = if let Some(limit) = limit {
461            filtered_traces.into_iter().rev().take(limit).collect()
462        } else {
463            filtered_traces
464        };
465
466        Ok(result)
467    }
468
469    /// Get detected anomalies
470    pub fn get_anomalies(
471        &self,
472        model_id: Option<&str>,
473        severity: Option<AnomalySeverity>,
474    ) -> Result<Vec<ModelAnomaly>> {
475        let model_info = self
476            .model_info
477            .lock()
478            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
479
480        let mut all_anomalies = Vec::new();
481
482        for (id, info) in model_info.iter() {
483            if let Some(target_id) = model_id {
484                if id != target_id {
485                    continue;
486                }
487            }
488
489            for anomaly in &info.anomalies_detected {
490                if let Some(target_severity) = severity {
491                    if anomaly.severity != target_severity {
492                        continue;
493                    }
494                }
495                all_anomalies.push(anomaly.clone());
496            }
497        }
498
499        // Sort by timestamp (most recent first)
500        all_anomalies.sort_by_key(|a| std::cmp::Reverse(a.timestamp));
501
502        Ok(all_anomalies)
503    }
504
505    /// Generate debugging report
506    pub fn generate_debug_report(&self, model_id: &str) -> Result<String> {
507        let info = self.get_model_debug_info(model_id)?;
508        let traces = self.get_inference_traces(Some(model_id), Some(10))?;
509        let anomalies = self.get_anomalies(Some(model_id), None)?;
510
511        let mut report = String::new();
512
513        report.push_str(&format!("# Model Debug Report: {}\n\n", model_id));
514
515        // Model information
516        report.push_str("## Model Information\n");
517        report.push_str(&format!("- Type: {}\n", info.model_type));
518        report.push_str(&format!("- Parameters: {}\n", info.parameter_count));
519        report.push_str(&format!(
520            "- Memory Usage: {} MB\n",
521            info.memory_usage / (1024 * 1024)
522        ));
523        report.push_str(&format!("- Inference Count: {}\n", info.inference_count));
524        report.push_str(&format!(
525            "- Average Inference Time: {:?}\n",
526            info.average_inference_time
527        ));
528        report.push('\n');
529
530        // Input/Output shapes
531        report.push_str("## Model Structure\n");
532        report.push_str("### Input Shapes\n");
533        for (i, shape) in info.input_shapes.iter().enumerate() {
534            report.push_str(&format!("- Input {}: {:?}\n", i, shape));
535        }
536        report.push_str("### Output Shapes\n");
537        for (i, shape) in info.output_shapes.iter().enumerate() {
538            report.push_str(&format!("- Output {}: {:?}\n", i, shape));
539        }
540        report.push('\n');
541
542        // Validation status
543        report.push_str("## Validation Status\n");
544        match &info.validation_status {
545            ValidationStatus::Valid => report.push_str("✅ Model validation passed\n"),
546            ValidationStatus::Warning(warnings) => {
547                report.push_str("⚠️ Model validation warnings:\n");
548                for warning in warnings {
549                    report.push_str(&format!("  - {}\n", warning));
550                }
551            },
552            ValidationStatus::Error(errors) => {
553                report.push_str("❌ Model validation errors:\n");
554                for error in errors {
555                    report.push_str(&format!("  - {}\n", error));
556                }
557            },
558            ValidationStatus::NotValidated => report.push_str("❓ Model not validated\n"),
559        }
560        report.push('\n');
561
562        // Anomalies
563        if !anomalies.is_empty() {
564            report.push_str("## Detected Anomalies\n");
565            for anomaly in anomalies.iter().take(5) {
566                let severity_emoji = match anomaly.severity {
567                    AnomalySeverity::Info => "ℹ️",
568                    AnomalySeverity::Warning => "⚠️",
569                    AnomalySeverity::Error => "❌",
570                    AnomalySeverity::Critical => "🔥",
571                };
572                report.push_str(&format!(
573                    "{} {:?}: {}\n",
574                    severity_emoji, anomaly.anomaly_type, anomaly.description
575                ));
576                report.push_str(&format!(
577                    "   Suggested action: {}\n",
578                    anomaly.suggested_action
579                ));
580            }
581            report.push('\n');
582        }
583
584        // Recent traces
585        if !traces.is_empty() {
586            report.push_str("## Recent Inference Traces\n");
587            for trace in traces.iter().take(5) {
588                report.push_str(&format!(
589                    "- Trace {}: {:?} execution time, {} MB memory\n",
590                    trace.trace_id,
591                    trace.execution_time,
592                    trace.memory_usage / (1024 * 1024)
593                ));
594                if !trace.anomalies.is_empty() {
595                    report.push_str(&format!("  Anomalies: {}\n", trace.anomalies.len()));
596                }
597            }
598        }
599
600        Ok(report)
601    }
602
603    /// Clear debugging data
604    pub fn clear_debug_data(&self, model_id: Option<&str>) -> Result<()> {
605        if let Some(id) = model_id {
606            // Clear data for specific model
607            let mut traces = self
608                .inference_traces
609                .lock()
610                .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
611
612            traces.retain(|trace| !trace.trace_id.contains(id));
613
614            let mut model_info = self
615                .model_info
616                .lock()
617                .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
618
619            if let Some(info) = model_info.get_mut(id) {
620                info.anomalies_detected.clear();
621                info.inference_count = 0;
622            }
623        } else {
624            // Clear all data
625            let mut traces = self
626                .inference_traces
627                .lock()
628                .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
629            traces.clear();
630
631            let mut model_info = self
632                .model_info
633                .lock()
634                .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
635
636            for info in model_info.values_mut() {
637                info.anomalies_detected.clear();
638                info.inference_count = 0;
639            }
640        }
641
642        Ok(())
643    }
644
645    // Private helper methods
646
647    fn analyze_tensor(&self, tensor: &Tensor, name: &str) -> Result<TensorDebugInfo> {
648        let data = tensor.data()?;
649        let shape = tensor.shape().to_vec();
650
651        if data.is_empty() {
652            return Ok(TensorDebugInfo {
653                name: name.to_string(),
654                shape,
655                dtype: "f32".to_string(),
656                min_value: 0.0,
657                max_value: 0.0,
658                mean_value: 0.0,
659                std_dev: 0.0,
660                zero_count: 0,
661                nan_count: 0,
662                inf_count: 0,
663                memory_size: 0,
664                sparsity: 0.0,
665            });
666        }
667
668        let min_value = data.iter().fold(f32::INFINITY, |acc, &val| acc.min(val));
669        let max_value = data.iter().fold(f32::NEG_INFINITY, |acc, &val| acc.max(val));
670        let mean_value = data.iter().sum::<f32>() / data.len() as f32;
671
672        let variance =
673            data.iter().map(|&val| (val - mean_value).powi(2)).sum::<f32>() / data.len() as f32;
674        let std_dev = variance.sqrt();
675
676        let zero_count = data.iter().filter(|&&val| val == 0.0).count();
677        let nan_count = data.iter().filter(|&&val| val.is_nan()).count();
678        let inf_count = data.iter().filter(|&&val| val.is_infinite()).count();
679
680        let memory_size = data.len() * std::mem::size_of::<f32>();
681        let sparsity = zero_count as f32 / data.len() as f32;
682
683        Ok(TensorDebugInfo {
684            name: name.to_string(),
685            shape,
686            dtype: "f32".to_string(),
687            min_value,
688            max_value,
689            mean_value,
690            std_dev,
691            zero_count,
692            nan_count,
693            inf_count,
694            memory_size,
695            sparsity,
696        })
697    }
698
699    fn detect_tensor_anomalies(
700        &self,
701        model_id: &str,
702        tensor_infos: &[TensorDebugInfo],
703    ) -> Result<Vec<ModelAnomaly>> {
704        let mut anomalies = Vec::new();
705        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
706
707        for tensor_info in tensor_infos {
708            // Check for NaN values
709            if tensor_info.nan_count > 0 {
710                anomalies.push(ModelAnomaly {
711                    anomaly_type: AnomalyType::NaNValues,
712                    severity: AnomalySeverity::Error,
713                    description: format!(
714                        "Tensor '{}' contains {} NaN values",
715                        tensor_info.name, tensor_info.nan_count
716                    ),
717                    location: format!("model:{}, tensor:{}", model_id, tensor_info.name),
718                    timestamp,
719                    suggested_action: "Check for division by zero or invalid operations"
720                        .to_string(),
721                    tensor_info: Some(tensor_info.clone()),
722                });
723            }
724
725            // Check for infinite values
726            if tensor_info.inf_count > 0 {
727                anomalies.push(ModelAnomaly {
728                    anomaly_type: AnomalyType::InfiniteValues,
729                    severity: AnomalySeverity::Error,
730                    description: format!(
731                        "Tensor '{}' contains {} infinite values",
732                        tensor_info.name, tensor_info.inf_count
733                    ),
734                    location: format!("model:{}, tensor:{}", model_id, tensor_info.name),
735                    timestamp,
736                    suggested_action: "Check for overflow or invalid mathematical operations"
737                        .to_string(),
738                    tensor_info: Some(tensor_info.clone()),
739                });
740            }
741
742            // Check for extreme values
743            let (min_normal, max_normal) = self.config.normal_value_range;
744            if tensor_info.min_value < min_normal || tensor_info.max_value > max_normal {
745                anomalies.push(ModelAnomaly {
746                    anomaly_type: AnomalyType::ExtremeValues,
747                    severity: AnomalySeverity::Warning,
748                    description: format!(
749                        "Tensor '{}' has extreme values: min={}, max={}",
750                        tensor_info.name, tensor_info.min_value, tensor_info.max_value
751                    ),
752                    location: format!("model:{}, tensor:{}", model_id, tensor_info.name),
753                    timestamp,
754                    suggested_action: "Consider value normalization or clipping".to_string(),
755                    tensor_info: Some(tensor_info.clone()),
756                });
757            }
758        }
759
760        Ok(anomalies)
761    }
762
763    fn detect_performance_anomalies(
764        &self,
765        model_id: &str,
766        execution_time: Duration,
767        memory_usage: usize,
768    ) -> Result<Vec<ModelAnomaly>> {
769        let mut anomalies = Vec::new();
770        let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_secs();
771
772        // Check for slow inference
773        if execution_time > self.config.slow_inference_threshold {
774            anomalies.push(ModelAnomaly {
775                anomaly_type: AnomalyType::PerformanceDegradation,
776                severity: AnomalySeverity::Warning,
777                description: format!("Slow inference detected: {:?}", execution_time),
778                location: format!("model:{}", model_id),
779                timestamp,
780                suggested_action: "Consider model optimization or hardware acceleration"
781                    .to_string(),
782                tensor_info: None,
783            });
784        }
785
786        // Check for high memory usage (simplified threshold)
787        let high_memory_threshold = 50 * 1024 * 1024; // 50MB
788        if memory_usage > high_memory_threshold {
789            anomalies.push(ModelAnomaly {
790                anomaly_type: AnomalyType::MemorySpike,
791                severity: AnomalySeverity::Warning,
792                description: format!(
793                    "High memory usage detected: {} MB",
794                    memory_usage / (1024 * 1024)
795                ),
796                location: format!("model:{}", model_id),
797                timestamp,
798                suggested_action: "Consider memory optimization or model compression".to_string(),
799                tensor_info: None,
800            });
801        }
802
803        Ok(anomalies)
804    }
805
806    fn update_model_info(
807        &self,
808        model_id: &str,
809        execution_time: Duration,
810        memory_usage: usize,
811        anomalies: Vec<ModelAnomaly>,
812    ) -> Result<()> {
813        let mut model_info = self
814            .model_info
815            .lock()
816            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
817
818        if let Some(info) = model_info.get_mut(model_id) {
819            info.inference_count += 1;
820            info.last_inference_time = execution_time;
821
822            // Update running average
823            let alpha = 0.1; // Smoothing factor
824            if info.inference_count == 1 {
825                info.average_inference_time = execution_time;
826            } else {
827                let current_avg_ms = info.average_inference_time.as_millis() as f64;
828                let new_time_ms = execution_time.as_millis() as f64;
829                let new_avg_ms = alpha * new_time_ms + (1.0 - alpha) * current_avg_ms;
830                info.average_inference_time = Duration::from_millis(new_avg_ms as u64);
831            }
832
833            info.memory_usage = memory_usage;
834            info.anomalies_detected.extend(anomalies);
835
836            // Keep only recent anomalies (last 100)
837            if info.anomalies_detected.len() > 100 {
838                info.anomalies_detected.drain(0..info.anomalies_detected.len() - 100);
839            }
840        }
841
842        Ok(())
843    }
844}
845
846impl Default for PerformanceProfile {
847    fn default() -> Self {
848        Self {
849            total_inference_time: Duration::from_millis(0),
850            preprocessing_time: Duration::from_millis(0),
851            model_execution_time: Duration::from_millis(0),
852            postprocessing_time: Duration::from_millis(0),
853            memory_allocation_time: Duration::from_millis(0),
854            memory_peak: 0,
855            cpu_usage: 0.0,
856            gpu_usage: 0.0,
857            bottlenecks: Vec::new(),
858        }
859    }
860}
861
862impl Default for TensorStats {
863    fn default() -> Self {
864        Self {
865            mean: 0.0,
866            std_dev: 0.0,
867            min_val: 0.0,
868            max_val: 0.0,
869            nan_rate: 0.0,
870            inf_rate: 0.0,
871        }
872    }
873}
874
875#[cfg(test)]
876mod tests {
877    use super::*;
878
879    #[test]
880    fn test_model_debugger_creation() {
881        let config = ModelDebuggerConfig::default();
882        let debugger = MobileModelDebugger::new(config);
883        assert!(debugger.config.enabled);
884    }
885
886    #[test]
887    fn test_model_registration() {
888        let config = ModelDebuggerConfig::default();
889        let debugger = MobileModelDebugger::new(config);
890
891        let result = debugger.register_model(
892            "test_model".to_string(),
893            "transformer".to_string(),
894            vec![vec![1, 224, 224, 3]],
895            vec![vec![1, 1000]],
896            1000000,
897        );
898
899        assert!(result.is_ok());
900
901        let info = debugger.get_model_debug_info("test_model").expect("Operation failed");
902        assert_eq!(info.model_id, "test_model");
903        assert_eq!(info.model_type, "transformer");
904        assert_eq!(info.parameter_count, 1000000);
905    }
906
907    #[test]
908    fn test_tensor_analysis() {
909        let config = ModelDebuggerConfig::default();
910        let debugger = MobileModelDebugger::new(config);
911
912        // Create test tensor with some problematic values
913        let data = vec![1.0, 2.0, f32::NAN, 4.0, f32::INFINITY, 0.0];
914        let tensor = Tensor::from_vec(data, &[6]).expect("Operation failed");
915
916        let analysis = debugger.analyze_tensor(&tensor, "test_tensor").expect("Operation failed");
917
918        assert_eq!(analysis.name, "test_tensor");
919        assert_eq!(analysis.nan_count, 1);
920        assert_eq!(analysis.inf_count, 1);
921        assert_eq!(analysis.zero_count, 1);
922    }
923
924    #[test]
925    fn test_anomaly_detection() {
926        let config = ModelDebuggerConfig::default();
927        let debugger = MobileModelDebugger::new(config);
928
929        // Register model
930        debugger
931            .register_model(
932                "test_model".to_string(),
933                "test".to_string(),
934                vec![vec![1, 4]],
935                vec![vec![1, 1]],
936                100,
937            )
938            .expect("Operation failed");
939
940        // Create tensors with anomalies
941        let input_data = vec![1.0, 2.0, f32::NAN, 4.0];
942        let output_data = vec![f32::INFINITY];
943
944        let input_tensor = Tensor::from_vec(input_data, &[1, 4]).expect("Operation failed");
945        let output_tensor = Tensor::from_vec(output_data, &[1, 1]).expect("Operation failed");
946
947        let trace = debugger
948            .debug_inference(
949                "test_model",
950                &[input_tensor],
951                &[output_tensor],
952                Duration::from_millis(50),
953                1024 * 1024,
954            )
955            .expect("Operation failed");
956
957        // Should detect NaN in input and infinity in output
958        assert!(!trace.anomalies.is_empty());
959        assert!(trace.anomalies.iter().any(|a| a.anomaly_type == AnomalyType::NaNValues));
960        assert!(trace.anomalies.iter().any(|a| a.anomaly_type == AnomalyType::InfiniteValues));
961    }
962
963    #[test]
964    fn test_model_validation() {
965        let config = ModelDebuggerConfig::default();
966        let debugger = MobileModelDebugger::new(config);
967
968        // Register a large model that should trigger warnings
969        debugger
970            .register_model(
971                "large_model".to_string(),
972                "large".to_string(),
973                vec![vec![1, 1000, 1000, 3]],
974                vec![vec![1, 10000]],
975                100_000_000, // 100M parameters
976            )
977            .expect("Operation failed");
978
979        let validation = debugger.validate_model("large_model").expect("Operation failed");
980
981        match validation {
982            ValidationStatus::Warning(warnings) => {
983                assert!(warnings.iter().any(|w| w.contains("too large for mobile")));
984            },
985            status => panic!(
986                "Expected ValidationStatus::Warning for large model, got {:?}",
987                status
988            ),
989        }
990    }
991}