hodu 0.2.4

A user-friendly ML framework built in Rust for rapid prototyping and embedded deployment
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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
# Neural Network Modules Guide

This document provides a comprehensive overview of neural network modules available in `hodu::nn`.

## Overview

`hodu::nn` provides PyTorch-style neural network building blocks organized into three main categories:

1. **Modules**: Layers and transformations (Linear, Activation functions)
2. **Loss Functions**: Training objectives (MSE, CrossEntropy, etc.)
3. **Optimizers**: Parameter update algorithms (SGD, Adam)

## Training/Evaluation Mode

Macros to switch the behavior mode of neural network modules.

### train!()

Switch to training mode. Regularization layers like Dropout are activated.

```rust
use hodu::prelude::*;

train!();  // Activate training mode
```

### eval!()

Switch to evaluation mode. Regularization layers like Dropout are deactivated.

```rust
use hodu::prelude::*;

eval!();  // Activate evaluation mode
```

**Usage Example:**

```rust
use hodu::prelude::*;

let dropout = Dropout::new(0.5);
let input = Tensor::randn(&[32, 128], 0.0, 1.0)?;

// During training
train!();
let output = dropout.forward(&input)?;  // Dropout applied

// During evaluation
eval!();
let output = dropout.forward(&input)?;  // Dropout not applied
```

## Modules

### Linear Layers

#### Linear

Fully connected (dense) layer with optional bias.

```rust
use hodu::prelude::*;
use hodu::nn::modules::Linear;

// Create linear layer: 784 -> 128
let layer = Linear::new(784, 128, true, DType::F32)?;

// Forward pass
let input = Tensor::randn(&[32, 784], 0.0, 1.0)?;  // batch_size=32
let output = layer.forward(&input)?;  // [32, 128]
```

**Parameters:**
- `in_features`: Input dimension
- `out_features`: Output dimension
- `with_bias`: Whether to include bias term
- `dtype`: Data type (F32, F64, etc.)

**Initialization:**
- Weight: Xavier/Glorot initialization scaled by `k = 1/√in_features`
- Bias: Same initialization if enabled

**Computation:**
```
output = input @ weight.T + bias
```

### Convolutional Layers

Convolutional layers are used for processing data with spatial structure such as images, time series, and 3D data.

#### Conv1D

1D convolutional layer for time series data or text sequences.

```rust
use hodu::nn::modules::Conv1D;

// Create Conv1D layer: 16 channels -> 32 channels, kernel_size=3
let conv = Conv1D::new(
    16,    // in_channels
    32,    // out_channels
    3,     // kernel_size
    1,     // stride
    1,     // padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass: [batch, channels, length]
let input = Tensor::randn(&[8, 16, 100], 0.0, 1.0)?;  // batch=8, in_channels=16, length=100
let output = conv.forward(&input)?;  // [8, 32, 100]
```

**Parameters:**
- `in_channels`: Number of input channels
- `out_channels`: Number of output channels (number of filters)
- `kernel_size`: Size of the convolutional kernel
- `stride`: Stride of the convolution
- `padding`: Zero-padding added to input
- `dilation`: Spacing between kernel elements
- `with_bias`: Whether to include bias term
- `dtype`: Data type

**Initialization:**
- Weight: Kaiming initialization, `k = √(2/(in_channels * kernel_size))`
- Bias: Same initialization

**Output Size:**
```
L_out = floor((L_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
```

#### Conv2D

2D convolutional layer, most widely used for image processing.

```rust
use hodu::nn::modules::Conv2D;

// Create Conv2D layer: 3 channels (RGB) -> 64 channels, 3x3 kernel
let conv = Conv2D::new(
    3,     // in_channels
    64,    // out_channels
    3,     // kernel_size
    1,     // stride
    1,     // padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass: [batch, channels, height, width]
let input = Tensor::randn(&[16, 3, 224, 224], 0.0, 1.0)?;  // batch=16, RGB image 224x224
let output = conv.forward(&input)?;  // [16, 64, 224, 224]
```

**Parameters:** Same as Conv1D but applied in 2D space

**Initialization:**
- Weight: Kaiming initialization, `k = √(2/(in_channels * kernel_size²))`

**Output Size:**
```
H_out = floor((H_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
W_out = floor((W_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
```

#### Conv3D

3D convolutional layer for video or 3D medical imaging.

```rust
use hodu::nn::modules::Conv3D;

// Create Conv3D layer
let conv = Conv3D::new(
    1,     // in_channels (grayscale)
    32,    // out_channels
    3,     // kernel_size
    1,     // stride
    1,     // padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass: [batch, channels, depth, height, width]
let input = Tensor::randn(&[4, 1, 64, 64, 64], 0.0, 1.0)?;  // batch=4, 64x64x64 volume
let output = conv.forward(&input)?;  // [4, 32, 64, 64, 64]
```

**Initialization:**
- Weight: Kaiming initialization, `k = √(2/(in_channels * kernel_size³))`

**Output Size:**
```
D_out = floor((D_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
H_out = floor((H_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
W_out = floor((W_in + 2*padding - dilation*(kernel_size-1) - 1) / stride + 1)
```

#### ConvTranspose1D

Transposed convolution (upsampling) layer for increasing resolution of 1D data.

```rust
use hodu::nn::modules::ConvTranspose1D;

// Create ConvTranspose1D layer
let conv_t = ConvTranspose1D::new(
    32,    // in_channels
    16,    // out_channels
    3,     // kernel_size
    2,     // stride (upsampling factor)
    1,     // padding
    0,     // output_padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass
let input = Tensor::randn(&[8, 32, 50], 0.0, 1.0)?;  // [batch, channels, length]
let output = conv_t.forward(&input)?;  // [8, 16, 99] (upsampled)
```

