rocmrc 0.1.0

Minimal safe ROCm bindings (HIP, hipRTC), modeled after cudarc
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
//! Safe wrappers for rocBLAS.
//!
//! Layout mirrors `cudarc::cublas`. Handle is bound to a single [`HipStream`] at
//! construction time and keeps it alive via `Arc`. Ops are exposed via
//! per-scalar-type traits (`Gemm<T>`, `Gemv<T>`, `Axpy<T>` …) so call sites can
//! be generic over the precision.

use std::{ffi::c_void, sync::Arc};

use crate::driver::HipStream;

pub mod result;
pub mod sys;

/// Re-exported sys enum that callers commonly pass into the safe wrappers.
/// Lets downstream code use `rocmrc::rocblas::rocblas_pointer_mode` instead of
/// reaching into the generated `sys::` module.
pub use sys::rocblas_pointer_mode;

#[derive(Debug, thiserror::Error)]
pub enum RocblasError {
    #[error("rocBLAS error: {0:?}")]
    Rocblas(sys::rocblas_status),
}

/// Transpose flag passed to BLAS ops. Maps to `sys::rocblas_operation`.
#[derive(Debug, Clone, Copy)]
pub enum Operation {
    None,
    Transpose,
    ConjugateTranspose,
}

impl From<Operation> for sys::rocblas_operation {
    fn from(op: Operation) -> Self {
        match op {
            Operation::None => sys::rocblas_operation::rocblas_operation_none,
            Operation::Transpose => sys::rocblas_operation::rocblas_operation_transpose,
            Operation::ConjugateTranspose => {
                sys::rocblas_operation::rocblas_operation_conjugate_transpose
            }
        }
    }
}

/// RAII rocBLAS handle bound to a single [`HipStream`].
///
/// rocBLAS handles are *not* thread-safe by the upstream contract — one handle
/// per host thread — but we mark `Send + Sync` to match the convention used
/// elsewhere in this crate (see [`HipStream`]). Callers sharing a handle across
/// threads are responsible for external synchronization.
pub struct RocblasHandle {
    raw: sys::rocblas_handle,
    #[allow(dead_code)]
    stream: Arc<HipStream>,
}

impl RocblasHandle {
    pub fn new(stream: Arc<HipStream>) -> Result<Arc<Self>, RocblasError> {
        let raw = result::create_handle()?;
        // driver::sys and rocblas::sys each redeclare ihipStream_t, so rustc
        // sees them as distinct types despite identical layout. Cast at the bridge.
        result::set_stream(raw, stream.hip_stream().cast())?;
        Ok(Arc::new(Self { raw, stream }))
    }

    /// Switch pointer mode (host vs device) for scalar args like `alpha`/`beta`
    /// and reduction `result` arguments. Defaults to host on a fresh handle.
    pub fn set_pointer_mode(&self, mode: sys::rocblas_pointer_mode) -> Result<(), RocblasError> {
        result::set_pointer_mode(self.raw, mode)
    }

    /// Raw handle. Exposed so callers can hand it to functions in
    /// [`result`] that haven't been wrapped yet.
    pub fn rocblas_handle(&self) -> sys::rocblas_handle {
        self.raw
    }
}

impl Drop for RocblasHandle {
    fn drop(&mut self) {
        let _ = result::destroy_handle(self.raw);
    }
}

// rocBLAS handle is not Sync per AMD docs (single-thread use). We mark it
// anyway for ergonomic parity with the rest of the crate; document and uphold
// the constraint externally.
unsafe impl Send for RocblasHandle {}
unsafe impl Sync for RocblasHandle {}

// ----- Config structs -----

#[derive(Clone, Copy)]
pub struct GemmConfig<T> {
    pub transa: Operation,
    pub transb: Operation,
    pub m: i32,
    pub n: i32,
    pub k: i32,
    pub alpha: T,
    pub lda: i32,
    pub ldb: i32,
    pub beta: T,
    pub ldc: i32,
}

#[derive(Clone, Copy)]
pub struct StridedBatchedConfig<T> {
    pub gemm: GemmConfig<T>,
    pub stride_a: i64,
    pub stride_b: i64,
    pub stride_c: i64,
    pub batch_count: i32,
}

#[derive(Clone, Copy)]
pub struct GemvConfig<T> {
    pub trans: Operation,
    pub m: i32,
    pub n: i32,
    pub alpha: T,
    pub lda: i32,
    pub incx: i32,
    pub beta: T,
    pub incy: i32,
}

