trueno 0.17.4

High-performance SIMD compute library with GPU support for matrix operations
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
//! Scalar (non-SIMD) backend implementation
//!
//! This is the portable baseline implementation that works on all platforms.
//! It uses simple loops without any SIMD instructions.
//!
//! # Performance
//!
//! This backend provides correctness reference but no SIMD acceleration.
//! Expected to be 8-32x slower than SIMD backends on operations with 1K+ elements.

use super::VectorBackend;

/// Scalar backend (portable, no SIMD)
pub struct ScalarBackend;

impl VectorBackend for ScalarBackend {
    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/indexing
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn add(a: &[f32], b: &[f32], result: &mut [f32]) {
        for i in 0..a.len() {
            result[i] = a[i] + b[i];
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/indexing
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sub(a: &[f32], b: &[f32], result: &mut [f32]) {
        for i in 0..a.len() {
            result[i] = a[i] - b[i];
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/indexing
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn mul(a: &[f32], b: &[f32], result: &mut [f32]) {
        for i in 0..a.len() {
            result[i] = a[i] * b[i];
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/indexing
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn div(a: &[f32], b: &[f32], result: &mut [f32]) {
        for i in 0..a.len() {
            result[i] = a[i] / b[i];
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/indexing
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    //
    // OPTIMIZATION: 4× unrolling with mul_add for better ILP and auto-vectorization.
    // This follows the cuda-tile pattern for improved throughput (spec: cuda-tile-behavior.md).
    // Using f32::mul_add provides FMA semantics where available, improving accuracy.
    #[inline(always)]
    // SAFETY: caller ensures preconditions are met for this unsafe function
    unsafe fn dot(a: &[f32], b: &[f32]) -> f32 {
        let len = a.len();
        let chunks = len / 4;

        // 4 independent accumulators for better ILP (cuda-tile inspired optimization)
        let mut acc0 = 0.0f32;
        let mut acc1 = 0.0f32;
        let mut acc2 = 0.0f32;
        let mut acc3 = 0.0f32;

        // Process 4 elements at a time with independent accumulation chains
        for i in 0..chunks {
            let base = i * 4;
            acc0 = a[base].mul_add(b[base], acc0);
            acc1 = a[base + 1].mul_add(b[base + 1], acc1);
            acc2 = a[base + 2].mul_add(b[base + 2], acc2);
            acc3 = a[base + 3].mul_add(b[base + 3], acc3);
        }

        // Combine all 4 accumulators
        let mut sum = (acc0 + acc1) + (acc2 + acc3);

        // Handle remainder
        for i in (chunks * 4)..len {
            sum = a[i].mul_add(b[i], sum);
        }

        sum
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sum(a: &[f32]) -> f32 {
        let mut total = 0.0;
        for &val in a {
            total += val;
        }
        total
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust slicing/iteration
    // 2. Caller must ensure slice is non-empty (a[0] access)
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn max(a: &[f32]) -> f32 {
        let mut maximum = a[0];
        for &val in a.get(1..).unwrap_or(&[]) {
            if val > maximum {
                maximum = val;
            }
        }
        maximum
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust slicing/iteration
    // 2. Caller must ensure slice is non-empty (a[0] access)
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn min(a: &[f32]) -> f32 {
        let mut minimum = a[0];
        for &val in a.get(1..).unwrap_or(&[]) {
            if val < minimum {
                minimum = val;
            }
        }
        minimum
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Caller must ensure slice is non-empty (a[0] access)
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn argmax(a: &[f32]) -> usize {
        let mut max_value = a[0];
        let mut max_index = 0;
        for (i, &val) in a.iter().enumerate() {
            if val > max_value {
                max_value = val;
                max_index = i;
            }
        }
        max_index
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Caller must ensure slice is non-empty (a[0] access)
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn argmin(a: &[f32]) -> usize {
        let mut min_value = a[0];
        let mut min_index = 0;
        for (i, &val) in a.iter().enumerate() {
            if val < min_value {
                min_value = val;
                min_index = i;
            }
        }
        min_index
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Kahan summation uses only safe floating-point arithmetic
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sum_kahan(a: &[f32]) -> f32 {
        let mut sum = 0.0;
        let mut c = 0.0; // Compensation for lost low-order bits

        for &value in a {
            let y = value - c; // Subtract the compensation
            let t = sum + y; // Add to sum
            c = (t - sum) - y; // Update compensation
            sum = t; // Update sum
        }

        sum
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Empty check prevents undefined behavior
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn norm_l2(a: &[f32]) -> f32 {
        if a.is_empty() {
            return 0.0;
        }

        let mut sum_of_squares = 0.0;
        for &val in a {
            sum_of_squares += val * val;
        }
        sum_of_squares.sqrt()
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Empty check prevents undefined behavior
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn norm_l1(a: &[f32]) -> f32 {
        if a.is_empty() {
            return 0.0;
        }

        let mut sum = 0.0;
        for &val in a {
            sum += val.abs();
        }
        sum
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator
    // 2. Empty check prevents undefined behavior
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn norm_linf(a: &[f32]) -> f32 {
        if a.is_empty() {
            return 0.0;
        }

        let mut max_val = 0.0_f32;
        for &val in a {
            let abs_val = val.abs();
            if abs_val > max_val {
                max_val = abs_val;
            }
        }
        max_val
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn scale(a: &[f32], scalar: f32, result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val * scalar;
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn abs(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.abs();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn clamp(a: &[f32], min_val: f32, max_val: f32, result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.max(min_val).min(max_val);
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate/zip
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn lerp(a: &[f32], b: &[f32], t: f32, result: &mut [f32]) {
        for (i, (&a_val, &b_val)) in a.iter().zip(b.iter()).enumerate() {
            // result = a + t * (b - a)
            result[i] = a_val + t * (b_val - a_val);
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate/zip
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn fma(a: &[f32], b: &[f32], c: &[f32], result: &mut [f32]) {
        for (i, ((&a_val, &b_val), &c_val)) in a.iter().zip(b.iter()).zip(c.iter()).enumerate() {
            // result = a * b + c
            result[i] = a_val * b_val + c_val;
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn relu(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = if val > 0.0 { val } else { 0.0 };
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn exp(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.exp();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. Clamping prevents exp() overflow
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sigmoid(a: &[f32], result: &mut [f32]) {
        contract_pre_sigmoid!(a);
        for (i, &val) in a.iter().enumerate() {
            // Handle extreme values for numerical stability
            result[i] = if val < -50.0 {
                0.0 // exp(-x) would overflow, but sigmoid approaches 0
            } else if val > 50.0 {
                1.0 // exp(-x) underflows to 0, sigmoid approaches 1
            } else {
                1.0 / (1.0 + (-val).exp())
            };
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn gelu(a: &[f32], result: &mut [f32]) {
        // GELU approximation: 0.5 * x * (1 + tanh(sqrt(2/π) * (x + 0.044715 * x³)))
        contract_pre_gelu!(a);
        const SQRT_2_OVER_PI: f32 = 0.797_884_6;
        const COEFF: f32 = 0.044715;

        for (i, &x) in a.iter().enumerate() {
            let x3 = x * x * x;
            let inner = SQRT_2_OVER_PI * (x + COEFF * x3);
            result[i] = 0.5 * x * (1.0 + inner.tanh());
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. Clamping prevents exp() overflow
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn swish(a: &[f32], result: &mut [f32]) {
        // Swish: x * sigmoid(x) = x / (1 + exp(-x))
        for (i, &x) in a.iter().enumerate() {
            if x < -50.0 {
                result[i] = 0.0; // x * 0 = 0
            } else if x > 50.0 {
                result[i] = x; // x * 1 = x
            } else {
                let sigmoid = 1.0 / (1.0 + (-x).exp());
                result[i] = x * sigmoid;
            }
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn tanh(a: &[f32], result: &mut [f32]) {
        // tanh(x) = (exp(2x) - 1) / (exp(2x) + 1)
        for (i, &x) in a.iter().enumerate() {
            result[i] = x.tanh();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sqrt(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.sqrt();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn recip(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.recip();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn ln(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.ln();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn log2(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.log2();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn log10(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.log10();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn sin(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.sin();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn cos(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.cos();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn tan(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.tan();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn floor(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.floor();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn ceil(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.ceil();
        }
    }

    // SAFETY: This function is safe because:
    // 1. All slice accesses are bounds-checked by Rust iterator/enumerate
    // 2. No raw pointer arithmetic is performed
    // 3. Marked unsafe only to match VectorBackend trait interface
    unsafe fn round(a: &[f32], result: &mut [f32]) {
        for (i, &val) in a.iter().enumerate() {
            result[i] = val.round();
        }
    }
}

#[cfg(test)]
mod tests;