torsh-nn 0.1.2

Neural network modules for ToRSh with PyTorch-compatible API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! Module trait ergonomic extensions
//!
//! This module provides additional ergonomic helpers and utilities for the Module trait,
//! following Rust best practices for trait extension patterns.

use crate::Module;
use torsh_core::device::DeviceType;
use torsh_core::error::Result;
use torsh_tensor::Tensor;

#[cfg(feature = "std")]
use std::collections::HashMap;

#[cfg(not(feature = "std"))]
use hashbrown::HashMap;

/// Extension trait providing additional ergonomic methods for Module
///
/// This trait is automatically implemented for all types that implement Module,
/// providing additional convenience methods without requiring changes to existing code.
///
/// # Design Philosophy
///
/// This extension follows Rust's extension trait pattern to:
/// - Add functionality without breaking backward compatibility
/// - Keep the core Module trait focused on essential methods
/// - Provide advanced features for users who need them
/// - Enable fluent/builder-style APIs
pub trait ModuleExt: Module {
    // === Fluent API / Builder Pattern Methods ===

    /// Chain forward pass with a transformation function
    ///
    /// This enables functional-style chaining of operations.
    ///
    /// # Arguments
    /// * `input` - Input tensor
    /// * `f` - Transformation function to apply to output
    ///
    /// # Returns
    /// * `Result<Tensor>` - Transformed output
    ///
    /// # Example
    /// ```ignore
    /// let output = layer.and_then(&input, |x| x.relu())?;
    /// ```
    fn and_then<F>(&self, input: &Tensor, f: F) -> Result<Tensor>
    where
        F: FnOnce(Tensor) -> Result<Tensor>,
    {
        let output = self.forward(input)?;
        f(output)
    }

    /// Apply module and map the output with a function
    ///
    /// Similar to `and_then` but for non-failable transformations.
    ///
    /// # Arguments
    /// * `input` - Input tensor
    /// * `f` - Mapping function
    ///
    /// # Returns
    /// * `Result<Tensor>` - Mapped output
    fn map<F>(&self, input: &Tensor, f: F) -> Result<Tensor>
    where
        F: FnOnce(Tensor) -> Tensor,
    {
        let output = self.forward(input)?;
        Ok(f(output))
    }

    /// Forward pass with input transformation
    ///
    /// Apply a transformation to the input before forwarding.
    ///
    /// # Arguments
    /// * `input` - Input tensor
    /// * `f` - Input transformation function
    ///
    /// # Returns
    /// * `Result<Tensor>` - Module output
    fn with_input<F>(&self, input: &Tensor, f: F) -> Result<Tensor>
    where
        F: FnOnce(&Tensor) -> Result<Tensor>,
    {
        let transformed = f(input)?;
        self.forward(&transformed)
    }

    // === Inspection and Debugging Methods ===

    /// Get human-readable summary of the module
    ///
    /// # Returns
    /// * `String` - Formatted module summary
    fn summary(&self) -> String {
        let info = self.module_info();
        format!(
            "Module: {}\n\
             Training: {}\n\
             Parameters: {} ({} trainable)\n\
             Memory: {:.2} MB\n\
             Children: {}",
            info.name,
            info.training,
            info.parameter_count,
            info.trainable_parameter_count,
            info.memory_usage_bytes as f64 / (1024.0 * 1024.0),
            info.children_count
        )
    }

    /// Print module summary to stdout
    fn print_summary(&self) {
        println!("{}", self.summary());
    }

    /// Get parameter statistics
    ///
    /// # Returns
    /// * `ParameterStats` - Statistical information about parameters
    fn parameter_stats(&self) -> ParameterStats {
        let params = self.all_parameters();
        let mut total_params = 0;
        let mut trainable_params = 0;
        let mut frozen_params = 0;
        let mut total_memory = 0;

        for param in params.values() {
            let numel = param.numel().unwrap_or(0);
            total_params += numel;
            total_memory += numel * 4; // Assume f32

            if param.requires_grad() {
                trainable_params += numel;
            } else {
                frozen_params += numel;
            }
        }

        ParameterStats {
            total_parameters: total_params,
            trainable_parameters: trainable_params,
            frozen_parameters: frozen_params,
            total_memory_bytes: total_memory,
            parameter_count: params.len(),
        }
    }

