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
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
// src/miopen/fusion.rs

use crate::miopen::activation::ActivationMode;
use crate::miopen::convolution::{ConvFwdAlgorithm, ConvolutionDescriptor};
use crate::miopen::error::{Error, Result};
use crate::miopen::ffi;
use crate::miopen::handle::Handle;
use crate::miopen::tensor::TensorDescriptor;
use std::os::raw::c_void;
use std::ptr;

/// Fusion direction
pub type FusionDirection = ffi::miopenFusionDirection_t;

/// Safe wrapper for MIOpen fusion plan descriptor
pub struct FusionPlanDescriptor {
    desc: ffi::miopenFusionPlanDescriptor_t,
}

/// Safe wrapper for MIOpen fusion operator descriptor
pub struct FusionOpDescriptor {
    desc: ffi::miopenFusionOpDescriptor_t,
}

/// Safe wrapper for MIOpen operator arguments
pub struct OperatorArgs {
    args: ffi::miopenOperatorArgs_t,
}

impl FusionPlanDescriptor {
    /// Create a new fusion plan descriptor
    pub fn new(fusion_direction: FusionDirection, input_desc: &TensorDescriptor) -> Result<Self> {
        let mut desc = ptr::null_mut();
        let status = unsafe {
            ffi::miopenCreateFusionPlan(&mut desc, fusion_direction, input_desc.as_raw())
        };

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

        Ok(Self { desc })
    }

    /// Compile the fusion plan
    pub fn compile(&self, handle: &Handle) -> Result<()> {
        let status = unsafe { ffi::miopenCompileFusionPlan(handle.as_raw(), self.desc) };

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

        Ok(())
    }

    /// Get an operator from the fusion plan
    pub fn get_op(&self, op_idx: i32) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe { ffi::miopenFusionPlanGetOp(self.desc, op_idx, &mut op) };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Get the workspace size required for the fusion plan
    pub fn get_workspace_size(&self, handle: &Handle, algo: ConvFwdAlgorithm) -> Result<usize> {
        let mut workspace_size = 0;

        let status = unsafe {
            ffi::miopenFusionPlanGetWorkSpaceSize(
                handle.as_raw(),
                self.desc,
                &mut workspace_size,
                algo,
            )
        };

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

        Ok(workspace_size)
    }

    /// Create a forward convolution operator in the fusion plan
    pub fn create_op_conv_forward(
        &self,
        conv_desc: &ConvolutionDescriptor,
        w_desc: &TensorDescriptor,
    ) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe {
            ffi::miopenCreateOpConvForward(self.desc, &mut op, conv_desc.as_raw(), w_desc.as_raw())
        };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a forward activation operator in the fusion plan
    pub fn create_op_activation_forward(&self, mode: ActivationMode) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe { ffi::miopenCreateOpActivationForward(self.desc, &mut op, mode as u32) };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a backward activation operator in the fusion plan
    pub fn create_op_activation_backward(
        &self,
        mode: ActivationMode,
    ) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe { ffi::miopenCreateOpActivationBackward(self.desc, &mut op, mode as u32) };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a forward bias operator in the fusion plan
    pub fn create_op_bias_forward(&self, b_desc: &TensorDescriptor) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe { ffi::miopenCreateOpBiasForward(self.desc, &mut op, b_desc.as_raw()) };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a batch normalization inference operator in the fusion plan
    pub fn create_op_batch_norm_inference(
        &self,
        bn_mode: ffi::miopenBatchNormMode_t,
        bn_scale_bias_mean_var_desc: &TensorDescriptor,
    ) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe {
            ffi::miopenCreateOpBatchNormInference(
                self.desc,
                &mut op,
                bn_mode,
                bn_scale_bias_mean_var_desc.as_raw(),
            )
        };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a batch normalization forward operator in the fusion plan
    pub fn create_op_batch_norm_forward(
        &self,
        bn_mode: ffi::miopenBatchNormMode_t,
        running_mean_variance: bool,
    ) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe {
            ffi::miopenCreateOpBatchNormForward(self.desc, &mut op, bn_mode, running_mean_variance)
        };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Create a batch normalization backward operator in the fusion plan
    pub fn create_op_batch_norm_backward(
        &self,
        bn_mode: ffi::miopenBatchNormMode_t,
    ) -> Result<FusionOpDescriptor> {
        let mut op = ptr::null_mut();

        let status = unsafe { ffi::miopenCreateOpBatchNormBackward(self.desc, &mut op, bn_mode) };

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

        Ok(FusionOpDescriptor { desc: op })
    }

