torsh-nn 0.2.0

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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# ToRSh-NN Best Practices

A comprehensive guide to writing efficient, maintainable, and idiomatic ToRSh-NN code.

## Table of Contents

1. [Code Organization]#code-organization
2. [Memory Management]#memory-management
3. [Error Handling]#error-handling
4. [Performance Optimization]#performance-optimization
5. [Testing Strategies]#testing-strategies
6. [API Design]#api-design
7. [Documentation]#documentation
8. [Common Anti-Patterns]#common-anti-patterns

---

## Code Organization

### Module Structure

**✅ DO**: Organize code into logical modules

```rust
pub mod layers {
    pub mod conv;
    pub mod linear;
    pub mod attention;
}

pub mod models {
    pub mod resnet;
    pub mod transformer;
}

pub mod utils {
    pub mod initialization;
    pub mod metrics;
}
```

**❌ DON'T**: Put everything in one file

```rust
// src/lib.rs with 5000+ lines
pub struct Linear { ... }
pub struct Conv2d { ... }
pub struct ResNet { ... }
// ... hundreds more
```

### Layer Organization

**✅ DO**: Separate concerns clearly

```rust
pub struct MyLayer {
    // Learnable parameters
    weight: Parameter,
    bias: Option<Parameter>,

    // Configuration (immutable)
    in_features: usize,
    out_features: usize,

    // State (mutable)
    training: bool,
}
```

**❌ DON'T**: Mix concerns

```rust
pub struct MyLayer {
    weight: Parameter,
    config: LayerConfig,  // Opaque configuration
    cache: Vec<Tensor>,   // Unclear purpose
}
```

---

## Memory Management

###  1: Avoid Unnecessary Clones

**✅ DO**: Use references when possible

```rust
impl Module for MyLayer {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let weight = self.weight.tensor().read();
        input.matmul(&weight.t()?)  // No clone needed
    }
}
```

**❌ DON'T**: Clone unnecessarily

```rust
impl Module for MyLayer {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let input_clone = input.clone();  // Unnecessary!
        let weight_clone = self.weight.tensor().read().clone();  // Unnecessary!
        input_clone.matmul(&weight_clone.t()?)
    }
}
```

### 2: Use Views for Reshaping

**✅ DO**: Use views to avoid data copying

```rust
fn flatten(&self, x: &Tensor) -> Result<Tensor> {
    let batch_size = x.shape().dims()[0];
    x.view(&[batch_size as i32, -1])  // No copy
}
```

**❌ DON'T**: Reshape by copying data

```rust
fn flatten(&self, x: &Tensor) -> Result<Tensor> {
    let data = x.to_vec()?;  // Copies all data!
    let batch_size = x.shape().dims()[0];
    let features = data.len() / batch_size;
    Tensor::from_vec(data, &[batch_size, features])
}
```

### 3: Reuse Buffers

**✅ DO**: Reuse pre-allocated tensors

```rust
pub struct CachedLayer {
    buffer: RefCell<Option<Tensor>>,
    output_shape: Vec<usize>,
}

impl CachedLayer {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        let mut buffer = self.buffer.borrow_mut();
        if buffer.is_none() {
            *buffer = Some(zeros(&self.output_shape)?);
        }
        // Reuse buffer
        Ok(buffer.as_ref().unwrap().clone())
    }
}
```

### 4: Parameter Sharing

**✅ DO**: Share parameters when appropriate

```rust
pub struct SiameseNetwork {
    encoder: Linear,  // Shared encoder
}

impl SiameseNetwork {
    fn forward_pair(&self, x1: &Tensor, x2: &Tensor) -> Result<(Tensor, Tensor)> {
        let h1 = self.encoder.forward(x1)?;  // Same encoder
        let h2 = self.encoder.forward(x2)?;  // Same encoder
        Ok((h1, h2))
    }
}
```

---

## Error Handling

### 1: Provide Context in Errors

**✅ DO**: Add helpful error messages

