numr 0.12.0

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
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
//! Forward kernels for GEMM epilogue operations.
//!
//! matmul_bias_activation: C = activation(A @ B + bias)
//! matmul_bias_residual: C = A @ B + bias + residual

use crate::dtype::Element;
use crate::ops::GemmActivation;

/// Fused matmul + bias + activation kernel.
///
/// Computes `activation(A @ B + bias)` in a single pass:
/// 1. Initialize output with bias
/// 2. Accumulate matmul result (ikj order)
/// 3. Apply activation in-place
///
/// # Safety
/// - All pointers must be valid for the specified dimensions
/// - `out` must not alias with `a`, `b`, or `bias`
#[inline]
#[allow(clippy::too_many_arguments)]
pub unsafe fn matmul_bias_activation_kernel<T: Element>(
    a: *const T,
    b: *const T,
    bias: *const T,
    out: *mut T,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    activation: GemmActivation,
) {
    // For GemmActivation::None, just do matmul_bias (avoid activation dispatch overhead)
    if activation == GemmActivation::None {
        crate::runtime::cpu::kernels::matmul_bias_kernel(a, b, bias, out, m, n, k, lda, ldb, ldc);
        return;
    }

    // F16/BF16 are storage formats: the sum, the bias and the activation all
    // run in F32 and round once at the store, as the CUDA kernels do. The
    // scalar fallback below accumulates in T, which loses the sum at long K.
    if T::DTYPE.is_narrow_float() {
        matmul_bias_activation_via_f32(a, b, bias, out, m, n, k, lda, ldb, ldc, activation);
        return;
    }

    // SIMD dispatch for f32/f64 on x86_64: matmul_bias first, then apply activation via SIMD
    #[cfg(target_arch = "x86_64")]
    {
        use crate::dtype::DType;
        match T::DTYPE {
            DType::F32 => {
                matmul_bias_activation_simd_f32(
                    a as *const f32,
                    b as *const f32,
                    bias as *const f32,
                    out as *mut f32,
                    m,
                    n,
                    k,
                    lda,
                    ldb,
                    ldc,
                    activation,
                );
                return;
            }
            DType::F64 => {
                matmul_bias_activation_simd_f64(
                    a as *const f64,
                    b as *const f64,
                    bias as *const f64,
                    out as *mut f64,
                    m,
                    n,
                    k,
                    lda,
                    ldb,
                    ldc,
                    activation,
                );
                return;
            }
            _ => {} // Fall through to scalar
        }
    }

    matmul_bias_activation_scalar(a, b, bias, out, m, n, k, lda, ldb, ldc, activation);
}

/// Fused matmul + bias + residual kernel.
///
/// Computes `A @ B + bias + residual` in a single pass.
///
/// # Safety
/// - All pointers must be valid for the specified dimensions
/// - `out` must not alias with `a`, `b`, `bias`, or `residual`
#[inline]
#[allow(clippy::too_many_arguments)]
pub unsafe fn matmul_bias_residual_kernel<T: Element>(
    a: *const T,
    b: *const T,
    bias: *const T,
    residual: *const T,
    out: *mut T,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
) {
    // Same F32 accumulation rule as `matmul_bias_activation_kernel`.
    if T::DTYPE.is_narrow_float() {
        matmul_bias_residual_via_f32(a, b, bias, residual, out, m, n, k, lda, ldb, ldc);
        return;
    }

    // Initialize output with bias + residual
    for i in 0..m {
        for j in 0..n {
            *out.add(i * ldc + j) = *bias.add(j) + *residual.add(i * ldc + j);
        }
    }

    // Accumulate matmul result (ikj order for cache locality)
    for i in 0..m {
        for kk in 0..k {
            let a_val = *a.add(i * lda + kk);
            for j in 0..n {
                let out_ptr = out.add(i * ldc + j);
                *out_ptr = *out_ptr + a_val * *b.add(kk * ldb + j);
            }
        }
    }
}

// ============================================================================
// Half-precision paths: F32 scratch, one rounding at the store
// ============================================================================

/// Copies a strided `rows x cols` matrix of `T` into a contiguous F32 buffer.
///
/// # Safety
/// - `src` must be valid for reads of `rows * ld` elements
/// - `dst` must be valid for writes of `rows * cols` elements
unsafe fn widen_to_f32<T: Element>(
    src: *const T,
    dst: *mut f32,
    rows: usize,
    cols: usize,
    ld: usize,
) {
    for i in 0..rows {
        for j in 0..cols {
            *dst.add(i * cols + j) = (*src.add(i * ld + j)).to_f32();
        }
    }
}