    /// Get the convolution algorithms available for the fusion plan
    pub fn get_conv_algorithms(
        &self,
        request_algo_count: i32,
    ) -> Result<(i32, Vec<ConvFwdAlgorithm>)> {
        let mut returned_algo_count = 0;
        let mut algos = vec![0; request_algo_count as usize];

        let status = unsafe {
            ffi::miopenFusionPlanConvolutionGetAlgo(
                self.desc,
                request_algo_count,
                &mut returned_algo_count,
                algos.as_mut_ptr(),
            )
        };

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

        algos.truncate(returned_algo_count as usize);
        Ok((returned_algo_count, algos))
    }

    /// Set the convolution algorithm for the fusion plan
    pub fn set_conv_algorithm(&self, algo: ConvFwdAlgorithm) -> Result<()> {
        let status = unsafe { ffi::miopenFusionPlanConvolutionSetAlgo(self.desc, algo) };

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

        Ok(())
    }

    /// Execute the fusion plan
    pub unsafe fn execute(
        &self,
        handle: &Handle,
        input_desc: &TensorDescriptor,
        input: *const c_void,
        output_desc: &TensorDescriptor,
        output: *mut c_void,
        args: &OperatorArgs,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenExecuteFusionPlan(
                handle.as_raw(),
                self.desc,
                input_desc.as_raw(),
                input,
                output_desc.as_raw(),
                output,
                args.as_raw(),
            )
        };

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

        Ok(())
    }

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

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

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

impl OperatorArgs {
    /// Create a new operator args
    pub fn new() -> Result<Self> {
        let mut args = ptr::null_mut();
        let status = unsafe { ffi::miopenCreateOperatorArgs(&mut args) };

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

        Ok(Self { args })
    }

    /// Set arguments for a forward convolution op
    pub unsafe fn set_conv_forward(
        &self,
        conv_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        w: *const c_void,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsConvForward(
                self.args,
                conv_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                w,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a forward activation op
    pub unsafe fn set_activation_forward(
        &self,
        activ_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        activ_alpha: f64,
        activ_beta: f64,
        activ_gamma: f64,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsActivForward(
                self.args,
                activ_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                activ_alpha,
                activ_beta,
                activ_gamma,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a backward activation op
    pub unsafe fn set_activation_backward(
        &self,
        activ_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        y: *const c_void,
        reserved: *const c_void,
        activ_alpha: f64,
        activ_beta: f64,
        activ_gamma: f64,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsActivBackward(
                self.args,
                activ_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                y,
                reserved,
                activ_alpha,
                activ_beta,
                activ_gamma,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a batch normalization inference op
    pub unsafe fn set_batch_norm_inference(
        &self,
        bn_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        bn_scale: *const c_void,
        bn_bias: *const c_void,
        estimated_mean: *const c_void,
        estimated_variance: *const c_void,
        epsilon: f64,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsBatchNormInference(
                self.args,
                bn_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                bn_scale,
                bn_bias,
                estimated_mean,
                estimated_variance,
                epsilon,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a batch normalization forward op
    pub unsafe fn set_batch_norm_forward(
        &self,
        bn_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        bn_scale: *const c_void,
        bn_bias: *const c_void,
        saved_mean: *mut c_void,
        saved_inv_variance: *mut c_void,
        running_mean: *mut c_void,
        running_variance: *mut c_void,
        exp_avg_factor: f64,
        epsilon: f64,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsBatchNormForward(
                self.args,
                bn_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                bn_scale,
                bn_bias,
                saved_mean,
                saved_inv_variance,
                running_mean,
                running_variance,
                exp_avg_factor,
                epsilon,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a batch normalization backward op
    pub unsafe fn set_batch_norm_backward(
        &self,
        bn_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        x: *const c_void,
        bn_scale: *const c_void,
        bn_bias: *const c_void,
        result_bn_scale_diff: *mut c_void,
        result_bn_bias_diff: *mut c_void,
        saved_mean: *const c_void,
        saved_inv_variance: *const c_void,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsBatchNormBackward(
                self.args,
                bn_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                x,
                bn_scale,
                bn_bias,
                result_bn_scale_diff,
                result_bn_bias_diff,
                saved_mean,
                saved_inv_variance,
            )
        };

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

        Ok(())
    }

    /// Set arguments for a bias forward op
    pub unsafe fn set_bias_forward(
        &self,
        bias_op: &FusionOpDescriptor,
        alpha: &[u8],
        beta: &[u8],
        bias: *const c_void,
    ) -> Result<()> {
        let status = unsafe {
            ffi::miopenSetOpArgsBiasForward(
                self.args,
                bias_op.as_raw(),
                alpha.as_ptr() as *const c_void,
                beta.as_ptr() as *const c_void,
                bias,
            )
        };

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

        Ok(())
    }

    /// Get the raw args
    pub fn as_raw(&self) -> ffi::miopenOperatorArgs_t {
        self.args
    }
}

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