**Output Size:**
```
L_out = (L_in - 1) * stride - 2*padding + dilation*(kernel_size-1) + output_padding + 1
```

#### ConvTranspose2D

Transposed convolution layer for image upsampling, decoders, GAN generators, etc.

```rust
use hodu::nn::modules::ConvTranspose2D;

// Create ConvTranspose2D layer
let conv_t = ConvTranspose2D::new(
    64,    // in_channels
    3,     // out_channels (RGB)
    4,     // kernel_size
    2,     // stride (2x upsampling)
    1,     // padding
    0,     // output_padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass
let input = Tensor::randn(&[16, 64, 56, 56], 0.0, 1.0)?;
let output = conv_t.forward(&input)?;  // [16, 3, 112, 112] (2x upsampled)
```

**Output Size:**
```
H_out = (H_in - 1) * stride - 2*padding + dilation*(kernel_size-1) + output_padding + 1
W_out = (W_in - 1) * stride - 2*padding + dilation*(kernel_size-1) + output_padding + 1
```

#### ConvTranspose3D

3D transposed convolution layer for upsampling 3D data.

```rust
use hodu::nn::modules::ConvTranspose3D;

// Create ConvTranspose3D layer
let conv_t = ConvTranspose3D::new(
    32,    // in_channels
    1,     // out_channels
    4,     // kernel_size
    2,     // stride
    1,     // padding
    0,     // output_padding
    1,     // dilation
    true,  // with_bias
    DType::F32
)?;

// Forward pass
let input = Tensor::randn(&[4, 32, 32, 32, 32], 0.0, 1.0)?;
let output = conv_t.forward(&input)?;  // [4, 1, 64, 64, 64] (2x upsampled)
```

### Convolutional Layer Comparison

| Layer | Input Shape | Use Case | Resolution Change |
|-------|------------|----------|------------------|
| Conv1D | `[N, C, L]` | Time series, text | Decrease/maintain |
| Conv2D | `[N, C, H, W]` | Images | Decrease/maintain |
| Conv3D | `[N, C, D, H, W]` | Video, 3D scans | Decrease/maintain |
| ConvTranspose1D | `[N, C, L]` | 1D upsampling | Increase |
| ConvTranspose2D | `[N, C, H, W]` | Image generation | Increase |
| ConvTranspose3D | `[N, C, D, H, W]` | 3D reconstruction | Increase |

**Key Concepts:**
- **stride**: Larger values decrease (Conv) or increase (ConvTranspose) output size
- **padding**: Add zeros around input to control output size
- **dilation**: Spacing between kernel elements, expands receptive field
- **output_padding**: Fine-tune output size in ConvTranspose

### Pooling Layers

Pooling layers downsample spatial dimensions and provide translation invariance.

#### MaxPool1D, MaxPool2D, MaxPool3D

Max pooling selects the maximum value in each window.

```rust
use hodu::nn::modules::{MaxPool1d, MaxPool2d, MaxPool3d};

// MaxPool1D: Time series data
let pool1d = MaxPool1d::new(
    2,  // kernel_size
    2,  // stride
    0,  // padding
);
let input = Tensor::randn(&[8, 16, 100], 0.0, 1.0)?;  // [batch, channels, length]
let output = pool1d.forward(&input)?;  // [8, 16, 50]

// MaxPool2D: Images
let pool2d = MaxPool2d::new(
    2,  // kernel_size
    2,  // stride
    0,  // padding
);
let input = Tensor::randn(&[16, 64, 224, 224], 0.0, 1.0)?;  // [batch, channels, H, W]
let output = pool2d.forward(&input)?;  // [16, 64, 112, 112]

// MaxPool3D: 3D data
let pool3d = MaxPool3d::new(
    2,  // kernel_size
    2,  // stride
    0,  // padding
);
let input = Tensor::randn(&[4, 32, 64, 64, 64], 0.0, 1.0)?;  // [batch, channels, D, H, W]
let output = pool3d.forward(&input)?;  // [4, 32, 32, 32, 32]
```

**Parameters:**
- `kernel_size`: Size of the pooling window
- `stride`: Stride of the pooling operation
- `padding`: Padding size

**Properties:**
- Preserves only maximum values (useful for feature detection)
- Limited backpropagation (only max positions recorded)
- Reduces spatial dimensions

#### AvgPool1D, AvgPool2D, AvgPool3D

Average pooling computes the average of each window.

```rust
use hodu::nn::modules::{AvgPool1d, AvgPool2d, AvgPool3d};

// AvgPool1D
let pool = AvgPool1d::new(2, 2, 0);
let output = pool.forward(&input)?;

// AvgPool2D
let pool = AvgPool2d::new(2, 2, 0);
let output = pool.forward(&input)?;

// AvgPool3D
let pool = AvgPool3d::new(2, 2, 0);
let output = pool.forward(&input)?;
```

**Properties:**
- Averages all values in the window
- Smooth downsampling
- Less information loss than MaxPool

#### AdaptiveMaxPool1D, AdaptiveMaxPool2D, AdaptiveMaxPool3D

Adaptive max pooling produces fixed output size regardless of input size.

