singe-cublas 0.1.0-alpha.5

Safe Rust wrappers for the NVIDIA cuBLAS dense linear algebra library (with cuBLASLt).
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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
#[allow(unused_imports)]
use crate::error::Status;

use std::ptr;

use singe_cuda::{data_type::DataType, memory::DeviceMemory};

use crate::{
    context::Context,
    error::{Error, Result},
    sys, try_ffi,
    utility::to_i32,
};

/// Supports the 64-bit integer interface.
///
/// Scales vector `x` by scalar $\alpha$ and overwrites it with the result.
/// The performed operation is $\mathbf{x}\lbrack j\rbrack = \alpha \times \mathbf{x}\lbrack j\rbrack$ for $i = 1,\ldots,n$ and $j = 1 + \left( {i - 1} \right)\cdot \text{incx}$.
/// The formula uses the BLAS 1-based indexing convention.
///
/// See NETLIB documentation:
///
/// [sscal()](https://www.netlib.org/blas/sscal.f), [dscal()](https://www.netlib.org/blas/dscal.f), [csscal()](https://www.netlib.org/blas/csscal.f), [cscal()](https://www.netlib.org/blas/cscal.f), [zdscal()](https://www.netlib.org/blas/zdscal.f), [zscal()](https://www.netlib.org/blas/zscal.f).
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// `incx` is zero or too large for cuBLAS, the vector length is invalid, or
/// cuBLAS rejects the operation.
pub fn sscal(ctx: &Context, alpha: &f32, x: &mut DeviceMemory<f32>, incx: usize) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;

    unsafe {
        try_ffi!(sys::cublasSscal_v2(
            ctx.as_raw(),
            n,
            alpha,
            x.as_mut_ptr(),
            incx,
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Generalizes the typed cuBLAS norm routines so input data, output data, and compute type can
/// be specified independently.
///
/// Computes the Euclidean norm of vector `x`.
/// The code uses a multiphase model of accumulation to avoid intermediate underflow and overflow, with the result being equivalent to $\sqrt{\sum\_{i = 1}^{n}\left( {\mathbf{x}\lbrack j\rbrack \times \mathbf{x}\lbrack j\rbrack} \right)}$ where $j = 1 + \left( {i - 1} \right)\cdot \text{incx}$ in exact arithmetic.
/// The formula uses the BLAS 1-based indexing convention.
///
/// See NETLIB documentation:
///
/// [snrm2()](https://www.netlib.org/blas/snrm2.f90), [dnrm2()](https://www.netlib.org/blas/dnrm2.f90), [scnrm2()](https://www.netlib.org/blas/scnrm2.f90), [dznrm2()](https://www.netlib.org/blas/dznrm2.f90).
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// `incx` is zero or too large for cuBLAS, `x` is too small for the requested
/// vector shape, a type combination is unsupported, cuBLAS cannot allocate its
/// reduction buffer, or cuBLAS rejects or fails the operation.
pub fn nrm2_ex<TX, TResult>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    result: &mut TResult,
    result_type: DataType,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;

    unsafe {
        try_ffi!(sys::cublasNrm2Ex(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            ptr::from_mut(result) as _,
            result_type.into(),
            execution_type.into(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Generalizes the typed cuBLAS dot-product routines so input data, output data,
/// and compute type can be specified independently.
/// The `dotc` variants compute conjugated dot products, and the `dotu` variants compute
/// unconjugated dot products.
///
/// Computes the dot product of vectors `x` and `y`.
/// The result is $\sum\_{i = 1}^{n}\left( {\mathbf{x}\lbrack k\rbrack \times \mathbf{y}\lbrack j\rbrack} \right)$ where $k = 1 + \left( {i - 1} \right)\cdot \text{incx}$ and $j = 1 + \left( {i - 1} \right)\cdot \text{incy}$.
/// For conjugated dot products, the element of vector `x` is conjugated.
/// The formula uses the BLAS 1-based indexing convention.
///
/// See NETLIB documentation:
///
/// [sdot()](https://www.netlib.org/blas/sdot.f), [ddot()](https://www.netlib.org/blas/ddot.f), [cdotu()](https://www.netlib.org/blas/cdotu.f), [cdotc()](https://www.netlib.org/blas/cdotc.f), [zdotu()](https://www.netlib.org/blas/zdotu.f), [zdotc()](https://www.netlib.org/blas/zdotc.f).
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// `incx` or `incy` is zero or too large for cuBLAS, `x` or `y` is too small
/// for the requested vector shape, a type combination is unsupported, cuBLAS
/// cannot allocate its reduction buffer, or cuBLAS rejects or fails the
/// operation.
pub fn dot_ex<TX, TY, TResult>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
    result: &mut TResult,
    result_type: DataType,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasDotEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            y.as_ptr() as _,
            y_type.into(),
            incy,
            ptr::from_mut(result) as _,
            result_type.into(),
            execution_type.into(),
        ))?;
    }

    Ok(())
}

pub fn dotc_ex<TX, TY, TResult>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
    result: &mut TResult,
    result_type: DataType,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasDotcEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            y.as_ptr() as _,
            y_type.into(),
            incy,
            ptr::from_mut(result) as _,
            result_type.into(),
            execution_type.into(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Applies the Givens rotation matrix to vectors `x` and `y`.
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// either increment is zero or too large for cuBLAS, the vector lengths are
/// incompatible, or cuBLAS rejects the operation.
pub fn drot(
    ctx: &Context,
    x: &mut DeviceMemory<f64>,
    incx: usize,
    y: &mut DeviceMemory<f64>,
    incy: usize,
    c: &f64,
    s: &f64,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasDrot_v2(
            ctx.as_raw(),
            n,
            x.as_mut_ptr(),
            incx,
            y.as_mut_ptr(),
            incy,
            c,
            s,
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Extends the typed cuBLAS rotation routines so vector and scalar types can be chosen independently.
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// either increment is zero or too large for cuBLAS, the vector lengths are
/// incompatible, the supplied data type combination is not supported, or
/// cuBLAS rejects the operation.
pub fn rot_ex<TX, TY, TCS>(
    ctx: &Context,
    x: &mut DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &mut DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
    c: &TCS,
    s: &TCS,
    cs_type: DataType,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasRotEx(
            ctx.as_raw(),
            n,
            x.as_mut_ptr() as _,
            x_type.into(),
            incx,
            y.as_mut_ptr() as _,
            y_type.into(),
            incy,
            ptr::from_ref(c) as _,
            ptr::from_ref(s) as _,
            cs_type.into(),
            execution_type.into(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Constructs the Givens rotation matrix parameters for `a` and `b`.
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode or
/// cuBLAS rejects the operation.
pub fn drotg(ctx: &Context, a: &mut f64, b: &mut f64, c: &mut f64, s: &mut f64) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;

    unsafe {
        try_ffi!(sys::cublasDrotg_v2(
            ctx.as_raw(),
            ptr::from_mut(a),
            ptr::from_mut(b),
            ptr::from_mut(c),
            ptr::from_mut(s),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Applies the modified Givens transformation described by `param` to vectors `x` and `y`.
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// either increment is zero or too large for cuBLAS, the vector lengths are
/// incompatible, or cuBLAS rejects the operation.
pub fn drotm(
    ctx: &Context,
    x: &mut DeviceMemory<f64>,
    incx: usize,
    y: &mut DeviceMemory<f64>,
    incy: usize,
    param: &[f64; 5],
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasDrotm_v2(
            ctx.as_raw(),
            n,
            x.as_mut_ptr(),
            incx,
            y.as_mut_ptr(),
            incy,
            param.as_ptr(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Constructs the modified Givens transformation parameters in `param`.
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode or
/// cuBLAS rejects the operation.
pub fn drotmg(
    ctx: &Context,
    d1: &mut f64,
    d2: &mut f64,
    x1: &mut f64,
    y1: &f64,
    param: &mut [f64; 5],
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;

    unsafe {
        try_ffi!(sys::cublasDrotmg_v2(
            ctx.as_raw(),
            ptr::from_mut(d1),
            ptr::from_mut(d2),
            ptr::from_mut(x1),
            ptr::from_ref(y1),
            param.as_mut_ptr(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Scales vector `x` by scalar $\alpha$ and overwrites it with the result.
/// The performed operation is $\mathbf{x}\lbrack j\rbrack = \alpha \times \mathbf{x}\lbrack j\rbrack$ for $i = 1,\ldots,n$ and $j = 1 + \left( {i - 1} \right)\cdot \text{incx}$.
/// The formula uses the BLAS 1-based indexing convention.
///
/// See NETLIB documentation:
///
/// [sscal()](https://www.netlib.org/blas/sscal.f), [dscal()](https://www.netlib.org/blas/dscal.f), [csscal()](https://www.netlib.org/blas/csscal.f), [cscal()](https://www.netlib.org/blas/cscal.f), [zdscal()](https://www.netlib.org/blas/zdscal.f), [zscal()](https://www.netlib.org/blas/zscal.f).
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// `incx` is zero or too large for cuBLAS, `x` is too small for the requested
/// vector shape, a type combination is unsupported, or cuBLAS rejects or fails
/// the operation.
pub fn scal_ex<TAlpha, TX>(
    ctx: &Context,
    alpha: &TAlpha,
    alpha_type: DataType,
    x: &mut DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;

    unsafe {
        try_ffi!(sys::cublasScalEx(
            ctx.as_raw(),
            n,
            ptr::from_ref(alpha) as _,
            alpha_type.into(),
            x.as_mut_ptr() as _,
            x_type.into(),
            incx,
            execution_type.into(),
        ))?;
    }

    Ok(())
}

/// Supports the 64-bit integer interface.
///
/// Generalizes the typed cuBLAS AXPY routines so input data, output data, and compute type can
/// be specified independently.
///
/// Multiplies vector `x` by scalar $\alpha$ and adds it to vector `y`, overwriting
/// `y` with the result.
/// The performed operation is $\mathbf{y}\lbrack j\rbrack = \alpha \times \mathbf{x}\lbrack k\rbrack + \mathbf{y}\lbrack j\rbrack$ for $i = 1,\ldots,n$, $k = 1 + \left( {i - 1} \right)\cdot \text{incx}$ and $j = 1 + \left( {i - 1} \right)\cdot \text{incy}$.
/// The formula uses the BLAS 1-based indexing convention.
///
/// See NETLIB documentation:
///
/// [saxpy()](https://www.netlib.org/blas/saxpy.f), [daxpy()](https://www.netlib.org/blas/daxpy.f), [caxpy()](https://www.netlib.org/blas/caxpy.f), [zaxpy()](https://www.netlib.org/blas/zaxpy.f).
///
/// # Errors
///
/// Returns an error if the context cannot be used with host pointer mode,
/// `incx` or `incy` is zero or too large for cuBLAS, `x` or `y` is too small
/// for the requested vector shape, a type combination is unsupported, or
/// cuBLAS rejects or fails the operation.
pub fn axpy_ex<TAlpha, TX, TY>(
    ctx: &Context,
    alpha: &TAlpha,
    alpha_type: DataType,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &mut DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasAxpyEx(
            ctx.as_raw(),
            n,
            ptr::from_ref(alpha) as _,
            alpha_type.into(),
            x.as_ptr() as _,
            x_type.into(),
            incx,
            y.as_mut_ptr() as _,
            y_type.into(),
            incy,
            execution_type.into(),
        ))?;
    }

    Ok(())
}

pub fn copy_ex<TX, TY>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &mut DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
) -> Result<()> {
    ctx.bind()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasCopyEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            y.as_mut_ptr() as _,
            y_type.into(),
            incy,
        ))?;
    }

    Ok(())
}

pub fn swap_ex<TX, TY>(
    ctx: &Context,
    x: &mut DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    y: &mut DeviceMemory<TY>,
    y_type: DataType,
    incy: usize,
) -> Result<()> {
    ctx.bind()?;
    if incx == 0 || incy == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_binary_len(x.len(), incx, y.len(), incy)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;
    let incy = to_i32(incy, "incy")?;

    unsafe {
        try_ffi!(sys::cublasSwapEx(
            ctx.as_raw(),
            n,
            x.as_mut_ptr() as _,
            x_type.into(),
            incx,
            y.as_mut_ptr() as _,
            y_type.into(),
            incy,
        ))?;
    }

    Ok(())
}

pub fn iamax_ex<TX>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
) -> Result<i32> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(0);
    }

    let incx = to_i32(incx, "incx")?;
    let mut result = 0;

    unsafe {
        try_ffi!(sys::cublasIamaxEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            &raw mut result,
        ))?;
    }

    Ok(result)
}

pub fn iamin_ex<TX>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
) -> Result<i32> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(0);
    }

    let incx = to_i32(incx, "incx")?;
    let mut result = 0;

    unsafe {
        try_ffi!(sys::cublasIaminEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            &raw mut result,
        ))?;
    }

    Ok(result)
}

pub fn asum_ex<TX, TResult>(
    ctx: &Context,
    x: &DeviceMemory<TX>,
    x_type: DataType,
    incx: usize,
    result: &mut TResult,
    result_type: DataType,
    execution_type: DataType,
) -> Result<()> {
    ctx.bind()?;
    ctx.require_host_pointer_mode()?;
    if incx == 0 {
        return Err(Error::InvalidIncrement);
    }

    let n = vector_len(x.len(), incx)?;
    if n == 0 {
        return Ok(());
    }

    let incx = to_i32(incx, "incx")?;

    unsafe {
        try_ffi!(sys::cublasAsumEx(
            ctx.as_raw(),
            n,
            x.as_ptr() as _,
            x_type.into(),
            incx,
            ptr::from_mut(result) as _,
            result_type.into(),
            execution_type.into(),
        ))?;
    }

    Ok(())
}

fn vector_len(length: usize, inc: usize) -> Result<i32> {
    if length == 0 {
        return Ok(0);
    }

    let n = 1 + (length - 1) / inc;
    i32::try_from(n).map_err(|_| Error::OutOfRange { name: "n".into() })
}

fn vector_binary_len(x_length: usize, incx: usize, y_length: usize, incy: usize) -> Result<i32> {
    let x_n = vector_len(x_length, incx)?;
    let y_n = vector_len(y_length, incy)?;

    if x_n != y_n {
        return Err(Error::InvalidVectorShape);
    }

    Ok(x_n)
}

#[cfg(all(test, feature = "testing"))]
mod tests {
    use super::*;
    use crate::testing::setup_context;

    #[test]
    fn test_sscal_scales_vector() -> Result<()> {
        let ctx = setup_context()?;

        let mut x = DeviceMemory::from_slice(&[1.0_f32, 2.0, 3.0, 4.0])?;
        sscal(&ctx, &2.5, &mut x, 1)?;

        let result = x.copy_to_host_vec()?;
        assert_eq!(result, vec![2.5, 5.0, 7.5, 10.0]);

        Ok(())
    }

    #[test]
    fn test_drot_rotates_vectors() -> Result<()> {
        let ctx = setup_context()?;

        let mut x = DeviceMemory::from_slice(&[1.0_f64, 2.0, 3.0, 4.0])?;
        let mut y = DeviceMemory::from_slice(&[5.0_f64, 6.0, 7.0, 8.0])?;
        drot(&ctx, &mut x, 1, &mut y, 1, &2.1, &1.2)?;

        let x_result = x.copy_to_host_vec()?;
        let y_result = y.copy_to_host_vec()?;
        let x_expected = [8.1, 11.4, 14.7, 18.0];
        let y_expected = [9.3, 10.2, 11.1, 12.0];

        for (actual, expected) in x_result.iter().zip(x_expected) {
            assert!((actual - expected).abs() < 1.0e-12);
        }
        for (actual, expected) in y_result.iter().zip(y_expected) {
            assert!((actual - expected).abs() < 1.0e-12);
        }

        Ok(())
    }
}