numrs2 0.3.3

A Rust implementation inspired by NumPy for numerical computing (NumRS2)
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
# Neural Network Module Guide

**NumRS2 v0.3.0 Neural Network Primitives**

This guide provides comprehensive documentation for NumRS2's neural network (`nn`) module, including architecture overview, usage patterns, performance optimization, and best practices.

---

## Table of Contents

1. [Overview]#overview
2. [Architecture]#architecture
3. [Quick Start]#quick-start
4. [Activation Functions]#activation-functions
5. [Convolution Operations]#convolution-operations
6. [Pooling Layers]#pooling-layers
7. [Normalization]#normalization
8. [Attention Mechanisms]#attention-mechanisms
9. [Loss Functions]#loss-functions
10. [SIMD Optimization]#simd-optimization
11. [Performance Tips]#performance-tips
12. [Training Patterns]#training-patterns
13. [Error Handling]#error-handling
14. [Examples]#examples
15. [API Reference]#api-reference

---

## Overview

The NumRS2 neural network module provides high-performance building blocks for deep learning applications. All operations are:

- **SIMD-optimized**: Leveraging AVX2/AVX512 (x86) and NEON (ARM)
- **Pure Rust**: No C/C++ dependencies via OxiBLAS
- **Numerically stable**: Careful handling of edge cases and overflow
- **Well-tested**: Comprehensive test coverage with property-based tests
- **SciRS2-integrated**: Following NumRS2's ecosystem policies

### Key Design Principles

1. **Performance First**: SIMD acceleration for all hot paths
2. **Numerical Stability**: Robust handling of edge cases
3. **Ergonomic API**: Clean, intuitive function signatures
4. **Zero-Cost Abstractions**: Compile-time optimization
5. **Pure Rust**: No foreign function interface overhead

---

## Architecture

### Module Structure

```
src/nn/
├── mod.rs              # Module exports and common types
├── activation.rs       # Activation functions
├── attention.rs        # Attention mechanisms
├── conv.rs            # Convolution operations
├── loss.rs            # Loss functions
├── normalization.rs   # Normalization and dropout
├── pooling.rs         # Pooling operations
└── simd_ops.rs        # SIMD-optimized kernels
```

### SCIRS2 Integration

The `nn` module strictly follows NumRS2's SCIRS2 integration policy:

```rust
// ✅ CORRECT: Use SciRS2 abstractions
use scirs2_core::ndarray::*;          // Array operations
use scirs2_core::simd_ops::*;         // SIMD operations
use scirs2_core::random::*;           // RNG for dropout
use scirs2_linalg::*;                 // Linear algebra (OxiBLAS)

// ❌ FORBIDDEN: Direct external dependencies
// use ndarray::*;                    // Use scirs2_core::ndarray
// use rand::*;                       // Use scirs2_core::random
```

### Type System

```rust
// Result type for all operations
pub type NnResult<T> = Result<T, NumRs2Error>;

// Reduction modes for loss functions
pub enum ReductionMode {
    None,   // No reduction (return per-element loss)
    Mean,   // Average over all elements
    Sum,    // Sum over all elements
}

// Padding modes for convolution
pub enum PaddingMode {
    Valid,             // No padding
    Same,              // Preserve input size
    Full,              // Maximum padding
    Explicit(usize),   // Custom padding
}

// Data format for tensors
pub enum DataFormat {
    NCHW,  // Channels first (N, C, H, W)
    NHWC,  // Channels last (N, H, W, C)
}
```

---

## Quick Start

### Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
numrs2 = "0.3.0"
scirs2-core = "0.3.0"
```

### Basic Example

```rust
use numrs2::nn::*;
use scirs2_core::ndarray::{Array1, Array2, array};

fn main() -> NnResult<()> {
    // Simple feedforward pass
    let input = array![-1.0, 0.0, 1.0, 2.0];

    // Apply activation
    let hidden = relu(&input.view())?;

    // Apply softmax
    let output = softmax(&hidden.view())?;

    println!("Output: {:?}", output);
    Ok(())
}
```

### Building a Network

```rust
use numrs2::nn::*;
use scirs2_core::ndarray::{Array1, Array2};

fn feedforward(
    input: &Array2<f64>,
    weights1: &Array2<f64>,
    weights2: &Array2<f64>,
) -> NnResult<Array2<f64>> {
    // Hidden layer: Linear + ReLU + BatchNorm
    let hidden = simd_matmul_f64(&input.view(), &weights1.view())?;
    let hidden = relu_2d(&hidden.view())?;

    let gamma = Array1::ones(hidden.ncols());
    let beta = Array1::zeros(hidden.ncols());
    let hidden = batch_norm_1d(&hidden.view(), &gamma.view(), &beta.view(), 1e-5)?;

    // Output layer: Linear + Softmax
    let output = simd_matmul_f64(&hidden.view(), &weights2.view())?;
    let output = softmax_2d(&output.view(), 1)?;

    Ok(output)
}
```

---

## Activation Functions

### ReLU and Variants

#### ReLU (Rectified Linear Unit)

**Formula**: `f(x) = max(0, x)`

```rust
use numrs2::nn::activation::*;
use scirs2_core::ndarray::array;