```rust
use hodu::nn::modules::{AdaptiveMaxPool1d, AdaptiveMaxPool2d, AdaptiveMaxPool3d};

// AdaptiveMaxPool1D
let pool = AdaptiveMaxPool1d::new(50);  // output_size
let input = Tensor::randn(&[8, 16, 100], 0.0, 1.0)?;
let output = pool.forward(&input)?;  // [8, 16, 50]

// AdaptiveMaxPool2D
let pool = AdaptiveMaxPool2d::new((7, 7));  // output_size (H, W)
let input = Tensor::randn(&[16, 512, 14, 14], 0.0, 1.0)?;
let output = pool.forward(&input)?;  // [16, 512, 7, 7]

// AdaptiveMaxPool3D
let pool = AdaptiveMaxPool3d::new((4, 4, 4));  // output_size (D, H, W)
let input = Tensor::randn(&[4, 64, 16, 16, 16], 0.0, 1.0)?;
let output = pool.forward(&input)?;  // [4, 64, 4, 4, 4]
```

**Parameters:**
- `output_size`: Desired output size (usize for 1D, tuple for 2D/3D)

**Properties:**
- Fixed output size regardless of input size
- Automatically calculates kernel size and stride
- Useful for networks that handle variable-sized inputs

#### AdaptiveAvgPool1D, AdaptiveAvgPool2D, AdaptiveAvgPool3D

Adaptive average pooling is the same as adaptive max pooling but uses averaging.

```rust
use hodu::nn::modules::{AdaptiveAvgPool1d, AdaptiveAvgPool2d, AdaptiveAvgPool3d};

// AdaptiveAvgPool1D
let pool = AdaptiveAvgPool1d::new(50);
let output = pool.forward(&input)?;

// AdaptiveAvgPool2D (e.g., Global Average Pooling in ResNet)
let pool = AdaptiveAvgPool2d::new((1, 1));  // Global pooling
let input = Tensor::randn(&[16, 2048, 7, 7], 0.0, 1.0)?;
let output = pool.forward(&input)?;  // [16, 2048, 1, 1]

// AdaptiveAvgPool3D
let pool = AdaptiveAvgPool3d::new((1, 1, 1));  // Global pooling
let output = pool.forward(&input)?;
```

**Use Cases:**
- Global Average Pooling (output size = 1x1)
- Final layer in classification networks
- Variable-sized input handling

### Pooling Layer Comparison

| Layer | Operation | Output Size | Backprop | Use Case |
|-------|-----------|-------------|----------|----------|
| MaxPool | Max | Computed | Limited | Feature detection, CNN |
| AvgPool | Mean | Computed | Full | Smooth downsampling |
| AdaptiveMaxPool | Max | Fixed | Limited | Variable-sized input |
| AdaptiveAvgPool | Mean | Fixed | Full | Global pooling, classification |

**Selection Guide:**
- **CNN intermediate layers**: MaxPool2d (feature detection)
- **Smooth downsampling**: AvgPool
- **Classification head**: AdaptiveAvgPool2d((1, 1)) (Global Average Pooling)
- **Variable-sized inputs**: Adaptive variants

### Embedding Layers

#### Embedding

Embedding layer converts integer indices to dense vectors. Primarily used in natural language processing to represent words as vectors.

```rust
use hodu::nn::modules::Embedding;

// Create Embedding layer: vocabulary size 10000, embedding dimension 256
let embedding = Embedding::new(
    10000,      // num_embeddings (vocabulary size)
    256,        // embedding_dim
    None,       // padding_idx (optional)
    None,       // max_norm (optional)
    2.0,        // norm_type (L2 norm)
    DType::F32
)?;

// Forward pass
let indices = Tensor::new(vec![5, 142, 8, 99])?;  // [batch_size]
let embedded = embedding.forward(&indices)?;  // [4, 256]

// For sequences
let indices = Tensor::new(vec![/* ... */])?.reshape(&[32, 50])?;  // [batch, seq_len]
let embedded = embedding.forward(&indices)?;  // [32, 50, 256]
```

**Parameters:**
- `num_embeddings`: Size of the embedding table (vocabulary size)
- `embedding_dim`: Dimension of each embedding vector
- `padding_idx`: Embeddings at this index are initialized to zeros and gradients are not updated (optional)
- `max_norm`: If specified, embedding vectors with norm exceeding this value are normalized (optional)
- `norm_type`: Norm type to use for max_norm (typically 2.0 for L2)
- `dtype`: Data type

**Initialization:**
- Weight: Xavier/Glorot initialization scaled by `k = 1/√embedding_dim`
- If padding_idx is specified, that embedding is initialized to zeros

**Shape:**
```
Input:  [batch_size] or [batch_size, seq_len] or any shape
Output: [...input_shape..., embedding_dim]
Weight: [num_embeddings, embedding_dim]
```

**Loading Pretrained Embeddings:**

```rust
// Create Embedding from pretrained weights
let pretrained_weight = Tensor::randn(&[10000, 256], 0.0, 1.0)?;
let embedding = Embedding::from_pretrained(
    pretrained_weight,
    false  // freeze: if true, weights are not updated
)?;
```

**Padding Handling:**

```rust
// Using padding_idx to handle padding tokens
let embedding = Embedding::new(
    10000,
    256,
    Some(0),    // Use index 0 as padding
    None,
    2.0,
    DType::F32
)?;

// Sequence with padding
let indices = Tensor::new(vec![5, 142, 0, 0, 8, 99])?;  // 0 is padding
let embedded = embedding.forward(&indices)?;  // Padding positions are zero vectors
```

**Max Norm Constraint:**

```rust
// Limit L2 norm of embedding vectors
let embedding = Embedding::new(
    10000,
    256,
    None,
    Some(1.0),  // max_norm: normalize if vector norm exceeds 1.0
    2.0,        // Use L2 norm
    DType::F32
)?;
```