/// Rounds a contiguous F32 `rows x cols` buffer into a strided `T` matrix.
///
/// # Safety
/// - `src` must be valid for reads of `rows * cols` elements
/// - `dst` must be valid for writes of `rows * ld` elements
unsafe fn narrow_from_f32<T: Element>(
    src: *const f32,
    dst: *mut T,
    rows: usize,
    cols: usize,
    ld: usize,
) {
    for i in 0..rows {
        for j in 0..cols {
            *dst.add(i * ld + j) = T::from_f32(*src.add(i * cols + j));
        }
    }
}

/// `activation(A @ B + bias)` for a narrow float `T`, computed in F32.
///
/// # Safety
/// Same as [`matmul_bias_activation_kernel`].
#[allow(clippy::too_many_arguments)]
unsafe fn matmul_bias_activation_via_f32<T: Element>(
    a: *const T,
    b: *const T,
    bias: *const T,
    out: *mut T,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    activation: GemmActivation,
) {
    let mut a_f32 = vec![0.0f32; m * k];
    let mut b_f32 = vec![0.0f32; k * n];
    let mut bias_f32 = vec![0.0f32; n];
    let mut c_f32 = vec![0.0f32; m * n];
    widen_to_f32(a, a_f32.as_mut_ptr(), m, k, lda);
    widen_to_f32(b, b_f32.as_mut_ptr(), k, n, ldb);
    widen_to_f32(bias, bias_f32.as_mut_ptr(), 1, n, n);
    matmul_bias_activation_kernel::<f32>(
        a_f32.as_ptr(),
        b_f32.as_ptr(),
        bias_f32.as_ptr(),
        c_f32.as_mut_ptr(),
        m,
        n,
        k,
        k,
        n,
        n,
        activation,
    );
    narrow_from_f32(c_f32.as_ptr(), out, m, n, ldc);
}

/// `A @ B + bias + residual` for a narrow float `T`, computed in F32.
///
/// # Safety
/// Same as [`matmul_bias_residual_kernel`].
#[allow(clippy::too_many_arguments)]
unsafe fn matmul_bias_residual_via_f32<T: Element>(
    a: *const T,
    b: *const T,
    bias: *const T,
    residual: *const T,
    out: *mut T,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
) {
    let mut a_f32 = vec![0.0f32; m * k];
    let mut b_f32 = vec![0.0f32; k * n];
    let mut bias_f32 = vec![0.0f32; n];
    let mut res_f32 = vec![0.0f32; m * n];
    let mut c_f32 = vec![0.0f32; m * n];
    widen_to_f32(a, a_f32.as_mut_ptr(), m, k, lda);
    widen_to_f32(b, b_f32.as_mut_ptr(), k, n, ldb);
    widen_to_f32(bias, bias_f32.as_mut_ptr(), 1, n, n);
    widen_to_f32(residual, res_f32.as_mut_ptr(), m, n, ldc);
    matmul_bias_residual_kernel::<f32>(
        a_f32.as_ptr(),
        b_f32.as_ptr(),
        bias_f32.as_ptr(),
        res_f32.as_ptr(),
        c_f32.as_mut_ptr(),
        m,
        n,
        k,
        k,
        n,
        n,
    );
    narrow_from_f32(c_f32.as_ptr(), out, m, n, ldc);
}

// ============================================================================
// SIMD-accelerated paths (matmul_bias then SIMD activation)
// ============================================================================

#[cfg(target_arch = "x86_64")]
#[allow(clippy::too_many_arguments, dead_code)]
unsafe fn matmul_bias_activation_simd_f32(
    a: *const f32,
    b: *const f32,
    bias: *const f32,
    out: *mut f32,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    activation: GemmActivation,
) {
    use super::super::simd::matmul;

    // Step 1: Compute matmul_bias into output buffer
    matmul::matmul_bias_f32(a, b, bias, out, m, n, k, lda, ldb, ldc);

    // Step 2: Apply activation in-place using SIMD
    let total = m * n;
    apply_activation_inplace_f32(out, total, activation);
}

#[cfg(target_arch = "x86_64")]
#[allow(clippy::too_many_arguments, dead_code)]
unsafe fn matmul_bias_activation_simd_f64(
    a: *const f64,
    b: *const f64,
    bias: *const f64,
    out: *mut f64,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    activation: GemmActivation,
) {
    use super::super::simd::matmul;

    // Step 1: Compute matmul_bias into output buffer
    matmul::matmul_bias_f64(a, b, bias, out, m, n, k, lda, ldb, ldc);

    // Step 2: Apply activation in-place using SIMD
    let total = m * n;
    apply_activation_inplace_f64(out, total, activation);
}

