numr 0.15.2

Numerical computing and tensor library for Rust, in the role of NumPy: n-dimensional arrays, linear algebra, FFT, statistics and autograd on CPU, CUDA and 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
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
//! Dense matmul dispatch.
//!
//! `launch_matmul_kernel` and its batched form pick between the FP8, WMMA,
//! integer, and F32 specialisations before falling back to the generic
//! tiled kernel. The choice reads the dtype and the shape, never M alone:
//! every M of a dtype runs one kernel family, whose per-element float
//! sequence is fixed, so a row's result does not depend on the batch it is
//! in. The `_with_config` entry points skip that choice and launch the
//! generic kernel at an explicit tile.

use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;

use crate::algorithm::TileConfig;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::Device;
use crate::runtime::cuda::CudaDevice;
use crate::runtime::cuda::GuardedStream;

use super::launch_dims::{LaunchConfig, check_shared_mem_fits};
use super::matmul_config::{
    default_tile_config, f32_batched_tile_config, matmul_batched_launch_config,
    matmul_launch_config,
};
use super::matmul_f32::{
    BLayout, launch_matmul_batched_f32_tiled, launch_matmul_f32_tiled, launch_matmul_f32_tiled_bt,
};
use super::matmul_fp8::launch_matmul_fp8_tiled;
use super::matmul_int::{int_matmul_has_kernel, launch_matmul_int_tiled};
use super::matmul_wmma::{launch_matmul_wmma_batched_kernel, launch_matmul_wmma_kernel};
use super::matmul_wmma_policy::use_wmma;
use super::module_cache::{get_kernel_function, get_or_load_module};
use super::names::{kernel_name, kernel_names};

/// Launch native tiled matmul kernel: C[M,N] = A[M,K] @ B[K,N]
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes:
/// - A: M * K elements
/// - B: K * N elements
/// - C: M * N elements
pub unsafe fn launch_matmul_kernel(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    m: usize,
    n: usize,
    k: usize,
) -> Result<()> {
    // FP8 has its own tiled family.
    if matches!(dtype, DType::FP8E4M3 | DType::FP8E5M2) {
        unsafe {
            return launch_matmul_fp8_tiled(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                None,
                c_ptr,
                1,
                m,
                n,
                k,
                1,
                1,
            );
        }
    }
    // No small-M GEMV switch here: every M of a dtype takes the same kernel
    // family, so a row's result never depends on how many rows share the
    // launch. The F32 family serves small M with its 16-row tile
    // (`f32_batched_tile_config`).
    //
    // Tensor-core WMMA path: F16/BF16 at any shape, unless padding the row
    // strides pays and the op has not done it yet (see `use_wmma`).
    // CudaDevice::new is a zero-cost index wrapper; profile() serves the
    // per-index cache (queried once, on first use of this device index).
    let caps = CudaDevice::new(device_index).profile().caps;
    if use_wmma(dtype, caps, m, n, k) {
        unsafe {
            return launch_matmul_wmma_kernel(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                c_ptr,
                m,
                n,
                k,
            );
        }
    }
    // Integers: same reason as F32 below. Their accumulator is a 16-byte
    // `Numr128`, so a runtime-sized `reg_c` spills four registers per slot.
    if int_matmul_has_kernel(dtype) {
        unsafe {
            return launch_matmul_int_tiled(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                None,
                c_ptr,
                1,
                m,
                n,
                k,
                1,
                1,
            );
        }
    }
    // F32: dispatch to compile-time-tiled kernels so NVCC can unroll micro-kernel
    // loops and keep accumulators in registers (avoids local-memory spill).
    if dtype == DType::F32 {
        let tile_cfg = f32_batched_tile_config(m, n, k);
        unsafe {
            return launch_matmul_f32_tiled(
                context,
                stream,
                device_index,
                a_ptr,
                b_ptr,
                c_ptr,
                m,
                n,
                k,
                &tile_cfg,
            );
        }
    }
    let tile_cfg = default_tile_config(dtype);
    unsafe {
        launch_matmul_kernel_with_config(
            context,
            stream,
            device_index,
            dtype,
            a_ptr,
            b_ptr,
            c_ptr,
            m,
            n,
            k,
            &tile_cfg,
        )
    }
}