**Features:**
- Efficient lookup of embedding vectors from indices (gather operation)
- Gradients for padding_idx are automatically set to zero
- max_norm prevents embeddings from growing too large (regularization effect)
- Can load pretrained embeddings (e.g., Word2Vec, GloVe)

**Use Cases:**
- Natural Language Processing: word, character, subword embeddings
- Recommendation systems: user/item embeddings
- Categorical feature encoding
- Knowledge Graph embeddings

**Example: Simple Text Classifier:**

```rust
use hodu::prelude::*;
use hodu::nn::modules::{Embedding, Linear, ReLU};

// Model setup
let embedding = Embedding::new(10000, 128, Some(0), None, 2.0, DType::F32)?;
let linear = Linear::new(128, 10, true, DType::F32)?;

// Forward pass
let input_ids = Tensor::new(vec![45, 123, 8, 0, 0])?.reshape(&[1, 5])?;  // [1, 5]
let embedded = embedding.forward(&input_ids)?;  // [1, 5, 128]

// Average pooling
let pooled = embedded.mean(&[1], false)?;  // [1, 128]
let logits = linear.forward(&pooled)?;  // [1, 10]
```

### Regularization Layers

#### Dropout

Randomly deactivates neurons to prevent overfitting.

```rust
use hodu::nn::modules::Dropout;

let dropout = Dropout::new(0.5);  // 50% drop probability
let output = dropout.forward(&input)?;
```

**Parameters:**
- `p`: Drop probability (0.0 ~ 1.0)

**Behavior:**
- Training: `output = input * mask * (1/(1-p))` (uniform distribution mask)
- Inference: `output = input` (no dropout)

**Recommended rates:** Hidden layers 0.3~0.5, Input layer 0.1~0.2

### Normalization Layers

Normalization layers stabilize training by normalizing layer inputs, enabling higher learning rates and faster convergence.

#### BatchNorm1D, BatchNorm2D, BatchNorm3D

Batch Normalization normalizes inputs using mini-batch statistics, reducing internal covariate shift.

```rust
use hodu::nn::modules::{BatchNorm1D, BatchNorm2D, BatchNorm3D};

// BatchNorm1D: For 2D inputs [N, C] or 3D inputs [N, C, L]
let bn1d = BatchNorm1D::new(
    128,        // num_features (number of channels)
    1e-5,       // eps (numerical stability)
    0.1,        // momentum (for running stats update)
    true,       // affine (learnable gamma/beta)
    DType::F32
)?;

// BatchNorm2D: For 4D inputs [N, C, H, W] (images)
let bn2d = BatchNorm2D::new(
    64,         // num_features
    1e-5,       // eps
    0.1,        // momentum
    true,       // affine
    DType::F32
)?;

// BatchNorm3D: For 5D inputs [N, C, D, H, W] (videos)
let bn3d = BatchNorm3D::new(
    32,         // num_features
    1e-5,       // eps
    0.1,        // momentum
    true,       // affine
    DType::F32
)?;

// Usage example
let input = Tensor::randn(&[16, 64, 32, 32], 0.0, 1.0)?;  // [N, C, H, W]
let output = bn2d.forward(&input)?;
```

**Parameters:**
- `num_features`: Number of channels (C dimension)
- `eps`: Small constant for numerical stability (default: 1e-5)
- `momentum`: Momentum for running statistics update (default: 0.1)
- `affine`: If true, learnable affine parameters (gamma, beta) are applied
- `dtype`: Data type

**Behavior:**

- **Training mode**: Normalizes using batch statistics and updates running statistics
  ```
  output = (input - batch_mean) / sqrt(batch_var + eps)
  output = gamma * output + beta  // if affine=true

  // Running statistics update (exponential moving average)
  running_mean = momentum * running_mean + (1 - momentum) * batch_mean
  running_var = momentum * running_var + (1 - momentum) * batch_var
  ```

- **Evaluation mode**: Normalizes using accumulated running statistics
  ```
  output = (input - running_mean) / sqrt(running_var + eps)
  output = gamma * output + beta  // if affine=true
  ```

**Input Shapes:**
- BatchNorm1D: `[N, C]` or `[N, C, L]`
  - Normalizes over N dimension (or [N, L] for 3D input)
- BatchNorm2D: `[N, C, H, W]`
  - Normalizes over [N, H, W] for each channel
- BatchNorm3D: `[N, C, D, H, W]`
  - Normalizes over [N, D, H, W] for each channel

**Use Cases:**
- CNN intermediate layers
- Stabilizing training in deep networks
- Enabling higher learning rates
- Reducing sensitivity to initialization

#### LayerNorm

Layer Normalization normalizes over feature dimensions instead of the batch dimension.

```rust
use hodu::nn::modules::LayerNorm;

// Single dimension
let ln = LayerNorm::new(
    vec![768],  // normalized_shape
    1e-5,       // eps
    true,       // elementwise_affine
    DType::F32
)?;

// Multiple dimensions (e.g., for images)
let ln_2d = LayerNorm::new(
    vec![64, 32, 32],  // normalized_shape: [C, H, W]
    1e-5,              // eps
    true,              // elementwise_affine
    DType::F32
)?;

// Usage example: Transformer
let input = Tensor::randn(&[32, 128, 768], 0.0, 1.0)?;  // [batch, seq_len, hidden_dim]
let output = ln.forward(&input)?;  // Normalizes over the last dimension (768)
```

