nnl 0.1.4

A high-performance neural network library for Rust with CPU and GPU support
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
# Neural Network Layer Guide

This guide provides comprehensive documentation for using layers in the NNL library, including shape calculations, configuration guidelines, and common pitfalls.

## Table of Contents
- [Shape Flow Basics]#shape-flow-basics
- [Convolutional Layers]#convolutional-layers
- [Pooling Layers]#pooling-layers
- [Dense Layers]#dense-layers
- [Normalization Layers]#normalization-layers
- [Utility Layers]#utility-layers
- [Common Patterns]#common-patterns
- [Troubleshooting]#troubleshooting

## Shape Flow Basics

Understanding how tensor shapes flow through your network is crucial for building working models. Each layer transforms the input shape according to its specific rules.

### Tensor Format
- **4D tensors**: `[batch_size, channels, height, width]` (for images)
- **2D tensors**: `[batch_size, features]` (for dense layers)
- **3D tensors**: `[batch_size, sequence_length, features]` (for sequences)

### Shape Calculation Functions
```rust
// Calculate convolution output size
fn conv_output_size(input_size: usize, kernel_size: usize, stride: usize, padding: usize, dilation: usize) -> usize {
    (input_size + 2 * padding - dilation * (kernel_size - 1) - 1) / stride + 1
}

// Calculate pooling output size
fn pool_output_size(input_size: usize, kernel_size: usize, stride: usize, padding: usize) -> usize {
    (input_size + 2 * padding - kernel_size) / stride + 1
}
```

## Convolutional Layers

### Conv2D Configuration

```rust
LayerConfig::Conv2D {
    in_channels: 3,        // Input channels (e.g., 3 for RGB images)
    out_channels: 64,      // Output channels (number of filters)
    kernel_size: (3, 3),   // Filter size (height, width)
    stride: (1, 1),        // Step size (height, width)
    padding: (1, 1),       // Padding (height, width)
    dilation: (1, 1),      // Dilation factor (height, width)
    activation: Activation::ReLU,
    use_bias: true,
    weight_init: WeightInit::HeNormal,
}
```

### Shape Calculation Example

**Input**: `[1, 3, 32, 32]` (CIFAR-10 image)
**Conv2D**: `kernel_size=(3,3), stride=(1,1), padding=(1,1)`

```
Output Height = (32 + 2*1 - 1*(3-1) - 1) / 1 + 1 = 32
Output Width  = (32 + 2*1 - 1*(3-1) - 1) / 1 + 1 = 32
Output Shape  = [1, 64, 32, 32]
```

### Common Patterns

#### Same Padding (preserve spatial dimensions)
```rust
LayerConfig::Conv2D {
    kernel_size: (3, 3),
    stride: (1, 1),
    padding: (1, 1),    // padding = (kernel_size - 1) / 2
    // ...
}
```

#### Downsampling (reduce spatial dimensions by 2)
```rust
LayerConfig::Conv2D {
    kernel_size: (3, 3),
    stride: (2, 2),     // stride = 2 for 2x downsampling
    padding: (1, 1),
    // ...
}
```

## Pooling Layers

### MaxPool2D and AvgPool2D

```rust
LayerConfig::MaxPool2D {
    kernel_size: (2, 2),     // Pooling window size
    stride: Some((2, 2)),    // Step size (None = kernel_size)
    padding: (0, 0),         // Padding
}
```

### Global Average Pooling

For global average pooling, use `stride: None` to make stride equal to kernel_size:

```rust
// Convert [batch, channels, H, W] -> [batch, channels, 1, 1]
LayerConfig::AvgPool2D {
    kernel_size: (H, W),     // Same as input spatial size
    stride: None,            // stride = kernel_size for global pooling
    padding: (0, 0),
}
```

### Shape Examples

#### Regular Pooling
**Input**: `[1, 64, 32, 32]`
**MaxPool2D**: `kernel_size=(2,2), stride=Some((2,2))`
**Output**: `[1, 64, 16, 16]`

#### Global Average Pooling
**Input**: `[1, 512, 4, 4]`
**AvgPool2D**: `kernel_size=(4,4), stride=None`
**Output**: `[1, 512, 1, 1]`

⚠️ **Common Mistake**: Using `stride: Some((1, 1))` for global pooling will not reduce spatial dimensions properly.