/// Launch native tiled matmul kernel with custom tile configuration.
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes.
pub unsafe fn launch_matmul_kernel_with_config(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    m: usize,
    n: usize,
    k: usize,
    tile_cfg: &TileConfig,
) -> Result<()> {
    let module = get_or_load_module(context, device_index, kernel_names::MATMUL_MODULE)?;
    let func_name = kernel_name("matmul", dtype);
    let func = get_kernel_function(&module, &func_name)?;

    let elem_size = dtype.size_in_bytes();
    // For F16/BF16, shared memory uses F32 for accumulation.
    // For F32, the kernel is double-buffered (2 ping-pong smem slots).
    let shared_elem_size = match dtype {
        DType::F16 | DType::BF16 => 4, // F32 accumulator
        _ => elem_size,
    };
    let smem_factor: u32 = if dtype == DType::F32 { 2 } else { 1 };

    let base_cfg = matmul_launch_config(m, n, tile_cfg, shared_elem_size);
    let shared_mem_bytes = base_cfg.shared_mem_bytes * smem_factor;
    check_shared_mem_fits(device_index, shared_mem_bytes, "matmul", || {
        format!(
            "{}x{}x{} {dtype} matmul tile",
            tile_cfg.block_m, tile_cfg.block_n, tile_cfg.block_k
        )
    })?;
    let cfg = LaunchConfig {
        shared_mem_bytes,
        ..base_cfg
    };
    let m_u32 = m as u32;
    let n_u32 = n as u32;
    let k_u32 = k as u32;
    let block_m = tile_cfg.block_m as u32;
    let block_n = tile_cfg.block_n as u32;
    let block_k = tile_cfg.block_k as u32;
    let thread_m = tile_cfg.thread_m as u32;
    let thread_n = tile_cfg.thread_n as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_ptr);
        builder.arg(&b_ptr);
        builder.arg(&c_ptr);
        builder.arg(&m_u32);
        builder.arg(&n_u32);
        builder.arg(&k_u32);
        builder.arg(&block_m);
        builder.arg(&block_n);
        builder.arg(&block_k);
        builder.arg(&thread_m);
        builder.arg(&thread_n);

        builder
            .launch(cfg)
            .map_err(|e| Error::Internal(format!("CUDA matmul kernel launch failed: {:?}", e)))?;
    }

    Ok(())
}

/// Launch native batched tiled matmul kernel: C[batch,M,N] = A[batch,M,K] @ B[batch,K,N]
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes:
/// - A: batch * M * K elements
/// - B: batch * K * N elements
/// - C: batch * M * N elements
pub unsafe fn launch_matmul_batched_kernel(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    batch: usize,
    m: usize,
    n: usize,
    k: usize,
    a_batch: usize,
    b_batch: usize,
) -> Result<()> {
    // FP8 has its own tiled family (see launch_matmul_kernel).
    if matches!(dtype, DType::FP8E4M3 | DType::FP8E5M2) {
        unsafe {
            return launch_matmul_fp8_tiled(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                None,
                c_ptr,
                batch,
                m,
                n,
                k,
                a_batch,
                b_batch,
            );
        }
    }
    // No small-M GEMV switch, as in `launch_matmul_kernel`.
    //
    // Tensor-core WMMA path for F16/BF16, same predicate as the 2-D form;
    // `src/ops/cuda/matmul.rs` applies the same pre-launch padding rule to
    // the batched call.
    let caps = CudaDevice::new(device_index).profile().caps;
    if use_wmma(dtype, caps, m, n, k) {
        unsafe {
            return launch_matmul_wmma_batched_kernel(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                c_ptr,
                batch,
                m,
                n,
                k,
                a_batch,
                b_batch,
            );
        }
    }
    // Integers use the compile-time-tiled kernels at every batch size.
    if int_matmul_has_kernel(dtype) {
        unsafe {
            return launch_matmul_int_tiled(
                context,
                stream,
                device_index,
                dtype,
                a_ptr,
                b_ptr,
                None,
                c_ptr,
                batch,
                m,
                n,
                k,
                a_batch,
                b_batch,
            );
        }
    }
    // F32 uses shape-aware tiles to avoid wasted columns and reduce sync count.
    let tile_cfg = match dtype {
        DType::F32 => f32_batched_tile_config(m, n, k),
        _ => default_tile_config(dtype),
    };
    // F32: the compile-time-tiled kernels keep accumulators in registers; the
    // runtime-tile fallback below spills them.
    if dtype == DType::F32 {
        let launched = unsafe {
            launch_matmul_batched_f32_tiled(
                context,
                stream,
                device_index,
                a_ptr,
                b_ptr,
                c_ptr,
                batch,
                m,
                n,
                k,
                a_batch,
                b_batch,
                &tile_cfg,
                BLayout::Kn,
            )?
        };
        if launched {
            return Ok(());
        }
    }
    unsafe {
        launch_matmul_batched_kernel_with_config(
            context,
            stream,
            device_index,
            dtype,
            a_ptr,
            b_ptr,
            c_ptr,
            batch,
            m,
            n,
            k,
            &tile_cfg,
            a_batch,
            b_batch,
        )
    }
}

