Skip to main content

trustformers_mobile/
inference_visualizer.rs

1//! Mobile Inference Visualizer for Real-time Debugging
2//!
3//! This module provides comprehensive real-time visualization capabilities for mobile ML inference,
4//! enabling developers to inspect tensor flows, intermediate outputs, attention patterns, and model
5//! behavior during inference with minimal performance impact.
6
7use crate::{
8    mobile_performance_profiler::MobileMetricsSnapshot,
9    model_debugger::{AnomalySeverity, AnomalyType},
10};
11use serde::{Deserialize, Serialize};
12use std::collections::{HashMap, VecDeque};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
15use trustformers_core::error::{CoreError, Result};
16use trustformers_core::Tensor;
17use trustformers_core::TrustformersError;
18
19/// Configuration for inference visualizer
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct InferenceVisualizerConfig {
22    /// Enable visualization
23    pub enabled: bool,
24    /// Visualization mode
25    pub mode: VisualizationMode,
26    /// Real-time rendering configuration
27    pub real_time_config: RealTimeVisualizationConfig,
28    /// Tensor visualization settings
29    pub tensor_visualization: TensorVisualizationConfig,
30    /// Attention visualization settings
31    pub attention_visualization: AttentionVisualizationConfig,
32    /// Flow visualization settings
33    pub flow_visualization: FlowVisualizationConfig,
34    /// Performance visualization settings
35    pub performance_visualization: PerformanceVisualizationConfig,
36    /// Export settings
37    pub export_config: VisualizationExportConfig,
38}
39
40/// Visualization modes
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
42pub enum VisualizationMode {
43    /// Full visualization (high detail, higher overhead)
44    Full,
45    /// Lightweight visualization (optimized for mobile)
46    Lightweight,
47    /// Debug mode (maximum detail for debugging)
48    Debug,
49    /// Performance mode (minimal overhead)
50    Performance,
51    /// Custom configuration
52    Custom,
53}
54
55/// Real-time visualization configuration
56#[derive(Debug, Clone, Serialize, Deserialize)]
57pub struct RealTimeVisualizationConfig {
58    /// Enable real-time rendering
59    pub enabled: bool,
60    /// Update frequency (FPS)
61    pub update_fps: u32,
62    /// Maximum history frames
63    pub max_history_frames: usize,
64    /// Enable animation
65    pub enable_animation: bool,
66    /// Animation duration (ms)
67    pub animation_duration_ms: u64,
68    /// Buffer size for smooth rendering
69    pub render_buffer_size: usize,
70}
71
72/// Tensor visualization configuration
73#[derive(Debug, Clone, Serialize, Deserialize)]
74pub struct TensorVisualizationConfig {
75    /// Enable tensor visualization
76    pub enabled: bool,
77    /// Visualization type
78    pub visualization_type: TensorVisualizationType,
79    /// Color mapping scheme
80    pub color_scheme: ColorScheme,
81    /// Normalize values
82    pub normalize_values: bool,
83    /// Show tensor statistics overlay
84    pub show_statistics: bool,
85    /// Highlight anomalies
86    pub highlight_anomalies: bool,
87    /// Maximum tensor size to visualize
88    pub max_tensor_size: usize,
89}
90
91/// Tensor visualization types
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93pub enum TensorVisualizationType {
94    /// Heatmap representation
95    Heatmap,
96    /// 3D surface plot
97    Surface3D,
98    /// Histogram distribution
99    Histogram,
100    /// Line plot for 1D tensors
101    LinePlot,
102    /// Bar chart
103    BarChart,
104    /// Scatter plot
105    ScatterPlot,
106}
107
108/// Color schemes for visualization
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110pub enum ColorScheme {
111    /// Viridis (perceptually uniform)
112    Viridis,
113    /// Plasma (high contrast)
114    Plasma,
115    /// Inferno (heat-like)
116    Inferno,
117    /// Magma (volcanic)
118    Magma,
119    /// Jet (rainbow)
120    Jet,
121    /// Grayscale
122    Grayscale,
123    /// Custom colors
124    Custom,
125}
126
127/// Attention visualization configuration
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct AttentionVisualizationConfig {
130    /// Enable attention visualization
131    pub enabled: bool,
132    /// Show attention matrices
133    pub show_attention_matrices: bool,
134    /// Show attention flow
135    pub show_attention_flow: bool,
136    /// Show head specialization
137    pub show_head_specialization: bool,
138    /// Maximum sequence length to visualize
139    pub max_sequence_length: usize,
140    /// Head sampling for large models
141    pub head_sampling_rate: f32,
142}
143
144/// Flow visualization configuration
145#[derive(Debug, Clone, Serialize, Deserialize)]
146pub struct FlowVisualizationConfig {
147    /// Enable flow visualization
148    pub enabled: bool,
149    /// Show data flow graph
150    pub show_data_flow: bool,
151    /// Show gradient flow
152    pub show_gradient_flow: bool,
153    /// Show computation graph
154    pub show_computation_graph: bool,
155    /// Flow animation speed
156    pub flow_animation_speed: f32,
157    /// Show bottlenecks
158    pub highlight_bottlenecks: bool,
159}
160
161/// Performance visualization configuration
162#[derive(Debug, Clone, Serialize, Deserialize)]
163pub struct PerformanceVisualizationConfig {
164    /// Enable performance visualization
165    pub enabled: bool,
166    /// Show real-time metrics
167    pub show_real_time_metrics: bool,
168    /// Show memory usage
169    pub show_memory_usage: bool,
170    /// Show timing breakdown
171    pub show_timing_breakdown: bool,
172    /// Show thermal state
173    pub show_thermal_state: bool,
174    /// Performance history length
175    pub history_length: usize,
176}
177
178/// Visualization export configuration
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct VisualizationExportConfig {
181    /// Enable automatic export
182    pub auto_export: bool,
183    /// Export format
184    pub format: VisualizationExportFormat,
185    /// Export quality
186    pub quality: ExportQuality,
187    /// Include metadata
188    pub include_metadata: bool,
189    /// Export directory
190    pub export_directory: String,
191}
192
193/// Export formats
194#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
195pub enum VisualizationExportFormat {
196    /// PNG image
197    PNG,
198    /// SVG vector graphics
199    SVG,
200    /// Interactive HTML
201    HTML,
202    /// Video (MP4)
203    MP4,
204    /// Raw data (JSON)
205    JSON,
206}
207
208/// Export quality levels
209#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
210pub enum ExportQuality {
211    Low,
212    Medium,
213    High,
214    Ultra,
215}
216
217/// Visualization frame containing all visualization data for a single inference step
218#[derive(Debug, Clone, Serialize, Deserialize)]
219pub struct VisualizationFrame {
220    /// Frame ID
221    pub frame_id: String,
222    /// Timestamp
223    pub timestamp: u64,
224    /// Model ID
225    pub model_id: String,
226    /// Inference step
227    pub inference_step: usize,
228    /// Tensor visualizations
229    pub tensor_visualizations: Vec<TensorVisualization>,
230    /// Attention visualizations
231    pub attention_visualizations: Vec<AttentionVisualization>,
232    /// Flow visualization
233    pub flow_visualization: Option<FlowVisualization>,
234    /// Performance visualization
235    pub performance_visualization: Option<PerformanceVisualization>,
236    /// Detected anomalies
237    pub anomalies: Vec<VisualizationAnomaly>,
238    /// Frame metadata
239    pub metadata: FrameMetadata,
240}
241
242/// Individual tensor visualization
243#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct TensorVisualization {
245    /// Tensor name
246    pub name: String,
247    /// Tensor shape
248    pub shape: Vec<usize>,
249    /// Visualization type
250    pub visualization_type: TensorVisualizationType,
251    /// Visualization data
252    pub data: VisualizationData,
253    /// Statistics
254    pub statistics: TensorStatistics,
255    /// Color mapping
256    pub color_mapping: ColorMapping,
257    /// Anomaly highlights
258    pub anomaly_highlights: Vec<AnomalyHighlight>,
259}
260
261/// Attention visualization
262#[derive(Debug, Clone, Serialize, Deserialize)]
263pub struct AttentionVisualization {
264    /// Layer name
265    pub layer_name: String,
266    /// Head index
267    pub head_index: usize,
268    /// Attention matrix
269    pub attention_matrix: AttentionMatrix,
270    /// Attention flow
271    pub attention_flow: Option<AttentionFlow>,
272    /// Head specialization info
273    pub head_specialization: Option<HeadSpecialization>,
274    /// Sequence information
275    pub sequence_info: SequenceInfo,
276}
277
278/// Flow visualization showing data/gradient flow
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct FlowVisualization {
281    /// Data flow graph
282    pub data_flow: Option<DataFlowGraph>,
283    /// Gradient flow graph
284    pub gradient_flow: Option<GradientFlowGraph>,
285    /// Computation graph
286    pub computation_graph: Option<ComputationGraph>,
287    /// Bottleneck locations
288    pub bottlenecks: Vec<FlowBottleneck>,
289    /// Flow statistics
290    pub flow_statistics: FlowStatistics,
291}
292
293/// Performance visualization
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct PerformanceVisualization {
296    /// Real-time metrics
297    pub real_time_metrics: MetricsVisualization,
298    /// Memory usage visualization
299    pub memory_visualization: MemoryVisualization,
300    /// Timing breakdown
301    pub timing_breakdown: TimingVisualization,
302    /// Thermal visualization
303    pub thermal_visualization: ThermalVisualization,
304    /// Performance trends
305    /// Trend analysis over a series of snapshots, or `None` when the
306    /// visualization was rendered from a single snapshot.
307    pub performance_trends: Option<PerformanceTrends>,
308}
309
310/// Visualization-specific anomaly
311#[derive(Debug, Clone, Serialize, Deserialize)]
312pub struct VisualizationAnomaly {
313    /// Anomaly type
314    pub anomaly_type: VisualizationAnomalyType,
315    /// Severity
316    pub severity: AnomalySeverity,
317    /// Location in visualization
318    pub location: VisualizationLocation,
319    /// Description
320    pub description: String,
321    /// Visual indicators
322    pub visual_indicators: Vec<VisualIndicator>,
323    /// Suggested actions
324    pub suggested_actions: Vec<String>,
325}
326
327/// Visualization anomaly types
328#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
329pub enum VisualizationAnomalyType {
330    /// Visual anomaly in tensor
331    TensorAnomaly,
332    /// Attention pattern anomaly
333    AttentionAnomaly,
334    /// Flow disruption
335    FlowDisruption,
336    /// Performance anomaly
337    PerformanceAnomaly,
338    /// Rendering anomaly
339    RenderingAnomaly,
340}
341
342/// Frame metadata
343#[derive(Debug, Clone, Serialize, Deserialize)]
344pub struct FrameMetadata {
345    /// How long the inference this frame visualises took.
346    ///
347    /// `None` when the visualizer was handed a metrics snapshot rather than a
348    /// timed inference: this type renders a frame, it does not run the model,
349    /// so it can only report a duration the caller measured and passed in.
350    pub inference_duration: Option<Duration>,
351    /// Rendering duration
352    pub rendering_duration: Duration,
353    /// Memory usage during frame, or `None` when memory was not measured.
354    pub memory_usage_mb: Option<f32>,
355    /// CPU usage during frame, or `None` when the CPU was not measured.
356    pub cpu_usage_percent: Option<f32>,
357    /// GPU usage during frame, or `None` when this build measures no GPU
358    /// telemetry.
359    pub gpu_usage_percent: Option<f32>,
360    /// Quality metrics
361    pub quality_metrics: QualityMetrics,
362}
363
364/// Main inference visualizer
365pub struct MobileInferenceVisualizer {
366    config: InferenceVisualizerConfig,
367    frame_buffer: Arc<Mutex<VecDeque<VisualizationFrame>>>,
368    renderer: VisualizationRenderer,
369    analyzer: VisualizationAnalyzer,
370    export_manager: VisualizationExportManager,
371    session_tracker: VisualizationSession,
372    real_time_monitor: RealTimeVisualizationMonitor,
373}
374
375/// Visualization renderer
376struct VisualizationRenderer {
377    tensor_renderer: TensorRenderer,
378    attention_renderer: AttentionRenderer,
379    flow_renderer: FlowRenderer,
380    performance_renderer: PerformanceRenderer,
381    composite_renderer: CompositeRenderer,
382}
383
384/// Visualization analyzer
385struct VisualizationAnalyzer {
386    pattern_detector: PatternDetector,
387    anomaly_detector: VisualizationAnomalyDetector,
388    quality_assessor: QualityAssessor,
389}
390
391/// Visualization session tracking
392struct VisualizationSession {
393    session_id: String,
394    start_time: Instant,
395    frame_count: usize,
396    total_render_time: Duration,
397    session_statistics: SessionStatistics,
398}
399
400/// Real-time visualization monitor
401struct RealTimeVisualizationMonitor {
402    config: RealTimeVisualizationConfig,
403    frame_buffer: VecDeque<VisualizationFrame>,
404    render_pipeline: RenderPipeline,
405    performance_tracker: VisualizationPerformanceTracker,
406}
407
408impl Default for InferenceVisualizerConfig {
409    fn default() -> Self {
410        Self {
411            enabled: true,
412            mode: VisualizationMode::Lightweight,
413            real_time_config: RealTimeVisualizationConfig::default(),
414            tensor_visualization: TensorVisualizationConfig::default(),
415            attention_visualization: AttentionVisualizationConfig::default(),
416            flow_visualization: FlowVisualizationConfig::default(),
417            performance_visualization: PerformanceVisualizationConfig::default(),
418            export_config: VisualizationExportConfig::default(),
419        }
420    }
421}
422
423impl Default for RealTimeVisualizationConfig {
424    fn default() -> Self {
425        Self {
426            enabled: true,
427            update_fps: 30,
428            max_history_frames: 100,
429            enable_animation: true,
430            animation_duration_ms: 500,
431            render_buffer_size: 10,
432        }
433    }
434}
435
436impl Default for TensorVisualizationConfig {
437    fn default() -> Self {
438        Self {
439            enabled: true,
440            visualization_type: TensorVisualizationType::Heatmap,
441            color_scheme: ColorScheme::Viridis,
442            normalize_values: true,
443            show_statistics: true,
444            highlight_anomalies: true,
445            max_tensor_size: 1000000, // 1M elements
446        }
447    }
448}
449
450impl Default for AttentionVisualizationConfig {
451    fn default() -> Self {
452        Self {
453            enabled: true,
454            show_attention_matrices: true,
455            show_attention_flow: true,
456            show_head_specialization: true,
457            max_sequence_length: 512,
458            head_sampling_rate: 1.0, // Show all heads by default
459        }
460    }
461}
462
463impl Default for FlowVisualizationConfig {
464    fn default() -> Self {
465        Self {
466            enabled: true,
467            show_data_flow: true,
468            show_gradient_flow: false, // Expensive
469            show_computation_graph: true,
470            flow_animation_speed: 1.0,
471            highlight_bottlenecks: true,
472        }
473    }
474}
475
476impl Default for PerformanceVisualizationConfig {
477    fn default() -> Self {
478        Self {
479            enabled: true,
480            show_real_time_metrics: true,
481            show_memory_usage: true,
482            show_timing_breakdown: true,
483            show_thermal_state: true,
484            history_length: 60, // 60 frames of history
485        }
486    }
487}
488
489impl Default for VisualizationExportConfig {
490    fn default() -> Self {
491        Self {
492            auto_export: false,
493            format: VisualizationExportFormat::PNG,
494            quality: ExportQuality::Medium,
495            include_metadata: true,
496            export_directory: "/tmp/trustformers_visualizations".to_string(),
497        }
498    }
499}
500
501impl MobileInferenceVisualizer {
502    /// Create new inference visualizer
503    pub fn new(config: InferenceVisualizerConfig) -> Result<Self> {
504        let frame_buffer = Arc::new(Mutex::new(VecDeque::new()));
505        let renderer = VisualizationRenderer::new(&config)?;
506        let analyzer = VisualizationAnalyzer::new(&config)?;
507        let export_manager = VisualizationExportManager::new(config.export_config.clone())?;
508        let session_tracker = VisualizationSession::new()?;
509        let real_time_monitor = RealTimeVisualizationMonitor::new(config.real_time_config.clone())?;
510
511        Ok(Self {
512            config,
513            frame_buffer,
514            renderer,
515            analyzer,
516            export_manager,
517            session_tracker,
518            real_time_monitor,
519        })
520    }
521
522    /// Start visualization session
523    pub fn start_session(&mut self, model_id: &str) -> Result<String> {
524        if !self.config.enabled {
525            return Err(TrustformersError::runtime_error("Visualizer is disabled".into()).into());
526        }
527
528        self.session_tracker.start(model_id)?;
529
530        if self.config.real_time_config.enabled {
531            self.real_time_monitor.start()?;
532        }
533
534        tracing::info!(
535            "Started visualization session: {}",
536            self.session_tracker.session_id
537        );
538        Ok(self.session_tracker.session_id.clone())
539    }
540
541    /// Stop visualization session
542    pub fn stop_session(&mut self) -> Result<VisualizationSessionReport> {
543        self.session_tracker.end()?;
544        self.real_time_monitor.stop()?;
545
546        let report = self.generate_session_report()?;
547
548        if self.config.export_config.auto_export {
549            self.export_session(&report)?;
550        }
551
552        Ok(report)
553    }
554
555    /// Visualize inference step
556    pub fn visualize_inference_step(
557        &mut self,
558        model_id: &str,
559        step: usize,
560        input_tensors: &[Tensor],
561        output_tensors: &[Tensor],
562        intermediate_tensors: &[(&str, &Tensor)],
563        attention_weights: Option<&[(&str, usize, &Tensor)]>, // (layer_name, head_idx, weights)
564        performance_metrics: &MobileMetricsSnapshot,
565    ) -> Result<VisualizationFrame> {
566        let start_time = Instant::now();
567
568        let frame_id = format!(
569            "{}_{}_frame_{}",
570            model_id, self.session_tracker.session_id, step
571        );
572        let timestamp =
573            SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis() as u64;
574
575        // Generate tensor visualizations
576        let mut tensor_visualizations = Vec::new();
577
578        if self.config.tensor_visualization.enabled {
579            // Input tensors
580            for (i, tensor) in input_tensors.iter().enumerate() {
581                if tensor.len() <= self.config.tensor_visualization.max_tensor_size {
582                    let viz = self.renderer.render_tensor(&format!("input_{}", i), tensor)?;
583                    tensor_visualizations.push(viz);
584                }
585            }
586
587            // Output tensors
588            for (i, tensor) in output_tensors.iter().enumerate() {
589                if tensor.len() <= self.config.tensor_visualization.max_tensor_size {
590                    let viz = self.renderer.render_tensor(&format!("output_{}", i), tensor)?;
591                    tensor_visualizations.push(viz);
592                }
593            }
594
595            // Intermediate tensors
596            for (name, tensor) in intermediate_tensors {
597                if tensor.len() <= self.config.tensor_visualization.max_tensor_size {
598                    let viz = self.renderer.render_tensor(name, tensor)?;
599                    tensor_visualizations.push(viz);
600                }
601            }
602        }
603
604        // Generate attention visualizations
605        let mut attention_visualizations = Vec::new();
606        if self.config.attention_visualization.enabled {
607            if let Some(attention_weights) = attention_weights {
608                for (layer_name, head_idx, weights) in attention_weights {
609                    let seq_len = self.estimate_sequence_length(weights);
610                    if seq_len <= self.config.attention_visualization.max_sequence_length {
611                        let viz = self.renderer.render_attention(layer_name, *head_idx, weights)?;
612                        attention_visualizations.push(viz);
613                    }
614                }
615            }
616        }
617
618        // Generate flow visualization
619        let flow_visualization = if self.config.flow_visualization.enabled {
620            Some(self.renderer.render_flow(input_tensors, output_tensors, intermediate_tensors)?)
621        } else {
622            None
623        };
624
625        // Generate performance visualization
626        let performance_visualization = if self.config.performance_visualization.enabled {
627            Some(self.renderer.render_performance(performance_metrics)?)
628        } else {
629            None
630        };
631
632        // Detect anomalies
633        let anomalies = self.analyzer.detect_anomalies(
634            &tensor_visualizations,
635            &attention_visualizations,
636            &flow_visualization,
637            &performance_visualization,
638        )?;
639
640        let rendering_duration = start_time.elapsed();
641
642        // Create frame metadata
643        let metadata = FrameMetadata {
644            // Not measured here: `capture_frame` renders an already-completed
645            // inference from a metrics snapshot and never times the model.
646            inference_duration: None,
647            rendering_duration,
648            memory_usage_mb: performance_metrics.memory.as_ref().map(|m| m.heap_used_mb),
649            cpu_usage_percent: performance_metrics.cpu.as_ref().map(|c| c.usage_percent),
650            gpu_usage_percent: performance_metrics.gpu.as_ref().map(|gpu| gpu.usage_percent),
651            quality_metrics: self.analyzer.assess_quality(&tensor_visualizations)?,
652        };
653
654        // Create visualization frame
655        let frame = VisualizationFrame {
656            frame_id: frame_id.clone(),
657            timestamp,
658            model_id: model_id.to_string(),
659            inference_step: step,
660            tensor_visualizations,
661            attention_visualizations,
662            flow_visualization,
663            performance_visualization,
664            anomalies,
665            metadata,
666        };
667
668        // Store frame
669        self.store_frame(frame.clone())?;
670
671        // Update session tracking
672        self.session_tracker.update_frame_stats(&frame);
673
674        // Update real-time monitor
675        if self.config.real_time_config.enabled {
676            self.real_time_monitor.update_frame(&frame)?;
677        }
678
679        tracing::debug!(
680            "Generated visualization frame: {} ({}ms)",
681            frame_id,
682            rendering_duration.as_millis()
683        );
684
685        Ok(frame)
686    }
687
688    /// Get visualization frame by ID
689    pub fn get_frame(&self, frame_id: &str) -> Result<Option<VisualizationFrame>> {
690        let frames = self
691            .frame_buffer
692            .lock()
693            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
694
695        Ok(frames.iter().find(|f| f.frame_id == frame_id).cloned())
696    }
697
698    /// Get recent frames
699    pub fn get_recent_frames(&self, limit: Option<usize>) -> Result<Vec<VisualizationFrame>> {
700        let frames = self
701            .frame_buffer
702            .lock()
703            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
704
705        let result = if let Some(limit) = limit {
706            frames.iter().rev().take(limit).cloned().collect()
707        } else {
708            frames.iter().cloned().collect()
709        };
710
711        Ok(result)
712    }
713
714    /// Export visualization frame
715    pub fn export_frame(&self, frame: &VisualizationFrame) -> Result<String> {
716        self.export_manager.export_frame(frame)
717    }
718
719    /// Export entire session
720    pub fn export_session(&self, report: &VisualizationSessionReport) -> Result<String> {
721        self.export_manager.export_session(report)
722    }
723
724    /// Get real-time visualization state
725    pub fn get_real_time_state(&self) -> Result<RealTimeVisualizationState> {
726        self.real_time_monitor.get_current_state()
727    }
728
729    /// Generate interactive visualization
730    pub fn generate_interactive_visualization(
731        &self,
732        frames: &[VisualizationFrame],
733    ) -> Result<InteractiveVisualization> {
734        self.renderer.generate_interactive(frames)
735    }
736
737    // Private helper methods
738
739    fn store_frame(&self, frame: VisualizationFrame) -> Result<()> {
740        let mut frames = self
741            .frame_buffer
742            .lock()
743            .map_err(|_| TrustformersError::runtime_error("Failed to acquire lock".into()))?;
744
745        frames.push_back(frame);
746
747        // Keep only recent frames
748        let max_frames = self.config.real_time_config.max_history_frames;
749        while frames.len() > max_frames {
750            frames.pop_front();
751        }
752
753        Ok(())
754    }
755
756    fn estimate_sequence_length(&self, attention_weights: &Tensor) -> usize {
757        // Estimate sequence length from attention tensor shape
758        let shape = attention_weights.shape();
759        if shape.len() >= 2 {
760            shape[shape.len() - 1]
761        } else {
762            0
763        }
764    }
765
766    fn generate_session_report(&self) -> Result<VisualizationSessionReport> {
767        let frames = self.get_recent_frames(None)?;
768        let anomaly_summary = self.generate_anomaly_summary(&frames);
769
770        Ok(VisualizationSessionReport {
771            session_id: self.session_tracker.session_id.clone(),
772            total_frames: frames.len(),
773            session_duration: self.session_tracker.get_duration(),
774            total_render_time: self.session_tracker.total_render_time,
775            average_frame_time: if frames.is_empty() {
776                Duration::from_millis(0)
777            } else {
778                self.session_tracker.total_render_time / frames.len() as u32
779            },
780            frames,
781            session_statistics: self.session_tracker.session_statistics.clone(),
782            anomaly_summary,
783        })
784    }
785
786    fn generate_anomaly_summary(&self, frames: &[VisualizationFrame]) -> AnomalySummary {
787        let mut summary = AnomalySummary {
788            total_anomalies: 0,
789            anomaly_types: HashMap::new(),
790            severity_distribution: HashMap::new(),
791            frames_with_anomalies: 0,
792        };
793
794        for frame in frames {
795            if !frame.anomalies.is_empty() {
796                summary.frames_with_anomalies += 1;
797
798                for anomaly in &frame.anomalies {
799                    summary.total_anomalies += 1;
800
801                    *summary.anomaly_types.entry(anomaly.anomaly_type).or_insert(0) += 1;
802                    *summary.severity_distribution.entry(anomaly.severity).or_insert(0) += 1;
803                }
804            }
805        }
806
807        summary
808    }
809}
810
811// Implementation of helper structs and data types
812
813#[derive(Debug, Clone, Serialize, Deserialize)]
814pub struct VisualizationData {
815    /// Raw data points
816    pub data_points: Vec<f32>,
817    /// Data dimensions
818    pub dimensions: Vec<usize>,
819    /// Data range
820    pub value_range: (f32, f32),
821    /// Normalized data
822    pub normalized_data: Option<Vec<f32>>,
823}
824
825#[derive(Debug, Clone, Serialize, Deserialize)]
826pub struct TensorStatistics {
827    pub mean: f32,
828    pub std_dev: f32,
829    pub min_value: f32,
830    pub max_value: f32,
831    pub zero_count: usize,
832    pub nan_count: usize,
833    pub inf_count: usize,
834    pub sparsity: f32,
835}
836
837#[derive(Debug, Clone, Serialize, Deserialize)]
838pub struct ColorMapping {
839    pub scheme: ColorScheme,
840    pub min_color: [u8; 3],
841    pub max_color: [u8; 3],
842    pub special_colors: HashMap<String, [u8; 3]>,
843}
844
845#[derive(Debug, Clone, Serialize, Deserialize)]
846pub struct AnomalyHighlight {
847    pub location: Vec<usize>,
848    pub anomaly_type: AnomalyType,
849    pub severity: AnomalySeverity,
850    pub highlight_color: [u8; 3],
851}
852
853#[derive(Debug, Clone, Serialize, Deserialize)]
854pub struct AttentionMatrix {
855    pub matrix_data: Vec<Vec<f32>>,
856    pub sequence_length: usize,
857    pub head_dim: usize,
858    pub attention_type: AttentionType,
859}
860
861#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
862pub enum AttentionType {
863    SelfAttention,
864    CrossAttention,
865    MultiQueryAttention,
866    GroupedQueryAttention,
867}
868
869#[derive(Debug, Clone, Serialize, Deserialize)]
870pub struct AttentionFlow {
871    pub flow_vectors: Vec<FlowVector>,
872    pub flow_strength: Vec<f32>,
873    pub dominant_patterns: Vec<AttentionPattern>,
874}
875
876#[derive(Debug, Clone, Serialize, Deserialize)]
877pub struct FlowVector {
878    pub from_position: usize,
879    pub to_position: usize,
880    pub strength: f32,
881    pub direction: FlowDirection,
882}
883
884#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
885pub enum FlowDirection {
886    Forward,
887    Backward,
888    Bidirectional,
889}
890
891#[derive(Debug, Clone, Serialize, Deserialize)]
892pub struct AttentionPattern {
893    pub pattern_type: AttentionPatternType,
894    pub confidence: f32,
895    pub affected_positions: Vec<usize>,
896}
897
898#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
899pub enum AttentionPatternType {
900    Diagonal,
901    Vertical,
902    Horizontal,
903    Block,
904    Sparse,
905    Dense,
906    Custom,
907}
908
909#[derive(Debug, Clone, Serialize, Deserialize)]
910pub struct HeadSpecialization {
911    pub specialization_type: HeadSpecializationType,
912    pub specialization_score: f32,
913    pub representative_patterns: Vec<String>,
914}
915
916#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
917pub enum HeadSpecializationType {
918    Positional,
919    Syntactic,
920    Semantic,
921    Local,
922    Global,
923    Redundant,
924    Unknown,
925}
926
927#[derive(Debug, Clone, Serialize, Deserialize)]
928pub struct SequenceInfo {
929    pub sequence_length: usize,
930    pub token_types: Vec<String>,
931    pub special_tokens: Vec<SpecialToken>,
932}
933
934#[derive(Debug, Clone, Serialize, Deserialize)]
935pub struct SpecialToken {
936    pub position: usize,
937    pub token_type: String,
938    pub token_value: String,
939}
940
941// Additional visualization data structures
942#[derive(Debug, Clone, Serialize, Deserialize)]
943pub struct DataFlowGraph {
944    pub nodes: Vec<FlowNode>,
945    pub edges: Vec<FlowEdge>,
946    pub flow_metrics: FlowMetrics,
947}
948
949#[derive(Debug, Clone, Serialize, Deserialize)]
950pub struct FlowNode {
951    pub id: String,
952    pub name: String,
953    pub node_type: FlowNodeType,
954    pub position: (f32, f32),
955    pub data_size: usize,
956    pub processing_time: Duration,
957}
958
959#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
960pub enum FlowNodeType {
961    Input,
962    Layer,
963    Operation,
964    Output,
965    Branch,
966    Merge,
967}
968
969#[derive(Debug, Clone, Serialize, Deserialize)]
970pub struct FlowEdge {
971    pub from_node: String,
972    pub to_node: String,
973    pub data_flow_rate: f32,
974    pub edge_type: FlowEdgeType,
975    pub bottleneck_score: f32,
976}
977
978#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
979pub enum FlowEdgeType {
980    Data,
981    Control,
982    Gradient,
983    Attention,
984}
985
986#[derive(Debug, Clone, Serialize, Deserialize)]
987pub struct FlowMetrics {
988    pub total_flow_rate: f32,
989    pub average_latency: Duration,
990    pub bottleneck_count: usize,
991    pub flow_efficiency: f32,
992}
993
994#[derive(Debug, Clone, Serialize, Deserialize)]
995pub struct GradientFlowGraph {
996    pub gradient_magnitudes: Vec<f32>,
997    pub flow_directions: Vec<FlowDirection>,
998    pub vanishing_regions: Vec<GradientRegion>,
999    pub exploding_regions: Vec<GradientRegion>,
1000}
1001
1002#[derive(Debug, Clone, Serialize, Deserialize)]
1003pub struct GradientRegion {
1004    pub start_layer: usize,
1005    pub end_layer: usize,
1006    pub severity: f32,
1007    pub gradient_norm: f32,
1008}
1009
1010#[derive(Debug, Clone, Serialize, Deserialize)]
1011pub struct ComputationGraph {
1012    pub operations: Vec<Operation>,
1013    pub dependencies: Vec<Dependency>,
1014    pub critical_path: Vec<String>,
1015    pub parallelization_opportunities: Vec<ParallelizationOpportunity>,
1016}
1017
1018#[derive(Debug, Clone, Serialize, Deserialize)]
1019pub struct Operation {
1020    pub id: String,
1021    pub operation_type: String,
1022    pub input_shapes: Vec<Vec<usize>>,
1023    pub output_shapes: Vec<Vec<usize>>,
1024    pub flops: u64,
1025    pub memory_usage: usize,
1026    pub execution_time: Duration,
1027}
1028
1029#[derive(Debug, Clone, Serialize, Deserialize)]
1030pub struct Dependency {
1031    pub from_operation: String,
1032    pub to_operation: String,
1033    pub dependency_type: DependencyType,
1034}
1035
1036#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1037pub enum DependencyType {
1038    Data,
1039    Control,
1040    Memory,
1041}
1042
1043#[derive(Debug, Clone, Serialize, Deserialize)]
1044pub struct ParallelizationOpportunity {
1045    pub operations: Vec<String>,
1046    pub potential_speedup: f32,
1047    pub memory_requirement: usize,
1048}
1049
1050#[derive(Debug, Clone, Serialize, Deserialize)]
1051pub struct FlowBottleneck {
1052    pub location: String,
1053    pub bottleneck_type: BottleneckType,
1054    pub severity: f32,
1055    pub impact_score: f32,
1056    pub suggested_optimizations: Vec<String>,
1057}
1058
1059#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1060pub enum BottleneckType {
1061    Computation,
1062    Memory,
1063    Communication,
1064    Synchronization,
1065}
1066
1067#[derive(Debug, Clone, Serialize, Deserialize)]
1068pub struct FlowStatistics {
1069    pub total_operations: usize,
1070    pub critical_path_length: Duration,
1071    pub parallelization_factor: f32,
1072    pub memory_efficiency: f32,
1073    pub compute_efficiency: f32,
1074}
1075
1076#[derive(Debug, Clone, Serialize, Deserialize)]
1077pub struct MetricsVisualization {
1078    pub cpu_timeline: Vec<(u64, f32)>,
1079    pub memory_timeline: Vec<(u64, f32)>,
1080    pub gpu_timeline: Vec<(u64, f32)>,
1081    pub inference_timeline: Vec<(u64, f32)>,
1082    pub current_values: HashMap<String, f32>,
1083}
1084
1085#[derive(Debug, Clone, Serialize, Deserialize)]
1086pub struct MemoryVisualization {
1087    pub memory_breakdown: HashMap<String, f32>,
1088    pub memory_timeline: Vec<(u64, MemorySnapshot)>,
1089    pub allocation_patterns: Vec<AllocationPattern>,
1090    pub leak_indicators: Vec<LeakIndicator>,
1091}
1092
1093#[derive(Debug, Clone, Serialize, Deserialize)]
1094pub struct MemorySnapshot {
1095    /// Resident memory of the process in MB (always measured).
1096    pub heap_used: f32,
1097    /// Free heap in MB, or `None` when the allocator publishes no such counter.
1098    pub heap_free: Option<f32>,
1099    /// Native (non-managed) memory in MB, or `None` off a managed runtime.
1100    pub native_used: Option<f32>,
1101    /// Graphics memory in MB, or `None` without a GPU driver query.
1102    pub graphics_used: Option<f32>,
1103}
1104
1105#[derive(Debug, Clone, Serialize, Deserialize)]
1106pub struct AllocationPattern {
1107    pub pattern_type: AllocationPatternType,
1108    pub frequency: f32,
1109    pub size_distribution: Vec<(usize, usize)>, // (size, count)
1110}
1111
1112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1113pub enum AllocationPatternType {
1114    Constant,
1115    Periodic,
1116    Burst,
1117    Gradual,
1118}
1119
1120#[derive(Debug, Clone, Serialize, Deserialize)]
1121pub struct LeakIndicator {
1122    pub location: String,
1123    pub growth_rate: f32,
1124    pub confidence: f32,
1125    pub suggested_action: String,
1126}
1127
1128#[derive(Debug, Clone, Serialize, Deserialize)]
1129pub struct TimingVisualization {
1130    pub operation_timings: Vec<OperationTiming>,
1131    pub timing_breakdown: HashMap<String, Duration>,
1132    pub critical_path: Vec<String>,
1133    pub optimization_opportunities: Vec<OptimizationOpportunity>,
1134}
1135
1136#[derive(Debug, Clone, Serialize, Deserialize)]
1137pub struct OperationTiming {
1138    pub operation_name: String,
1139    pub start_time: Duration,
1140    pub end_time: Duration,
1141    pub duration: Duration,
1142    pub percentage_of_total: f32,
1143}
1144
1145#[derive(Debug, Clone, Serialize, Deserialize)]
1146pub struct OptimizationOpportunity {
1147    pub operation: String,
1148    pub opportunity_type: OptimizationType,
1149    pub potential_speedup: f32,
1150    pub implementation_difficulty: f32,
1151}
1152
1153#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1154pub enum OptimizationType {
1155    Parallelization,
1156    Caching,
1157    AlgorithmOptimization,
1158    HardwareOptimization,
1159    MemoryOptimization,
1160}
1161
1162#[derive(Debug, Clone, Serialize, Deserialize)]
1163pub struct ThermalVisualization {
1164    pub temperature_timeline: Vec<(u64, f32)>,
1165    pub thermal_zones: Vec<ThermalZone>,
1166    pub throttling_events: Vec<ThrottlingEvent>,
1167    /// Forecast peak temperature, or `None` when no thermal model has been
1168    /// fitted to a temperature history.
1169    pub thermal_prediction: Option<ThermalPrediction>,
1170}
1171
1172#[derive(Debug, Clone, Serialize, Deserialize)]
1173pub struct ThermalZone {
1174    pub zone_name: String,
1175    pub current_temperature: f32,
1176    pub critical_temperature: f32,
1177    pub thermal_state: String,
1178}
1179
1180#[derive(Debug, Clone, Serialize, Deserialize)]
1181pub struct ThrottlingEvent {
1182    pub timestamp: u64,
1183    pub severity: f32,
1184    pub affected_components: Vec<String>,
1185    pub duration: Duration,
1186}
1187
1188#[derive(Debug, Clone, Serialize, Deserialize)]
1189pub struct ThermalPrediction {
1190    pub predicted_peak: f32,
1191    pub time_to_peak: Duration,
1192    pub confidence: f32,
1193    pub recommended_actions: Vec<String>,
1194}
1195
1196#[derive(Debug, Clone, Serialize, Deserialize)]
1197pub struct PerformanceTrends {
1198    pub latency_trend: TrendData,
1199    pub throughput_trend: TrendData,
1200    pub memory_trend: TrendData,
1201    pub efficiency_trend: TrendData,
1202}
1203
1204#[derive(Debug, Clone, Serialize, Deserialize)]
1205pub struct TrendData {
1206    pub current_value: f32,
1207    pub trend_direction: TrendDirection,
1208    pub trend_strength: f32,
1209    pub prediction: Option<TrendPrediction>,
1210}
1211
1212#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1213pub enum TrendDirection {
1214    Improving,
1215    Stable,
1216    Degrading,
1217}
1218
1219#[derive(Debug, Clone, Serialize, Deserialize)]
1220pub struct TrendPrediction {
1221    pub predicted_value: f32,
1222    pub confidence: f32,
1223    pub time_horizon: Duration,
1224}
1225
1226#[derive(Debug, Clone, Serialize, Deserialize)]
1227pub struct VisualizationLocation {
1228    pub component: String,
1229    pub layer: Option<String>,
1230    pub tensor_name: Option<String>,
1231    pub coordinates: Option<Vec<usize>>,
1232}
1233
1234#[derive(Debug, Clone, Serialize, Deserialize)]
1235pub struct VisualIndicator {
1236    pub indicator_type: VisualIndicatorType,
1237    pub color: [u8; 3],
1238    pub intensity: f32,
1239    pub blinking: bool,
1240}
1241
1242#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1243pub enum VisualIndicatorType {
1244    Highlight,
1245    Border,
1246    Overlay,
1247    Arrow,
1248    Text,
1249    Icon,
1250}
1251
1252#[derive(Debug, Clone, Serialize, Deserialize)]
1253pub struct QualityMetrics {
1254    pub render_quality: f32,
1255    pub data_accuracy: f32,
1256    pub visual_clarity: f32,
1257    pub information_density: f32,
1258    pub performance_impact: f32,
1259}
1260
1261#[derive(Debug, Clone, Serialize, Deserialize)]
1262pub struct VisualizationSessionReport {
1263    pub session_id: String,
1264    pub total_frames: usize,
1265    pub session_duration: Duration,
1266    pub total_render_time: Duration,
1267    pub average_frame_time: Duration,
1268    pub frames: Vec<VisualizationFrame>,
1269    pub session_statistics: SessionStatistics,
1270    pub anomaly_summary: AnomalySummary,
1271}
1272
1273#[derive(Debug, Clone, Serialize, Deserialize)]
1274pub struct SessionStatistics {
1275    pub frames_generated: usize,
1276    pub anomalies_detected: usize,
1277    pub average_render_time: Duration,
1278    pub peak_memory_usage: f32,
1279    pub total_data_processed: usize,
1280    pub quality_score: f32,
1281}
1282
1283#[derive(Debug, Clone, Serialize, Deserialize)]
1284pub struct AnomalySummary {
1285    pub total_anomalies: usize,
1286    pub anomaly_types: HashMap<VisualizationAnomalyType, usize>,
1287    pub severity_distribution: HashMap<AnomalySeverity, usize>,
1288    pub frames_with_anomalies: usize,
1289}
1290
1291#[derive(Debug, Clone, Serialize, Deserialize)]
1292pub struct RealTimeVisualizationState {
1293    pub current_frame: Option<VisualizationFrame>,
1294    /// Frames per second measured over the frames still in the buffer, or
1295    /// `None` with fewer than two frames to measure an interval between.
1296    pub frame_rate: Option<f32>,
1297    pub render_performance: RenderPerformance,
1298    pub buffer_status: BufferStatus,
1299    pub active_visualizations: Vec<String>,
1300}
1301
1302#[derive(Debug, Clone, Serialize, Deserialize)]
1303pub struct RenderPerformance {
1304    /// Frames per second measured over the buffered frames, or `None` with
1305    /// fewer than two frames.
1306    pub frames_per_second: Option<f32>,
1307    /// Mean of the render durations this monitor actually timed, or `None`
1308    /// when the buffer is empty.
1309    pub average_render_time: Option<Duration>,
1310    /// Frames dropped. `None` -- this monitor is handed completed frames and
1311    /// never observes a drop, so it cannot count them.
1312    pub dropped_frames: Option<usize>,
1313    /// Render quality score. `None` -- no quality model is evaluated over the
1314    /// rendered output.
1315    pub render_quality: Option<f32>,
1316}
1317
1318#[derive(Debug, Clone, Serialize, Deserialize)]
1319pub struct BufferStatus {
1320    pub current_size: usize,
1321    pub maximum_size: usize,
1322    pub utilization: f32,
1323    pub overflow_count: usize,
1324}
1325
1326#[derive(Debug, Clone, Serialize, Deserialize)]
1327pub struct InteractiveVisualization {
1328    pub visualization_id: String,
1329    pub visualization_type: InteractiveVisualizationType,
1330    pub html_content: String,
1331    pub javascript_code: String,
1332    pub css_styles: String,
1333    pub data_json: String,
1334}
1335
1336#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1337pub enum InteractiveVisualizationType {
1338    Dashboard,
1339    Timeline,
1340    FlowGraph,
1341    TensorExplorer,
1342    AttentionViewer,
1343    PerformanceMonitor,
1344}
1345
1346// Implementation stubs for helper components
1347
1348impl VisualizationRenderer {
1349    fn new(_config: &InferenceVisualizerConfig) -> Result<Self> {
1350        Ok(Self {
1351            tensor_renderer: TensorRenderer,
1352            attention_renderer: AttentionRenderer,
1353            flow_renderer: FlowRenderer,
1354            performance_renderer: PerformanceRenderer,
1355            composite_renderer: CompositeRenderer,
1356        })
1357    }
1358
1359    fn render_tensor(&self, name: &str, tensor: &Tensor) -> Result<TensorVisualization> {
1360        let data = tensor.data()?;
1361        let shape = tensor.shape().to_vec();
1362
1363        let statistics = TensorStatistics {
1364            mean: data.iter().sum::<f32>() / data.len() as f32,
1365            std_dev: 0.0, // Would calculate actual std dev
1366            min_value: data.iter().fold(f32::INFINITY, |acc, &val| acc.min(val)),
1367            max_value: data.iter().fold(f32::NEG_INFINITY, |acc, &val| acc.max(val)),
1368            zero_count: data.iter().filter(|&&val| val == 0.0).count(),
1369            nan_count: data.iter().filter(|&&val| val.is_nan()).count(),
1370            inf_count: data.iter().filter(|&&val| val.is_infinite()).count(),
1371            sparsity: data.iter().filter(|&&val| val == 0.0).count() as f32 / data.len() as f32,
1372        };
1373
1374        Ok(TensorVisualization {
1375            name: name.to_string(),
1376            shape,
1377            visualization_type: TensorVisualizationType::Heatmap,
1378            data: VisualizationData {
1379                data_points: data,
1380                dimensions: tensor.shape().to_vec(),
1381                value_range: (statistics.min_value, statistics.max_value),
1382                normalized_data: None,
1383            },
1384            statistics,
1385            color_mapping: ColorMapping {
1386                scheme: ColorScheme::Viridis,
1387                min_color: [0, 0, 0],
1388                max_color: [255, 255, 255],
1389                special_colors: HashMap::new(),
1390            },
1391            anomaly_highlights: Vec::new(),
1392        })
1393    }
1394
1395    fn render_attention(
1396        &self,
1397        layer_name: &str,
1398        head_idx: usize,
1399        weights: &Tensor,
1400    ) -> Result<AttentionVisualization> {
1401        let shape = weights.shape();
1402        let seq_len = if shape.len() >= 2 { shape[shape.len() - 1] } else { 0 };
1403
1404        // The real attention weights, read out of the tensor the caller
1405        // supplied. The previous line emitted a uniform 0.5 matrix, so every
1406        // rendered attention map was identical and showed nothing about the
1407        // model. The last `seq_len * seq_len` elements are the requested
1408        // head's map for tensors shaped [.., seq, seq].
1409        let values = weights.to_vec_f32()?;
1410        let matrix_data = if seq_len > 0 && values.len() >= seq_len * seq_len {
1411            let head_offset = values.len() - seq_len * seq_len;
1412            (0..seq_len)
1413                .map(|row| {
1414                    let start = head_offset + row * seq_len;
1415                    values[start..start + seq_len].to_vec()
1416                })
1417                .collect()
1418        } else {
1419            return Err(TrustformersError::invalid_input(format!(
1420                "attention visualization needs a [.., {seq_len}, {seq_len}] weight tensor; got \
1421                 shape {shape:?} with {} elements",
1422                values.len()
1423            ))
1424            .into());
1425        };
1426
1427        Ok(AttentionVisualization {
1428            layer_name: layer_name.to_string(),
1429            head_index: head_idx,
1430            attention_matrix: AttentionMatrix {
1431                matrix_data,
1432                sequence_length: seq_len,
1433                head_dim: shape.get(shape.len().saturating_sub(2)).copied().unwrap_or(64),
1434                attention_type: AttentionType::SelfAttention,
1435            },
1436            attention_flow: None,
1437            head_specialization: None,
1438            sequence_info: SequenceInfo {
1439                sequence_length: seq_len,
1440                token_types: vec!["token".to_string(); seq_len],
1441                special_tokens: Vec::new(),
1442            },
1443        })
1444    }
1445
1446    fn render_flow(
1447        &self,
1448        _input_tensors: &[Tensor],
1449        _output_tensors: &[Tensor],
1450        _intermediate_tensors: &[(&str, &Tensor)],
1451    ) -> Result<FlowVisualization> {
1452        Ok(FlowVisualization {
1453            data_flow: Some(DataFlowGraph {
1454                nodes: Vec::new(),
1455                edges: Vec::new(),
1456                flow_metrics: FlowMetrics {
1457                    total_flow_rate: 1.0,
1458                    average_latency: Duration::from_millis(10),
1459                    bottleneck_count: 0,
1460                    flow_efficiency: 0.95,
1461                },
1462            }),
1463            gradient_flow: None,
1464            computation_graph: None,
1465            bottlenecks: Vec::new(),
1466            flow_statistics: FlowStatistics {
1467                total_operations: 10,
1468                critical_path_length: Duration::from_millis(50),
1469                parallelization_factor: 2.0,
1470                memory_efficiency: 0.8,
1471                compute_efficiency: 0.9,
1472            },
1473        })
1474    }
1475
1476    fn render_performance(
1477        &self,
1478        metrics: &MobileMetricsSnapshot,
1479    ) -> Result<PerformanceVisualization> {
1480        Ok(PerformanceVisualization {
1481            real_time_metrics: MetricsVisualization {
1482                cpu_timeline: metrics
1483                    .cpu
1484                    .as_ref()
1485                    .map(|cpu| vec![(metrics.timestamp, cpu.usage_percent)])
1486                    .unwrap_or_default(),
1487                memory_timeline: metrics
1488                    .memory
1489                    .as_ref()
1490                    .map(|memory| vec![(metrics.timestamp, memory.heap_used_mb)])
1491                    .unwrap_or_default(),
1492                gpu_timeline: metrics
1493                    .gpu
1494                    .as_ref()
1495                    .map(|gpu| vec![(metrics.timestamp, gpu.usage_percent)])
1496                    .unwrap_or_default(),
1497                inference_timeline: vec![(
1498                    metrics.timestamp,
1499                    metrics.inference.avg_latency_ms as f32,
1500                )],
1501                current_values: {
1502                    let mut values = HashMap::new();
1503                    // Only measured families contribute a key.
1504                    if let Some(cpu) = metrics.cpu.as_ref() {
1505                        values.insert("cpu_usage".to_string(), cpu.usage_percent);
1506                    }
1507                    if let Some(memory) = metrics.memory.as_ref() {
1508                        values.insert("memory_usage".to_string(), memory.heap_used_mb);
1509                    }
1510                    if let Some(gpu) = metrics.gpu.as_ref() {
1511                        values.insert("gpu_usage".to_string(), gpu.usage_percent);
1512                    }
1513                    values
1514                },
1515            },
1516            memory_visualization: MemoryVisualization {
1517                memory_breakdown: {
1518                    // Only the segments that were actually measured appear.
1519                    let mut breakdown = HashMap::new();
1520                    if let Some(memory) = metrics.memory.as_ref() {
1521                        breakdown.insert("resident".to_string(), memory.heap_used_mb);
1522                        if let Some(native_mb) = memory.native_used_mb {
1523                            breakdown.insert("native".to_string(), native_mb);
1524                        }
1525                        if let Some(graphics_mb) = memory.graphics_used_mb {
1526                            breakdown.insert("graphics".to_string(), graphics_mb);
1527                        }
1528                    }
1529                    breakdown
1530                },
1531                memory_timeline: metrics
1532                    .memory
1533                    .as_ref()
1534                    .map(|memory| {
1535                        vec![(
1536                            metrics.timestamp,
1537                            MemorySnapshot {
1538                                heap_used: memory.heap_used_mb,
1539                                heap_free: memory.heap_free_mb,
1540                                native_used: memory.native_used_mb,
1541                                graphics_used: memory.graphics_used_mb,
1542                            },
1543                        )]
1544                    })
1545                    .unwrap_or_default(),
1546                allocation_patterns: Vec::new(),
1547                leak_indicators: Vec::new(),
1548            },
1549            timing_breakdown: TimingVisualization {
1550                operation_timings: Vec::new(),
1551                timing_breakdown: HashMap::new(),
1552                critical_path: Vec::new(),
1553                optimization_opportunities: Vec::new(),
1554            },
1555            thermal_visualization: ThermalVisualization {
1556                temperature_timeline: metrics
1557                    .thermal
1558                    .as_ref()
1559                    .map(|thermal| vec![(metrics.timestamp, thermal.temperature_c)])
1560                    .unwrap_or_default(),
1561                thermal_zones: Vec::new(),
1562                throttling_events: Vec::new(),
1563                // A peak prediction needs a thermal model fitted to a
1564                // temperature history; a single sample plus a fixed "+5 C in
1565                // 60 s at 0.7 confidence" was an invented forecast, not one.
1566                thermal_prediction: None,
1567            },
1568            // A trend needs a series. `render_performance` is handed a single
1569            // snapshot, so there is no slope, strength or efficiency figure to
1570            // report; the previous body emitted four trends with a fixed
1571            // `trend_strength: 0.1` and a fixed efficiency `current_value` of
1572            // 0.85.
1573            performance_trends: None,
1574        })
1575    }
1576
1577    fn generate_interactive(
1578        &self,
1579        _frames: &[VisualizationFrame],
1580    ) -> Result<InteractiveVisualization> {
1581        Ok(InteractiveVisualization {
1582            visualization_id: "interactive_viz".to_string(),
1583            visualization_type: InteractiveVisualizationType::Dashboard,
1584            html_content: "<div>Interactive Visualization</div>".to_string(),
1585            javascript_code: "// JavaScript code".to_string(),
1586            css_styles: "/* CSS styles */".to_string(),
1587            data_json: "{}".to_string(),
1588        })
1589    }
1590}
1591
1592impl VisualizationAnalyzer {
1593    fn new(_config: &InferenceVisualizerConfig) -> Result<Self> {
1594        Ok(Self {
1595            pattern_detector: PatternDetector,
1596            anomaly_detector: VisualizationAnomalyDetector,
1597            quality_assessor: QualityAssessor,
1598        })
1599    }
1600
1601    fn detect_anomalies(
1602        &self,
1603        _tensor_visualizations: &[TensorVisualization],
1604        _attention_visualizations: &[AttentionVisualization],
1605        _flow_visualization: &Option<FlowVisualization>,
1606        _performance_visualization: &Option<PerformanceVisualization>,
1607    ) -> Result<Vec<VisualizationAnomaly>> {
1608        Ok(Vec::new()) // Would implement actual anomaly detection
1609    }
1610
1611    fn assess_quality(
1612        &self,
1613        _tensor_visualizations: &[TensorVisualization],
1614    ) -> Result<QualityMetrics> {
1615        Ok(QualityMetrics {
1616            render_quality: 0.9,
1617            data_accuracy: 0.95,
1618            visual_clarity: 0.85,
1619            information_density: 0.8,
1620            performance_impact: 0.1,
1621        })
1622    }
1623}
1624
1625impl VisualizationExportManager {
1626    fn new(_config: VisualizationExportConfig) -> Result<Self> {
1627        Ok(Self { config: _config })
1628    }
1629
1630    fn export_frame(&self, _frame: &VisualizationFrame) -> Result<String> {
1631        Ok("/tmp/visualization_frame.png".to_string())
1632    }
1633
1634    fn export_session(&self, _report: &VisualizationSessionReport) -> Result<String> {
1635        Ok("/tmp/visualization_session.html".to_string())
1636    }
1637}
1638
1639struct VisualizationExportManager {
1640    config: VisualizationExportConfig,
1641}
1642
1643impl VisualizationSession {
1644    fn new() -> Result<Self> {
1645        Ok(Self {
1646            session_id: format!(
1647                "vis_session_{}",
1648                SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_millis()
1649            ),
1650            start_time: Instant::now(),
1651            frame_count: 0,
1652            total_render_time: Duration::from_millis(0),
1653            session_statistics: SessionStatistics {
1654                frames_generated: 0,
1655                anomalies_detected: 0,
1656                average_render_time: Duration::from_millis(0),
1657                peak_memory_usage: 0.0,
1658                total_data_processed: 0,
1659                quality_score: 0.0,
1660            },
1661        })
1662    }
1663
1664    fn start(&mut self, _model_id: &str) -> Result<()> {
1665        self.start_time = Instant::now();
1666        Ok(())
1667    }
1668
1669    fn end(&mut self) -> Result<()> {
1670        if self.frame_count > 0 {
1671            self.session_statistics.average_render_time =
1672                self.total_render_time / self.frame_count as u32;
1673        }
1674        Ok(())
1675    }
1676
1677    fn update_frame_stats(&mut self, frame: &VisualizationFrame) {
1678        self.frame_count += 1;
1679        self.total_render_time += frame.metadata.rendering_duration;
1680        self.session_statistics.frames_generated += 1;
1681        self.session_statistics.anomalies_detected += frame.anomalies.len();
1682
1683        if let Some(memory_usage_mb) = frame.metadata.memory_usage_mb {
1684            if memory_usage_mb > self.session_statistics.peak_memory_usage {
1685                self.session_statistics.peak_memory_usage = memory_usage_mb;
1686            }
1687        }
1688    }
1689
1690    fn get_duration(&self) -> Duration {
1691        self.start_time.elapsed()
1692    }
1693}
1694
1695impl RealTimeVisualizationMonitor {
1696    fn new(config: RealTimeVisualizationConfig) -> Result<Self> {
1697        Ok(Self {
1698            config,
1699            frame_buffer: VecDeque::new(),
1700            render_pipeline: RenderPipeline,
1701            performance_tracker: VisualizationPerformanceTracker,
1702        })
1703    }
1704
1705    fn start(&mut self) -> Result<()> {
1706        tracing::info!("Started real-time visualization monitor");
1707        Ok(())
1708    }
1709
1710    fn stop(&mut self) -> Result<()> {
1711        tracing::info!("Stopped real-time visualization monitor");
1712        Ok(())
1713    }
1714
1715    fn update_frame(&mut self, frame: &VisualizationFrame) -> Result<()> {
1716        self.frame_buffer.push_back(frame.clone());
1717
1718        if self.frame_buffer.len() > self.config.max_history_frames {
1719            self.frame_buffer.pop_front();
1720        }
1721
1722        Ok(())
1723    }
1724
1725    /// Current monitor state, computed from the buffered frames.
1726    ///
1727    /// The previous body reported a fixed 30 fps, a fixed 16 ms mean render
1728    /// time, zero dropped frames and a 0.9 quality score on every call, none
1729    /// of which anything had measured.
1730    fn get_current_state(&self) -> Result<RealTimeVisualizationState> {
1731        // Real mean of the render durations recorded on the buffered frames.
1732        let average_render_time = if self.frame_buffer.is_empty() {
1733            None
1734        } else {
1735            let total: Duration =
1736                self.frame_buffer.iter().map(|frame| frame.metadata.rendering_duration).sum();
1737            Some(total / self.frame_buffer.len() as u32)
1738        };
1739
1740        // Real frame rate from the span between the oldest and newest buffered
1741        // frame timestamps (milliseconds since the Unix epoch).
1742        let frames_per_second = match (self.frame_buffer.front(), self.frame_buffer.back()) {
1743            (Some(oldest), Some(newest)) if self.frame_buffer.len() > 1 => {
1744                let span_ms = newest.timestamp.saturating_sub(oldest.timestamp);
1745                if span_ms > 0 {
1746                    Some((self.frame_buffer.len() - 1) as f32 * 1000.0 / span_ms as f32)
1747                } else {
1748                    None
1749                }
1750            },
1751            _ => None,
1752        };
1753
1754        Ok(RealTimeVisualizationState {
1755            current_frame: self.frame_buffer.back().cloned(),
1756            frame_rate: frames_per_second,
1757            render_performance: RenderPerformance {
1758                frames_per_second,
1759                average_render_time,
1760                // Frames arrive here already rendered, so a drop is not
1761                // observable, and no quality model runs over the output.
1762                dropped_frames: None,
1763                render_quality: None,
1764            },
1765            buffer_status: BufferStatus {
1766                current_size: self.frame_buffer.len(),
1767                maximum_size: self.config.max_history_frames,
1768                utilization: self.frame_buffer.len() as f32 / self.config.max_history_frames as f32,
1769                overflow_count: 0,
1770            },
1771            active_visualizations: vec!["tensor".to_string(), "performance".to_string()],
1772        })
1773    }
1774}
1775
1776// Zero-sized marker fields. Each is held by one of the types above purely to
1777// name a responsibility; none carries state and none is dispatched through, so
1778// the corresponding rendering/analysis is done inline by the owning type's
1779// methods. They produce no data, invented or otherwise -- kept because the
1780// field names document the pipeline's stages.
1781struct TensorRenderer;
1782struct AttentionRenderer;
1783struct FlowRenderer;
1784struct PerformanceRenderer;
1785struct CompositeRenderer;
1786struct PatternDetector;
1787struct VisualizationAnomalyDetector;
1788struct QualityAssessor;
1789struct RenderPipeline;
1790struct VisualizationPerformanceTracker;
1791
1792#[cfg(test)]
1793mod tests {
1794    use super::*;
1795
1796    #[test]
1797    fn test_visualizer_creation() {
1798        let config = InferenceVisualizerConfig::default();
1799        let visualizer = MobileInferenceVisualizer::new(config);
1800        assert!(visualizer.is_ok());
1801    }
1802
1803    #[test]
1804    fn test_visualization_config() {
1805        let config = InferenceVisualizerConfig::default();
1806        assert!(config.enabled);
1807        assert_eq!(config.mode, VisualizationMode::Lightweight);
1808        assert!(config.tensor_visualization.enabled);
1809        assert!(config.real_time_config.enabled);
1810    }
1811
1812    #[test]
1813    fn test_tensor_visualization_types() {
1814        let viz_type = TensorVisualizationType::Heatmap;
1815        assert_eq!(viz_type, TensorVisualizationType::Heatmap);
1816
1817        let color_scheme = ColorScheme::Viridis;
1818        assert_eq!(color_scheme, ColorScheme::Viridis);
1819    }
1820
1821    #[test]
1822    fn test_attention_patterns() {
1823        let pattern = AttentionPatternType::Diagonal;
1824        assert_eq!(pattern, AttentionPatternType::Diagonal);
1825
1826        let attention_type = AttentionType::SelfAttention;
1827        assert_eq!(attention_type, AttentionType::SelfAttention);
1828    }
1829
1830    #[test]
1831    fn test_visualization_frame() {
1832        let frame = VisualizationFrame {
1833            frame_id: "test_frame".to_string(),
1834            timestamp: 0,
1835            model_id: "test_model".to_string(),
1836            inference_step: 0,
1837            tensor_visualizations: Vec::new(),
1838            attention_visualizations: Vec::new(),
1839            flow_visualization: None,
1840            performance_visualization: None,
1841            anomalies: Vec::new(),
1842            metadata: FrameMetadata {
1843                inference_duration: Some(Duration::from_millis(50)),
1844                rendering_duration: Duration::from_millis(10),
1845                memory_usage_mb: Some(128.0),
1846                cpu_usage_percent: Some(25.0),
1847                gpu_usage_percent: Some(40.0),
1848                quality_metrics: QualityMetrics {
1849                    render_quality: 0.9,
1850                    data_accuracy: 0.95,
1851                    visual_clarity: 0.85,
1852                    information_density: 0.8,
1853                    performance_impact: 0.1,
1854                },
1855            },
1856        };
1857
1858        assert_eq!(frame.frame_id, "test_frame");
1859        assert_eq!(frame.inference_step, 0);
1860    }
1861}