**Parameters:**
- `normalized_shape`: Shape of dimensions to normalize over (Vec<usize>)
- `eps`: Small constant for numerical stability (default: 1e-5)
- `elementwise_affine`: If true, learnable affine parameters are applied
- `dtype`: Data type

**Behavior:**

LayerNorm always computes statistics from the current input (no running statistics).

```
mean = mean(input, dims=normalized_shape)
var = var(input, dims=normalized_shape)
output = (input - mean) / sqrt(var + eps)
output = gamma * output + beta  // if elementwise_affine=true
```

**Normalization axes:**
If `normalized_shape = [d1, d2, ..., dk]` and input shape is `[N, ..., d1, d2, ..., dk]`, normalization is performed over the last k dimensions.

**Example:**
```rust
// Input: [batch=32, seq_len=100, hidden=512]
// LayerNorm with normalized_shape=[512]
// -> Normalizes over the last dimension for each (batch, seq_len) position
let ln = LayerNorm::new(vec![512], 1e-5, true, DType::F32)?;
```

**Characteristics:**
- Batch-size independent
- No distinction between training/evaluation modes
- Preferred for RNNs and Transformers
- Suitable for small batch sizes or online learning

**Use Cases:**
- Transformer models (BERT, GPT, etc.)
- Recurrent Neural Networks (RNNs, LSTMs)
- Situations with variable batch sizes
- Small batch training

### Normalization Comparison

| Feature | BatchNorm | LayerNorm |
|---------|-----------|-----------|
| Normalization Axis | Batch dimension | Feature dimensions |
| Batch Dependency | Yes | No |
| Train/Eval Difference | Yes | No |
| Running Statistics | Yes | No |
| Best For | CNNs, fixed batch sizes | RNNs, Transformers, variable batch |
| Computational Cost | Lower | Higher |

**Selection Guide:**
- **CNN image processing**: BatchNorm2D
- **Transformers/NLP**: LayerNorm
- **RNNs/sequence modeling**: LayerNorm
- **Small or variable batch sizes**: LayerNorm
- **Large fixed batch sizes**: BatchNorm
- **Training stability issues**: Try LayerNorm

**Complete Example:**

```rust
use hodu::prelude::*;

// CNN with BatchNorm
let conv = Conv2D::new(3, 64, 3, 1, 1, 1, true, DType::F32)?;
let bn = BatchNorm2D::new(64, 1e-5, 0.1, true, DType::F32)?;
let relu = ReLU::new();

train!();  // Training mode
let x = Tensor::randn(&[16, 3, 224, 224], 0.0, 1.0)?;
let x = conv.forward(&x)?;
let x = bn.forward(&x)?;       // Uses batch statistics
let x = relu.forward(&x)?;

eval!();   // Evaluation mode
let x = bn.forward(&x)?;       // Uses running statistics

// Transformer with LayerNorm
let ln = LayerNorm::new(vec![512], 1e-5, true, DType::F32)?;
let x = Tensor::randn(&[32, 100, 512], 0.0, 1.0)?;
let x = ln.forward(&x)?;       // Same behavior in train/eval
```

### Activation Functions

All activation functions are stateless and have no parameters.

#### ReLU

Rectified Linear Unit: `max(0, x)`

```rust
use hodu::nn::modules::ReLU;

let relu = ReLU::new();
let output = relu.forward(&input)?;
```

**Properties:**
- Range: `[0, ∞)`
- Gradient: 1 if x > 0, else 0
- Most common activation in deep learning

#### Sigmoid

Logistic sigmoid: `σ(x) = 1 / (1 + e^(-x))`

```rust
use hodu::nn::modules::Sigmoid;

let sigmoid = Sigmoid::new();
let output = sigmoid.forward(&input)?;
```

**Properties:**
- Range: `(0, 1)`
- Used for binary classification
- Gradient: `σ(x) * (1 - σ(x))`

#### Tanh

Hyperbolic tangent: `tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))`

```rust
use hodu::nn::modules::Tanh;

let tanh = Tanh::new();
let output = tanh.forward(&input)?;
```

**Properties:**
- Range: `(-1, 1)`
- Zero-centered (better than sigmoid)
- Gradient: `1 - tanh²(x)`

#### GELU

Gaussian Error Linear Unit: `x * Φ(x)` where Φ is standard normal CDF

```rust
use hodu::nn::modules::Gelu;

let gelu = Gelu::new();
let output = gelu.forward(&input)?;
```

**Properties:**
- Smooth approximation of ReLU
- Used in Transformers (BERT, GPT)
- Non-monotonic

#### Softplus

Smooth approximation of ReLU: `log(1 + e^x)`

```rust
use hodu::nn::modules::Softplus;

let softplus = Softplus::new();
let output = softplus.forward(&input)?;
```

**Properties:**
- Range: `(0, ∞)`
- Smooth everywhere
- Gradient: sigmoid function

#### SiLU (Swish)

Sigmoid Linear Unit (also known as Swish): `x * σ(x)`

```rust
use hodu::nn::modules::SiLU;
// or
use hodu::nn::modules::Swish;

let silu = SiLU::new();
let output = silu.forward(&input)?;
```

**Formula:**
```
f(x) = x * sigmoid(x) = x / (1 + e^(-x))
```

**Properties:**
- Smooth and non-monotonic
- Self-gating activation
- Used in modern architectures (EfficientNet, etc.)
- Better than ReLU in many cases

#### Mish

Self-regularized non-monotonic activation: `x * tanh(softplus(x))`

```rust
use hodu::nn::modules::Mish;

let mish = Mish::new();
let output = mish.forward(&input)?;
```

**Formula:**
```
f(x) = x * tanh(ln(1 + e^x))
```