let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = relu(&x.view())?;
// y = [0.0, 0.0, 0.0, 1.0, 2.0]
```

**Properties**:
- Fast computation (simple comparison)
- Non-saturating for positive values
- Can cause "dying ReLU" problem (neurons output 0)
- SIMD-optimized: ~4-8x speedup

**When to use**: Default choice for hidden layers, especially in CNNs.

#### Leaky ReLU

**Formula**: `f(x) = x if x > 0 else α * x` (typically α = 0.01)

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = leaky_relu(&x.view(), 0.01)?;
// y = [-0.02, -0.01, 0.0, 1.0, 2.0]
```

**When to use**: When experiencing dying ReLU problem.

#### ELU (Exponential Linear Unit)

**Formula**: `f(x) = x if x > 0 else α(exp(x) - 1)`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = elu(&x.view(), 1.0)?;
```

**Properties**:
- Smooth negative part
- Mean activation closer to zero
- More computationally expensive

**When to use**: When you need smoother gradients than ReLU.

#### SELU (Scaled ELU)

**Formula**: `f(x) = λ * (x if x > 0 else α(exp(x) - 1))`

Constants chosen for self-normalizing properties.

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = selu(&x.view())?;
```

**Properties**:
- Self-normalizing (maintains mean and variance)
- Requires special initialization (LeCun normal)

**When to use**: Deep fully-connected networks (>4 layers).

### Smooth Activations

#### Sigmoid

**Formula**: `f(x) = 1 / (1 + exp(-x))`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = sigmoid(&x.view())?;
// y ≈ [0.119, 0.269, 0.5, 0.731, 0.881]
```

**Properties**:
- Output range: (0, 1)
- Can saturate (gradients → 0)

**When to use**: Binary classification output, gates in RNNs.

#### Tanh

**Formula**: `f(x) = tanh(x)`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = tanh(&x.view())?;
// y ≈ [-0.964, -0.762, 0.0, 0.762, 0.964]
```

**Properties**:
- Output range: (-1, 1)
- Zero-centered (better than sigmoid)

**When to use**: RNN hidden states, when zero-centered output needed.

### Modern Activations

#### GELU (Gaussian Error Linear Unit)

**Formula**: `f(x) = x * Φ(x)` where Φ is the CDF of standard normal

**Approximation**: `f(x) ≈ 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x³)))`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = gelu(&x.view())?;
```

**Properties**:
- Smooth, non-monotonic
- Stochastic regularization interpretation
- Used in BERT, GPT models

**When to use**: Transformer models, modern architectures.

#### Swish / SiLU (Sigmoid Linear Unit)

**Formula**: `f(x) = x * sigmoid(x)`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = swish(&x.view())?;
// or: let y = silu(&x.view())?;  // same function
```

**Properties**:
- Self-gating mechanism
- Smooth, non-monotonic
- Better than ReLU in many cases

**When to use**: When you need better performance than ReLU.

#### Mish

**Formula**: `f(x) = x * tanh(softplus(x))`

```rust
let x = array![-2.0, -1.0, 0.0, 1.0, 2.0];
let y = mish(&x.view())?;
```

**Properties**:
- Smooth throughout
- Better than Swish in some cases
- More expensive to compute

**When to use**: When training time is not critical and you want best accuracy.

### Probability Distributions

#### Softmax

**Formula**: `f(x)_i = exp(x_i) / Σ exp(x_j)`

```rust
let logits = array![1.0, 2.0, 3.0];
let probs = softmax(&logits.view())?;
// Sum of probs = 1.0
```

**Properties**:
- Converts logits to probabilities
- Temperature parameter available (via scaling input)
- Numerically stable implementation

**When to use**: Multi-class classification output layer.

#### Log-Softmax

**Formula**: `f(x)_i = log(exp(x_i) / Σ exp(x_j))`

```rust
let logits = array![1.0, 2.0, 3.0];
let log_probs = log_softmax(&logits.view())?;
```

**Properties**:
- More numerically stable than log(softmax(x))
- Used with negative log-likelihood loss

**When to use**: When computing log probabilities for NLL loss.

### SIMD-Optimized Variants

All activation functions have SIMD-optimized versions for f32:

```rust
use numrs2::nn::simd_ops::*;

let x = Array1::from_vec(vec![-1.0f32, 0.0, 1.0, 2.0]);

let y1 = simd_relu_f32(&x.view());        // 4-8x faster
let y2 = simd_sigmoid_f32(&x.view());     // 3-5x faster
let y3 = simd_gelu_f32(&x.view());        // 3-4x faster
let y4 = simd_swish_f32(&x.view());       // 3-5x faster
```

**Performance tip**: Use f32 for activations when precision allows (2x more data per SIMD instruction).

---

## Convolution Operations

### 1D Convolution

For sequence/time-series data.