```rust
fn forward(&self, input: &Tensor) -> Result<Tensor> {
    let shape = input.shape().dims();

    if shape[shape.len() - 1] != self.in_features {
        return Err(TorshError::ShapeMismatch {
            expected: vec![self.in_features],
            got: vec![shape[shape.len() - 1]],
        }.with_context(format!(
            "Layer '{}' expected {} input features, got {}",
            self.name(), self.in_features, shape[shape.len() - 1]
        )));
    }

    // ... rest of implementation
}
```

**❌ DON'T**: Use generic errors

```rust
fn forward(&self, input: &Tensor) -> Result<Tensor> {
    let shape = input.shape().dims();

    if shape[shape.len() - 1] != self.in_features {
        return Err(TorshError::RuntimeError("Bad shape".to_string()));
    }

    // ... rest
}
```

### 2: Validate Inputs Early

**✅ DO**: Check preconditions at the start

```rust
pub fn new(in_features: usize, out_features: usize, dropout: f32) -> Result<Self> {
    if in_features == 0 {
        return Err(TorshError::InvalidArgument(
            "in_features must be positive".to_string()
        ));
    }

    if !(0.0..=1.0).contains(&dropout) {
        return Err(TorshError::InvalidArgument(
            format!("dropout must be in [0, 1], got {}", dropout)
        ));
    }

    // Continue with construction
    Ok(Self {
        // ...
    })
}
```

### 3: Use Type System for Safety

**✅ DO**: Use types to prevent errors

```rust
pub enum ActivationType {
    ReLU,
    GELU,
    Tanh,
}

pub struct LayerConfig {
    activation: ActivationType,  // Can't be invalid!
    dropout: Option<f32>,         // Explicit optionality
}
```

**❌ DON'T**: Use strings for enums

```rust
pub struct LayerConfig {
    activation: String,  // Could be anything!
    dropout: f32,        // -1 for "no dropout"?
}
```

---

## Performance Optimization

### 1: Batch Operations

**✅ DO**: Process in batches

```rust
// Process entire batch at once
let batch_output = model.forward(&batch_input)?;  // [32, 128]
```

**❌ DON'T**: Process one at a time

```rust
// Process samples individually
let mut outputs = Vec::new();
for sample in batch_input.iter() {
    outputs.push(model.forward(&sample)?);  // Slow!
}
```

### 2: Use SciRS2 Optimizations

**✅ DO**: Leverage SciRS2 features

```rust
// SciRS2 handles SIMD and parallelization automatically
use scirs2_core::ndarray::*;
use scirs2_core::random::*;

// Efficient array operations
let result = array1.dot(&array2);  // Optimized BLAS
```

### 3: Avoid Redundant Computations

**✅ DO**: Cache expensive computations

```rust
pub struct AttentionLayer {
    cached_keys: RefCell<Option<Tensor>>,
    cached_values: RefCell<Option<Tensor>>,
}

impl AttentionLayer {
    fn forward(&self, query: &Tensor, key: &Tensor, value: &Tensor) -> Result<Tensor> {
        // Cache keys and values if they don't change
        let k = if let Some(cached) = self.cached_keys.borrow().as_ref() {
            cached.clone()
        } else {
            let k = self.project_keys(key)?;
            *self.cached_keys.borrow_mut() = Some(k.clone());
            k
        };

        // ... use cached key
        Ok(output)
    }
}
```

### 4: Profile Before Optimizing

**✅ DO**: Measure performance first

```rust
use std::time::Instant;

let start = Instant::now();
let output = model.forward(&input)?;
println!("Forward pass took: {:?}", start.elapsed());

// Use proper profiling tools
#[cfg(feature = "profiling")]
use torsh_nn::profiling::Profiler;

#[cfg(feature = "profiling")]
{
    let mut profiler = Profiler::new();
    profiler.start("forward_pass");
    let output = model.forward(&input)?;
    profiler.stop("forward_pass");
    profiler.report();
}
```

