onemkl 0.4.4

Safe, idiomatic Rust wrapper over Intel oneAPI Math Kernel Library (oneMKL).
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! Pack / Compute GEMM API.
//!
//! When the same operand is used in many GEMMs (e.g. a fixed weight
//! matrix multiplied by many input batches), MKL can pack it once
//! into an internal layout and reuse the packed form in repeated
//! `gemm_compute` calls. This avoids re-doing the same data
//! reordering on every call and yields a meaningful speedup for
//! medium-sized matrices.
//!
//! Two-step usage:
//!
//! ```ignore
//! use onemkl::blas::packed::{gemm_compute_packed_a, PackedMatrix};
//! use onemkl::{Layout, Transpose};
//!
//! // Pack A once.
//! let packed_a = PackedMatrix::<f64>::pack_a(
//!     Layout::RowMajor, Transpose::NoTrans,
//!     m, n, k, alpha, &a_storage, lda,
//! ).unwrap();
//!
//! // Reuse in many GEMMs against different B / C.
//! for batch in batches {
//!     gemm_compute_packed_a(
//!         Layout::RowMajor, Transpose::NoTrans,
//!         m, n, k, &packed_a, &batch.b, ldb, 0.0, &mut batch.c, ldc,
//!     ).unwrap();
//! }
//! ```
//!
//! Pack/compute is available for f32 and f64 only — MKL doesn't ship
//! complex variants.

use core::ffi::c_int;
use core::marker::PhantomData;

use onemkl_sys as sys;

use crate::enums::{Layout, Transpose};
use crate::error::{Error, Result};

/// Which GEMM operand is being packed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PackIdentifier {
    /// Pack the `A` operand (left-hand side).
    A,
    /// Pack the `B` operand (right-hand side).
    B,
}

impl PackIdentifier {
    #[inline]
    fn as_cblas(self) -> sys::CBLAS_IDENTIFIER::Type {
        match self {
            Self::A => sys::CBLAS_IDENTIFIER::CblasAMatrix,
            Self::B => sys::CBLAS_IDENTIFIER::CblasBMatrix,
        }
    }
}

/// Real scalar types supported by the pack / compute GEMM API.
#[allow(missing_docs)]
pub trait PackedGemmScalar: Copy + 'static {
    /// Raw `gemm_pack_get_size` call.
    ///
    /// # Safety
    ///
    /// No pointers. `identifier` must be `CblasAMatrix` or `CblasBMatrix` and `m`, `n`, `k` the GEMM dimensions (non-negative). The returned size is a **byte** count (the wrapper allocates it as bytes; unverified against MKL docs, but for `m = n = k = 100` `f64` it returned 5017728, far above the 80000 bytes of the matrix, so it includes blocking padding); callers must size `dest` of `gemm_pack` with at least this many bytes. The prototype `size_t cblas_?gemm_pack_get_size(CBLAS_IDENTIFIER, MKL_INT, MKL_INT, MKL_INT)` is in `mkl_cblas.h`.
    /// The MKL library must be linked and usable.
    unsafe fn gemm_pack_get_size(
        identifier: sys::CBLAS_IDENTIFIER::Type,
        m: c_int,
        n: c_int,
        k: c_int,
    ) -> usize;

    /// Raw `gemm_pack` call.
    ///
    /// # Safety
    ///
    /// `src` must be valid for reads of the matrix `identifier` selects (`A`: `m x k`, `B`: `k x n`, after `trans`) with leading dimension `ld` per `layout`: `ld * cols` elements (column-major, `ld >= rows`) or `ld * rows` (row-major, `ld >= cols`).
    /// `dest` must be valid for writes of at least `gemm_pack_get_size(identifier, m, n, k)` bytes and suitably aligned as MKL requires (at least `Self` alignment; MKL recommends 64 bytes); it must not overlap `src`. `alpha` is folded into the packed data.
    /// The MKL library must be linked and usable.
    #[allow(clippy::too_many_arguments)]
    unsafe fn gemm_pack(
        layout: sys::CBLAS_LAYOUT::Type,
        identifier: sys::CBLAS_IDENTIFIER::Type,
        trans: sys::CBLAS_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        src: *const Self,
        ld: c_int,
        dest: *mut Self,
    );

    /// Raw `gemm_compute` call.
    ///
    /// # Safety
    ///
    /// `a` and `b` are either ordinary matrices or buffers produced by `gemm_pack` with the same `layout`, dimensions and operand `identifier`, matching `transa`/`transb` (`CblasPacked` for a packed operand); a packed buffer must not have been freed, resized or modified since packing, and the `alpha` used when packing is the one applied.
    /// For an unpacked operand the usual extent rule holds: `ld * cols` (column-major) or `ld * rows` (row-major) elements, `ld` at least the row/column length. `c` is `m x n` with `ldc`, read when `beta != 0` and written; it must be valid for `ldc * n` (column-major) or `ldc * m` (row-major) elements and must not overlap `a` or `b`.
    /// The MKL library must be linked and usable.
    #[allow(clippy::too_many_arguments)]
    unsafe fn gemm_compute(
        layout: sys::CBLAS_LAYOUT::Type,
        transa: c_int,
        transb: c_int,
        m: c_int,
        n: c_int,
        k: c_int,
        a: *const Self,
        lda: c_int,
        b: *const Self,
        ldb: c_int,
        beta: Self,
        c: *mut Self,
        ldc: c_int,
    );
}