```rust
use numrs2::nn::conv::*;
use scirs2_core::ndarray::array;

let signal = array![1.0, 2.0, 3.0, 4.0, 5.0];
let kernel = array![1.0, 0.0, -1.0];  // Edge detection

let output = conv1d(&signal.view(), &kernel.view(), 1)?;
// Applies convolution with stride 1
```

**Applications**:
- Text processing (character/word level)
- Time series analysis
- Audio signal processing

### 2D Convolution

For image/spatial data.

```rust
use numrs2::nn::conv::*;
use scirs2_core::ndarray::Array2;

let image = Array2::ones((5, 5));
let kernel = Array2::from_shape_vec(
    (3, 3),
    vec![1.0, 1.0, 1.0,
         1.0, -8.0, 1.0,
         1.0, 1.0, 1.0]
)?;  // Laplacian edge detection

let output = conv2d(&image.view(), &kernel.view(), (1, 1))?;
```

**Parameters**:
- `stride`: `(stride_h, stride_w)` - how many pixels to move
- Higher stride = smaller output, faster computation

### Padding Modes

```rust
// Valid convolution (no padding)
let output = conv2d(&image.view(), &kernel.view(), (1, 1))?;

// Explicit padding
let output = conv2d_with_padding(
    &image.view(),
    &kernel.view(),
    (1, 1),
    1  // pad by 1 on all sides
)?;
```

**Padding types**:
- **Valid**: No padding, output smaller than input
- **Same**: Pad to preserve input size (for stride=1)
- **Explicit**: Custom padding amount

### Depthwise Separable Convolution

Efficient convolution for mobile models:

```rust
let output = depthwise_conv2d(&input.view(), &kernel.view(), (1, 1))?;
```

**Benefits**:
- Fewer parameters than regular convolution
- Faster computation
- Used in MobileNet, EfficientNet

---

## Pooling Layers

Reduce spatial dimensions while preserving important features.

### Max Pooling

Extracts maximum value from each window.

```rust
use numrs2::nn::pooling::*;
use scirs2_core::ndarray::Array2;

let feature_map = Array2::from_shape_fn((4, 4), |(i, j)| (i * 4 + j) as f64);

// Pool with 2x2 window, stride 2
let output = max_pool2d(&feature_map.view(), (2, 2), (2, 2))?;
// Output: (2, 2) - downsampled by 2x
```

**Properties**:
- Preserves strongest activations
- Translation invariant
- Non-differentiable (but sub-differentiable)

**When to use**: CNNs for classification (preserves edge features).

### Average Pooling

Computes mean over each window.

```rust
let output = avg_pool2d(&feature_map.view(), (2, 2), (2, 2))?;
```

**Properties**:
- Smoother than max pooling
- All values contribute
- Differentiable

**When to use**: When you want smoother downsampling, before final classification layer.

### Adaptive Pooling

Pools to a fixed output size regardless of input size.

```rust
let input = Array2::ones((8, 8));

// Always outputs 4x4, regardless of input size
let output = adaptive_avg_pool2d(&input.view(), (4, 4))?;
```

**When to use**: When input sizes vary, or for multi-scale feature extraction.

### Global Pooling

Reduces entire spatial dimensions to single values.

```rust
// Global average: entire feature map → single value
let avg = global_avg_pool(&feature_map.view())?;

// Global max: entire feature map → single value
let max = global_max_pool(&feature_map.view())?;
```

**When to use**:
- Classifier head (replace fully-connected layers)
- Reduce parameters in CNNs
- Feature extraction

---

## Normalization

Techniques to stabilize training and improve convergence.

### Batch Normalization

Normalizes across the batch dimension.

**Formula**: `y = (x - μ_batch) / √(σ²_batch + ε) * γ + β`

```rust
use numrs2::nn::normalization::*;
use scirs2_core::ndarray::{Array1, Array2};

let x = Array2::from_shape_fn((4, 10), |(i, j)| (i + j) as f64);

// Learnable parameters (typically learned during training)
let gamma = Array1::ones(10);   // Scale
let beta = Array1::zeros(10);   // Shift
let epsilon = 1e-5;

let normalized = batch_norm_1d(&x.view(), &gamma.view(), &beta.view(), epsilon)?;
```

**Properties**:
- Stabilizes training
- Allows higher learning rates
- Acts as regularizer
- Different behavior in training vs inference

**When to use**: After convolutional or fully-connected layers in CNNs.

### Layer Normalization

Normalizes across features for each sample independently.

**Formula**: `y = (x - μ_features) / √(σ²_features + ε) * γ + β`

```rust
let normalized = layer_norm(&x.view(), &gamma.view(), &beta.view(), epsilon)?;
```

**Properties**:
- Independent of batch size
- Same behavior in training and inference
- Used in transformers (BERT, GPT)

**When to use**: RNNs, transformers, or small batch sizes.

### RMS Normalization

Simplified normalization without mean subtraction.

**Formula**: `y = x / √(mean(x²) + ε) * γ`