---

## Testing Strategies

### 1: Test Layer Creation

**✅ DO**: Test basic construction

```rust
#[test]
fn test_layer_creation() {
    let layer = MyLayer::new(128, 64, true);
    assert!(layer.is_ok());

    let layer = layer.unwrap();
    assert_eq!(layer.in_features(), 128);
    assert_eq!(layer.out_features(), 64);
}

#[test]
fn test_invalid_dimensions() {
    let layer = MyLayer::new(0, 64, true);
    assert!(layer.is_err());  // Should reject invalid input
}
```

### 2: Test Forward Pass Shapes

**✅ DO**: Verify output dimensions

```rust
#[test]
fn test_forward_shapes() {
    let layer = MyLayer::new(128, 64, true).unwrap();

    // Test 2D input
    let input_2d = randn::<f32>(&[32, 128]).unwrap();
    let output = layer.forward(&input_2d).unwrap();
    assert_eq!(output.shape().dims(), &[32, 64]);

    // Test 3D input
    let input_3d = randn::<f32>(&[16, 10, 128]).unwrap();
    let output = layer.forward(&input_3d).unwrap();
    assert_eq!(output.shape().dims(), &[16, 10, 64]);
}
```

### 3: Test Parameter Count

**✅ DO**: Verify parameters are registered

```rust
#[test]
fn test_parameter_count() {
    let layer = MyLayer::new(128, 64, true).unwrap();
    let params = layer.parameters();

    let total: usize = params.iter()
        .map(|(_, p)| p.tensor().read().numel())
        .sum();

    // weight: 128 * 64 = 8192
    // bias: 64
    // total: 8256
    assert_eq!(total, 8256);
}
```

### 4: Test Training/Eval Modes

**✅ DO**: Verify mode switching

```rust
#[test]
fn test_training_mode() {
    let mut layer = MyLayer::new(128, 64, true).unwrap();

    assert!(layer.is_training());

    layer.eval();
    assert!(!layer.is_training());

    layer.train();
    assert!(layer.is_training());
}
```

### 5: Test Numerical Correctness

**✅ DO**: Compare with reference implementation

```rust
#[test]
fn test_numerical_correctness() {
    let layer = Linear::new(10, 5, false).unwrap();

    // Set known weights
    let weight_data = vec![1.0; 50];
    let weight = Tensor::from_vec(weight_data, &[5, 10]).unwrap();
    // ... set layer weight

    let input = ones(&[2, 10]).unwrap();
    let output = layer.forward(&input).unwrap();

    // Expected: sum of weights for each output neuron
    let expected = vec![10.0; 5];
    let output_data = output.to_vec().unwrap();

    for (got, expected) in output_data.iter().zip(expected.iter()) {
        assert!((got - expected).abs() < 1e-5);
    }
}
```

### 6: Test Gradient Flow

**✅ DO**: Verify gradients are computed

```rust
#[test]
fn test_gradient_flow() {
    let layer = Linear::new(10, 5, true).unwrap();
    let input = randn::<f32>(&[2, 10]).unwrap();

    let output = layer.forward(&input).unwrap();
    let loss = output.sum().unwrap();

    // Verify parameters require gradients
    for (_, param) in layer.parameters().iter() {
        assert!(param.requires_grad());
    }
}
```

---

## API Design

### 1: Follow Rust Conventions

**✅ DO**: Use idiomatic Rust naming

```rust
// Use snake_case for functions and variables
pub fn linear_layer(input: &Tensor) -> Result<Tensor> { ... }

// Use CamelCase for types
pub struct LinearLayer { ... }

// Use SCREAMING_SNAKE_CASE for constants
const DEFAULT_DROPOUT_RATE: f32 = 0.5;
```

### 2: Builder Pattern for Complex Construction

**✅ DO**: Use builders for many options