**Properties:**
- Smooth and non-monotonic
- Unbounded above, bounded below
- Improved accuracy over ReLU and Swish in some tasks
- Self-regularizing

#### LeakyReLU

Leaky ReLU: `max(αx, x)`

```rust
use hodu::nn::modules::LeakyReLU;

let leaky = LeakyReLU::new(0.01);  // α = 0.01
let output = leaky.forward(&input)?;
```

**Parameters:**
- `exponent`: Slope for negative values (typically 0.01)

**Properties:**
- Prevents "dying ReLU" problem
- Non-zero gradient for x < 0

#### ELU

Exponential Linear Unit

```rust
use hodu::nn::modules::ELU;

let elu = ELU::new(1.0);  // α = 1.0
let output = elu.forward(&input)?;
```

**Formula:**
```
f(x) = x           if x > 0
     = α(e^x - 1)  if x ≤ 0
```

**Properties:**
- Smooth everywhere
- Negative values push mean towards zero
- Self-normalizing in some networks

#### PReLU

Parametric ReLU with learnable slope

```rust
use hodu::nn::modules::PReLU;

let prelu = PReLU::new(0.25);  // Initial weight/slope
let output = prelu.forward(&input)?;
```

**Formula:**
```
f(x) = x           if x > 0
     = weight * x  if x ≤ 0
```

**Properties:**
- Learnable negative slope parameter
- Can adapt to data
- More flexible than LeakyReLU

#### RReLU

Randomized Leaky ReLU

```rust
use hodu::nn::modules::RReLU;

let rrelu = RReLU::new(0.125, 0.333);  // lower, upper bounds
let input = Tensor::randn(&[32, 128], 0.0, 1.0)?;

// Training mode
train!();
let output = rrelu.forward(&input)?;  // Each element uses different random alpha

// Evaluation mode
eval!();
let output = rrelu.forward(&input)?;  // Uses fixed average alpha
```

**Formula:**
```
f(x) = x           if x > 0
     = α * x       if x ≤ 0

Training mode: α ~ Uniform(lower, upper) (different random value per element)
Evaluation mode: α = (lower + upper) / 2 (fixed value)
```

**Properties:**
- Each element uses different random negative slope during training
- Regularization through randomization
- Reduces overfitting
- Similar regularization effect as Dropout
- Deterministic during evaluation (reproducible)

### Activation Function Comparison

| Activation | Range | Smooth | Zero-centered | Use Case |
|-----------|-------|--------|---------------|----------|
| ReLU | `[0, ∞)` | No | No | General purpose, fast |
| Sigmoid | `(0, 1)` | Yes | No | Binary classification output |
| Tanh | `(-1, 1)` | Yes | Yes | RNNs, hidden layers |
| GELU | `(-∞, ∞)` | Yes | Yes | Transformers, modern architectures |
| Softplus | `(0, ∞)` | Yes | No | Smooth ReLU alternative |
| SiLU/Swish | `(-∞, ∞)` | Yes | No | Modern CNNs (EfficientNet) |
| Mish | `(-∞, ∞)` | Yes | No | High accuracy tasks |
| LeakyReLU | `(-∞, ∞)` | No | Yes | Prevent dying ReLU |
| ELU | `(-α, ∞)` | Yes | No | Self-normalizing networks |
| PReLU | `(-∞, ∞)` | No | Yes | Learnable negative slope |
| RReLU | `(-∞, ∞)` | No | Yes | Regularization, reduce overfitting |

## Loss Functions

### Regression Losses

#### MSELoss

Mean Squared Error: Average of squared differences

```rust
use hodu::nn::losses::MSELoss;

let criterion = MSELoss::new();
let loss = criterion.forward((&predictions, &targets))?;
```

**Formula:**
```
MSE = mean((predictions - targets)²)
```

**Use Cases:**
- Regression tasks
- Sensitive to outliers

#### MAELoss

Mean Absolute Error: Average of absolute differences

```rust
use hodu::nn::losses::MAELoss;

let criterion = MAELoss::new();
let loss = criterion.forward((&predictions, &targets))?;
```

**Formula:**
```
MAE = mean(|predictions - targets|)
```

**Use Cases:**
- Regression tasks
- More robust to outliers than MSE

#### HuberLoss

Combination of MSE and MAE with configurable threshold

```rust
use hodu::nn::losses::HuberLoss;

let criterion = HuberLoss::new(1.0);  // delta = 1.0
let loss = criterion.forward((&predictions, &targets))?;
```

**Formula:**
```
L(x) = 0.5 * x²           if |x| ≤ δ
     = δ * (|x| - 0.5*δ)  if |x| > δ
where x = predictions - targets
```

**Use Cases:**
- Regression with outliers
- Balances MSE and MAE benefits

### Classification Losses

#### BCELoss

Binary Cross Entropy: For binary classification with probabilities

```rust
use hodu::nn::losses::BCELoss;

let criterion = BCELoss::new();
// Or with custom epsilon for numerical stability
let criterion = BCELoss::with_epsilon(1e-7);

let predictions = predictions.sigmoid()?;  // Must be in (0, 1)
let loss = criterion.forward((&predictions, &targets))?;
```

**Formula:**
```
BCE = -mean[target * log(pred) + (1 - target) * log(1 - pred)]
```

**Features:**
- Automatic clamping: `pred ∈ [ε, 1-ε]` to avoid `log(0)`
- Configurable epsilon (default: 1e-7)

**Requirements:**
- Predictions must be probabilities (0 to 1)
- Apply sigmoid before this loss