```rust
let gamma = Array1::ones(10);
let normalized = rms_norm(&x.view(), &gamma.view(), epsilon)?;
```

**Properties**:
- Faster than layer norm (no mean calculation)
- Used in modern LLMs (LLaMA, PaLM)

**When to use**: Large language models where speed matters.

### Dropout

Randomly zeros elements during training for regularization.

```rust
use numrs2::nn::normalization::*;

// Training mode: apply dropout
let x = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0]);
let output = dropout(&x.view(), 0.5, true)?;
// ~50% of elements are zero, others scaled by 2.0

// Inference mode: no dropout
let output = dropout(&x.view(), 0.5, false)?;
// output == x (no change)
```

**Parameters**:
- `p`: Probability of dropping (0.0 to 1.0)
- `training`: Enable dropout (true) or pass-through (false)

**When to use**: Prevent overfitting, especially in large networks.

### Spatial Dropout

Drops entire feature maps/channels instead of individual elements.

```rust
let x = Array2::ones((4, 10));  // batch=4, channels=10
let output = spatial_dropout(&x.view(), 0.2, true)?;
// Entire channels are dropped
```

**When to use**: Convolutional layers (preserves spatial correlation).

---

## Attention Mechanisms

Core component of transformer models.

### Scaled Dot-Product Attention

**Formula**: `Attention(Q, K, V) = softmax(QK^T / √d_k) * V`

```rust
use numrs2::nn::attention::*;
use scirs2_core::ndarray::Array2;

let seq_len = 10;
let d_k = 64;

let query = Array2::ones((seq_len, d_k));
let key = Array2::ones((seq_len, d_k));
let value = Array2::ones((seq_len, d_k));

// Basic attention
let output = scaled_dot_product_attention(
    &query.view(),
    &key.view(),
    &value.view(),
    None,  // no mask
)?;

// With attention mask (prevent attending to certain positions)
let mask = Array2::ones((seq_len, seq_len));  // 1 = attend, 0 = mask
let output = scaled_dot_product_attention(
    &query.view(),
    &key.view(),
    &value.view(),
    Some(&mask.view()),
)?;
```

**Components**:
- **Query (Q)**: What we're looking for
- **Key (K)**: What each position has
- **Value (V)**: Actual content to retrieve
- **Scaling (√d_k)**: Prevents softmax saturation

### Self-Attention

Query, key, and value all come from the same input.

```rust
let x = Array2::ones((10, 512));  // seq_len=10, d_model=512

// Projection matrices (typically learned)
let w_q = Array2::from_shape_fn((512, 64), |(i, j)| 0.1);
let w_k = Array2::from_shape_fn((512, 64), |(i, j)| 0.1);
let w_v = Array2::from_shape_fn((512, 64), |(i, j)| 0.1);

let output = self_attention(
    &x.view(),
    &w_q.view(),
    &w_k.view(),
    &w_v.view(),
)?;
```

### Embeddings

Convert discrete tokens to dense vectors.

```rust
use numrs2::nn::attention::*;

let vocab_size = 10000;
let embedding_dim = 512;
let embedding_matrix = Array2::ones((vocab_size, embedding_dim));

let indices = vec![1, 42, 100, 256];  // Token IDs
let embeddings = embedding(&indices, &embedding_matrix.view())?;
// Output: (4, 512) - one embedding per token
```

### Positional Encoding

Add position information to embeddings.

```rust
// Sinusoidal positional encoding
let seq_len = 100;
let d_model = 512;
let pos_encoding = positional_encoding::<f64>(seq_len, d_model)?;

// Add to embeddings
let embeddings_with_pos = add_positional_encoding(&embeddings.view())?;
```

**Why needed**: Transformers have no inherent notion of position.

### Embedding Bag

Aggregate multiple embeddings.

```rust
let indices = vec![1, 2, 3, 4, 5];

// Sum aggregation
let sum_emb = embedding_bag(&indices, &embedding_matrix.view(), "sum")?;

// Mean aggregation
let mean_emb = embedding_bag(&indices, &embedding_matrix.view(), "mean")?;

// Max aggregation
let max_emb = embedding_bag(&indices, &embedding_matrix.view(), "max")?;
```

**When to use**: Bag-of-words models, document embeddings.

---

## Loss Functions

### Regression Losses

#### Mean Squared Error (MSE)

**Formula**: `L = (1/n) Σ (y_true - y_pred)²`

```rust
use numrs2::nn::loss::*;
use scirs2_core::ndarray::array;

let y_true = array![1.0, 2.0, 3.0];
let y_pred = array![1.1, 2.1, 2.9];

let loss = mse_loss(&y_true.view(), &y_pred.view(), ReductionMode::Mean)?;
// loss ≈ 0.0067
```

**Properties**:
- Sensitive to outliers (squared error)
- Smooth gradients
- Assumes Gaussian noise

**When to use**: Regression when data is Gaussian, no outliers.

#### Mean Absolute Error (MAE)