/// Apply activation in-place on f32 buffer using SIMD helpers.
#[cfg(target_arch = "x86_64")]
#[allow(dead_code)]
unsafe fn apply_activation_inplace_f32(buf: *mut f32, len: usize, activation: GemmActivation) {
    use super::super::simd::activations;

    match activation {
        GemmActivation::None => {}
        GemmActivation::ReLU => {
            // ReLU is simple: max(0, x) — use scalar for in-place
            for i in 0..len {
                let val = *buf.add(i);
                if val < 0.0 {
                    *buf.add(i) = 0.0;
                }
            }
        }
        GemmActivation::GELU => {
            // Use SIMD gelu (reads from buf, writes to buf — safe since non-overlapping access)
            activations::gelu_f32(buf as *const f32, buf, len);
        }
        GemmActivation::SiLU => {
            activations::silu_f32(buf as *const f32, buf, len);
        }
        GemmActivation::Sigmoid => {
            activations::sigmoid_f32(buf as *const f32, buf, len);
        }
        GemmActivation::Tanh => {
            for i in 0..len {
                *buf.add(i) = (*buf.add(i)).tanh();
            }
        }
    }
}

/// Apply activation in-place on f64 buffer using SIMD helpers.
#[cfg(target_arch = "x86_64")]
#[allow(dead_code)]
unsafe fn apply_activation_inplace_f64(buf: *mut f64, len: usize, activation: GemmActivation) {
    use super::super::simd::activations;

    match activation {
        GemmActivation::None => {}
        GemmActivation::ReLU => {
            for i in 0..len {
                let val = *buf.add(i);
                if val < 0.0 {
                    *buf.add(i) = 0.0;
                }
            }
        }
        GemmActivation::GELU => {
            activations::gelu_f64(buf as *const f64, buf, len);
        }
        GemmActivation::SiLU => {
            activations::silu_f64(buf as *const f64, buf, len);
        }
        GemmActivation::Sigmoid => {
            activations::sigmoid_f64(buf as *const f64, buf, len);
        }
        GemmActivation::Tanh => {
            for i in 0..len {
                *buf.add(i) = (*buf.add(i)).tanh();
            }
        }
    }
}

// ============================================================================
// Scalar fallback
// ============================================================================

#[allow(clippy::too_many_arguments, dead_code)]
unsafe fn matmul_bias_activation_scalar<T: Element>(
    a: *const T,
    b: *const T,
    bias: *const T,
    out: *mut T,
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    activation: GemmActivation,
) {
    // Initialize output with bias
    for i in 0..m {
        for j in 0..n {
            *out.add(i * ldc + j) = *bias.add(j);
        }
    }

    // Accumulate matmul result (ikj order)
    for i in 0..m {
        for kk in 0..k {
            let a_val = *a.add(i * lda + kk);
            for j in 0..n {
                let out_ptr = out.add(i * ldc + j);
                *out_ptr = *out_ptr + a_val * *b.add(kk * ldb + j);
            }
        }
    }

    // Apply activation in-place
    apply_activation_scalar(out, m * n, activation);
}

/// Apply activation element-wise using scalar math (generic over Element).
#[allow(dead_code)]
unsafe fn apply_activation_scalar<T: Element>(buf: *mut T, len: usize, activation: GemmActivation) {
    match activation {
        GemmActivation::None => {}
        GemmActivation::ReLU => {
            for i in 0..len {
                let val = *buf.add(i);
                if val < T::zero() {
                    *buf.add(i) = T::zero();
                }
            }
        }
        GemmActivation::GELU => {
            // GELU needs float math — convert through f64
            for i in 0..len {
                let x = (*buf.add(i)).to_f64();
                let inner = 0.7978845608028654 * (x + 0.044715 * x * x * x);
                let result = 0.5 * x * (1.0 + inner.tanh());
                *buf.add(i) = T::from_f64(result);
            }
        }
        GemmActivation::SiLU => {
            for i in 0..len {
                let x = (*buf.add(i)).to_f64();
                let result = x / (1.0 + (-x).exp());
                *buf.add(i) = T::from_f64(result);
            }
        }
        GemmActivation::Sigmoid => {
            for i in 0..len {
                let x = (*buf.add(i)).to_f64();
                let result = 1.0 / (1.0 + (-x).exp());
                *buf.add(i) = T::from_f64(result);
            }
        }
        GemmActivation::Tanh => {
            for i in 0..len {
                let x = (*buf.add(i)).to_f64();
                *buf.add(i) = T::from_f64(x.tanh());
            }
        }
    }
}