numr 0.5.1

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
//! Generic CUDA launcher helpers for special mathematical functions
//!
//! Provides reusable launcher infrastructure for unary, binary, and ternary
//! special function kernels.

use super::super::loader::{
    elementwise_launch_config, get_kernel_function, get_or_load_module, launch_config,
};
use crate::dtype::DType;
use crate::error::{Error, Result};
use cudarc::driver::{CudaContext, CudaStream, PushKernelArg};
use std::sync::Arc;

pub(crate) const SPECIAL_MODULE: &str = "special";

/// Get kernel name with dtype suffix for special functions
pub(crate) fn special_kernel_name(
    base: &str,
    dtype: DType,
    op_name: &'static str,
) -> Result<String> {
    let suffix = match dtype {
        DType::F32 => "f32",
        DType::F64 => "f64",
        DType::F16 => "f16",
        DType::BF16 => "bf16",
        DType::FP8E4M3 => "fp8_e4m3",
        DType::FP8E5M2 => "fp8_e5m2",
        _ => {
            return Err(Error::UnsupportedDType { dtype, op: op_name });
        }
    };
    Ok(format!("{}_{}", base, suffix))
}

/// Generic launcher for unary special functions (1 input -> 1 output)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_unary_special(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    x_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&x_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for binary special functions (2 inputs -> 1 output)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_binary_special(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    a_ptr: u64,
    b_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_ptr);
        builder.arg(&b_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for ternary special functions (3 inputs -> 1 output)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_ternary_special(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    a_ptr: u64,
    b_ptr: u64,
    x_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_ptr);
        builder.arg(&b_ptr);
        builder.arg(&x_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

// ============================================================================
// Extended Launchers with Parameters
// ============================================================================

/// Generic launcher for unary special functions with one i32 parameter
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_unary_special_with_int(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    n_param: i32,
    x_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&n_param);
        builder.arg(&x_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for unary special functions with two i32 parameters
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_unary_special_with_two_ints(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    n_param: i32,
    m_param: i32,
    x_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&n_param);
        builder.arg(&m_param);
        builder.arg(&x_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for binary special functions with two i32 parameters (sph_harm)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_binary_special_with_two_ints(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    n_param: i32,
    m_param: i32,
    a_ptr: u64,
    b_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    unsafe {
        let mut builder = stream.launch_builder(&func);
        builder.arg(&n_param);
        builder.arg(&m_param);
        builder.arg(&a_ptr);
        builder.arg(&b_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for unary special functions with two f64 parameters (hyp1f1)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_unary_special_with_2f64(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    a: f64,
    b: f64,
    z_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    // Convert params to appropriate type based on dtype
    let (a_f32, b_f32) = (a as f32, b as f32);

    unsafe {
        let mut builder = stream.launch_builder(&func);
        if dtype == DType::F64 {
            builder.arg(&a);
            builder.arg(&b);
        } else {
            builder.arg(&a_f32);
            builder.arg(&b_f32);
        }
        builder.arg(&z_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}

/// Generic launcher for unary special functions with three f64 parameters (hyp2f1)
///
/// # Safety
/// Pointers must be valid GPU memory of correct size.
pub(crate) unsafe fn launch_unary_special_with_3f64(
    ctx: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    kernel_base: &str,
    op_name: &'static str,
    a: f64,
    b: f64,
    c: f64,
    z_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = special_kernel_name(kernel_base, dtype, op_name)?;
    let module = get_or_load_module(ctx, device_index, SPECIAL_MODULE)?;
    let func = get_kernel_function(&module, &kernel_name)?;

    let grid = elementwise_launch_config(numel);
    let cfg = launch_config(grid, (256, 1, 1), 0);
    let n = numel as u32;

    // Convert params to appropriate type based on dtype
    let (a_f32, b_f32, c_f32) = (a as f32, b as f32, c as f32);

    unsafe {
        let mut builder = stream.launch_builder(&func);
        if dtype == DType::F64 {
            builder.arg(&a);
            builder.arg(&b);
            builder.arg(&c);
        } else {
            builder.arg(&a_f32);
            builder.arg(&b_f32);
            builder.arg(&c_f32);
        }
        builder.arg(&z_ptr);
        builder.arg(&out_ptr);
        builder.arg(&n);

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

    Ok(())
}