numr 0.5.2

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
//! Complex number operation CUDA kernel launchers
//!
//! Provides launchers for complex number operations:
//! - conj: Complex conjugate
//! - real: Extract real part
//! - imag: Extract imaginary part
//! - angle: Compute phase angle

use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::{CudaContext, CudaStream};
use std::sync::Arc;

use super::loader::{
    BLOCK_SIZE, elementwise_launch_config, get_kernel_function, get_or_load_module, launch_config,
};
use crate::dtype::DType;
use crate::error::{Error, Result};

/// Module name for complex operations
const COMPLEX_MODULE: &str = "complex";

/// Launch complex conjugate kernel.
///
/// Computes: output[i] = conj(input[i])
/// For complex numbers a + bi, returns a - bi
///
/// # Supported Dtypes
/// - Complex64: float2 → float2
/// - Complex128: double2 → double2
///
/// # Safety
/// - All pointers must be valid device memory
/// - Input and output tensors must have at least `numel` elements of appropriate dtype
pub unsafe fn launch_conj(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match dtype {
        DType::Complex64 => "conj_complex64",
        DType::Complex128 => "conj_complex128",
        _ => return Err(Error::UnsupportedDType { dtype, op: "conj" }),
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_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(())
    }
}

/// Launch real part extraction kernel.
///
/// Extracts real component from complex numbers.
///
/// # Output Dtypes
/// - Complex64 input → F32 output
/// - Complex128 input → F64 output
///
/// # Safety
/// - All pointers must be valid device memory
/// - Input tensor must have at least `numel` complex elements
/// - Output tensor must have at least `numel` float elements
pub unsafe fn launch_real(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    input_dtype: DType,
    a_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match input_dtype {
        DType::Complex64 => "real_complex64",
        DType::Complex128 => "real_complex128",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: input_dtype,
                op: "real",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_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(())
    }
}

/// Launch imaginary part extraction kernel.
///
/// Extracts imaginary component from complex numbers.
///
/// # Output Dtypes
/// - Complex64 input → F32 output
/// - Complex128 input → F64 output
///
/// # Safety
/// - All pointers must be valid device memory
/// - Input tensor must have at least `numel` complex elements
/// - Output tensor must have at least `numel` float elements
pub unsafe fn launch_imag(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    input_dtype: DType,
    a_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match input_dtype {
        DType::Complex64 => "imag_complex64",
        DType::Complex128 => "imag_complex128",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: input_dtype,
                op: "imag",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_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(())
    }
}

/// Launch phase angle computation kernel.
///
/// Computes phase angle of complex numbers using atan2(imag, real).
/// Returns angles in radians, range [-π, π].
///
/// # Output Dtypes
/// - Complex64 input → F32 output (angles in radians)
/// - Complex128 input → F64 output (angles in radians)
///
/// # Safety
/// - All pointers must be valid device memory
/// - Input tensor must have at least `numel` complex elements
/// - Output tensor must have at least `numel` float elements
pub unsafe fn launch_angle(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    input_dtype: DType,
    a_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match input_dtype {
        DType::Complex64 => "angle_complex64",
        DType::Complex128 => "angle_complex128",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: input_dtype,
                op: "angle",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_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(())
    }
}

/// Launch angle kernel for real types.
///
/// Computes phase angle for real numbers: angle(x) = 0 if x >= 0, π if x < 0
///
/// # Supported Dtypes
/// - F32 → F32 output
/// - F64 → F64 output
///
/// # Safety
/// - All pointers must be valid device memory
/// - Input and output tensors must have at least `numel` elements
pub unsafe fn launch_angle_real(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    dtype: DType,
    a_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match dtype {
        DType::F32 => "angle_real_f32",
        DType::F64 => "angle_real_f64",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype,
                op: "angle_real",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&a_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(())
    }
}

/// Launch from_real_imag kernel.
///
/// Constructs complex tensor from separate real and imaginary arrays.
///
/// # Output Dtypes
/// - F32 real, F32 imag → Complex64 output
/// - F64 real, F64 imag → Complex128 output
///
/// # Safety
/// - All pointers must be valid device memory
/// - Real and imag tensors must have at least `numel` elements
/// - Output tensor must have at least `numel` complex elements
pub unsafe fn launch_from_real_imag(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    input_dtype: DType,
    real_ptr: u64,
    imag_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match input_dtype {
        DType::F32 => "from_real_imag_f32",
        DType::F64 => "from_real_imag_f64",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: input_dtype,
                op: "from_real_imag",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&real_ptr);
        builder.arg(&imag_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(())
    }
}

/// Launch complex × real multiplication kernel.
///
/// Computes (a + bi) * r = ar + br*i element-wise.
///
/// # Supported Dtypes
/// - Complex64 × F32 → Complex64
/// - Complex128 × F64 → Complex128
///
/// # Safety
/// - All pointers must be valid device memory
/// - Complex tensor must have at least `numel` complex elements
/// - Real tensor must have at least `numel` float elements
/// - Output tensor must have at least `numel` complex elements
pub unsafe fn launch_complex_mul_real(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    complex_dtype: DType,
    complex_ptr: u64,
    real_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match complex_dtype {
        DType::Complex64 => "complex64_mul_real",
        DType::Complex128 => "complex128_mul_real",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: complex_dtype,
                op: "complex_mul_real",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&complex_ptr);
        builder.arg(&real_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(())
    }
}

/// Launch complex / real division kernel.
///
/// Computes (a + bi) / r = (a/r) + (b/r)*i element-wise.
///
/// # Supported Dtypes
/// - Complex64 / F32 → Complex64
/// - Complex128 / F64 → Complex128
///
/// # Safety
/// - All pointers must be valid device memory
/// - Complex tensor must have at least `numel` complex elements
/// - Real tensor must have at least `numel` float elements
/// - Output tensor must have at least `numel` complex elements
pub unsafe fn launch_complex_div_real(
    context: &Arc<CudaContext>,
    stream: &CudaStream,
    device_index: usize,
    complex_dtype: DType,
    complex_ptr: u64,
    real_ptr: u64,
    out_ptr: u64,
    numel: usize,
) -> Result<()> {
    let kernel_name = match complex_dtype {
        DType::Complex64 => "complex64_div_real",
        DType::Complex128 => "complex128_div_real",
        _ => {
            return Err(Error::UnsupportedDType {
                dtype: complex_dtype,
                op: "complex_div_real",
            });
        }
    };

    unsafe {
        let module = get_or_load_module(context, device_index, COMPLEX_MODULE)?;
        let func = get_kernel_function(&module, kernel_name)?;

        let grid = elementwise_launch_config(numel);
        let block = (BLOCK_SIZE, 1, 1);
        let n = numel as u32;

        let cfg = launch_config(grid, block, 0);
        let mut builder = stream.launch_builder(&func);
        builder.arg(&complex_ptr);
        builder.arg(&real_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(())
    }
}