## Dense Layers

### Configuration

```rust
LayerConfig::Dense {
    input_size: 512,          // Must match flattened input size
    output_size: 256,         // Number of output neurons
    activation: Activation::ReLU,
    use_bias: true,
    weight_init: WeightInit::HeNormal,
}
```

### Shape Calculation

Dense layers expect 2D input: `[batch_size, input_size]`

**Example**:
- Input: `[batch_size, 512]`
- Dense layer: `input_size=512, output_size=256`
- Output: `[batch_size, 256]`

### Calculating Input Size After Convolutions

After convolution and pooling layers, you need to flatten to feed into dense layers:

```rust
// CIFAR-10 example shape flow:
// [1, 3, 32, 32]    <- Input image
// [1, 64, 32, 32]   <- After Conv2D (same padding)
// [1, 128, 16, 16]  <- After Conv2D (stride=2)
// [1, 256, 8, 8]    <- After Conv2D (stride=2)
// [1, 512, 4, 4]    <- After Conv2D (stride=2)
// [1, 512, 1, 1]    <- After AvgPool2D global pooling
// [1, 512]          <- After Flatten
```

The Dense layer input_size should be: `512 * 1 * 1 = 512`

## Normalization Layers

### BatchNorm

```rust
LayerConfig::BatchNorm {
    num_features: 64,         // Same as input channels
    eps: 1e-5,
    momentum: 0.1,
    affine: true,             // Enable learnable parameters
}
```

**Shape**: Input and output shapes are identical.

### LayerNorm

```rust
LayerConfig::LayerNorm {
    normalized_shape: vec![512],  // Shape of dimensions to normalize
    eps: 1e-5,
    elementwise_affine: true,
}
```

## Utility Layers

### Flatten

```rust
LayerConfig::Flatten {
    start_dim: 1,            // Start flattening from dimension 1
    end_dim: None,           // Flatten to the end (None = last dim)
}
```

**Shape Examples**:
- Input: `[1, 512, 4, 4]`
- Flatten: `start_dim=1, end_dim=None`
- Output: `[1, 8192]` (1 * 512 * 4 * 4 = 8192)

### Dropout

```rust
LayerConfig::Dropout {
    dropout_rate: 0.5,       // Probability of setting elements to zero
}
```

**Shape**: Input and output shapes are identical.

## Common Patterns

### CIFAR-10 CNN Architecture

```rust
NetworkBuilder::new()
    // Input: [batch, 3, 32, 32]
    .add_layer(LayerConfig::Conv2D {
        in_channels: 3, out_channels: 64,
        kernel_size: (3, 3), stride: (1, 1), padding: (1, 1),
        activation: Activation::ReLU, use_bias: true,
        weight_init: WeightInit::HeNormal,
    })
    // Shape: [batch, 64, 32, 32]
    
    .add_layer(LayerConfig::Conv2D {
        in_channels: 64, out_channels: 128,
        kernel_size: (3, 3), stride: (2, 2), padding: (1, 1),
        activation: Activation::ReLU, use_bias: true,
        weight_init: WeightInit::HeNormal,
    })
    // Shape: [batch, 128, 16, 16]
    
    .add_layer(LayerConfig::Conv2D {
        in_channels: 128, out_channels: 256,
        kernel_size: (3, 3), stride: (2, 2), padding: (1, 1),
        activation: Activation::ReLU, use_bias: true,
        weight_init: WeightInit::HeNormal,
    })
    // Shape: [batch, 256, 8, 8]
    
    .add_layer(LayerConfig::Conv2D {
        in_channels: 256, out_channels: 512,
        kernel_size: (3, 3), stride: (2, 2), padding: (1, 1),
        activation: Activation::ReLU, use_bias: true,
        weight_init: WeightInit::HeNormal,
    })
    // Shape: [batch, 512, 4, 4]
    
    .add_layer(LayerConfig::AvgPool2D {
        kernel_size: (4, 4),
        stride: None,  // Global average pooling
        padding: (0, 0),
    })
    // Shape: [batch, 512, 1, 1]
    
    .add_layer(LayerConfig::Flatten {
        start_dim: 1,
        end_dim: None,
    })
    // Shape: [batch, 512]
    
    .add_layer(LayerConfig::Dense {
        input_size: 512,  // Must match flattened size
        output_size: 10,  // Number of classes
        activation: Activation::Softmax,
        use_bias: true,
        weight_init: WeightInit::Xavier,
    })
    // Shape: [batch, 10]
```

