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
#[allow(unused_imports)]
use crate::error::Status;
use std::{
mem::{MaybeUninit, size_of, size_of_val},
ptr,
};
use singe_cublas_sys as sys;
use singe_cuda::{
data_type::DataType,
memory::DeviceMemory,
types::{EmulationMantissaControl, EmulationSpecialValuesSupport},
};
use singe_cuda_sys::library_types;
use crate::{
error::{Error, Result},
lt::{
types::{
BatchMode, EmulationDescAttribute, IntegerWidth, MatrixLayoutAttribute,
MatrixTransformDescAttribute, Order, PointerMode,
},
utility::{read_attribute, set_attribute},
},
try_ffi,
types::Operation,
utility::{ensure_exact_size, to_i32},
};
/// Associates a matrix layout dimension type with its integer width for
/// grouped matrix descriptors.
pub trait GroupedMatrixLayoutValue: Copy + 'static {
const INTEGER_WIDTH: IntegerWidth;
}
impl GroupedMatrixLayoutValue for i32 {
const INTEGER_WIDTH: IntegerWidth = IntegerWidth::Bits32;
}
impl GroupedMatrixLayoutValue for u32 {
const INTEGER_WIDTH: IntegerWidth = IntegerWidth::Bits32;
}
impl GroupedMatrixLayoutValue for i64 {
const INTEGER_WIDTH: IntegerWidth = IntegerWidth::Bits64;
}
impl GroupedMatrixLayoutValue for u64 {
const INTEGER_WIDTH: IntegerWidth = IntegerWidth::Bits64;
}
#[derive(Debug)]
pub struct MatrixLayout {
raw: sys::cublasLtMatrixLayout_t,
}
impl MatrixLayout {
/// Creates a matrix layout descriptor.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot allocate the descriptor or if it does not return
/// a valid handle.
pub fn create(data_type: DataType, rows: u64, cols: u64, ld: i64) -> Result<Self> {
let mut raw = ptr::null_mut();
unsafe {
try_ffi!(sys::cublasLtMatrixLayoutCreate(
&raw mut raw,
data_type.into(),
rows,
cols,
ld,
))?;
}
if raw.is_null() {
return Err(Error::NullHandle);
}
Ok(Self { raw })
}
/// Experimental: creates a grouped matrix layout descriptor.
///
/// All device arrays must have the same length and remain valid while the
/// grouped layout descriptor is used.
///
/// # Errors
///
/// Returns an error if the grouped dimension slices have mismatched lengths, if cuBLASLt
/// cannot allocate the descriptor, or if it does not return a valid handle.
pub fn create_grouped<T: GroupedMatrixLayoutValue>(
data_type: DataType,
rows: &DeviceMemory<T>,
cols: &DeviceMemory<T>,
ld: &DeviceMemory<T>,
) -> Result<Self> {
if rows.len() != cols.len() || rows.len() != ld.len() {
return Err(Error::MismatchedLength {
name: "grouped matrix layout arrays".into(),
});
}
let group_count = to_i32(rows.len(), "group count")?;
let mut raw = ptr::null_mut();
unsafe {
try_ffi!(sys::cublasLtGroupedMatrixLayoutCreate(
&raw mut raw,
data_type.into(),
group_count,
rows.as_ptr().cast(),
cols.as_ptr().cast(),
ld.as_ptr().cast(),
))?;
}
if raw.is_null() {
return Err(Error::NullHandle);
}
let mut layout = Self { raw };
layout.set_attribute(
MatrixLayoutAttribute::GroupedRowsColsArrayIntegerWidth,
&T::INTEGER_WIDTH,
)?;
layout.set_attribute(
MatrixLayoutAttribute::GroupedLeadingDimensionArrayIntegerWidth,
&T::INTEGER_WIDTH,
)?;
Ok(layout)
}
/// Sets a matrix layout attribute from a single value.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute or the value size does not match the
/// attribute storage expected by cuBLASLt.
pub fn set_attribute<T>(&mut self, attr: MatrixLayoutAttribute, value: &T) -> Result<()> {
set_attribute(
|value, size| unsafe {
sys::cublasLtMatrixLayoutSetAttribute(self.raw, attr.into(), value, size)
},
(value as *const T).cast(),
size_of::<T>(),
)
}
/// Sets a matrix layout attribute from a slice.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute or the slice size does not match the
/// attribute storage expected by cuBLASLt.
pub fn set_attribute_slice<T>(
&mut self,
attr: MatrixLayoutAttribute,
values: &[T],
) -> Result<()> {
set_attribute(
|value, size| unsafe {
sys::cublasLtMatrixLayoutSetAttribute(self.raw, attr.into(), value, size)
},
values.as_ptr().cast(),
size_of_val(values),
)
}
/// Returns a matrix layout attribute value.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the query or if the returned attribute size does not
/// match `T`.
pub fn attribute<T: Copy>(&self, attr: MatrixLayoutAttribute) -> Result<T> {
let mut value = MaybeUninit::<T>::uninit();
let written = read_attribute(
|value, size, written| unsafe {
sys::cublasLtMatrixLayoutGetAttribute(self.raw, attr.into(), value, size, written)
},
value.as_mut_ptr().cast(),
size_of::<T>(),
"matrix layout attribute",
)?;
ensure_exact_size(written, size_of::<T>())?;
Ok(unsafe { value.assume_init() })
}
/// Sets the matrix data ordering.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_order(&mut self, order: Order) -> Result<()> {
self.set_attribute(
MatrixLayoutAttribute::Order,
&sys::cublasLtOrder_t::from(order),
)
}
/// Returns the matrix data ordering.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot report the attribute.
pub fn order(&self) -> Result<Order> {
Ok(self
.attribute::<sys::cublasLtOrder_t>(MatrixLayoutAttribute::Order)?
.into())
}
/// Sets the batch count for batched computation.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_batch_count(&mut self, batch_count: i32) -> Result<()> {
self.set_attribute(MatrixLayoutAttribute::BatchCount, &batch_count)
}
/// Returns the batch count.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot report the attribute.
pub fn batch_count(&self) -> Result<i32> {
self.attribute(MatrixLayoutAttribute::BatchCount)
}
/// Sets the batch mode for the matrix layout.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_batch_mode(&mut self, batch_mode: BatchMode) -> Result<()> {
self.set_attribute(
MatrixLayoutAttribute::BatchMode,
&sys::cublasLtBatchMode_t::from(batch_mode),
)
}
/// Returns the batch mode.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot report the attribute.
pub fn batch_mode(&self) -> Result<BatchMode> {
Ok(self
.attribute::<sys::cublasLtBatchMode_t>(MatrixLayoutAttribute::BatchMode)?
.into())
}
/// Sets the strided batch offset between consecutive matrices in a batch.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_strided_batch_offset(&mut self, offset: i64) -> Result<()> {
self.set_attribute(MatrixLayoutAttribute::StridedBatchOffset, &offset)
}
/// Returns the strided batch offset.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot report the attribute.
pub fn strided_batch_offset(&self) -> Result<i64> {
self.attribute(MatrixLayoutAttribute::StridedBatchOffset)
}
/// Sets the plane offset in bytes for 3D matrix layouts.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_plane_offset(&mut self, offset_bytes: i64) -> Result<()> {
self.set_attribute(MatrixLayoutAttribute::PlaneOffset, &offset_bytes)
}
/// Returns the raw cuBLASLt matrix layout handle.
///
/// The returned handle is borrowed and remains valid only while the layout
/// is alive.
pub fn as_raw(&self) -> sys::cublasLtMatrixLayout_t {
self.raw
}
}
impl Drop for MatrixLayout {
fn drop(&mut self) {
unsafe {
if let Err(err) = try_ffi!(sys::cublasLtMatrixLayoutDestroy(self.raw)) {
#[cfg(debug_assertions)]
eprintln!("failed to destroy cublasLt matrix layout: {err}");
}
}
}
}
#[derive(Debug)]
pub struct MatrixTransformDescriptor {
raw: sys::cublasLtMatrixTransformDesc_t,
}
impl MatrixTransformDescriptor {
/// Creates a matrix transform descriptor.
///
/// The descriptor owns its cuBLASLt handle and destroys it when dropped.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot allocate the descriptor or if it does not return
/// a valid handle.
pub fn create(scale_type: DataType) -> Result<Self> {
let mut raw = ptr::null_mut();
unsafe {
try_ffi!(sys::cublasLtMatrixTransformDescCreate(
&raw mut raw,
scale_type.into(),
))?;
}
if raw.is_null() {
return Err(Error::NullHandle);
}
Ok(Self { raw })
}
/// Sets a matrix transform descriptor attribute.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute or the value size does not match the
/// attribute storage expected by cuBLASLt.
pub fn set_attribute<T>(
&mut self,
attr: MatrixTransformDescAttribute,
value: &T,
) -> Result<()> {
set_attribute(
|value, size| unsafe {
sys::cublasLtMatrixTransformDescSetAttribute(self.raw, attr.into(), value, size)
},
(value as *const T).cast(),
size_of::<T>(),
)
}
/// Returns a matrix transform descriptor attribute value.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the query or if the returned attribute size does not
/// match `T`.
pub fn attribute<T: Copy>(&self, attr: MatrixTransformDescAttribute) -> Result<T> {
let mut value = MaybeUninit::<T>::uninit();
let written = read_attribute(
|value, size, written| unsafe {
sys::cublasLtMatrixTransformDescGetAttribute(
self.raw,
attr.into(),
value,
size,
written,
)
},
value.as_mut_ptr().cast(),
size_of::<T>(),
"matrix transform descriptor attribute",
)?;
ensure_exact_size(written, size_of::<T>())?;
Ok(unsafe { value.assume_init() })
}
/// Sets the pointer mode for alpha and beta scalars.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_pointer_mode(&mut self, pointer_mode: PointerMode) -> Result<()> {
self.set_attribute(
MatrixTransformDescAttribute::PointerMode,
&sys::cublasLtPointerMode_t::from(pointer_mode),
)
}
/// Sets the transpose mode applied to input matrix A.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_transpose_a(&mut self, operation: Operation) -> Result<()> {
self.set_attribute(
MatrixTransformDescAttribute::TransposeA,
&sys::cublasOperation_t::from(operation),
)
}
/// Sets the transpose mode applied to input matrix B.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_transpose_b(&mut self, operation: Operation) -> Result<()> {
self.set_attribute(
MatrixTransformDescAttribute::TransposeB,
&sys::cublasOperation_t::from(operation),
)
}
/// Returns the raw cuBLASLt matrix transform descriptor handle.
///
/// The returned handle is borrowed and remains valid only while the
/// descriptor is alive.
pub fn as_raw(&self) -> sys::cublasLtMatrixTransformDesc_t {
self.raw
}
}
impl Drop for MatrixTransformDescriptor {
fn drop(&mut self) {
unsafe {
if let Err(err) = try_ffi!(sys::cublasLtMatrixTransformDescDestroy(self.raw)) {
#[cfg(debug_assertions)]
eprintln!("failed to destroy cublasLt matrix transform descriptor: {err}");
}
}
}
}
#[derive(Debug)]
pub struct EmulationDescriptor {
raw: sys::cublasLtEmulationDesc_t,
}
impl EmulationDescriptor {
/// Creates an emulation descriptor.
///
/// The descriptor owns its cuBLASLt handle and destroys it when dropped.
///
/// # Errors
///
/// Returns an error if cuBLASLt cannot allocate the descriptor or if it does not return
/// a valid handle.
pub fn create() -> Result<Self> {
let mut raw = ptr::null_mut();
unsafe {
try_ffi!(sys::cublasLtEmulationDescCreate(&raw mut raw))?;
}
if raw.is_null() {
return Err(Error::NullHandle);
}
Ok(Self { raw })
}
/// Sets an emulation descriptor attribute.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute or the value size does not match the
/// attribute storage expected by cuBLASLt.
pub fn set_attribute<T>(&mut self, attr: EmulationDescAttribute, value: &T) -> Result<()> {
set_attribute(
|value, size| unsafe {
sys::cublasLtEmulationDescSetAttribute(self.raw, attr.into(), value, size)
},
(value as *const T).cast(),
size_of::<T>(),
)
}
/// Returns an emulation descriptor attribute value.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the query or if the returned attribute size does not
/// match `T`.
pub fn attribute<T: Copy>(&self, attr: EmulationDescAttribute) -> Result<T> {
let mut value = MaybeUninit::<T>::uninit();
let written = read_attribute(
|value, size, written| unsafe {
sys::cublasLtEmulationDescGetAttribute(self.raw, attr.into(), value, size, written)
},
value.as_mut_ptr().cast(),
size_of::<T>(),
"emulation descriptor attribute",
)?;
ensure_exact_size(written, size_of::<T>())?;
Ok(unsafe { value.assume_init() })
}
/// Sets the floating-point emulation strategy.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_strategy(&mut self, strategy: singe_cuda::types::EmulationStrategy) -> Result<()> {
self.set_attribute(
EmulationDescAttribute::Strategy,
&library_types::cudaEmulationStrategy::from(strategy),
)
}
/// Sets the special values support for floating-point emulation.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_special_values_support(
&mut self,
support: EmulationSpecialValuesSupport,
) -> Result<()> {
let support = library_types::cudaEmulationSpecialValuesSupport::from(support);
self.set_attribute(EmulationDescAttribute::SpecialValuesSupport, &support)
}
/// Sets the mantissa bit control for fixed-point emulation.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_mantissa_control(&mut self, control: EmulationMantissaControl) -> Result<()> {
self.set_attribute(
EmulationDescAttribute::FixedPointMantissaControl,
&library_types::cudaEmulationMantissaControl::from(control),
)
}
/// Sets the maximum mantissa bit count for fixed-point emulation.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_max_mantissa_bit_count(&mut self, count: i32) -> Result<()> {
self.set_attribute(
EmulationDescAttribute::FixedPointMaxMantissaBitCount,
&count,
)
}
/// Sets the mantissa bit offset for fixed-point emulation.
///
/// # Errors
///
/// Returns an error if cuBLASLt rejects the attribute.
pub fn set_mantissa_bit_offset(&mut self, offset: i32) -> Result<()> {
self.set_attribute(EmulationDescAttribute::FixedPointMantissaBitOffset, &offset)
}
/// Returns the raw cuBLASLt emulation descriptor handle.
///
/// The returned handle is borrowed and remains valid only while the
/// descriptor is alive.
pub fn as_raw(&self) -> sys::cublasLtEmulationDesc_t {
self.raw
}
}
impl Drop for EmulationDescriptor {
fn drop(&mut self) {
unsafe {
if let Err(err) = try_ffi!(sys::cublasLtEmulationDescDestroy(self.raw)) {
#[cfg(debug_assertions)]
eprintln!("failed to destroy cublasLt emulation descriptor: {err}");
}
}
}
}