/// Launch native batched tiled matmul kernel with custom tile configuration.
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes.
pub unsafe fn launch_matmul_batched_kernel_with_config(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    batch: usize,
    m: usize,
    n: usize,
    k: usize,
    tile_cfg: &TileConfig,
    a_batch: usize,
    b_batch: usize,
) -> Result<()> {
    let module = get_or_load_module(context, device_index, kernel_names::MATMUL_MODULE)?;
    let func_name = kernel_name("matmul_batched", dtype);
    let func = get_kernel_function(&module, &func_name)?;

    let elem_size = dtype.size_in_bytes();
    // For F16/BF16, shared memory uses F32 for accumulation.
    // For F32, the kernel is double-buffered (2 ping-pong smem slots).
    let shared_elem_size = match dtype {
        DType::F16 | DType::BF16 => 4,
        _ => elem_size,
    };
    let smem_factor: u32 = if dtype == DType::F32 { 2 } else { 1 };

    let base_cfg = matmul_batched_launch_config(batch, m, n, tile_cfg, shared_elem_size);
    let shared_mem_bytes = base_cfg.shared_mem_bytes * smem_factor;
    check_shared_mem_fits(device_index, shared_mem_bytes, "matmul", || {
        format!(
            "{}x{}x{} {dtype} batched matmul tile",
            tile_cfg.block_m, tile_cfg.block_n, tile_cfg.block_k
        )
    })?;
    let cfg = LaunchConfig {
        shared_mem_bytes,
        ..base_cfg
    };
    let batch_u32 = batch as u32;
    let m_u32 = m as u32;
    let n_u32 = n as u32;
    let k_u32 = k as u32;
    let block_m = tile_cfg.block_m as u32;
    let block_n = tile_cfg.block_n as u32;
    let block_k = tile_cfg.block_k as u32;
    let thread_m = tile_cfg.thread_m as u32;
    let thread_n = tile_cfg.thread_n as u32;
    let a_batch_u32 = a_batch as u32;
    let b_batch_u32 = b_batch as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_ptr);
        builder.arg(&b_ptr);
        builder.arg(&c_ptr);
        builder.arg(&batch_u32);
        builder.arg(&m_u32);
        builder.arg(&n_u32);
        builder.arg(&k_u32);
        builder.arg(&block_m);
        builder.arg(&block_n);
        builder.arg(&block_k);
        builder.arg(&thread_m);
        builder.arg(&thread_n);
        builder.arg(&a_batch_u32);
        builder.arg(&b_batch_u32);

        builder.launch(cfg).map_err(|e| {
            Error::Internal(format!("CUDA batched matmul kernel launch failed: {:?}", e))
        })?;
    }

    Ok(())
}

/// F32 GEMM against a transposed-view operand: `C[M,N] = A[M,K] · Bᵀ` where
/// `b_ptr` is the contiguous `[N, K]` matrix behind the view. Returns
/// `Ok(false)` when no tiled kernel covers the shape, in which case the caller
/// materialises the transpose and uses [`launch_matmul_kernel`]. F32 only:
/// other dtypes have no transposed-B tile loader.
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes.
pub unsafe fn launch_matmul_kernel_bt(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    m: usize,
    n: usize,
    k: usize,
) -> Result<bool> {
    if dtype != DType::F32 {
        return Ok(false);
    }
    let tile_cfg = f32_batched_tile_config(m, n, k);
    unsafe {
        launch_matmul_f32_tiled_bt(
            context,
            stream,
            device_index,
            a_ptr,
            b_ptr,
            c_ptr,
            m,
            n,
            k,
            &tile_cfg,
        )
    }
}

/// Batched form of [`launch_matmul_kernel_bt`]: `b_ptr` is `[batch, N, K]`.
///
/// # Safety
///
/// All pointers must be valid device memory with correct sizes.
pub unsafe fn launch_matmul_batched_kernel_bt(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    b_ptr: u64,
    c_ptr: u64,
    batch: usize,
    m: usize,
    n: usize,
    k: usize,
    a_batch: usize,
    b_batch: usize,
) -> Result<bool> {
    if dtype != DType::F32 {
        return Ok(false);
    }
    let tile_cfg = f32_batched_tile_config(m, n, k);
    unsafe {
        launch_matmul_batched_f32_tiled(
            context,
            stream,
            device_index,
            a_ptr,
            b_ptr,
            c_ptr,
            batch,
            m,
            n,
            k,
            a_batch,
            b_batch,
            &tile_cfg,
            BLayout::Nk,
        )
    }
}