numr 0.10.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
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
//! Reduction CUDA kernel launchers
//!
//! Provides launchers for reduction operations (sum, max, min, and the fused
//! integer mean) that reduce tensors along specified dimensions.
//!
//! See [`AccumulationPrecision`] for documentation on accumulation precision options.

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

use super::loader::{
    BLOCK_SIZE, MAX_GRID_DIM_X, dtype_suffix, get_kernel_function, get_or_load_module, kernel_name,
    kernel_names, launch_config, reduce_dim_launch_config, reduce_launch_config, reduce_module,
    reduce_split_count,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
// Re-export AccumulationPrecision from ops for convenience
pub(crate) use crate::ops::AccumulationPrecision;
use crate::runtime::cuda::GuardedStream;

/// Reduction ops whose F16/BF16 kernels ship an `_fp32acc` variant.
///
/// `reduce.cu` instantiates `_fp32acc` for the four accumulating dim
/// reductions only. `reduce_any_dim` and `reduce_all_dim` hold no accumulator
/// and exist in the native suffix alone, so asking for `_fp32acc` there would
/// name a kernel that does not exist.
fn has_fp32acc_variant(base_op: &str) -> bool {
    matches!(
        base_op,
        "reduce_sum_dim"
            | "reduce_max_dim"
            | "reduce_min_dim"
            | "reduce_prod_dim"
            | "reduce_sum_dim_serial"
            | "reduce_max_dim_serial"
            | "reduce_min_dim_serial"
            | "reduce_prod_dim_serial"
    )
}

/// Longest reduced axis the one-thread-per-output `_serial` kernels take.
///
/// The block-per-output kernels leave most of their threads idle on a short
/// axis and launch one block per output; below this length a thread walking
/// the axis in order does the same work with a grid sized to the outputs.
/// See the serial section of `reduce.cu`.
const SERIAL_REDUCE_MAX: usize = 32;

/// Whether `op` has a `_serial` twin. The float module instantiates them for
/// the four core reductions; the integer module has none.
fn has_serial_variant(op: &str, dtype: DType) -> bool {
    !dtype.is_int() && matches!(op, "sum" | "max" | "min" | "prod")
}

/// Generate kernel name with accumulation precision suffix.
///
/// Kernel naming conventions:
/// - F16/BF16: `{op}_{dtype}_fp32acc` (FP32, and the default), `{op}_{dtype}_fp64acc` (FP64),
///   `{op}_{dtype}` (native, reachable only for ops with no `_fp32acc` variant)
/// - FP8: `{op}_{dtype}` (FP32 default), `{op}_{dtype}_bf16acc` (BF16), `{op}_{dtype}_fp64acc` (FP64)
/// - F32: `{op}_{dtype}` (native) or `{op}_{dtype}_fp64acc` (FP64)
/// - F64/integers: `{op}_{dtype}` (always native, ignore acc_precision)
fn reduce_kernel_name(base_op: &str, dtype: DType, acc_precision: AccumulationPrecision) -> String {
    let suffix = dtype_suffix(dtype);

    // Determine accumulation suffix based on dtype and requested precision
    let acc_suffix = match dtype {
        // F16/BF16: FP32 accumulation by default, _fp64acc for FP64.
        //
        // `Native` means "let the library choose", and the library never
        // chooses F16/BF16: a running sum held in 16 bits stops growing once
        // its spacing exceeds twice the increment, so the reduction stalls on
        // a constant regardless of the data. This matches the default stated
        // in `reduce.cu`.
        DType::F16 | DType::BF16 => match acc_precision {
            AccumulationPrecision::FP64 => Some("_fp64acc"),
            AccumulationPrecision::FP32
            | AccumulationPrecision::Native
            | AccumulationPrecision::BF16 => {
                if has_fp32acc_variant(base_op) {
                    Some("_fp32acc")
                } else {
                    None
                }
            }
        },
        // FP8: FP32 by default (no suffix), _bf16acc for BF16, _fp64acc for FP64
        DType::FP8E4M3 | DType::FP8E5M2 => match acc_precision {
            AccumulationPrecision::BF16 => Some("_bf16acc"),
            AccumulationPrecision::FP64 => Some("_fp64acc"),
            // Native and FP32 both map to FP32 accumulation for FP8
            AccumulationPrecision::Native | AccumulationPrecision::FP32 => None,
        },
        // F32: native by default, _fp64acc for maximum precision
        DType::F32 => match acc_precision {
            AccumulationPrecision::FP64 => Some("_fp64acc"),
            // Native, BF16, FP32 all use native f32 accumulation
            _ => None,
        },
        // F64/integers: always native, ignore acc_precision
        _ => None,
    };

    match acc_suffix {
        Some(s) => format!("{}_{}{}", base_op, suffix, s),
        None => format!("{}_{}", base_op, suffix),
    }
}

/// Whether the dim kernel selected for `dtype`/`acc_precision` accumulates in
/// the element type itself, so writing a partial result out and reading it back
/// loses nothing.
///
/// The dim kernels store into `T*` whatever accumulator they held, so a
/// two-stage split re-rounds every partial through `T` before the second stage
/// reads it. That extra rounding is invisible only when the accumulator is `T`.
fn accumulates_in_element_type(dtype: DType, acc_precision: AccumulationPrecision) -> bool {
    match dtype {
        // No F16/BF16/FP8 dim instantiation accumulates in the element type:
        // `reduce_kernel_name` routes them to an f32, f64 or bf16 accumulator.
        DType::F16 | DType::BF16 | DType::FP8E4M3 | DType::FP8E5M2 => false,
        // Native f32 accumulation; `_fp64acc` holds a wider accumulator than
        // the store type.
        DType::F32 => acc_precision != AccumulationPrecision::FP64,
        DType::F64 => true,
        // `reduce_int.cu` accumulates sums and products in a saturating 128-bit
        // type and narrows exactly once. Splitting would saturate per chunk,
        // which is not the same answer.
        _ => false,
    }
}

/// Number of equal chunks to cut the reduced axis into for a two-stage
/// dimension-wise reduction, or `None` to keep the single-stage launch.
///
/// Two stages are the same kernel called twice: viewing the contiguous
/// `[outer, reduce, inner]` input as `[outer, splits, chunk, inner]`, stage 1
/// reduces `chunk` with `outer * splits` as its outer extent and writes a
/// contiguous `[outer, splits, inner]` buffer, and stage 2 reduces `splits`
/// over that buffer. Both calls are ordinary dim reductions, so the split needs
/// no kernel of its own.
///
/// Beyond the shape rule in [`reduce_split_count`], the op must also merge
/// exactly:
///
/// - `max`, `min`, `any` and `all` split for every dtype. Each partial is
///   either an input element, which round-trips through `T` exactly because it
///   came from there, or the kernel's own `one()`/`zero()`.
/// - `sum` and `prod` split only when the accumulator is the element type. They
///   are still reassociated, which moves the last bits of a float result the way
///   any reassociated accumulation does, but no partial is re-rounded.
/// - Every other op keeps the single-stage launch. `argmax`/`argmin` return
///   chunk-local indices that stage 2 cannot merge without remapping them, and
///   the integer `reduce_mean_dim` would divide once per chunk instead of once.
#[inline]
pub(crate) fn reduce_dim_split_count(
    device_index: usize,
    op: &str,
    dtype: DType,
    acc_precision: AccumulationPrecision,
    outer_size: usize,
    reduce_size: usize,
    inner_size: usize,
) -> Option<usize> {
    let merges_exactly = match op {
        "max" | "min" | "any" | "all" => true,
        "sum" | "prod" => accumulates_in_element_type(dtype, acc_precision),
        _ => false,
    };
    if !merges_exactly {
        return None;
    }
    reduce_split_count(device_index, outer_size, reduce_size, inner_size)
}

/// Launch a global reduction kernel.
///
/// Performs a parallel reduction across all elements, producing partial results
/// (one per block). For complete reduction, call multiple times until only one
/// element remains.
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` must have at least `numel` elements
/// - `output_ptr` must have space for the number of blocks launched
///
/// # Returns
///
/// The number of blocks launched (equals the number of partial results).
#[allow(dead_code)] // Kept for potential future optimization of global reductions
pub unsafe fn launch_reduce_op(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    op: &str,
    dtype: DType,
    input_ptr: u64,
    output_ptr: u64,
    numel: usize,
) -> Result<u32> {
    unsafe {
        let module = get_or_load_module(context, device_index, reduce_module(dtype))?;
        let func_name = kernel_name(&kernel_names::reduce_kernel(op), dtype);
        let func = get_kernel_function(&module, &func_name)?;

        let (grid_size, block_size) = reduce_launch_config(numel);
        let n = numel as u32;

        let cfg = launch_config((grid_size, 1, 1), (block_size, 1, 1), 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&input_ptr);
        builder.arg(&output_ptr);
        builder.arg(&n);

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

        Ok(grid_size)
    }
}

/// Launch a dimension-wise reduction kernel.
///
/// Reduces a tensor along a single dimension, preserving the outer and inner
/// dimensions. The tensor is conceptually reshaped to `[outer, reduce, inner]`
/// and reduced along the middle dimension.
///
/// # Accumulation Precision
///
/// For F16/BF16 dtypes, set `acc_precision` to control accumulation:
/// - `AccumulationPrecision::Native`: Use native dtype (faster, default)
/// - `AccumulationPrecision::FP32`: Use FP32 accumulation (more precise)
///
/// FP8 types always use FP32 accumulation regardless of this setting.
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` must have `outer_size * reduce_size * inner_size` elements
/// - `output_ptr` must have `outer_size * inner_size` elements
///
/// # Arguments
///
/// * `context` - CUDA context
/// * `stream` - CUDA stream for async execution
/// * `device_index` - Device index for module caching
/// * `op` - Reduction operation ("sum", "max", or "min")
/// * `dtype` - Data type of the tensor
/// * `input_ptr` - Device pointer to input tensor
/// * `output_ptr` - Device pointer to output tensor
/// * `outer_size` - Product of dimensions before the reduction dimension
/// * `reduce_size` - Size of the dimension being reduced
/// * `inner_size` - Product of dimensions after the reduction dimension
/// * `acc_precision` - Accumulation precision (affects F16/BF16 only)
pub unsafe fn launch_reduce_dim_op(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    op: &str,
    dtype: DType,
    input_ptr: u64,
    output_ptr: u64,
    outer_size: usize,
    reduce_size: usize,
    inner_size: usize,
    acc_precision: AccumulationPrecision,
) -> Result<()> {
    unsafe {
        let module = get_or_load_module(context, device_index, reduce_module(dtype))?;
        let serial = reduce_size <= SERIAL_REDUCE_MAX && has_serial_variant(op, dtype);
        let base_op = if serial {
            format!("{}_serial", kernel_names::reduce_dim_kernel(op))
        } else {
            kernel_names::reduce_dim_kernel(op)
        };
        let func_name = reduce_kernel_name(&base_op, dtype, acc_precision);
        let func = get_kernel_function(&module, &func_name)?;

        // Serial: one thread per output. Otherwise one block per output.
        let (grid, block) = if serial {
            let outputs = outer_size * inner_size;
            // The kernel strides its grid, so a grid capped below the output
            // count is still correct; the elementwise helper only errors past
            // the hardware limit, which the cap avoids.
            let blocks = outputs
                .div_ceil(BLOCK_SIZE as usize)
                .clamp(1, MAX_GRID_DIM_X as usize);
            ((blocks as u32, 1, 1), BLOCK_SIZE)
        } else {
            reduce_dim_launch_config(outer_size, inner_size)
        };
        let outer = outer_size as u32;
        let reduce = reduce_size as u32;
        let inner = inner_size as u32;

        let cfg = launch_config(grid, (block, 1, 1), 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&input_ptr);
        builder.arg(&output_ptr);
        builder.arg(&outer);
        builder.arg(&reduce);
        builder.arg(&inner);

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

        Ok(())
    }
}

/// Launch the fused integer `reduce_mean_dim` kernel along one dimension.
///
/// Only integer dtypes have this kernel (see `reduce_int.cu`): it sums the
/// reduced axis in a 128-bit accumulator, divides by `divisor` inside that
/// accumulator, and narrows to the element type exactly once. Unlike
/// [`launch_reduce_dim_op`], `divisor` is a caller-supplied kernel argument
/// rather than always `reduce_size` - a plain mean passes `reduce_size`
/// itself, but an unbiased variance's `n - correction` is not the reduced
/// axis length and needs the same divide-once guarantee.
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` must have `outer_size * reduce_size * inner_size` elements
/// - `output_ptr` must have space for `outer_size * inner_size` elements
/// - `dtype` must be an integer dtype - the fused mean kernel has no float
///   instantiation
///
/// # Arguments
///
/// * `divisor` - value the finished sum is divided by; the kernel forces a
///   zero divisor to 1, mirroring the CPU epilogue's `count.max(1)`
pub unsafe fn launch_reduce_mean_dim_int_op(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    input_ptr: u64,
    output_ptr: u64,
    outer_size: usize,
    reduce_size: usize,
    inner_size: usize,
    divisor: u64,
) -> Result<()> {
    unsafe {
        let module = get_or_load_module(context, device_index, reduce_module(dtype))?;
        let func_name = kernel_name("reduce_mean_dim", dtype);
        let func = get_kernel_function(&module, &func_name)?;

        let (grid, block) = reduce_dim_launch_config(outer_size, inner_size);
        let outer = outer_size as u32;
        let reduce = reduce_size as u32;
        let inner = inner_size as u32;

        let cfg = launch_config(grid, (block, 1, 1), 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&input_ptr);
        builder.arg(&output_ptr);
        builder.arg(&outer);
        builder.arg(&reduce);
        builder.arg(&inner);
        builder.arg(&divisor);

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

        Ok(())
    }
}

/// Launch an argmax kernel along a dimension.
///
/// Returns indices (I64) of maximum values along the specified dimension.
/// The tensor is conceptually reshaped to `[outer, reduce, inner]` and
/// argmax is computed along the middle dimension.
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` must have `outer_size * reduce_size * inner_size` elements
/// - `output_ptr` must have `outer_size * inner_size` I64 elements
///
/// # Arguments
///
/// * `context` - CUDA context
/// * `stream` - CUDA stream for async execution
/// * `device_index` - Device index for module caching
/// * `dtype` - Data type of the input tensor (output is always I64)
/// * `input_ptr` - Device pointer to input tensor
/// * `output_ptr` - Device pointer to output tensor (I64 indices)
/// * `outer_size` - Product of dimensions before the reduction dimension
/// * `reduce_size` - Size of the dimension being reduced
/// * `inner_size` - Product of dimensions after the reduction dimension
pub unsafe fn launch_argmax_dim(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    input_ptr: u64,
    output_ptr: u64,
    outer_size: usize,
    reduce_size: usize,
    inner_size: usize,
) -> Result<()> {
    unsafe {
        let module = get_or_load_module(context, device_index, reduce_module(dtype))?;
        let func_name = kernel_name("argmax_dim", dtype);
        let func = get_kernel_function(&module, &func_name)?;

        let (grid, block) = reduce_dim_launch_config(outer_size, inner_size);
        let outer = outer_size as u32;
        let reduce = reduce_size as u32;
        let inner = inner_size as u32;

        let cfg = launch_config(grid, (block, 1, 1), 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&input_ptr);
        builder.arg(&output_ptr);
        builder.arg(&outer);
        builder.arg(&reduce);
        builder.arg(&inner);

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

        Ok(())
    }
}

/// Launch an argmin kernel along a dimension.
///
/// Returns indices (I64) of minimum values along the specified dimension.
/// The tensor is conceptually reshaped to `[outer, reduce, inner]` and
/// argmin is computed along the middle dimension.
///
/// # Safety
///
/// - All pointers must be valid device memory
/// - `input_ptr` must have `outer_size * reduce_size * inner_size` elements
/// - `output_ptr` must have `outer_size * inner_size` I64 elements
///
/// # Arguments
///
/// * `context` - CUDA context
/// * `stream` - CUDA stream for async execution
/// * `device_index` - Device index for module caching
/// * `dtype` - Data type of the input tensor (output is always I64)
/// * `input_ptr` - Device pointer to input tensor
/// * `output_ptr` - Device pointer to output tensor (I64 indices)
/// * `outer_size` - Product of dimensions before the reduction dimension
/// * `reduce_size` - Size of the dimension being reduced
/// * `inner_size` - Product of dimensions after the reduction dimension
pub unsafe fn launch_argmin_dim(
    context: &Arc<CudaContext>,
    stream: &GuardedStream,
    device_index: usize,
    dtype: DType,
    input_ptr: u64,
    output_ptr: u64,
    outer_size: usize,
    reduce_size: usize,
    inner_size: usize,
) -> Result<()> {
    unsafe {
        let module = get_or_load_module(context, device_index, reduce_module(dtype))?;
        let func_name = kernel_name("argmin_dim", dtype);
        let func = get_kernel_function(&module, &func_name)?;

        let (grid, block) = reduce_dim_launch_config(outer_size, inner_size);
        let outer = outer_size as u32;
        let reduce = reduce_size as u32;
        let inner = inner_size as u32;

        let cfg = launch_config(grid, (block, 1, 1), 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&input_ptr);
        builder.arg(&output_ptr);
        builder.arg(&outer);
        builder.arg(&reduce);
        builder.arg(&inner);

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

        Ok(())
    }
}