    /// Check if module has NaN or Inf in parameters
    ///
    /// # Returns
    /// * `bool` - true if all parameters are finite
    fn has_finite_parameters(&self) -> bool {
        self.all_parameters()
            .values()
            .all(|p| p.is_finite().unwrap_or(false))
    }

    /// Get list of parameter names
    ///
    /// # Returns
    /// * `Vec<String>` - Sorted list of parameter names
    fn parameter_names(&self) -> Vec<String> {
        let mut names: Vec<String> = self.all_named_parameters().keys().cloned().collect();
        names.sort();
        names
    }

    /// Get parameter by name
    ///
    /// # Arguments
    /// * `name` - Parameter name
    ///
    /// # Returns
    /// * `Option<Parameter>` - Parameter if found
    fn get_parameter(&self, name: &str) -> Option<crate::Parameter> {
        self.all_named_parameters().get(name).cloned()
    }

    // === Training Utilities ===

    /// Freeze specific parameters by name pattern
    ///
    /// # Arguments
    /// * `pattern` - String pattern to match parameter names
    ///
    /// # Returns
    /// * `usize` - Number of parameters frozen
    ///
    /// # Note
    /// This method currently returns a count but doesn't actually freeze parameters
    /// because Parameter's requires_grad is immutable. This is a placeholder for
    /// future implementation when mutable parameter access is available.
    fn freeze_matching(&mut self, pattern: &str) -> usize {
        let mut count = 0;
        for (name, _param) in self.all_named_parameters() {
            if name.contains(pattern) {
                // TODO: Implement actual freezing when Parameter supports it
                count += 1;
            }
        }
        count
    }

    /// Unfreeze specific parameters by name pattern
    ///
    /// # Arguments
    /// * `pattern` - String pattern to match parameter names
    ///
    /// # Returns
    /// * `usize` - Number of parameters unfrozen
    ///
    /// # Note
    /// This method currently returns a count but doesn't actually unfreeze parameters
    /// because Parameter's requires_grad is immutable. This is a placeholder for
    /// future implementation when mutable parameter access is available.
    fn unfreeze_matching(&mut self, pattern: &str) -> usize {
        let mut count = 0;
        for (name, _param) in self.all_named_parameters() {
            if name.contains(pattern) {
                // TODO: Implement actual unfreezing when Parameter supports it
                count += 1;
            }
        }
        count
    }

    /// Get list of frozen parameters
    ///
    /// # Returns
    /// * `Vec<String>` - Names of frozen parameters
    fn frozen_parameters(&self) -> Vec<String> {
        self.all_named_parameters()
            .into_iter()
            .filter(|(_, p)| !p.requires_grad())
            .map(|(name, _)| name)
            .collect()
    }

    /// Get list of trainable parameters
    ///
    /// # Returns
    /// * `Vec<String>` - Names of trainable parameters
    fn trainable_parameters(&self) -> Vec<String> {
        self.all_named_parameters()
            .into_iter()
            .filter(|(_, p)| p.requires_grad())
            .map(|(name, _)| name)
            .collect()
    }

    // === Advanced Operations ===

    /// Clone module parameters into a new state dict
    ///
    /// # Returns
    /// * `HashMap<String, Tensor>` - Cloned state dictionary
    fn clone_state_dict(&self) -> HashMap<String, Tensor> {
        self.state_dict()
    }

    /// Apply a function to all parameters
    ///
    /// # Arguments
    /// * `f` - Function to apply to each parameter
    fn apply_to_parameters<F>(&self, mut f: F)
    where
        F: FnMut(&str, &crate::Parameter),
    {
        for (name, param) in self.all_named_parameters() {
            f(&name, &param);
        }
    }

    /// Count parameters by layer type
    ///
    /// # Returns
    /// * `HashMap<String, usize>` - Parameter count per layer type
    fn parameters_by_type(&self) -> HashMap<String, usize> {
        let mut counts = HashMap::new();

        for (name, param) in self.all_named_parameters() {
            // Extract layer type from name (first component)
            let layer_type = name.split('.').next().unwrap_or("unknown").to_string();

            let numel = param.numel().unwrap_or(0);
            *counts.entry(layer_type).or_insert(0) += numel;
        }

        counts
    }