**Formula**: `L = (1/n) Σ |y_true - y_pred|`

```rust
let loss = mae_loss(&y_true.view(), &y_pred.view(), ReductionMode::Mean)?;
```

**Properties**:
- Robust to outliers
- Constant gradient magnitude
- Assumes Laplacian noise

**When to use**: Regression with outliers.

#### Huber Loss

**Formula**:
- For |x| ≤ δ: `L = 0.5 * x²`
- For |x| > δ: `L = δ * (|x| - 0.5 * δ)`

```rust
let delta = 1.0;
let loss = huber_loss(&y_true.view(), &y_pred.view(), delta, ReductionMode::Mean)?;
```

**Properties**:
- Combines MSE and MAE
- Smooth near zero, linear for outliers
- Robust to outliers while maintaining smoothness

**When to use**: Regression with some outliers, when you want smooth gradients.

### Classification Losses

#### Binary Cross-Entropy

**Formula**: `L = -(1/n) Σ [y*log(p) + (1-y)*log(1-p)]`

```rust
let y_true = array![1.0, 0.0, 1.0];  // Binary labels
let y_pred = array![0.9, 0.1, 0.8];  // Probabilities

let loss = binary_cross_entropy(
    &y_true.view(),
    &y_pred.view(),
    ReductionMode::Mean
)?;
```

**When to use**: Binary classification with probabilities.

#### BCE with Logits

More numerically stable variant that takes logits (pre-sigmoid).

```rust
let logits = array![2.0, -2.0, 1.5];  // Raw outputs
let loss = bce_with_logits(&y_true.view(), &logits.view(), ReductionMode::Mean)?;
```

**When to use**: Binary classification (preferred over BCE).

#### Categorical Cross-Entropy

**Formula**: `L = -(1/n) Σ Σ_c y_true_c * log(y_pred_c)`

```rust
use scirs2_core::ndarray::Array2;

// One-hot encoded labels
let y_true = Array2::from_shape_vec((2, 3), vec![
    1.0, 0.0, 0.0,  // Sample 0: class 0
    0.0, 1.0, 0.0,  // Sample 1: class 1
])?;

// Predicted probabilities (after softmax)
let y_pred = Array2::from_shape_vec((2, 3), vec![
    0.7, 0.2, 0.1,
    0.1, 0.8, 0.1,
])?;

let loss = categorical_cross_entropy(
    &y_true.view(),
    &y_pred.view(),
    ReductionMode::Mean
)?;
```

**When to use**: Multi-class classification with one-hot labels.

#### Sparse Categorical Cross-Entropy

Optimized for integer labels instead of one-hot vectors.

```rust
let y_true = vec![0, 1, 2];  // Class indices
let y_pred = Array2::from_shape_vec((3, 3), vec![
    0.7, 0.2, 0.1,
    0.1, 0.8, 0.1,
    0.1, 0.1, 0.8,
])?;

let loss = sparse_categorical_cross_entropy(
    &y_true,
    &y_pred.view(),
    ReductionMode::Mean
)?;
```

**When to use**: Multi-class classification (more efficient than categorical).

#### Negative Log-Likelihood (NLL)

For use with log-softmax outputs.

```rust
let log_probs = log_softmax_2d(&logits.view(), 1)?;
let loss = nll_loss(&y_true_indices, &log_probs.view(), ReductionMode::Mean)?;
```

**When to use**: With log-softmax activation (common in PyTorch-style code).

#### Focal Loss

**Formula**: `FL(p_t) = -α(1 - p_t)^γ log(p_t)`

Addresses class imbalance by down-weighting easy examples.

```rust
let alpha = 0.25;  // Class weighting
let gamma = 2.0;   // Focusing parameter

let loss = focal_loss(
    &y_true.view(),
    &y_pred.view(),
    alpha,
    gamma,
    ReductionMode::Mean
)?;
```

**Parameters**:
- **α**: Balances positive/negative examples
- **γ**: Focuses on hard examples (γ=0 → standard CE)

**When to use**: Object detection (RetinaNet), heavily imbalanced datasets.

### Distance Losses

#### KL Divergence

**Formula**: `KL(P||Q) = Σ P(x) * log(P(x) / Q(x))`

Measures how one probability distribution differs from another.

```rust
let p = array![0.4, 0.3, 0.3];  // True distribution
let q = array![0.5, 0.3, 0.2];  // Approximate distribution

let kl = kl_div_loss(&p.view(), &q.view(), ReductionMode::Mean)?;
```

**When to use**: Distillation, VAE regularization.

#### Hinge Loss

**Formula**: `L = max(0, 1 - y_true * y_pred)`

```rust
let y_true = array![1.0, -1.0, 1.0];   // Labels: +1 or -1
let y_pred = array![0.8, -0.9, 0.7];   // Scores (not probabilities)

let loss = hinge_loss(&y_true.view(), &y_pred.view(), ReductionMode::Mean)?;
```

**When to use**: SVM classification, margin-based learning.

#### Cosine Embedding Loss

Measures cosine similarity between embeddings.