impl PackedGemmScalar for f32 {
    unsafe fn gemm_pack_get_size(
        identifier: sys::CBLAS_IDENTIFIER::Type,
        m: c_int,
        n: c_int,
        k: c_int,
    ) -> usize {
        unsafe { sys::cblas_sgemm_pack_get_size(identifier, m, n, k) }
    }
    unsafe fn gemm_pack(
        layout: sys::CBLAS_LAYOUT::Type,
        identifier: sys::CBLAS_IDENTIFIER::Type,
        trans: sys::CBLAS_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        src: *const Self,
        ld: c_int,
        dest: *mut Self,
    ) {
        unsafe { sys::cblas_sgemm_pack(layout, identifier, trans, m, n, k, alpha, src, ld, dest) }
    }
    unsafe fn gemm_compute(
        layout: sys::CBLAS_LAYOUT::Type,
        transa: c_int,
        transb: c_int,
        m: c_int,
        n: c_int,
        k: c_int,
        a: *const Self,
        lda: c_int,
        b: *const Self,
        ldb: c_int,
        beta: Self,
        c: *mut Self,
        ldc: c_int,
    ) {
        unsafe {
            sys::cblas_sgemm_compute(
                layout, transa, transb, m, n, k, a, lda, b, ldb, beta, c, ldc,
            )
        }
    }
}

impl PackedGemmScalar for f64 {
    unsafe fn gemm_pack_get_size(
        identifier: sys::CBLAS_IDENTIFIER::Type,
        m: c_int,
        n: c_int,
        k: c_int,
    ) -> usize {
        unsafe { sys::cblas_dgemm_pack_get_size(identifier, m, n, k) }
    }
    unsafe fn gemm_pack(
        layout: sys::CBLAS_LAYOUT::Type,
        identifier: sys::CBLAS_IDENTIFIER::Type,
        trans: sys::CBLAS_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        src: *const Self,
        ld: c_int,
        dest: *mut Self,
    ) {
        unsafe { sys::cblas_dgemm_pack(layout, identifier, trans, m, n, k, alpha, src, ld, dest) }
    }
    unsafe fn gemm_compute(
        layout: sys::CBLAS_LAYOUT::Type,
        transa: c_int,
        transb: c_int,
        m: c_int,
        n: c_int,
        k: c_int,
        a: *const Self,
        lda: c_int,
        b: *const Self,
        ldb: c_int,
        beta: Self,
        c: *mut Self,
        ldc: c_int,
    ) {
        unsafe {
            sys::cblas_dgemm_compute(
                layout, transa, transb, m, n, k, a, lda, b, ldb, beta, c, ldc,
            )
        }
    }
}