#[derive(Clone, Copy)]
pub struct AxpyConfig<T> {
    pub n: i32,
    pub alpha: T,
    pub incx: i32,
    pub incy: i32,
}

#[derive(Clone, Copy)]
pub struct ScalConfig<T> {
    pub n: i32,
    pub alpha: T,
    pub incx: i32,
}

#[derive(Clone, Copy)]
pub struct Nrm2Config {
    pub n: i32,
    pub incx: i32,
}

#[derive(Clone, Copy)]
pub struct DotConfig {
    pub n: i32,
    pub incx: i32,
    pub incy: i32,
}

#[derive(Clone, Copy)]
pub struct CopyConfig {
    pub n: i32,
    pub incx: i32,
    pub incy: i32,
}

// ----- Traits -----

pub trait Gemm<T> {
    /// # Safety
    /// `a`, `b`, `c` must be valid device pointers sized for `cfg`'s dimensions
    /// and leading dimensions. `c` is read for `beta != 0` and always written.
    unsafe fn gemm(
        &self,
        cfg: GemmConfig<T>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError>;

    /// # Safety: same as [`Gemm::gemm`], applied per batch element.
    unsafe fn gemm_strided_batched(
        &self,
        cfg: StridedBatchedConfig<T>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError>;
}

pub trait Gemv<T> {
    /// # Safety: device pointers must be valid for `cfg`'s dimensions.
    unsafe fn gemv(
        &self,
        cfg: GemvConfig<T>,
        a: u64,
        x: u64,
        y: u64,
    ) -> Result<(), RocblasError>;
}

pub trait Axpy<T> {
    /// y := alpha*x + y.
    ///
    /// # Safety: device pointers must be valid for `cfg.n` elements at the given strides.
    unsafe fn axpy(&self, cfg: AxpyConfig<T>, x: u64, y: u64) -> Result<(), RocblasError>;
}

pub trait Scal<T> {
    /// x := alpha*x.
    /// # Safety: device pointer must be valid for `cfg.n * cfg.incx` elements.
    unsafe fn scal(&self, cfg: ScalConfig<T>, x: u64) -> Result<(), RocblasError>;
}

pub trait Nrm2<T> {
    /// result := sqrt(sum(x[i]^2)). `result` is interpreted per the handle's pointer mode.
    /// # Safety: pointers valid; `result` points to a single `T`.
    unsafe fn nrm2(
        &self,
        cfg: Nrm2Config,
        x: u64,
        result: u64,
    ) -> Result<(), RocblasError>;
}

pub trait Dot<T> {
    /// result := sum(x[i] * y[i]). `result` is interpreted per the handle's pointer mode.
    /// # Safety: pointers valid; `result` points to a single `T`.
    unsafe fn dot(
        &self,
        cfg: DotConfig,
        x: u64,
        y: u64,
        result: u64,
    ) -> Result<(), RocblasError>;
}

pub trait Copy<T> {
    /// y := x.
    /// # Safety: pointers valid for `cfg.n` elements.
    unsafe fn copy(&self, cfg: CopyConfig, x: u64, y: u64) -> Result<(), RocblasError>;
}

// ----- Trait impls: f32 -----

impl Gemm<f32> for RocblasHandle {
    unsafe fn gemm(
        &self,
        cfg: GemmConfig<f32>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        unsafe {
            result::sgemm(
                self.raw,
                cfg.transa.into(),
                cfg.transb.into(),
                cfg.m,
                cfg.n,
                cfg.k,
                &cfg.alpha,
                a,
                cfg.lda,
                b,
                cfg.ldb,
                &cfg.beta,
                c,
                cfg.ldc,
            )
        }
    }

    unsafe fn gemm_strided_batched(
        &self,
        cfg: StridedBatchedConfig<f32>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let g = cfg.gemm;
        unsafe {
            result::sgemm_strided_batched(
                self.raw,
                g.transa.into(),
                g.transb.into(),
                g.m,
                g.n,
                g.k,
                &g.alpha,
                a,
                g.lda,
                cfg.stride_a,
                b,
                g.ldb,
                cfg.stride_b,
                &g.beta,
                c,
                g.ldc,
                cfg.stride_c,
                cfg.batch_count,
            )
        }
    }
}

impl Gemm<f64> for RocblasHandle {
    unsafe fn gemm(
        &self,
        cfg: GemmConfig<f64>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        unsafe {
            result::dgemm(
                self.raw,
                cfg.transa.into(),
                cfg.transb.into(),
                cfg.m,
                cfg.n,
                cfg.k,
                &cfg.alpha,
                a,
                cfg.lda,
                b,
                cfg.ldb,
                &cfg.beta,
                c,
                cfg.ldc,
            )
        }
    }

    unsafe fn gemm_strided_batched(
        &self,
        cfg: StridedBatchedConfig<f64>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let g = cfg.gemm;
        unsafe {
            result::dgemm_strided_batched(
                self.raw,
                g.transa.into(),
                g.transb.into(),
                g.m,
                g.n,
                g.k,
                &g.alpha,
                a,
                g.lda,
                cfg.stride_a,
                b,
                g.ldb,
                cfg.stride_b,
                &g.beta,
                c,
                g.ldc,
                cfg.stride_c,
                cfg.batch_count,
            )
        }
    }
}

// ----- Trait impls: f16 and bf16 via gemm_ex -----
//
// gemm_ex compute mode is f32 (HPA). Alpha/beta are promoted to f32 here.

impl Gemm<half::f16> for RocblasHandle {
    unsafe fn gemm(
        &self,
        cfg: GemmConfig<half::f16>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let alpha = cfg.alpha.to_f32();
        let beta = cfg.beta.to_f32();
        unsafe {
            result::gemm_ex(
                self.raw,
                cfg.transa.into(),
                cfg.transb.into(),
                cfg.m,
                cfg.n,
                cfg.k,
                &alpha as *const _ as *const c_void,
                a,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                cfg.lda,
                b,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                cfg.ldb,
                &beta as *const _ as *const c_void,
                c,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                cfg.ldc,
                c,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                cfg.ldc,
                sys::rocblas_datatype::rocblas_datatype_f32_r,
                sys::rocblas_gemm_algo::rocblas_gemm_algo_standard,
                0,
                0,
            )
        }
    }

    unsafe fn gemm_strided_batched(
        &self,
        cfg: StridedBatchedConfig<half::f16>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let g = cfg.gemm;
        let alpha = g.alpha.to_f32();
        let beta = g.beta.to_f32();
        unsafe {
            result::gemm_strided_batched_ex(
                self.raw,
                g.transa.into(),
                g.transb.into(),
                g.m,
                g.n,
                g.k,
                &alpha as *const _ as *const c_void,
                a,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                g.lda,
                cfg.stride_a,
                b,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                g.ldb,
                cfg.stride_b,
                &beta as *const _ as *const c_void,
                c,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                g.ldc,
                cfg.stride_c,
                c,
                sys::rocblas_datatype::rocblas_datatype_f16_r,
                g.ldc,
                cfg.stride_c,
                cfg.batch_count,
                sys::rocblas_datatype::rocblas_datatype_f32_r,
                sys::rocblas_gemm_algo::rocblas_gemm_algo_standard,
                0,
                0,
            )
        }
    }
}

impl Gemm<half::bf16> for RocblasHandle {
    unsafe fn gemm(
        &self,
        cfg: GemmConfig<half::bf16>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let alpha = cfg.alpha.to_f32();
        let beta = cfg.beta.to_f32();
        unsafe {
            result::gemm_ex(
                self.raw,
                cfg.transa.into(),
                cfg.transb.into(),
                cfg.m,
                cfg.n,
                cfg.k,
                &alpha as *const _ as *const c_void,
                a,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                cfg.lda,
                b,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                cfg.ldb,
                &beta as *const _ as *const c_void,
                c,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                cfg.ldc,
                c,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                cfg.ldc,
                sys::rocblas_datatype::rocblas_datatype_f32_r,
                sys::rocblas_gemm_algo::rocblas_gemm_algo_standard,
                0,
                0,
            )
        }
    }

    unsafe fn gemm_strided_batched(
        &self,
        cfg: StridedBatchedConfig<half::bf16>,
        a: u64,
        b: u64,
        c: u64,
    ) -> Result<(), RocblasError> {
        let g = cfg.gemm;
        let alpha = g.alpha.to_f32();
        let beta = g.beta.to_f32();
        unsafe {
            result::gemm_strided_batched_ex(
                self.raw,
                g.transa.into(),
                g.transb.into(),
                g.m,
                g.n,
                g.k,
                &alpha as *const _ as *const c_void,
                a,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                g.lda,
                cfg.stride_a,
                b,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                g.ldb,
                cfg.stride_b,
                &beta as *const _ as *const c_void,
                c,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                g.ldc,
                cfg.stride_c,
                c,
                sys::rocblas_datatype::rocblas_datatype_bf16_r,
                g.ldc,
                cfg.stride_c,
                cfg.batch_count,
                sys::rocblas_datatype::rocblas_datatype_f32_r,
                sys::rocblas_gemm_algo::rocblas_gemm_algo_standard,
                0,
                0,
            )
        }
    }
}

// ----- L2: GEMV (f32, f64) -----

impl Gemv<f32> for RocblasHandle {
    unsafe fn gemv(
        &self,
        cfg: GemvConfig<f32>,
        a: u64,
        x: u64,
        y: u64,
    ) -> Result<(), RocblasError> {
        unsafe {
            result::sgemv(
                self.raw,
                cfg.trans.into(),
                cfg.m,
                cfg.n,
                &cfg.alpha,
                a,
                cfg.lda,
                x,
                cfg.incx,
                &cfg.beta,
                y,
                cfg.incy,
            )
        }
    }
}

impl Gemv<f64> for RocblasHandle {
    unsafe fn gemv(
        &self,
        cfg: GemvConfig<f64>,
        a: u64,
        x: u64,
        y: u64,
    ) -> Result<(), RocblasError> {
        unsafe {
            result::dgemv(
                self.raw,
                cfg.trans.into(),
                cfg.m,
                cfg.n,
                &cfg.alpha,
                a,
                cfg.lda,
                x,
                cfg.incx,
                &cfg.beta,
                y,
                cfg.incy,
            )
        }
    }
}

// ----- L1 impls (f32 + f64) -----

impl Axpy<f32> for RocblasHandle {
    unsafe fn axpy(
        &self,
        cfg: AxpyConfig<f32>,
        x: u64,
        y: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::saxpy(self.raw, cfg.n, &cfg.alpha, x, cfg.incx, y, cfg.incy) }
    }
}

impl Axpy<f64> for RocblasHandle {
    unsafe fn axpy(
        &self,
        cfg: AxpyConfig<f64>,
        x: u64,
        y: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::daxpy(self.raw, cfg.n, &cfg.alpha, x, cfg.incx, y, cfg.incy) }
    }
}

