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
//! Individual fused operation implementations
//!
//! This module contains the actual implementations of fused operations,
//! including basic arithmetic fusions and complex operations like batch norm.
use crateTorshResult;
use TorshError;
use Tensor;
/// Fused ReLU + Add operation: relu(x + y)
///
/// # Mathematical Formula
/// ```text
/// output[i] = max(0, x[i] + y[i])
/// ```
/// where the max operation is applied element-wise.
///
/// # Applications
/// - **Residual connections**: Used in ResNet architectures to combine skip connections
/// - **Gated networks**: Part of gating mechanisms in RNNs and Transformers
/// - **Activation after bias**: Common pattern of adding bias followed by activation
///
/// # Performance Benefits
/// - **Memory efficiency**: Single pass through data instead of two separate operations
/// - **Cache optimization**: Better temporal locality of reference
/// - **SIMD acceleration**: Leverages vectorized instructions when available
/// - **Reduced kernel launches**: Important for GPU implementations
/// Fused Multiply + Add operation: x * y + z (FMADD)
///
/// # Mathematical Formula
/// ```text
/// output[i] = x[i] * y[i] + z[i]
/// ```
/// This implements the fused multiply-add (FMA) operation element-wise.
///
/// # Mathematical Properties
/// - **Associative**: (a * b) + c = a * (b + c/a) when c/a is defined
/// - **Distributive**: Can be factored as x * (y + z/x) when z/x is defined
/// - **Numerical stability**: Hardware FMA reduces intermediate rounding errors
///
/// # Applications
/// - **Linear transformations**: Core operation in fully connected layers
/// - **Convolution**: Inner product computation in conv layers
/// - **Attention mechanisms**: Query-key-value computations in Transformers
/// - **Bias addition**: Adding bias terms after matrix multiplication
/// - **Polynomial evaluation**: Horner's method for efficient polynomial computation
///
/// # Performance Benefits
/// - **Hardware acceleration**: Leverages dedicated FMA units on modern CPUs/GPUs
/// - **Reduced memory bandwidth**: Single read/write cycle for three operations
/// - **Improved numerical accuracy**: Hardware FMA has single rounding step
/// - **Vectorization**: Excellent SIMD/GPU parallelization characteristics
/// Fused Add + Multiply operation: (x + y) * z
///
/// # Mathematical Formula
/// ```text
/// output[i] = (x[i] + y[i]) * z[i]
/// ```
/// This computes element-wise addition followed by element-wise multiplication.
///
/// # Mathematical Properties
/// - **Distributive**: Equivalent to x*z + y*z (when beneficial for optimization)
/// - **Commutative in addition**: (x + y) * z = (y + x) * z
/// - **Associative with scaling**: Can be reordered for numerical stability
///
/// # Applications
/// - **Gating mechanisms**: Used in LSTM and GRU cells
/// - **Attention weights**: Combining attention scores with values
/// - **Normalization**: Part of layer normalization computation
/// - **Activation scaling**: Applying learned scaling after bias addition
///
/// # Performance Benefits
/// - **Memory efficiency**: Avoids storing intermediate (x + y) result
/// - **Cache locality**: Better temporal access pattern than separate operations
/// - **SIMD optimization**: Efficient vectorization on modern architectures
/// - **Reduced memory bandwidth**: Fewer memory transactions than separate operations
/// Fused Sigmoid + Multiply operation: sigmoid(x) * y
///
/// # Mathematical Formula
/// ```text
/// output[i] = sigmoid(x[i]) * y[i] = (1 / (1 + exp(-x[i]))) * y[i]
/// ```
/// When y = x, this becomes the SiLU (Swish) activation function.
///
/// # Mathematical Properties
/// - **Bounded output**: sigmoid(x) ∈ (0, 1), so output is scaled version of y
/// - **Smooth**: Infinitely differentiable with well-behaved gradients
/// - **Monotonic in x**: Sigmoid function is strictly increasing
///
/// # Applications
/// - **SiLU activation**: When y = x, creates x * sigmoid(x) (Swish/SiLU)
/// - **Gated units**: Sigmoid acts as a gate controlling information flow
/// - **Attention mechanisms**: Sigmoid gates in some attention variants
/// - **Highway networks**: Gating mechanism for information highways
///
/// # Performance Benefits
/// - **Single memory pass**: Avoids intermediate sigmoid storage
/// - **SIMD efficiency**: Good vectorization characteristics
/// - **Numerical stability**: Combined operation reduces precision loss
/// - **Cache optimization**: Better memory access pattern than separate operations
/// Fused SiLU activation: x * sigmoid(x)
///
/// # Mathematical Formula
/// ```text
/// output[i] = x[i] * sigmoid(x[i]) = x[i] / (1 + exp(-x[i]))
/// ```
/// This is the Sigmoid Linear Unit (SiLU), also known as Swish activation.
///
/// # Mathematical Properties
/// - **Self-gated**: Uses its own values as gates (x * sigmoid(x))
/// - **Smooth**: Infinitely differentiable, unlike ReLU
/// - **Non-monotonic**: Has a small negative region for negative inputs
/// - **Bounded below**: Approaches -0.278 as x → -∞, unlike ReLU's hard cutoff
///
/// # Applications
/// - **Modern architectures**: Increasingly used instead of ReLU in newer models
/// - **Transformer variants**: Some attention mechanisms and FFN layers
/// - **EfficientNet**: Used as primary activation in EfficientNet architectures
/// - **Swish activation**: Equivalent implementation of Google's Swish function
///
/// # Performance Benefits
/// - **Single tensor pass**: Avoids creating intermediate sigmoid tensor
/// - **SIMD optimization**: Excellent vectorization characteristics
/// - **Memory efficiency**: Lower memory bandwidth than separate sigmoid + multiply
/// - **Gradient efficiency**: Smooth gradients improve training stability
/// Fused Tanh + Scale operation: tanh(x) * scale
///
/// # Mathematical Formula
/// ```text
/// output[i] = tanh(x[i]) * scale = ((exp(x[i]) - exp(-x[i])) / (exp(x[i]) + exp(-x[i]))) * scale
/// ```
/// This applies hyperbolic tangent followed by scalar scaling.
///
/// # Mathematical Properties
/// - **Bounded**: tanh(x) ∈ (-1, 1), so output ∈ (-scale, scale)
/// - **Odd function**: tanh(-x) = -tanh(x), preserving sign symmetry
/// - **Smooth**: Infinitely differentiable with bounded derivatives
/// - **Saturating**: Approaches ±1 for large |x|, providing natural gradient clipping
///
/// # Applications
/// - **Scaled activations**: Custom activation functions with controlled output range
/// - **Gating mechanisms**: Tanh gates in LSTM cells with scaling
/// - **Attention mechanisms**: Scaled tanh in some attention formulations
/// - **Normalization**: Part of custom normalization schemes
///
/// # Performance Benefits
/// - **Single memory pass**: Avoids intermediate tanh storage
/// - **SIMD acceleration**: Good vectorization for both tanh and scaling
/// - **Reduced memory bandwidth**: Fewer memory operations than separate tanh + scale
/// - **Cache efficiency**: Better temporal locality than separate operations
/// Fused Add + ReLU + Multiply operation: relu(x + bias) * scale
///
/// # Mathematical Formula
/// ```text
/// output[i] = max(0, x[i] + bias[i]) * scale[i]
/// ```
/// This combines bias addition, ReLU activation, and scaling in a single operation.
///
/// # Mathematical Properties
/// - **Non-linear transformation**: Combines linear (add, multiply) and non-linear (ReLU) operations
/// - **Piecewise linear**: Output is piecewise linear due to ReLU
/// - **Sparse activation**: ReLU creates sparsity, multiplication preserves or amplifies it
///
/// # Applications
/// - **Batch normalization**: Part of batch norm when followed by learned scaling
/// - **Residual connections**: Advanced residual blocks with scaling
/// - **Attention mechanisms**: Scaled attention values with ReLU gating
/// - **Custom activations**: Building blocks for complex activation functions
///
/// # Performance Benefits
/// - **Memory efficiency**: Avoids two intermediate tensor allocations
/// - **Cache optimization**: Single pass through data improves cache utilization
/// - **SIMD acceleration**: All operations vectorize well independently
/// - **Reduced memory bandwidth**: 3x reduction in memory operations vs separate functions
/// Fused Batch Normalization operation
///
/// # Mathematical Formula
/// ```text
/// output[i] = ((x[i] - mean[i]) / sqrt(var[i] + eps)) * gamma[i] + beta[i]
/// ```
/// This implements the complete batch normalization transformation in a single fused operation.
///
/// # Mathematical Properties
/// - **Standardization**: Centers data around zero with unit variance
/// - **Affine transformation**: Gamma and beta allow learning optimal scale and shift
/// - **Numerical stability**: Epsilon prevents division by zero in variance calculation
///
/// # Applications
/// - **Deep networks**: Enables training of very deep networks by normalizing activations
/// - **Convergence speed**: Accelerates training by reducing internal covariate shift
/// - **Regularization**: Provides mild regularization effect during training
/// - **Broadcasting**: Parameters broadcast along batch and spatial dimensions
/// - **Inference mode**: Uses pre-computed running statistics
/// - **Training mode**: Computes batch statistics on-the-fly
///
/// # Performance Benefits
/// - **Single kernel**: Combines 4-5 separate operations into one pass
/// - **Memory efficiency**: Reduces intermediate tensor allocations
/// - **Cache optimization**: Better data locality than separate operations
/// - **Numerical precision**: Minimizes accumulation of floating-point errors