/// A GEMM operand pre-packed into MKL's internal layout. The packed
/// form encodes the `alpha` scaling that was applied at pack time;
/// pass `1.0` if you want to apply scaling separately at compute
/// time.
pub struct PackedMatrix<T: PackedGemmScalar> {
    /// Backing storage. The packed format is opaque; we expose only
    /// the typed pointer to MKL's compute kernel.
    buffer: Vec<T>,
    identifier: PackIdentifier,
    m: usize,
    n: usize,
    k: usize,
    _marker: PhantomData<T>,
}

unsafe impl<T: PackedGemmScalar + Send> Send for PackedMatrix<T> {}

impl<T: PackedGemmScalar> PackedMatrix<T> {
    /// Pack the `A` operand of a future GEMM. `src` / `ld` describe
    /// the unpacked source matrix in the usual CBLAS convention; the
    /// resulting [`PackedMatrix`] can then be used in repeated
    /// [`gemm_compute_packed_a`] calls.
    #[allow(clippy::too_many_arguments)]
    pub fn pack_a(
        layout: Layout,
        trans: Transpose,
        m: usize,
        n: usize,
        k: usize,
        alpha: T,
        src: &[T],
        ld: usize,
    ) -> Result<Self> {
        Self::pack(layout, PackIdentifier::A, trans, m, n, k, alpha, src, ld)
    }

    /// Pack the `B` operand of a future GEMM.
    #[allow(clippy::too_many_arguments)]
    pub fn pack_b(
        layout: Layout,
        trans: Transpose,
        m: usize,
        n: usize,
        k: usize,
        alpha: T,
        src: &[T],
        ld: usize,
    ) -> Result<Self> {
        Self::pack(layout, PackIdentifier::B, trans, m, n, k, alpha, src, ld)
    }

    #[allow(clippy::too_many_arguments)]
    fn pack(
        layout: Layout,
        identifier: PackIdentifier,
        trans: Transpose,
        m: usize,
        n: usize,
        k: usize,
        alpha: T,
        src: &[T],
        ld: usize,
    ) -> Result<Self> {
        let m_i: c_int = m.try_into().map_err(|_| Error::DimensionOverflow)?;
        let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
        let k_i: c_int = k.try_into().map_err(|_| Error::DimensionOverflow)?;
        let ld_i: c_int = ld.try_into().map_err(|_| Error::DimensionOverflow)?;

        let bytes_needed = unsafe { T::gemm_pack_get_size(identifier.as_cblas(), m_i, n_i, k_i) };
        let elem_size = core::mem::size_of::<T>();
        if elem_size == 0 {
            return Err(Error::InvalidArgument("zero-sized scalar"));
        }
        let elements_needed = bytes_needed.div_ceil(elem_size);
        // Validate src is large enough for the unpacked source. The
        // source has shape (m × k) for A or (k × n) for B, possibly
        // transposed.
        let (src_rows, src_cols) = match identifier {
            PackIdentifier::A => match trans {
                Transpose::NoTrans => (m, k),
                _ => (k, m),
            },
            PackIdentifier::B => match trans {
                Transpose::NoTrans => (k, n),
                _ => (n, k),
            },
        };
        let needed_src = match layout {
            Layout::RowMajor => src_rows.saturating_mul(ld),
            Layout::ColMajor => src_cols.saturating_mul(ld),
        };
        if src.len() < needed_src {
            return Err(Error::InvalidArgument(
                "src buffer too small for pack source shape",
            ));
        }

        let mut buffer: Vec<T> = Vec::with_capacity(elements_needed);
        // Safety: MKL writes `bytes_needed` bytes into the buffer;
        // we set len after the pack call. The buffer's allocation
        // is sized to fit those bytes (rounded up to an element
        // count).
        unsafe {
            T::gemm_pack(
                layout.as_cblas(),
                identifier.as_cblas(),
                trans.as_cblas(),
                m_i,
                n_i,
                k_i,
                alpha,
                src.as_ptr(),
                ld_i,
                buffer.as_mut_ptr(),
            );
            buffer.set_len(elements_needed);
        }
        Ok(Self {
            buffer,
            identifier,
            m,
            n,
            k,
            _marker: PhantomData,
        })
    }