#### BCEWithLogitsLoss

Binary Cross Entropy with logits: More numerically stable

```rust
use hodu::nn::losses::BCEWithLogitsLoss;

let criterion = BCEWithLogitsLoss::new();
let loss = criterion.forward((&logits, &targets))?;  // No sigmoid needed
```

**Formula:**
```
loss = max(x, 0) - x * target + log(1 + exp(-|x|))
where x = logits
```

**Advantages:**
- More numerically stable than BCELoss
- Combines sigmoid + BCE in one operation
- No need to apply sigmoid separately

#### NLLLoss

Negative Log Likelihood: For multi-class classification with log probabilities

```rust
use hodu::nn::losses::NLLLoss;

let criterion = NLLLoss::new();  // Default: dim=-1
// Or specify class dimension
let criterion = NLLLoss::with_dim(1);

let log_probs = logits.log_softmax(-1)?;
let loss = criterion.forward((&log_probs, &targets))?;
```

**Parameters:**
- `dim`: Dimension along which classes are arranged (default: -1)

**Formula:**
```
NLL = -mean(log_probs[batch_idx, target[batch_idx]])
```

**Requirements:**
- Input must be log probabilities
- Apply `log_softmax` before this loss
- Targets are class indices (not one-hot)

**Shape Examples:**
```rust
// Example 1: Standard classification
// log_probs: [batch=32, classes=10]
// targets: [batch=32] with values in [0, 9]

// Example 2: Sequence modeling
// log_probs: [batch=8, seq_len=50, vocab=1000]
// targets: [batch=8, seq_len=50]
// Use NLLLoss::with_dim(-1) or with_dim(2)
```

#### CrossEntropyLoss

Cross Entropy: Combines log_softmax + NLLLoss

```rust
use hodu::nn::losses::CrossEntropyLoss;

let criterion = CrossEntropyLoss::new();  // Default: dim=-1
// Or specify class dimension
let criterion = CrossEntropyLoss::with_dim(1);

let loss = criterion.forward((&logits, &targets))?;  // No softmax needed
```

**Parameters:**
- `dim`: Dimension along which classes are arranged (default: -1)

**Formula:**
```
CE = -mean(log(softmax(logits))[batch_idx, target[batch_idx]])
```

**Advantages:**
- Most commonly used for classification
- More numerically stable than softmax + log + NLLLoss
- Combines everything in one operation

**Shape Examples:**
```rust
// Example 1: Image classification
// logits: [batch=32, classes=10]
// targets: [batch=32]

// Example 2: Language modeling
// logits: [batch=4, seq_len=100, vocab=50000]
// targets: [batch=4, seq_len=100]
```

### Loss Function Comparison

| Loss | Input Type | Use Case | Stability |
|------|-----------|----------|-----------|
| MSELoss | Any | Regression | Good |
| MAELoss | Any | Regression (robust) | Good |
| HuberLoss | Any | Regression (outliers) | Excellent |
| BCELoss | Probabilities (0-1) | Binary classification | Good with clamping |
| BCEWithLogitsLoss | Logits | Binary classification | Excellent |
| NLLLoss | Log probabilities | Multi-class | Good |
| CrossEntropyLoss | Logits | Multi-class | Excellent |

### Loss Selection Guide

**For Regression:**
- Default: `MSELoss`
- With outliers: `HuberLoss` or `MAELoss`

**For Binary Classification:**
- Default: `BCEWithLogitsLoss` (most stable)
- If you need probabilities: `sigmoid()` + `BCELoss`

**For Multi-class Classification:**
- Default: `CrossEntropyLoss` (most convenient and stable)
- If you need probabilities: `log_softmax()` + `NLLLoss`

## Optimizers

### SGD

Stochastic Gradient Descent

```rust
use hodu::nn::optimizers::SGD;

let mut optimizer = SGD::new(0.01);  // learning_rate = 0.01

// Training loop
for epoch in 0..epochs {
    let loss = model.forward(&input)?;
    loss.backward()?;

    optimizer.step(&mut model.parameters())?;
    model.zero_grad()?;
}

// Adjust learning rate
optimizer.set_learning_rate(0.001);
```

**Update Rule:**
```
θ_new = θ_old - lr * ∇θ
```

**Parameters:**
- `learning_rate`: Step size (typically 0.001 - 0.1)

**Characteristics:**
- Simple and fast
- Works well for convex problems
- May need learning rate scheduling

### Adam

Adaptive Moment Estimation

```rust
use hodu::nn::optimizers::Adam;

let mut optimizer = Adam::new(
    0.001,  // learning_rate
    0.9,    // beta1 (first moment decay)
    0.999,  // beta2 (second moment decay)
    1e-8,   // epsilon (numerical stability)
);

// Training loop
for epoch in 0..epochs {
    let loss = model.forward(&input)?;
    loss.backward()?;

    optimizer.step(&mut model.parameters())?;
    model.zero_grad()?;
}
```

**Update Rules:**
```
m_t = β₁ * m_(t-1) + (1 - β₁) * g_t
v_t = β₂ * v_(t-1) + (1 - β₂) * g_t²
m̂_t = m_t / (1 - β₁^t)
v̂_t = v_t / (1 - β₂^t)
θ_new = θ_old - lr * m̂_t / (√v̂_t + ε)
```

**Parameters:**
- `learning_rate`: Base learning rate (typically 0.001)
- `beta1`: First moment decay (typically 0.9)
- `beta2`: Second moment decay (typically 0.999)
- `epsilon`: Numerical stability (typically 1e-8)