impl Scal<f32> for RocblasHandle {
    unsafe fn scal(&self, cfg: ScalConfig<f32>, x: u64) -> Result<(), RocblasError> {
        unsafe { result::sscal(self.raw, cfg.n, &cfg.alpha, x, cfg.incx) }
    }
}

impl Scal<f64> for RocblasHandle {
    unsafe fn scal(&self, cfg: ScalConfig<f64>, x: u64) -> Result<(), RocblasError> {
        unsafe { result::dscal(self.raw, cfg.n, &cfg.alpha, x, cfg.incx) }
    }
}

impl Nrm2<f32> for RocblasHandle {
    unsafe fn nrm2(
        &self,
        cfg: Nrm2Config,
        x: u64,
        result_ptr: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::snrm2(self.raw, cfg.n, x, cfg.incx, result_ptr) }
    }
}

impl Nrm2<f64> for RocblasHandle {
    unsafe fn nrm2(
        &self,
        cfg: Nrm2Config,
        x: u64,
        result_ptr: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::dnrm2(self.raw, cfg.n, x, cfg.incx, result_ptr) }
    }
}

impl Dot<f32> for RocblasHandle {
    unsafe fn dot(
        &self,
        cfg: DotConfig,
        x: u64,
        y: u64,
        result_ptr: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::sdot(self.raw, cfg.n, x, cfg.incx, y, cfg.incy, result_ptr) }
    }
}

impl Dot<f64> for RocblasHandle {
    unsafe fn dot(
        &self,
        cfg: DotConfig,
        x: u64,
        y: u64,
        result_ptr: u64,
    ) -> Result<(), RocblasError> {
        unsafe { result::ddot(self.raw, cfg.n, x, cfg.incx, y, cfg.incy, result_ptr) }
    }
}

impl Copy<f32> for RocblasHandle {
    unsafe fn copy(&self, cfg: CopyConfig, x: u64, y: u64) -> Result<(), RocblasError> {
        unsafe { result::scopy(self.raw, cfg.n, x, cfg.incx, y, cfg.incy) }
    }
}

impl Copy<f64> for RocblasHandle {
    unsafe fn copy(&self, cfg: CopyConfig, x: u64, y: u64) -> Result<(), RocblasError> {
        unsafe { result::dcopy(self.raw, cfg.n, x, cfg.incx, y, cfg.incy) }
    }
}