    /// Which operand this packed matrix represents.
    #[inline]
    #[must_use]
    pub fn identifier(&self) -> PackIdentifier {
        self.identifier
    }
}

const CBLAS_PACKED: c_int = 151; // sys::CBLAS_STORAGE::CblasPacked

#[inline]
fn trans_as_compute_int(t: Transpose) -> c_int {
    t.as_cblas() as c_int
}

/// Run `C ← op(A_packed) · op(B) + beta · C` where `A_packed` was
/// produced by [`PackedMatrix::pack_a`].
///
/// `transb` applies to the unpacked `B` operand. `alpha` is baked
/// into `A_packed` (it was applied at pack time), so this function
/// has no `alpha` parameter.
#[allow(clippy::too_many_arguments)]
pub fn gemm_compute_packed_a<T: PackedGemmScalar>(
    layout: Layout,
    transb: Transpose,
    m: usize,
    n: usize,
    k: usize,
    a_packed: &PackedMatrix<T>,
    b: &[T],
    ldb: usize,
    beta: T,
    c: &mut [T],
    ldc: usize,
) -> Result<()> {
    if a_packed.identifier != PackIdentifier::A {
        return Err(Error::InvalidArgument(
            "a_packed must be packed as the A operand",
        ));
    }
    if a_packed.m != m || a_packed.n != n || a_packed.k != k {
        return Err(Error::InvalidArgument(
            "a_packed shape does not match the requested compute shape",
        ));
    }
    let m_i: c_int = m.try_into().map_err(|_| Error::DimensionOverflow)?;
    let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
    let k_i: c_int = k.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldb_i: c_int = ldb.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldc_i: c_int = ldc.try_into().map_err(|_| Error::DimensionOverflow)?;
    // For packed compute, MKL ignores lda but still reads it as a
    // parameter; pass m to keep it well-defined.
    let lda_i: c_int = m_i;
    unsafe {
        T::gemm_compute(
            layout.as_cblas(),
            CBLAS_PACKED,
            trans_as_compute_int(transb),
            m_i,
            n_i,
            k_i,
            a_packed.buffer.as_ptr(),
            lda_i,
            b.as_ptr(),
            ldb_i,
            beta,
            c.as_mut_ptr(),
            ldc_i,
        );
    }
    Ok(())
}

/// Run `C ← op(A) · op(B_packed) + beta · C` where `B_packed` was
/// produced by [`PackedMatrix::pack_b`].
#[allow(clippy::too_many_arguments)]
pub fn gemm_compute_packed_b<T: PackedGemmScalar>(
    layout: Layout,
    transa: Transpose,
    m: usize,
    n: usize,
    k: usize,
    a: &[T],
    lda: usize,
    b_packed: &PackedMatrix<T>,
    beta: T,
    c: &mut [T],
    ldc: usize,
) -> Result<()> {
    if b_packed.identifier != PackIdentifier::B {
        return Err(Error::InvalidArgument(
            "b_packed must be packed as the B operand",
        ));
    }
    if b_packed.m != m || b_packed.n != n || b_packed.k != k {
        return Err(Error::InvalidArgument(
            "b_packed shape does not match the requested compute shape",
        ));
    }
    let m_i: c_int = m.try_into().map_err(|_| Error::DimensionOverflow)?;
    let n_i: c_int = n.try_into().map_err(|_| Error::DimensionOverflow)?;
    let k_i: c_int = k.try_into().map_err(|_| Error::DimensionOverflow)?;
    let lda_i: c_int = lda.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldc_i: c_int = ldc.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldb_i: c_int = n_i;
    unsafe {
        T::gemm_compute(
            layout.as_cblas(),
            trans_as_compute_int(transa),
            CBLAS_PACKED,
            m_i,
            n_i,
            k_i,
            a.as_ptr(),
            lda_i,
            b_packed.buffer.as_ptr(),
            ldb_i,
            beta,
            c.as_mut_ptr(),
            ldc_i,
        );
    }
    Ok(())
}