hanzo-rocm 0.5.2

Rust bindings for AMD ROCm libraries
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
// src/miopen/tensor.rs

use crate::miopen::error::{Error, Result};
use crate::miopen::ffi;
use crate::miopen::handle::Handle;
use std::ptr;

// pub type DataType = ffi::miopenDataType_t;

/// MIOpen data types
#[repr(u32)]
pub enum DataType {
    MiopenHalf = ffi::miopenDataType_t_miopenHalf,
    MiopenFloat = ffi::miopenDataType_t_miopenFloat,
    MiopenInt32 = ffi::miopenDataType_t_miopenInt32,
    MiopenInt8 = ffi::miopenDataType_t_miopenInt8,
    MiopenBFloat16 = ffi::miopenDataType_t_miopenBFloat16,
    MiopenDouble = ffi::miopenDataType_t_miopenDouble,
    MiopenInt64 = ffi::miopenDataType_t_miopenInt64,
}

impl TryFrom<u32> for DataType {
    type Error = Error;

    fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
        match value {
            ffi::miopenDataType_t_miopenHalf => Ok(DataType::MiopenHalf),
            ffi::miopenDataType_t_miopenFloat => Ok(DataType::MiopenFloat),
            ffi::miopenDataType_t_miopenInt32 => Ok(DataType::MiopenInt32),
            ffi::miopenDataType_t_miopenInt8 => Ok(DataType::MiopenInt8),
            ffi::miopenDataType_t_miopenBFloat16 => Ok(DataType::MiopenBFloat16),
            ffi::miopenDataType_t_miopenDouble => Ok(DataType::MiopenDouble),
            ffi::miopenDataType_t_miopenInt64 => Ok(DataType::MiopenInt64),
            _ => Err(Error::new(ffi::miopenStatus_t_miopenStatusUnknownError)),
        }
    }
}

/// MIOpen tensor layout
pub type TensorLayout = ffi::miopenTensorLayout_t;

/// Safe wrapper for MIOpen tensor descriptor
pub struct TensorDescriptor {
    desc: ffi::miopenTensorDescriptor_t,
}

impl TensorDescriptor {
    /// Create a new tensor descriptor
    pub fn new() -> Result<Self> {
        let mut desc = ptr::null_mut();
        let status = unsafe { ffi::miopenCreateTensorDescriptor(&mut desc) };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(Self { desc })
    }

