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
//! Advanced activation functions
//!
//! This module provides advanced activation functions including GELU, GLU,
//! scaled dot-product attention, and local response normalization.
use ;
use Tensor;
/// Gaussian Error Linear Unit (GELU) activation function
///
/// **Mathematical Definition (Exact):**
/// ```text
/// GELU(x) = x * Φ(x) = x * (1/2)[1 + erf(x/√2)]
/// ```
/// where Φ(x) is the CDF of standard normal distribution, and erf is the error function.
///
/// **Approximation (Commonly Used):**
/// ```text
/// GELU(x) ≈ 0.5 * x * (1 + tanh(√(2/π) * (x + 0.044715 * x³)))
/// ```
///
/// **Alternative Sigmoid Approximation:**
/// ```text
/// GELU(x) ≈ x * σ(1.702 * x), where σ is sigmoid
/// ```
///
/// **Intuition:**
/// GELU applies a "soft" version of ReLU by weighting inputs by their percentile in a standard
/// normal distribution. Inputs that are "typical" (around 0) get partial activation, while
/// extreme positive values get nearly full activation and extreme negative values get nearly zero.
///
/// **Properties:**
/// - **Smooth**: Differentiable everywhere (unlike ReLU)
/// - **Non-monotonic**: Has a small negative region for negative inputs
/// - **Probabilistic**: Based on cumulative distribution function
/// - **Self-gating**: Multiplies input by its activation probability
/// - **Near-zero derivative**: At x = 0, derivative ≈ 0.5
///
/// **Derivative:**
/// ```text
/// d/dx GELU(x) = Φ(x) + x * φ(x)
/// ```
/// where φ(x) = (1/√(2π)) * exp(-x²/2) is the PDF of standard normal distribution.
///
/// **Applications:**
/// - **Transformers**: Used in BERT, GPT, and other transformer models
/// - **Modern CNNs**: Increasingly popular replacement for ReLU
/// - **NLP models**: Particularly effective in language models
/// - **Computer Vision**: Good performance in vision transformers
/// - **Research models**: Default choice in many recent architectures
///
/// **Advantages:**
/// - **Smooth gradients**: No dead neurons like ReLU
/// - **Non-zero negative**: Small gradient for negative inputs prevents dying neurons
/// - **Empirically strong**: Often outperforms ReLU in practice
/// - **Principled**: Theoretically motivated by dropout and ReLU
/// - **Context-dependent**: Activation depends on input distribution
///
/// **Disadvantages:**
/// - **Computational cost**: More expensive than ReLU (requires erf or tanh)
/// - **Approximation errors**: Common approximations introduce small errors
/// - **Less interpretable**: More complex than simple thresholding
///
/// **Comparison to Other Activations:**
/// - vs ReLU: Smooth, no dying neurons, but more expensive
/// - vs ELU: Similar smoothness but different mathematical foundation
/// - vs Swish: Very similar performance, GELU often preferred in transformers
/// GLU (Gated Linear Unit) activation function
///
/// **Mathematical Definition:**
/// ```text
/// GLU(x) = (x_a) ⊙ σ(x_b)
/// ```
/// where x is split into two halves: x_a (first half) and x_b (second half),
/// and ⊙ denotes element-wise multiplication.
///
/// **Detailed Form:**
/// For input tensor x with shape (..., 2d), GLU produces output with shape (..., d):
/// ```text
/// GLU(x)[..., i] = x[..., i] * σ(x[..., i + d])
/// ```
/// where σ is the sigmoid function.
///
/// **Properties:**
/// - **Gating mechanism**: Second half controls flow of first half
/// - **Dimension reduction**: Output has half the channels of input
/// - **Learnable gating**: Gate values learned during training
/// - **Multiplicative**: Uses element-wise multiplication for gating
/// - **Sigmoid-based**: Uses sigmoid for gate activation
///
/// **Variants:**
/// - **GLU**: Original with sigmoid gates: GLU(x) = x_a * σ(x_b)
/// - **Swish GLU**: Uses Swish instead of sigmoid: x_a * swish(x_b)
/// - **GELU GLU**: Uses GELU instead of sigmoid: x_a * GELU(x_b)
/// - **ReGLU**: Uses ReLU instead of sigmoid: x_a * ReLU(x_b)
///
/// **Applications:**
/// - **Language models**: Particularly effective in transformer feed-forward layers
/// - **Computer vision**: Used in some CNN architectures
/// - **Speech processing**: Helps with temporal modeling
/// - **Sequence modeling**: General purpose gating for sequences
/// - **Feed-forward networks**: Alternative to standard linear layers
///
/// **Advantages:**
/// - **Selective information flow**: Can learn to gate irrelevant information
/// - **Non-linear gating**: More flexible than linear transformations
/// - **Empirically effective**: Often improves model performance
/// - **Gradient flow**: Can help with gradient flow in deep networks
///
/// **Disadvantages:**
/// - **Parameter overhead**: Requires double the input channels
/// - **Computational cost**: Additional sigmoid and multiplication operations
/// - **Dimension constraint**: Input channels must be even
/// - **Complexity**: More complex than simple activations
///
/// **Usage Notes:**
/// - Input tensor must have even size in the specified dimension
/// - Commonly used in transformer feed-forward networks
/// - Often combined with layer normalization and residual connections
/// Scaled Dot-Product Attention activation
///
/// **Mathematical Definition:**
/// ```text
/// Attention(Q, K, V) = softmax(QK^T / √d_k)V
/// ```
/// where:
/// - Q: Query matrix (batch_size, seq_len, d_k)
/// - K: Key matrix (batch_size, seq_len, d_k)
/// - V: Value matrix (batch_size, seq_len, d_v)
/// - d_k: Dimension of key vectors (used for scaling)
///
/// **With Optional Components:**
/// ```text
/// Attention(Q, K, V) = softmax((QK^T + mask) / √d_k)V
/// ```
/// where mask can be:
/// - Attention mask: Prevents attention to certain positions
/// - Causal mask: Prevents attention to future positions
///
/// **Scaling Factor:**
/// The scaling factor 1/√d_k prevents the dot products from growing too large,
/// which would push the softmax into saturation regions with small gradients.
///
/// **Properties:**
/// - **Permutation equivariant**: Order of inputs affects output consistently
/// - **Context mixing**: Each output is a weighted combination of all values
/// - **Learned attention**: Attention weights learned during training
/// - **Differentiable**: All operations are differentiable
/// - **Parallelizable**: Can be computed efficiently in parallel
///
/// **Components:**
/// 1. **Query-Key similarity**: QK^T computes pairwise similarities
/// 2. **Scaling**: Division by √d_k for numerical stability
/// 3. **Masking**: Optional masking for causal or padding tokens
/// 4. **Normalization**: Softmax to create probability distribution
/// 5. **Value aggregation**: Weighted sum of values
///
/// **Applications:**
/// - **Transformers**: Core component of transformer architectures
/// - **BERT/GPT**: Foundation of modern language models
/// - **Vision Transformers**: Applied to image patches
/// - **Multi-modal models**: Attention across different modalities
/// - **Sequence-to-sequence**: Translation, summarization, etc.
///
/// **Advantages:**
/// - **Long-range dependencies**: Can attend to any position
/// - **Parallel computation**: Unlike RNNs, can be computed in parallel
/// - **Interpretable**: Attention weights provide interpretability
/// - **Flexible**: Can handle variable-length sequences
///
/// **Disadvantages:**
/// - **Quadratic complexity**: O(n²) memory and computation w.r.t. sequence length
/// - **Attention collapse**: May attend to only a few positions
/// - **Computational cost**: Expensive for very long sequences
/// - **Memory requirements**: Stores full attention matrix
///
/// **Optimizations:**
/// - **Flash Attention**: Memory-efficient implementation
/// - **Sparse attention**: Only attend to subset of positions
/// - **Linear attention**: Approximate attention with linear complexity
/// - **Gradient checkpointing**: Trade computation for memory
/// Local Response Normalization (LRN) activation function
///
/// **Mathematical Definition:**
/// ```text
/// LRN(x_i) = x_i / (k + α * Σ_{j=max(0,i-n/2)}^{min(N-1,i+n/2)} x_j²)^β
/// ```
/// where:
/// - x_i: Input at position i
/// - N: Total number of elements
/// - n: Local size (number of adjacent elements to consider)
/// - k: Bias parameter (typically 1.0 or 2.0)
/// - α: Scale parameter (typically 1e-4)
/// - β: Exponential parameter (typically 0.75)
///
/// **Simplified Form (used here):**
/// For computational simplicity, we normalize across channels:
/// ```text
/// LRN(x) = x / (k + (α/size) * sum(x²))^β
/// ```
///
/// **Properties:**
/// - **Local normalization**: Each element normalized by its local neighborhood
/// - **Lateral inhibition**: Strong activations suppress nearby activations
/// - **Contrast enhancement**: Increases contrast between strong and weak activations
/// - **Non-linear**: Non-linear normalization function
/// - **Parameter dependent**: Behavior controlled by k, α, β parameters
///
/// **Historical Context:**
/// LRN was popularized by AlexNet (2012) and was commonly used in early CNNs.
/// It has largely been replaced by batch normalization in modern architectures.
///
/// **Applications:**
/// - **Legacy CNNs**: AlexNet, early convolutional networks
/// - **Object detection**: Some early detection frameworks
/// - **Contrast enhancement**: When local contrast is important
/// - **Biological inspiration**: Models lateral inhibition in neuroscience
///
/// **Advantages:**
/// - **Local contrast**: Enhances local feature contrast
/// - **Normalization**: Prevents activation magnitudes from growing too large
/// - **Biological plausibility**: Inspired by biological neural networks
/// - **Simple**: Relatively simple to implement and understand
///
/// **Disadvantages:**
/// - **Outdated**: Largely superseded by batch normalization
/// - **Computational cost**: More expensive than batch norm
/// - **Less effective**: Generally less effective than modern normalization methods
/// - **Hyperparameter sensitive**: Requires careful tuning of k, α, β
///
/// **Modern Alternatives:**
/// - **Batch Normalization**: Normalizes across batch dimension
/// - **Layer Normalization**: Normalizes across feature dimension
/// - **Group Normalization**: Normalizes across groups of channels
/// - **Instance Normalization**: Normalizes per sample and channel
///
/// **Usage Notes:**
/// - Mainly of historical interest in modern deep learning
/// - Consider batch normalization or layer normalization for new models
/// - May still be useful in specific applications requiring local contrast