### ResNet-style Block

```rust
// Residual block pattern
.add_layer(LayerConfig::Conv2D { /* ... */ })
.add_layer(LayerConfig::BatchNorm { /* ... */ })
.add_layer(LayerConfig::Conv2D { 
    activation: Activation::Linear, // No activation here
    /* ... */ 
})
.add_layer(LayerConfig::BatchNorm { /* ... */ })
// Add skip connection here (not shown - would need custom layer)
.add_layer(LayerConfig::Conv2D {
    kernel_size: (1, 1), // Activation via 1x1 conv
    activation: Activation::ReLU,
    /* ... */
})
```

## Troubleshooting

### Common Errors and Solutions

#### 1. Shape Mismatch in Dense Layer

**Error**: `Shape mismatch: expected [512], got [8192]`

**Cause**: The flattened tensor size doesn't match the Dense layer's `input_size`.

**Solution**: Calculate the correct flattened size:
```rust
// After convolutions ending with shape [batch, 512, 4, 4]:
// Flattened size = 512 * 4 * 4 = 8192
LayerConfig::Dense {
    input_size: 8192,  // Not 512!
    // ...
}
```

Or use proper global average pooling to get [batch, 512, 1, 1] → [batch, 512].

#### 2. Global Average Pooling Not Working

**Problem**: Using `stride: Some((1, 1))` doesn't reduce spatial dimensions.

**Solution**: Use `stride: None` for global average pooling:
```rust
LayerConfig::AvgPool2D {
    kernel_size: (4, 4),  // Same as input spatial size
    stride: None,         // This makes stride = kernel_size
    padding: (0, 0),
}
```

#### 3. Negative Output Dimensions

**Error**: Calculation results in negative or zero output dimensions.

**Causes**:
- Kernel size larger than input size
- Insufficient padding
- Stride too large

**Solution**: Adjust parameters:
```rust
// For input size 32x32 with kernel 5x5:
LayerConfig::Conv2D {
    kernel_size: (5, 5),
    stride: (1, 1),
    padding: (2, 2),  // padding = (kernel_size - 1) / 2
    // ...
}
```

#### 4. Channel Mismatch

**Error**: `expected [64], actual [128]`

**Cause**: Output channels of one layer don't match input channels of the next.

**Solution**: Ensure channel continuity:
```rust
.add_layer(LayerConfig::Conv2D {
    in_channels: 64,
    out_channels: 128,  // Output 128 channels
    // ...
})
.add_layer(LayerConfig::Conv2D {
    in_channels: 128,   // Input must be 128 channels
    out_channels: 256,
    // ...
})
```

### Debugging Shape Flow

Add debug prints to trace shapes:
```rust
// Test network with dummy input
let test_input = Tensor::zeros(&[1, 3, 32, 32])?;
let output = network.forward(&test_input)?;
println!("Final output shape: {:?}", output.shape());
```

Or create a simple debug network that stops at each layer to check intermediate shapes.

### Best Practices

1. **Plan your architecture**: Calculate shapes on paper before implementing
2. **Use same padding**: For preserving spatial dimensions in early layers
3. **Power-of-2 channels**: Use 32, 64, 128, 256, 512 for better hardware utilization
4. **Gradual downsampling**: Reduce spatial dimensions while increasing channels
5. **Global pooling**: Prefer global average pooling over large dense layers
6. **Batch normalization**: Add after Conv2D layers (before activation)
7. **Proper initialization**: Use HeNormal for ReLU, Xavier for Sigmoid/Tanh

### Weight Initialization Guidelines

```rust
// For ReLU activations
weight_init: WeightInit::HeNormal,

// For Sigmoid/Tanh activations  
weight_init: WeightInit::Xavier,

// For linear layers (no activation)
weight_init: WeightInit::Xavier,

// For final classification layer
weight_init: WeightInit::Xavier,
```

This guide should help you build robust neural networks with proper shape flow and avoid common pitfalls. Remember to always verify your shape calculations and test with dummy inputs before training.