    /// Validate module configuration
    ///
    /// Performs comprehensive validation of module state.
    ///
    /// # Returns
    /// * `Result<ValidationReport>` - Validation results
    fn validate(&self) -> Result<ValidationReport> {
        let mut report = ValidationReport::default();

        // Check for parameters
        if !self.has_parameters() {
            report.warnings.push("Module has no parameters".to_string());
        }

        // Check for finite parameters
        if !self.has_finite_parameters() {
            report
                .errors
                .push("Module has non-finite parameters (NaN or Inf)".to_string());
        }

        // Check memory usage
        let memory_mb = self.memory_usage_mb();
        if memory_mb > 1024.0 {
            report
                .warnings
                .push(format!("Large memory usage: {:.2} GB", memory_mb / 1024.0));
        }

        // Check parameter count
        let param_count = self.num_parameters();
        if param_count > 100_000_000 {
            report
                .warnings
                .push(format!("Very large model: {} parameters", param_count));
        }

        report.is_valid = report.errors.is_empty();
        Ok(report)
    }

    /// Get device of parameters (if consistent)
    ///
    /// # Returns
    /// * `Option<DeviceType>` - Device if all parameters are on same device
    ///
    /// # Note
    /// Currently returns None as Parameter doesn't expose device information.
    /// This is a placeholder for future implementation.
    fn device(&self) -> Option<DeviceType> {
        // TODO: Implement when Parameter exposes device information
        // For now, assume CPU as default
        if self.has_parameters() {
            Some(DeviceType::Cpu)
        } else {
            None
        }
    }

    /// Check if all parameters are on CPU
    ///
    /// # Returns
    /// * `bool` - true if all parameters on CPU
    fn is_cpu(&self) -> bool {
        self.device() == Some(DeviceType::Cpu)
    }

    /// Check if all parameters are on CUDA device
    ///
    /// # Returns
    /// * `bool` - true if all parameters on CUDA
    fn is_cuda(&self) -> bool {
        matches!(self.device(), Some(DeviceType::Cuda(_)))
    }
}

// Automatically implement ModuleExt for all types that implement Module
impl<T: Module + ?Sized> ModuleExt for T {}

// === Supporting Types ===

/// Parameter statistics for a module
#[derive(Debug, Clone)]
pub struct ParameterStats {
    /// Total number of parameter elements
    pub total_parameters: usize,
    /// Number of trainable parameter elements
    pub trainable_parameters: usize,
    /// Number of frozen parameter elements
    pub frozen_parameters: usize,
    /// Total memory usage in bytes
    pub total_memory_bytes: usize,
    /// Number of distinct parameters
    pub parameter_count: usize,
}

impl ParameterStats {
    /// Get memory usage in megabytes
    pub fn memory_mb(&self) -> f64 {
        self.total_memory_bytes as f64 / (1024.0 * 1024.0)
    }

    /// Get memory usage in gigabytes
    pub fn memory_gb(&self) -> f64 {
        self.memory_mb() / 1024.0
    }

    /// Get percentage of parameters that are trainable
    pub fn trainable_percentage(&self) -> f64 {
        if self.total_parameters == 0 {
            0.0
        } else {
            (self.trainable_parameters as f64 / self.total_parameters as f64) * 100.0
        }
    }
}

/// Validation report for a module
#[derive(Debug, Clone, Default)]
pub struct ValidationReport {
    /// Whether the module is valid
    pub is_valid: bool,
    /// List of errors found
    pub errors: Vec<String>,
    /// List of warnings
    pub warnings: Vec<String>,
}

impl ValidationReport {
    /// Check if validation passed without errors
    pub fn passed(&self) -> bool {
        self.is_valid && self.errors.is_empty()
    }

    /// Get total number of issues (errors + warnings)
    pub fn issue_count(&self) -> usize {
        self.errors.len() + self.warnings.len()
    }

    /// Format as human-readable string
    pub fn format(&self) -> String {
        let mut result = String::new();

        result.push_str(&format!(
            "Validation: {}\n",
            if self.is_valid { "PASSED" } else { "FAILED" }
        ));

        if !self.errors.is_empty() {
            result.push_str("\nErrors:\n");
            for error in &self.errors {
                result.push_str(&format!("  - {}\n", error));
            }
        }

        if !self.warnings.is_empty() {
            result.push_str("\nWarnings:\n");
            for warning in &self.warnings {
                result.push_str(&format!("  - {}\n", warning));
            }
        }

        result
    }
}

#[cfg(test)]
mod tests {

    // Tests would go here - skipped for brevity
}