```rust
let x1 = array![1.0, 2.0, 3.0];
let x2 = array![1.1, 2.1, 3.1];
let y = 1.0;      // 1 = similar, -1 = dissimilar
let margin = 0.5;

let loss = cosine_embedding_loss(&x1.view(), &x2.view(), y, margin)?;
```

**When to use**: Siamese networks, metric learning.

### Reduction Modes

All loss functions support three reduction modes:

```rust
// No reduction: return per-element loss
let losses = mse_loss(&y_true.view(), &y_pred.view(), ReductionMode::None)?;

// Mean: average over all elements
let loss = mse_loss(&y_true.view(), &y_pred.view(), ReductionMode::Mean)?;

// Sum: sum over all elements
let loss = mse_loss(&y_true.view(), &y_pred.view(), ReductionMode::Sum)?;
```

---

## SIMD Optimization

### Platform Detection

Check SIMD capabilities at runtime:

```rust
use numrs2::nn::simd_ops::*;

// Get detailed SIMD information
println!("{}", get_simd_info());

// Check if SIMD is available
if is_simd_available() {
    println!("SIMD acceleration enabled");
}

// Get recommended batch size for optimal SIMD usage
let batch_size = recommended_batch_size();
```

### SIMD Operations

All major operations have SIMD-optimized variants:

```rust
use numrs2::nn::simd_ops::*;
use scirs2_core::ndarray::Array1;

let x = Array1::from_vec(vec![1.0f32, 2.0, 3.0, 4.0]);

// Activations (4-8x faster)
let relu = simd_relu_f32(&x.view());
let sigmoid = simd_sigmoid_f32(&x.view());
let tanh = simd_tanh_f32(&x.view());
let gelu = simd_gelu_f32(&x.view());
let swish = simd_swish_f32(&x.view());

// Element-wise operations (8-16x faster)
let y = Array1::from_vec(vec![0.5f32, 1.0, 1.5, 2.0]);
let sum = simd_add_f32(&x.view(), &y.view());
let product = simd_mul_f32(&x.view(), &y.view());

// Reductions (4-8x faster)
let total = simd_sum_f32(&x.view());
let average = simd_mean_f32(&x.view());
let maximum = simd_max_f32(&x.view());

// Matrix operations (10-30x faster for small matrices)
let a = Array2::ones((4, 8));
let b = Array2::ones((8, 4));
let c = simd_matmul_f32(&a.view(), &b.view())?;
```

### Performance Comparison

Typical speedups on modern CPUs:

| Operation        | Scalar | SIMD (AVX2) | SIMD (AVX512) | SIMD (NEON) |
|------------------|--------|-------------|---------------|-------------|
| ReLU             | 1x     | 6x          | 12x           | 4x          |
| Sigmoid          | 1x     | 4x          | 8x            | 3x          |
| GELU             | 1x     | 3x          | 6x            | 2.5x        |
| Element-wise add | 1x     | 8x          | 16x           | 4x          |
| Matrix multiply  | 1x     | 15x         | 30x           | 8x          |

### f32 vs f64

Use f32 when possible for 2x better SIMD performance:

```rust
// f64: 4 elements per AVX2 instruction
let x_f64 = Array1::from_vec(vec![1.0f64, 2.0, 3.0, 4.0]);
let y_f64 = simd_relu_f64(&x_f64.view());

// f32: 8 elements per AVX2 instruction (2x throughput)
let x_f32 = Array1::from_vec(vec![1.0f32, 2.0, 3.0, 4.0]);
let y_f32 = simd_relu_f32(&x_f32.view());
```

**Recommendation**: Use f32 for forward pass, f64 for numerical stability in sensitive operations.

---

## Performance Tips

### 1. Use Appropriate Data Types

```rust
// ✅ GOOD: f32 for better SIMD performance
let x = Array1::from_vec(vec![1.0f32, 2.0, 3.0]);
let y = simd_relu_f32(&x.view());

// ⚠️ OK: f64 when precision is critical
let x = Array1::from_vec(vec![1.0f64, 2.0, 3.0]);
let y = relu(&x.view())?;
```

### 2. Batch Operations

Process multiple samples at once:

```rust
// ❌ BAD: Process one at a time
for i in 0..1000 {
    let sample = samples.row(i);
    let output = relu(&sample)?;
    // ...
}

// ✅ GOOD: Process entire batch
let output = relu_2d(&samples.view())?;
```

### 3. Minimize Allocations

```rust
// ❌ BAD: Allocate every iteration
for epoch in 0..100 {
    let output = Array2::zeros((batch_size, hidden_size));
    // ...
}

// ✅ GOOD: Reuse allocation
let mut output = Array2::zeros((batch_size, hidden_size));
for epoch in 0..100 {
    // Reuse output
    // ...
}
```

### 4. Use In-Place Operations