```rust
pub struct LayerBuilder {
    in_features: usize,
    out_features: usize,
    bias: bool,
    activation: Option<ActivationType>,
    dropout: Option<f32>,
    init_method: InitMethod,
}

impl LayerBuilder {
    pub fn new(in_features: usize, out_features: usize) -> Self {
        Self {
            in_features,
            out_features,
            bias: true,
            activation: None,
            dropout: None,
            init_method: InitMethod::kaiming_normal(),
        }
    }

    pub fn bias(mut self, bias: bool) -> Self {
        self.bias = bias;
        self
    }

    pub fn activation(mut self, activation: ActivationType) -> Self {
        self.activation = Some(activation);
        self
    }

    pub fn build(self) -> Result<MyLayer> {
        // Construct layer with all options
        MyLayer::from_builder(self)
    }
}

// Usage
let layer = LayerBuilder::new(128, 64)
    .bias(false)
    .activation(ActivationType::GELU)
    .dropout(0.1)
    .build()?;
```

### 3: Provide Convenience Constructors

**✅ DO**: Offer multiple construction methods

```rust
impl Linear {
    /// Create with defaults
    pub fn new(in_features: usize, out_features: usize, bias: bool) -> Self {
        Self::with_init(in_features, out_features, bias, InitMethod::kaiming_uniform())
    }

    /// Create with custom initialization
    pub fn with_init(
        in_features: usize,
        out_features: usize,
        bias: bool,
        init: InitMethod,
    ) -> Self {
        // ... implementation
    }

    /// Create without bias (common pattern)
    pub fn no_bias(in_features: usize, out_features: usize) -> Self {
        Self::new(in_features, out_features, false)
    }
}
```

### 4: Use Type States for Safety

**✅ DO**: Use phantom types to enforce states

```rust
pub struct Untrained;
pub struct Trained;

pub struct Model<State> {
    layers: Vec<Box<dyn Module>>,
    _state: PhantomData<State>,
}

impl Model<Untrained> {
    pub fn new() -> Self {
        // ... create model
    }

    pub fn train(self, data: &Dataset) -> Model<Trained> {
        // ... training logic
        Model {
            layers: self.layers,
            _state: PhantomData,
        }
    }
}

impl Model<Trained> {
    pub fn predict(&self, input: &Tensor) -> Result<Tensor> {
        // Only trained models can predict
        self.forward(input)
    }
}
```

---

## Documentation

### 1: Document Public APIs

**✅ DO**: Provide comprehensive documentation