    /// Set the descriptor for a 4D tensor (NCHW format)
    pub fn set_4d(&mut self, data_type: DataType, n: i32, c: i32, h: i32, w: i32) -> Result<()> {
        let status =
            unsafe { ffi::miopenSet4dTensorDescriptor(self.desc, data_type as u32, n, c, h, w) };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Create a 4D tensor (NCHW format)
    pub fn new_4d(data_type: DataType, n: i32, c: i32, h: i32, w: i32) -> Result<Self> {
        let mut desc = Self::new()?;
        desc.set_4d(data_type, n, c, h, w)?;
        Ok(desc)
    }

    /// Set the descriptor for a 4D tensor with strides
    pub fn set_4d_ex(
        &mut self,
        data_type: DataType,
        n: i32,
        c: i32,
        h: i32,
        w: i32,
        n_stride: i32,
        c_stride: i32,
        h_stride: i32,
        w_stride: i32,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSet4dTensorDescriptorEx(
                self.desc,
                data_type as u32,
                n,
                c,
                h,
                w,
                n_stride,
                c_stride,
                h_stride,
                w_stride,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Set the descriptor for an N-dimensional tensor with specific layout
    pub fn set_nd_with_layout(
        &mut self,
        data_type: DataType,
        layout: TensorLayout,
        dims: &[i32],
    ) -> Result<()> {
        let num_dims = dims.len() as i32;

        let status = unsafe {
            ffi::miopenSetNdTensorDescriptorWithLayout(
                self.desc,
                data_type as u32,
                layout,
                dims.as_ptr(),
                num_dims,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Get the details of a 4D tensor descriptor
    pub fn get_4d(&self) -> Result<(DataType, i32, i32, i32, i32, i32, i32, i32, i32)> {
        let mut data_type = 0;
        let mut n = 0;
        let mut c = 0;
        let mut h = 0;
        let mut w = 0;
        let mut n_stride = 0;
        let mut c_stride = 0;
        let mut h_stride = 0;
        let mut w_stride = 0;

        let status = unsafe {
            ffi::miopenGet4dTensorDescriptor(
                self.desc,
                &mut data_type,
                &mut n,
                &mut c,
                &mut h,
                &mut w,
                &mut n_stride,
                &mut c_stride,
                &mut h_stride,
                &mut w_stride,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok((
            DataType::try_from(data_type)?,
            n,
            c,
            h,
            w,
            n_stride,
            c_stride,
            h_stride,
            w_stride,
        ))
    }

    /// Set the descriptor for an N-dimensional tensor
    pub fn set_nd(&mut self, data_type: DataType, dims: &[i32], strides: &[i32]) -> Result<()> {
        let nb_dims = dims.len() as i32;

        if nb_dims != strides.len() as i32 {
            return Err(Error::new(ffi::miopenStatus_t_miopenStatusBadParm));
        }

        let status = unsafe {
            ffi::miopenSetTensorDescriptor(
                self.desc,
                data_type as u32,
                nb_dims,
                dims.as_ptr(),
                strides.as_ptr(),
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Gets the size of tensor dimensions
    pub fn get_size(&self) -> Result<i32> {
        let mut size = 0;

        let status = unsafe { ffi::miopenGetTensorDescriptorSize(self.desc, &mut size) };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(size)
    }

    /// Get the descriptor details for an N-dimensional tensor
    pub fn get_nd(
        &self,
        dims_capacity: usize,
        strides_capacity: usize,
    ) -> Result<(DataType, Vec<i32>, Vec<i32>)> {
        let mut data_type = 0;
        let mut dims = vec![0; dims_capacity];
        let mut strides = vec![0; strides_capacity];

        let status = unsafe {
            ffi::miopenGetTensorDescriptor(
                self.desc,
                &mut data_type,
                dims.as_mut_ptr(),
                strides.as_mut_ptr(),
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok((DataType::try_from(data_type)?, dims, strides))
    }

    /// Get the number of bytes for a tensor
    pub fn get_num_bytes(&self) -> Result<usize> {
        let mut num_bytes = 0;

        let status = unsafe { ffi::miopenGetTensorNumBytes(self.desc, &mut num_bytes) };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(num_bytes)
    }

    /// Transform tensor from one layout to another
    pub unsafe fn transform(
        &self,
        handle: &Handle,
        alpha: &[u8],
        x_desc: &TensorDescriptor,
        x: *const ::std::os::raw::c_void,
        beta: &[u8],
        y: *mut ::std::os::raw::c_void,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenTransformTensor(
                handle.as_raw(),
                alpha.as_ptr() as *const ::std::os::raw::c_void,
                x_desc.as_raw(),
                x,
                beta.as_ptr() as *const ::std::os::raw::c_void,
                self.as_raw(),
                y,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Set tensor to a single value
    pub unsafe fn set_tensor(
        &self,
        handle: &Handle,
        y: *mut ::std::os::raw::c_void,
        alpha: &[u8],
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetTensor(
                handle.as_raw(),
                self.as_raw(),
                y,
                alpha.as_ptr() as *const ::std::os::raw::c_void,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Scale a tensor by a single value
    pub unsafe fn scale_tensor(
        &self,
        handle: &Handle,
        y: *mut ::std::os::raw::c_void,
        alpha: &[u8],
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenScaleTensor(
                handle.as_raw(),
                self.as_raw(),
                y,
                alpha.as_ptr() as *const ::std::os::raw::c_void,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Execute element-wise tensor operations
    pub unsafe fn op_tensor(
        &self,
        handle: &Handle,
        tensor_op: ffi::miopenTensorOp_t,
        alpha1: &[u8],
        a_desc: &TensorDescriptor,
        a: *const ::std::os::raw::c_void,
        alpha2: &[u8],
        b_desc: &TensorDescriptor,
        b: *const ::std::os::raw::c_void,
        beta: &[u8],
        c: *mut ::std::os::raw::c_void,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenOpTensor(
                handle.as_raw(),
                tensor_op,
                alpha1.as_ptr() as *const ::std::os::raw::c_void,
                a_desc.as_raw(),
                a,
                alpha2.as_ptr() as *const ::std::os::raw::c_void,
                b_desc.as_raw(),
                b,
                beta.as_ptr() as *const ::std::os::raw::c_void,
                self.as_raw(),
                c,
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Get the raw descriptor handle
    pub fn as_raw(&self) -> ffi::miopenTensorDescriptor_t {
        self.desc
    }
}

impl Drop for TensorDescriptor {
    fn drop(&mut self) {
        if !self.desc.is_null() {
            unsafe {
                let _ = ffi::miopenDestroyTensorDescriptor(self.desc);
                // We cannot handle errors in drop, so just ignore the result
            };
            self.desc = ptr::null_mut();
        }
    }
}

/// Safe wrapper for MIOpen sequence tensor descriptor
pub struct SeqTensorDescriptor {
    desc: ffi::miopenSeqTensorDescriptor_t,
}

impl SeqTensorDescriptor {
    /// Create a new sequence tensor descriptor
    pub fn new() -> Result<Self> {
        let mut desc = ptr::null_mut();
        let status = unsafe { ffi::miopenCreateSeqTensorDescriptor(&mut desc) };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(Self { desc })
    }

    /// Set the descriptor for a RNN sequence data tensor
    pub fn set_rnn_data_seq_tensor(
        &mut self,
        data_type: DataType,
        layout: ffi::miopenRNNBaseLayout_t,
        max_sequence_len: i32,
        batch_size: i32,
        vector_size: i32,
        sequence_len_array: &[i32],
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetRNNDataSeqTensorDescriptor(
                self.desc,
                data_type as u32,
                layout,
                max_sequence_len,
                batch_size,
                vector_size,
                sequence_len_array.as_ptr(),
                ptr::null_mut(), // paddingMarker, should be NULL
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok(())
    }

    /// Get the descriptor details for a RNN sequence data tensor
    pub fn get_rnn_data_seq_tensor(
        &self,
        sequence_len_array_limit: i32,
    ) -> Result<(
        DataType,
        ffi::miopenRNNBaseLayout_t,
        i32,
        i32,
        i32,
        Vec<i32>,
    )> {
        let mut data_type = 0;
        let mut layout = 0;
        let mut max_sequence_len = 0;
        let mut batch_size = 0;
        let mut vector_size = 0;
        let mut sequence_len_array = vec![0; sequence_len_array_limit as usize];

        let status = unsafe {
            ffi::miopenGetRNNDataSeqTensorDescriptor(
                self.desc,
                &mut data_type,
                &mut layout,
                &mut max_sequence_len,
                &mut batch_size,
                &mut vector_size,
                sequence_len_array_limit,
                if sequence_len_array_limit > 0 {
                    sequence_len_array.as_mut_ptr()
                } else {
                    ptr::null_mut()
                },
                ptr::null_mut(), // paddingMarker, should be NULL
            )
        };

        if status != ffi::miopenStatus_t_miopenStatusSuccess {
            return Err(Error::new(status));
        }

        Ok((
            DataType::try_from(data_type)?,
            layout,
            max_sequence_len,
            batch_size,
            vector_size,
            sequence_len_array,
        ))
    }

    /// Get the raw descriptor handle
    pub fn as_raw(&self) -> ffi::miopenSeqTensorDescriptor_t {
        self.desc
    }
}

impl Drop for SeqTensorDescriptor {
    fn drop(&mut self) {
        if !self.desc.is_null() {
            unsafe {
                let _ = ffi::miopenDestroySeqTensorDescriptor(self.desc);
                // We cannot handle errors in drop, so just ignore the result
            };
            self.desc = ptr::null_mut();
        }
    }
}