```rust
// ❌ BAD: Allocate new array
let x = Array1::from_vec(vec![-1.0, 0.0, 1.0]);
let y = relu(&x.view())?;

// ✅ GOOD: Modify in-place
let mut x = Array1::from_vec(vec![-1.0, 0.0, 1.0]);
relu_inplace(&mut x);
```

### 5. Choose Right Loss Function

```rust
// ❌ SLOWER: Categorical with one-hot encoding
let y_onehot = Array2::from_shape_vec((n, num_classes), one_hot_data)?;
let loss = categorical_cross_entropy(&y_onehot.view(), &probs.view(), ReductionMode::Mean)?;

// ✅ FASTER: Sparse categorical with indices
let y_indices = vec![0, 1, 2, 0, 1];
let loss = sparse_categorical_cross_entropy(&y_indices, &probs.view(), ReductionMode::Mean)?;
```

### 6. Profile Your Code

Use NumRS2's benchmarking tools:

```rust
use criterion::{black_box, criterion_group, criterion_main, Criterion};

fn bench_activation(c: &mut Criterion) {
    let x = Array1::from_vec(vec![1.0f32; 1024]);

    c.bench_function("relu_scalar", |b| {
        b.iter(|| relu(&black_box(x.view())))
    });

    c.bench_function("relu_simd", |b| {
        b.iter(|| simd_relu_f32(&black_box(x.view())))
    });
}
```

### 7. Optimize Memory Layout

```rust
// ✅ GOOD: Contiguous memory layout
let x = Array2::from_shape_vec((n, m), data)?;

// ⚠️ SLOWER: Non-contiguous (after transpose)
let x_t = x.t();
```

---

## Training Patterns

### Basic Training Loop

```rust
use numrs2::nn::*;
use scirs2_core::ndarray::{Array1, Array2};

fn train_epoch(
    data: &Array2<f64>,
    labels: &[usize],
    weights: &mut Array2<f64>,
    learning_rate: f64,
) -> NnResult<f64> {
    let batch_size = data.nrows();

    // Forward pass
    let logits = simd_matmul_f64(&data.view(), &weights.view())?;
    let probs = softmax_2d(&logits.view(), 1)?;

    // Compute loss
    let loss = sparse_categorical_cross_entropy(
        labels,
        &probs.view(),
        ReductionMode::Mean,
    )?;

    // Backward pass (gradient computation)
    // ... compute gradients ...

    // Update weights
    // weights -= learning_rate * gradients

    Ok(loss)
}
```

### Multi-Layer Network

```rust
struct Network {
    w1: Array2<f64>,
    b1: Array1<f64>,
    w2: Array2<f64>,
    b2: Array1<f64>,
    gamma1: Array1<f64>,
    beta1: Array1<f64>,
}

impl Network {
    fn forward(&self, x: &Array2<f64>, training: bool) -> NnResult<Array2<f64>> {
        // Layer 1: Linear + ReLU + BatchNorm + Dropout
        let h1 = simd_matmul_f64(&x.view(), &self.w1.view())?;
        let h1 = relu_2d(&h1.view())?;
        let h1 = batch_norm_1d(
            &h1.view(),
            &self.gamma1.view(),
            &self.beta1.view(),
            1e-5
        )?;
        let h1 = dropout_2d(&h1.view(), 0.5, training)?;

        // Layer 2: Linear + Softmax
        let h2 = simd_matmul_f64(&h1.view(), &self.w2.view())?;
        let output = softmax_2d(&h2.view(), 1)?;

        Ok(output)
    }
}
```

### Validation Loop

```rust
fn evaluate(
    network: &Network,
    val_data: &Array2<f64>,
    val_labels: &[usize],
) -> NnResult<(f64, f64)> {
    // Forward pass in inference mode
    let probs = network.forward(val_data, false)?;

    // Compute loss
    let loss = sparse_categorical_cross_entropy(
        val_labels,
        &probs.view(),
        ReductionMode::Mean,
    )?;

    // Compute accuracy
    let mut correct = 0;
    for (i, &label) in val_labels.iter().enumerate() {
        let pred = probs.row(i)
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
            .map(|(idx, _)| idx)
            .unwrap();

        if pred == label {
            correct += 1;
        }
    }

    let accuracy = correct as f64 / val_labels.len() as f64;

    Ok((loss, accuracy))
}
```

---

## Error Handling

All operations return `NnResult<T>` for comprehensive error handling:

```rust
use numrs2::nn::*;
use numrs2::error::NumRs2Error;

fn process_data(x: &Array1<f64>) -> NnResult<Array1<f64>> {
    // Dimension validation
    if x.is_empty() {
        return Err(NumRs2Error::DimensionMismatch(
            "Input cannot be empty".to_string()
        ));
    }

    // Operation with error propagation
    let y = relu(&x.view())?;
    let z = softmax(&y.view())?;

    Ok(z)
}
```

### Common Error Types

