1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
//! # ToRSh Utilities
//!
//! `torsh-utils` provides essential utility functions and tools for the ToRSh deep learning framework.
//! This crate contains functionality for development, deployment, profiling, and model management.
//!
//! ## Features
//!
//! ### 🔧 Development Tools
//! - **Benchmarking**: Comprehensive model performance analysis with timing and memory tracking
//! - **Profiling**: Advanced bottleneck detection with flame graphs, memory profiling, and GPU analysis
//! - **Environment Collection**: System and framework information gathering for debugging
//!
//! ### 📊 Monitoring & Visualization
//! - **TensorBoard Integration**: Compatible logging for training metrics, histograms, and graphs
//! - **Interactive Visualizations**: D3.js-based model architecture visualization
//! - **Real-time Monitoring**: Live performance metrics and memory tracking
//!
//! ### 🚀 Deployment Tools
//! - **Mobile Optimization**: Model compression, quantization, and platform-specific optimizations
//! - **C++ Extensions**: Build custom CUDA kernels and operations
//! - **Model Zoo**: Pre-trained model management with HuggingFace Hub integration
//!
//! ## Quick Start
//!
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! torsh-utils = { version = "0.1.3", features = ["tensorboard", "collect_env"] }
//! ```
//!
//! ### Basic Usage Examples
//!
//! #### Benchmarking a Model
//!
//! ```rust,no_run
//! use torsh_utils::prelude::*;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Configure benchmarking
//! let config = BenchmarkConfig {
//! warmup_iterations: 10,
//! benchmark_iterations: 100,
//! batch_sizes: vec![1, 8, 16, 32],
//! input_shapes: vec![vec![3, 224, 224]],
//! profile_memory: true,
//! ..Default::default()
//! };
//!
//! // Benchmark your model (model would be your actual neural network)
//! // let model = MyModel::new();
//! // let results = benchmark_model(&model, config)?;
//! // print_benchmark_results(&results);
//! # Ok(())
//! # }
//! ```
//!
//! #### Profiling Bottlenecks
//!
//! ```rust,no_run
//! use torsh_utils::prelude::*;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Profile model performance
//! // let model = MyModel::new();
//! // let report = profile_bottlenecks(
//! // &model,
//! // &[1, 3, 224, 224],
//! // 100,
//! // true // profile backward pass
//! // )?;
//! //
//! // // Print recommendations
//! // print_bottleneck_report(&report);
//! # Ok(())
//! # }
//! ```
//!
//! #### TensorBoard Logging
//!
//! ```rust,no_run
//! # #[cfg(feature = "tensorboard")]
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use torsh_utils::prelude::*;
//!
//! let mut writer = SummaryWriter::new("runs/experiment1")?;
//!
//! // Log training metrics
//! for epoch in 0..10 {
//! let loss = 0.5 / (epoch + 1) as f32; // Example loss
//! writer.add_scalar("loss/train", loss, Some(epoch as i64))?;
//! }
//! # Ok(())
//! # }
//! ```
//!
//! #### Mobile Optimization
//!
//! ```rust,no_run
//! use torsh_utils::prelude::*;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Configure mobile optimization
//! let config = MobileOptimizerConfig {
//! quantize: true,
//! fuse_ops: true,
//! remove_dropout: true,
//! fold_bn: true,
//! backend: MobileBackend::Cpu,
//! ..Default::default()
//! };
//!
//! // Optimize model for mobile (model would be your actual neural network)
//! // let optimized = optimize_for_mobile(&model, config)?;
//! # Ok(())
//! # }
//! ```
//!
//! #### Model Zoo Usage
//!
//! ```rust,no_run
//! use torsh_utils::prelude::*;
//! # use std::path::PathBuf;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create model zoo
//! let mut zoo = ModelZoo::new("~/.torsh/models")?;
//!
//! // Search for models
//! // let models = zoo.search_models("resnet", Some(ModelSearchQuery::new()))?;
//!
//! // Download a model
//! // let model_info = zoo.download_model("resnet50-imagenet", None)?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Module Overview
//!
//! - [`benchmark`]: Model performance benchmarking with comprehensive metrics
//! - [`bottleneck`]: Advanced profiling for performance bottleneck detection
//! - [`collect_env`]: System and environment information collection
//! - [`cpp_extension`]: C++ and CUDA extension building utilities
//! - [`mobile_optimizer`]: Mobile deployment optimization tools
//! - [`model_zoo`]: Pre-trained model repository and management
//! - [`tensorboard`]: TensorBoard-compatible logging and visualization
//!
//! ## Feature Flags
//!
//! - `tensorboard` (default): Enable TensorBoard integration
//! - `collect_env` (default): Enable environment information collection
//!
//! ## Architecture
//!
//! This crate is designed to work seamlessly with the ToRSh ecosystem:
//! - Integrates with `torsh-core` for device abstraction
//! - Uses `torsh-tensor` for tensor operations
//! - Compatible with `torsh-nn` for neural network modules
//! - Leverages `torsh-profiler` for performance profiling
//!
//! ## Best Practices
//!
//! 1. **Benchmarking**: Always use warmup iterations to avoid cold start overhead
//! 2. **Profiling**: Profile with representative workloads
//! 3. **Mobile Optimization**: Test on actual target devices
//! 4. **TensorBoard**: Use meaningful tag names for easier analysis
//! 5. **Model Zoo**: Verify checksums for downloaded models
//!
//! ## PyTorch Migration
//!
//! For users migrating from PyTorch:
//! - `SummaryWriter` is compatible with `torch.utils.tensorboard.SummaryWriter`
//! - `benchmark_model` provides similar functionality to `torch.utils.benchmark`
//! - Mobile optimization is similar to `torch.utils.mobile_optimizer`
//!
//! ## Examples
//!
//! See the `examples/` directory for complete working examples:
//! - `benchmark_model.rs`: Complete benchmarking workflow
//! - `profile_bottlenecks.rs`: Performance profiling example
//! - `mobile_optimization.rs`: Model optimization for mobile deployment
//! - `tensorboard_logging.rs`: Training visualization with TensorBoard
/// Re-export commonly used items for convenience.
///
/// This module provides quick access to the most frequently used types and functions
/// from the torsh-utils crate. Import this module to get started quickly:
///
/// ```rust
/// use torsh_utils::prelude::*;
/// ```
///
/// # Included Items
///
/// ## TensorBoard (with `tensorboard` feature)
/// - [`SummaryWriter`](crate::tensorboard::SummaryWriter): Main TensorBoard writer
/// - [`TensorBoardWriter`](crate::tensorboard::TensorBoardWriter): Enhanced writer with advanced features
///
/// ## Benchmarking
/// - [`benchmark_model`](crate::benchmark::benchmark_model): Benchmark a model
/// - [`BenchmarkConfig`](crate::benchmark::BenchmarkConfig): Benchmarking configuration
/// - [`BenchmarkResult`](crate::benchmark::BenchmarkResult): Benchmark results
///
/// ## Profiling
/// - [`profile_bottlenecks`](crate::bottleneck::profile_bottlenecks): Profile performance bottlenecks
/// - [`BottleneckReport`](crate::bottleneck::BottleneckReport): Profiling report
///
/// ## Environment
/// - [`collect_env`](crate::collect_env::collect_env): Collect environment information
/// - [`EnvironmentInfo`](crate::collect_env::EnvironmentInfo): Environment details
///
/// ## C++ Extensions
/// - [`build_cpp_extension`](crate::cpp_extension::build_cpp_extension): Build C++ extensions
/// - [`CppExtensionConfig`](crate::cpp_extension::CppExtensionConfig): Extension build configuration
///
/// ## Mobile Optimization
/// - [`optimize_for_mobile`](crate::mobile_optimizer::optimize_for_mobile): Optimize model for mobile
/// - [`ExportFormat`](crate::mobile_optimizer::ExportFormat): Mobile export formats
/// - [`MobileBackend`](crate::mobile_optimizer::MobileBackend): Target mobile backend
/// - [`MobileOptimizerConfig`](crate::mobile_optimizer::MobileOptimizerConfig): Optimization configuration
///
/// ## Model Zoo
/// - [`ModelInfo`](crate::model_zoo::ModelInfo): Model metadata
/// - [`ModelZoo`](crate::model_zoo::ModelZoo): Model repository manager