```rust
/// Multi-layer perceptron for classification
///
/// This module implements a fully-connected neural network with configurable
/// hidden layers, activation functions, and dropout regularization.
///
/// # Arguments
///
/// * `input_dim` - Dimension of input features
/// * `hidden_dims` - Dimensions of hidden layers
/// * `output_dim` - Number of output classes
/// * `dropout` - Dropout probability (0.0 to 1.0)
///
/// # Examples
///
/// ```
/// use torsh_nn::MLP;
///
/// let model = MLP::new(784, vec![256, 128], 10, 0.5)?;
/// let input = randn::<f32>(&[32, 784])?;
/// let output = model.forward(&input)?;
/// assert_eq!(output.shape().dims(), &[32, 10]);
/// ```
///
/// # Panics
///
/// Panics if `dropout` is not in the range [0.0, 1.0].
pub struct MLP {
    // ...
}
```

### 2: Document Implementation Details

**✅ DO**: Explain non-obvious behavior

```rust
impl BatchNorm2d {
    /// Forward pass through batch normalization
    ///
    /// During training, normalizes using batch statistics and updates
    /// running statistics. During evaluation, uses running statistics.
    ///
    /// # Implementation Notes
    ///
    /// - Running statistics use exponential moving average
    /// - Momentum parameter controls update rate (default: 0.1)
    /// - Epsilon prevents division by zero (default: 1e-5)
    ///
    /// # Shape
    ///
    /// - Input: `(batch_size, num_features, height, width)`
    /// - Output: `(batch_size, num_features, height, width)`
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // ...
    }
}
```

### 3: Provide Examples

**✅ DO**: Include working examples

```rust
/// Apply attention mechanism to input
///
/// # Example
///
/// ```
/// use torsh_nn::Attention;
///
/// let attn = Attention::new(512, 8, 0.1)?;
/// let query = randn::<f32>(&[32, 10, 512])?;  // (batch, seq, dim)
/// let key = randn::<f32>(&[32, 20, 512])?;
/// let value = randn::<f32>(&[32, 20, 512])?;
///
/// let output = attn.forward_qkv(&query, &key, &value, None)?;
/// assert_eq!(output.shape().dims(), &[32, 10, 512]);
/// ```
pub fn forward_qkv(/* ... */) -> Result<Tensor> {
    // ...
}
```

---

## Common Anti-Patterns

### Anti-Pattern 1: Ignoring Errors

**❌ DON'T**: Use unwrap() liberally

```rust
let output = model.forward(&input).unwrap();  // Could panic!
let value = tensor.item().unwrap();  // Could panic!
```

**✅ DO**: Handle errors properly

```rust
let output = model.forward(&input)?;  // Propagate error
let value = tensor.item().map_err(|e| {
    TorshError::RuntimeError(format!("Failed to get item: {}", e))
})?;
```

### Anti-Pattern 2: Mutation Through Shared References

**❌ DON'T**: Mutate through shared references unsafely

```rust
impl Module for BadLayer {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        // ❌ Trying to mutate through &self
        self.cache = Some(input.clone());  // Won't compile!
        // ...
    }
}
```

**✅ DO**: Use interior mutability correctly

```rust
pub struct GoodLayer {
    cache: RefCell<Option<Tensor>>,
}

impl Module for GoodLayer {
    fn forward(&self, input: &Tensor) -> Result<Tensor> {
        *self.cache.borrow_mut() = Some(input.clone());
        // ...
    }
}
```

### Anti-Pattern 3: Overly Generic APIs

**❌ DON'T**: Make everything generic without reason

```rust
pub struct OverGeneric<T, U, V, W> {
    layer1: T,
    layer2: U,
    activation: V,
    dropout: W,
}
// Hard to use, hard to understand
```

**✅ DO**: Use generics judiciously

```rust
pub struct Practical {
    layer1: Linear,
    layer2: Linear,
    activation: ActivationType,  // Enum is fine
    dropout: Dropout,
}
// Easy to use, clear intent
```

### Anti-Pattern 4: Premature Optimization

**❌ DON'T**: Optimize without measuring

```rust
// Complex caching that may not help
pub struct OverOptimized {
    cache1: HashMap<String, Tensor>,
    cache2: Vec<Option<Tensor>>,
    cache3: RefCell<BTreeMap<usize, Tensor>>,
    // ... more caches
}
```

**✅ DO**: Start simple, profile, then optimize

```rust
// Simple and clear
pub struct Simple {
    layer: Linear,
}

// Add caching only if profiling shows benefit
```

---

## Checklist

Before submitting code, ensure:

- [ ] All public APIs have documentation
- [ ] Examples compile and run
- [ ] Tests cover main functionality
- [ ] Error messages are helpful
- [ ] No unnecessary clones or allocations
- [ ] Parameters are registered correctly
- [ ] Training/eval modes handled properly
- [ ] Input validation is thorough
- [ ] Code follows Rust naming conventions
- [ ] Complex logic has explanatory comments

---

## Additional Resources

- **Rust API Guidelines**: https://rust-lang.github.io/api-guidelines/
- **Layer Implementation Guide**: See `LAYER_IMPLEMENTATION_GUIDE.md`
- **Custom Module Tutorial**: See `CUSTOM_MODULE_TUTORIAL.md`
- **Performance Tuning Guide**: See `PERFORMANCE_TUNING.md`

For questions or contributions, visit: https://github.com/cool-japan/torsh