**Characteristics:**
- Adaptive learning rates per parameter
- Works well in practice
- Default choice for most deep learning tasks
- Includes bias correction for initial steps

### AdamW

Adam with Decoupled Weight Decay

```rust
use hodu::nn::optimizers::AdamW;

let mut optimizer = AdamW::new(
    0.001,  // learning_rate
    0.9,    // beta1 (first moment decay)
    0.999,  // beta2 (second moment decay)
    1e-8,   // epsilon (numerical stability)
    0.01,   // weight_decay
);

// Training loop
for epoch in 0..epochs {
    let loss = model.forward(&input)?;
    loss.backward()?;

    optimizer.step(&mut model.parameters())?;
    model.zero_grad()?;
}

// Adjust hyperparameters
optimizer.set_learning_rate(0.0001);
optimizer.set_weight_decay(0.001);
```

**Update Rules:**
```
θ = θ * (1 - lr * λ)                    // Weight decay (decoupled)
m_t = β₁ * m_(t-1) + (1 - β₁) * g_t
v_t = β₂ * v_(t-1) + (1 - β₂) * g_t²
m̂_t = m_t / (1 - β₁^t)
v̂_t = v_t / (1 - β₂^t)
θ = θ - lr * m̂_t / (√v̂_t + ε)         // Gradient update
```

**Parameters:**
- `learning_rate`: Base learning rate (typically 0.001)
- `beta1`: First moment decay (typically 0.9)
- `beta2`: Second moment decay (typically 0.999)
- `epsilon`: Numerical stability (typically 1e-8)
- `weight_decay`: L2 regularization strength (typically 0.01)

**Characteristics:**
- Decouples weight decay from gradient-based optimization
- Better generalization than Adam in many cases
- Fixes issues with L2 regularization in adaptive optimizers
- Recommended for transformer models and fine-tuning

**Key Difference from Adam:**
- Adam: Weight decay is coupled with adaptive learning rate
- AdamW: Weight decay is applied directly to parameters before gradient update
- This makes weight decay behave more consistently across different learning rates

### Optimizer Comparison

| Optimizer | Speed | Memory | Hyperparameters | Convergence | Weight Decay |
|-----------|-------|--------|-----------------|-------------|--------------|
| SGD | Fast | Low | 1 (lr) | Requires tuning | Not built-in |
| Adam | Medium | High | 4 (lr, β₁, β₂, ε) | Robust, fast | Coupled (incorrect) |
| AdamW | Medium | High | 5 (lr, β₁, β₂, ε, λ) | Robust, fast | Decoupled (correct) |

**Selection Guide:**
- **Default choice**: AdamW with default parameters (best for most cases)
- **Without regularization**: Adam with default parameters
- **Limited memory**: SGD
- **Fine-tuning pretrained models**: AdamW with small weight decay
- **Fast prototyping**: AdamW or Adam

## Complete Example

```rust
use hodu::prelude::*;
use hodu::nn::{modules::*, losses::*, optimizers::*};

fn main() -> HoduResult<()> {
    // Create model layers
    let layer1 = Linear::new(784, 128, true, DType::F32)?;
    let relu = ReLU::new();
    let layer2 = Linear::new(128, 10, true, DType::F32)?;

    // Create loss and optimizer
    let criterion = CrossEntropyLoss::new();
    let mut optimizer = Adam::new(0.001, 0.9, 0.999, 1e-8);

    // Training loop
    for epoch in 0..10 {
        // Forward pass
        let input = Tensor::randn(&[32, 784], 0.0, 1.0)?;
        let targets = Tensor::new(vec![0i64, 1, 2, 3, 4, 5, 6, 7, 8, 9])?;

        let hidden = layer1.forward(&input)?;
        let activated = relu.forward(&hidden)?;
        let logits = layer2.forward(&activated)?;

        // Compute loss
        let loss = criterion.forward((&logits, &targets))?;

        // Backward pass
        loss.backward()?;

        // Update parameters
        let mut params = layer1.parameters();
        params.extend(layer2.parameters());
        optimizer.step(&mut params)?;

        // Zero gradients
        for param in params {
            param.zero_grad()?;
        }

        println!("Epoch {}: Loss = {}", epoch, loss);
    }

    Ok(())
}
```

## Notes

### Module Pattern

All modules follow a consistent pattern:

```rust
impl Module {
    pub fn new(...) -> Self { ... }
    pub fn forward(&self, input: &Tensor) -> HoduResult<Tensor> { ... }
    pub fn parameters(&mut self) -> Vec<&mut Tensor> { ... }
}
```

### Loss Pattern

All losses accept `(&Tensor, &Tensor)` tuple:

```rust
impl Loss {
    pub fn new() -> Self { ... }
    pub fn forward(&self, (prediction, target): (&Tensor, &Tensor)) -> HoduResult<Tensor> { ... }
}
```

### Optimizer Pattern

All optimizers operate on mutable parameter slices:

```rust
impl Optimizer {
    pub fn new(...) -> Self { ... }
    pub fn step(&mut self, parameters: &mut [&mut Tensor]) -> HoduResult<()> { ... }
    pub fn set_learning_rate(&mut self, lr: impl Into<Scalar>) { ... }
}
```

### Gradient Management

Remember to:
1. Call `backward()` after computing loss
2. Call `optimizer.step()` to update parameters
3. Call `zero_grad()` on all parameters before next iteration

### Numerical Stability

For classification:
- Use `BCEWithLogitsLoss` instead of `sigmoid() + BCELoss`
- Use `CrossEntropyLoss` instead of `softmax() + log() + NLLLoss`
- These combined operations are more numerically stable