```rust
match result {
    Err(NumRs2Error::DimensionMismatch(msg)) => {
        // Shape incompatibility
        eprintln!("Dimension error: {}", msg);
    }
    Err(NumRs2Error::InvalidOperation(msg)) => {
        // Invalid parameters (e.g., negative probability)
        eprintln!("Invalid operation: {}", msg);
    }
    Err(NumRs2Error::ConversionError(msg)) => {
        // Type conversion failure
        eprintln!("Conversion error: {}", msg);
    }
    Err(NumRs2Error::IndexOutOfBounds(msg)) => {
        // Index out of range
        eprintln!("Index error: {}", msg);
    }
    Ok(value) => {
        // Success
    }
}
```

---

## Examples

### Complete Neural Network Example

See `examples/neural_network_basics.rs` for a comprehensive demonstration including:

- Activation functions showcase
- Normalization and dropout
- Convolution and pooling
- Loss function comparisons
- Complete feedforward network
- Mini training loop structure

Run the example:

```bash
cargo run --example neural_network_basics
```

### Simple Classification Network

```rust
use numrs2::nn::*;
use scirs2_core::ndarray::{Array1, Array2};
use scirs2_core::random::*;

fn main() -> NnResult<()> {
    // Network architecture: 4 inputs -> 8 hidden -> 3 outputs

    // Generate synthetic data
    let mut rng = thread_rng();
    let input = Array2::from_shape_fn((100, 4), |_| rng.gen::<f64>());
    let labels = (0..100).map(|i| i % 3).collect::<Vec<_>>();

    // Initialize weights
    let w1 = Array2::from_shape_fn((4, 8), |_| rng.gen::<f64>() * 0.1);
    let w2 = Array2::from_shape_fn((8, 3), |_| rng.gen::<f64>() * 0.1);

    // Forward pass
    let h1 = simd_matmul_f64(&input.view(), &w1.view())?;
    let h1 = relu_2d(&h1.view())?;

    let logits = simd_matmul_f64(&h1.view(), &w2.view())?;
    let probs = softmax_2d(&logits.view(), 1)?;

    // Compute loss
    let loss = sparse_categorical_cross_entropy(
        &labels,
        &probs.view(),
        ReductionMode::Mean,
    )?;

    println!("Loss: {:.4}", loss);

    Ok(())
}
```

---

## API Reference

### Module Structure

- **`activation`**: Activation functions
  - `relu`, `leaky_relu`, `elu`, `selu`
  - `sigmoid`, `tanh`, `swish`, `mish`, `gelu`
  - `softmax`, `log_softmax`, `softplus`
  - 2D variants: `relu_2d`, `softmax_2d`, etc.
  - In-place: `relu_inplace`

- **`attention`**: Attention and embeddings
  - `scaled_dot_product_attention`
  - `self_attention`
  - `embedding`, `embedding_bag`
  - `positional_encoding`, `add_positional_encoding`

- **`conv`**: Convolution operations
  - `conv1d`, `conv2d`
  - `conv2d_with_padding`
  - `depthwise_conv2d`

- **`loss`**: Loss functions
  - Regression: `mse_loss`, `mae_loss`, `huber_loss`
  - Classification: `binary_cross_entropy`, `categorical_cross_entropy`, `sparse_categorical_cross_entropy`
  - Advanced: `focal_loss`, `kl_div_loss`, `hinge_loss`, `cosine_embedding_loss`

- **`normalization`**: Normalization and regularization
  - `batch_norm_1d`, `layer_norm`, `rms_norm`
  - `dropout`, `dropout_2d`, `spatial_dropout`

- **`pooling`**: Pooling operations
  - `max_pool2d`, `avg_pool2d`
  - `adaptive_avg_pool2d`
  - `global_avg_pool`, `global_max_pool`

- **`simd_ops`**: SIMD-optimized operations
  - Detection: `detect_simd_capabilities`, `get_simd_info`, `is_simd_available`
  - Activations: `simd_relu_f32`, `simd_sigmoid_f32`, `simd_gelu_f32`, etc.
  - Operations: `simd_add_f32`, `simd_mul_f32`, `simd_matmul_f32`, etc.
  - Reductions: `simd_sum_f32`, `simd_mean_f32`, `simd_max_f32`

### Common Types

```rust
// Result type
pub type NnResult<T> = Result<T, NumRs2Error>;

// Enumerations
pub enum ReductionMode { None, Mean, Sum }
pub enum PaddingMode { Valid, Same, Full, Explicit(usize) }
pub enum DataFormat { NCHW, NHWC }
```

---

## Further Reading

- **Examples**: `examples/neural_network_basics.rs`
- **Benchmarks**: `bench/nn_benchmarks.rs`
- **Tests**: `tests/nn/`
- **SciRS2 Policy**: `SCIRS2_INTEGRATION_POLICY.md`
- **Architecture**: `docs/ARCHITECTURE.md`

---

## Version History

- **v0.3.0**: Initial neural network module release
  - Complete activation functions
  - Convolution and pooling operations
  - Attention mechanisms
  - Comprehensive loss functions
  - SIMD optimization
  - Pure Rust implementation via OxiBLAS

---

*For questions, issues, or contributions, please visit the NumRS2 repository.*