onemkl 0.4.3

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
467
468
// SPDX-License-Identifier: MIT OR Apache-2.0
//! JIT GEMM — runtime-specialized small-matrix kernels.
//!
//! For small fixed-shape GEMMs called many times (transformer
//! attention heads, MLP blocks, batched element-wise compute),
//! oneMKL can JIT-compile a kernel specialized to the exact M, N, K,
//! transposes, leading dimensions, and `alpha` / `beta`. The
//! resulting kernel skips the dispatch overhead and the parameter
//! checks of the regular GEMM call, often yielding 1.5–3× speedup
//! for shapes where M·N·K ≲ 64³.
//!
//! Usage:
//!
//! ```ignore
//! use onemkl::blas::jit::JitGemm;
//! use onemkl::{Layout, Transpose};
//!
//! let plan = JitGemm::<f64>::new(
//!     Layout::RowMajor, Transpose::NoTrans, Transpose::NoTrans,
//!     32, 32, 32, 1.0, 32, 32, 0.0, 32,
//! ).unwrap();
//! // ... call plan.execute(a, b, c) many times ...
//! ```
//!
//! `Drop` frees the JIT'd kernel.

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

use num_complex::{Complex32, Complex64};
use onemkl_sys as sys;

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

/// Status returned by `mkl_jit_create_*gemm`. `Success` means a JIT
/// kernel was generated; `NoJit` means the host doesn't support JIT
/// for the requested shape (e.g. unsupported architecture or the
/// shape is too large) and MKL has fallen back to the standard GEMM
/// path internally — the wrapper still works either way.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum JitStatus {
    /// A specialized kernel was compiled successfully.
    Compiled,
    /// JIT not available; the kernel falls back to standard GEMM.
    Fallback,
}

impl JitStatus {
    #[inline]
    fn from_raw(status: sys::mkl_jit_status_t::Type) -> Result<Self> {
        // Compare against the bindgen-typed constants directly so
        // this works on both Linux (where the type is u32) and
        // Windows (where it's i32).
        match status {
            s if s == sys::mkl_jit_status_t::MKL_JIT_SUCCESS => Ok(Self::Compiled),
            s if s == sys::mkl_jit_status_t::MKL_NO_JIT => Ok(Self::Fallback),
            other => Err(Error::LapackComputationFailure { info: other as i32 }),
        }
    }
}

/// Trait wiring up the four `mkl_cblas_jit_create_*gemm` /
/// `mkl_jit_get_*gemm_ptr` variants for f32 / f64 / Complex32 /
/// Complex64.
#[allow(missing_docs)]
pub trait JitGemmScalar: Copy + 'static {
    /// Function-pointer type the kernel returns to.
    type Kernel: Copy;

    /// Raw `jit_create` call.
    ///
    /// # Safety
    ///
    /// `jitter` must be valid for a write of one `*mut c_void`; on success it receives an opaque JIT handle the caller must release with `mkl_jit_destroy` exactly once. On a non-success status `*jitter` must not be used.
    /// `layout`, `transa`, `transb` must be valid MKL enumerators; `m`, `n`, `k` non-negative; `lda`, `ldb`, `ldc` must satisfy the usual GEMM leading-dimension constraints for the chosen layout because the kernel does no checking. `alpha` and `beta` are baked into the kernel.
    /// The MKL library must be linked and usable.
    #[allow(clippy::too_many_arguments)]
    unsafe fn jit_create(
        jitter: *mut *mut core::ffi::c_void,
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        lda: c_int,
        ldb: c_int,
        beta: Self,
        ldc: c_int,
    ) -> sys::mkl_jit_status_t::Type;

    /// Raw `jit_get_kernel` call.
    ///
    /// # Safety
    ///
    /// `jitter` must be a live handle from a successful `jit_create` that has not been destroyed. The returned function pointer is valid only while that handle is alive and must not be called after `mkl_jit_destroy`. Returns `None` if MKL has no kernel (the generic fallback is then not available through this pointer).
    /// The MKL library must be linked and usable.
    unsafe fn jit_get_kernel(jitter: *const core::ffi::c_void) -> Option<Self::Kernel>;

    /// Call the kernel: `c ← alpha · op(a) · op(b) + beta · c` with
    /// the parameters baked in at JIT time.
    ///
    /// # Safety
    ///
    /// `kernel` must have been obtained from `jit_get_kernel` for this same `jitter` (not destroyed), and `jitter` is the handle it was created for.
    /// `a`, `b` and `c` must point to matrices whose shapes, `trans*` and leading dimensions equal the ones baked in at `jit_create`: `a` readable, `b` readable (despite the `*mut` type MKL does not write them), `c` readable when `beta != 0` and writable. `c` must not overlap `a` or `b`, and no Rust reference to `c` may be live during the call.
    /// The kernel performs no argument validation. The MKL library must be linked and usable.
    unsafe fn invoke_kernel(
        kernel: Self::Kernel,
        jitter: *mut core::ffi::c_void,
        a: *mut Self,
        b: *mut Self,
        c: *mut Self,
    );
}

impl JitGemmScalar for f32 {
    type Kernel = unsafe extern "C" fn(*mut core::ffi::c_void, *mut f32, *mut f32, *mut f32);

    unsafe fn jit_create(
        jitter: *mut *mut core::ffi::c_void,
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        lda: c_int,
        ldb: c_int,
        beta: Self,
        ldc: c_int,
    ) -> sys::mkl_jit_status_t::Type {
        unsafe {
            sys::mkl_cblas_jit_create_sgemm(
                jitter, layout, transa, transb, m, n, k, alpha, lda, ldb, beta, ldc,
            )
        }
    }
    unsafe fn jit_get_kernel(jitter: *const core::ffi::c_void) -> Option<Self::Kernel> {
        unsafe { sys::mkl_jit_get_sgemm_ptr(jitter) }
    }
    unsafe fn invoke_kernel(
        kernel: Self::Kernel,
        jitter: *mut core::ffi::c_void,
        a: *mut Self,
        b: *mut Self,
        c: *mut Self,
    ) {
        unsafe { kernel(jitter, a, b, c) }
    }
}

impl JitGemmScalar for f64 {
    type Kernel = unsafe extern "C" fn(*mut core::ffi::c_void, *mut f64, *mut f64, *mut f64);

    unsafe fn jit_create(
        jitter: *mut *mut core::ffi::c_void,
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        lda: c_int,
        ldb: c_int,
        beta: Self,
        ldc: c_int,
    ) -> sys::mkl_jit_status_t::Type {
        unsafe {
            sys::mkl_cblas_jit_create_dgemm(
                jitter, layout, transa, transb, m, n, k, alpha, lda, ldb, beta, ldc,
            )
        }
    }
    unsafe fn jit_get_kernel(jitter: *const core::ffi::c_void) -> Option<Self::Kernel> {
        unsafe { sys::mkl_jit_get_dgemm_ptr(jitter) }
    }
    unsafe fn invoke_kernel(
        kernel: Self::Kernel,
        jitter: *mut core::ffi::c_void,
        a: *mut Self,
        b: *mut Self,
        c: *mut Self,
    ) {
        unsafe { kernel(jitter, a, b, c) }
    }
}

impl JitGemmScalar for Complex32 {
    type Kernel = unsafe extern "C" fn(
        *mut core::ffi::c_void,
        *mut sys::MKL_Complex8,
        *mut sys::MKL_Complex8,
        *mut sys::MKL_Complex8,
    );

    unsafe fn jit_create(
        jitter: *mut *mut core::ffi::c_void,
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        lda: c_int,
        ldb: c_int,
        beta: Self,
        ldc: c_int,
    ) -> sys::mkl_jit_status_t::Type {
        unsafe {
            sys::mkl_cblas_jit_create_cgemm(
                jitter,
                layout,
                transa,
                transb,
                m,
                n,
                k,
                (&alpha as *const Self).cast(),
                lda,
                ldb,
                (&beta as *const Self).cast(),
                ldc,
            )
        }
    }
    unsafe fn jit_get_kernel(jitter: *const core::ffi::c_void) -> Option<Self::Kernel> {
        unsafe { sys::mkl_jit_get_cgemm_ptr(jitter) }
    }
    unsafe fn invoke_kernel(
        kernel: Self::Kernel,
        jitter: *mut core::ffi::c_void,
        a: *mut Self,
        b: *mut Self,
        c: *mut Self,
    ) {
        unsafe { kernel(jitter, a.cast(), b.cast(), c.cast()) }
    }
}

impl JitGemmScalar for Complex64 {
    type Kernel = unsafe extern "C" fn(
        *mut core::ffi::c_void,
        *mut sys::MKL_Complex16,
        *mut sys::MKL_Complex16,
        *mut sys::MKL_Complex16,
    );

    unsafe fn jit_create(
        jitter: *mut *mut core::ffi::c_void,
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: c_int,
        n: c_int,
        k: c_int,
        alpha: Self,
        lda: c_int,
        ldb: c_int,
        beta: Self,
        ldc: c_int,
    ) -> sys::mkl_jit_status_t::Type {
        unsafe {
            sys::mkl_cblas_jit_create_zgemm(
                jitter,
                layout,
                transa,
                transb,
                m,
                n,
                k,
                (&alpha as *const Self).cast(),
                lda,
                ldb,
                (&beta as *const Self).cast(),
                ldc,
            )
        }
    }
    unsafe fn jit_get_kernel(jitter: *const core::ffi::c_void) -> Option<Self::Kernel> {
        unsafe { sys::mkl_jit_get_zgemm_ptr(jitter) }
    }
    unsafe fn invoke_kernel(
        kernel: Self::Kernel,
        jitter: *mut core::ffi::c_void,
        a: *mut Self,
        b: *mut Self,
        c: *mut Self,
    ) {
        unsafe { kernel(jitter, a.cast(), b.cast(), c.cast()) }
    }
}

#[inline]
fn map_layout(layout: Layout) -> sys::MKL_LAYOUT::Type {
    match layout {
        Layout::RowMajor => sys::MKL_LAYOUT::MKL_ROW_MAJOR,
        Layout::ColMajor => sys::MKL_LAYOUT::MKL_COL_MAJOR,
    }
}

#[inline]
fn map_transpose(t: Transpose) -> sys::MKL_TRANSPOSE::Type {
    match t {
        Transpose::NoTrans => sys::MKL_TRANSPOSE::MKL_NOTRANS,
        Transpose::Trans => sys::MKL_TRANSPOSE::MKL_TRANS,
        Transpose::ConjTrans => sys::MKL_TRANSPOSE::MKL_CONJTRANS,
    }
}

/// JIT-compiled GEMM kernel for a fixed shape.
pub struct JitGemm<T: JitGemmScalar> {
    jitter: *mut core::ffi::c_void,
    kernel: T::Kernel,
    /// Shape information retained for input validation.
    m: usize,
    n: usize,
    k: usize,
    lda: usize,
    ldb: usize,
    ldc: usize,
    transa: Transpose,
    transb: Transpose,
    layout: Layout,
    /// Whether the underlying kernel was actually JIT-compiled or
    /// fell back to a regular GEMM.
    status: JitStatus,
    _marker: PhantomData<T>,
}

unsafe impl<T: JitGemmScalar + Send> Send for JitGemm<T> {}

impl<T: JitGemmScalar> JitGemm<T> {
    /// Compile a JIT'd GEMM kernel for the supplied shape and
    /// scaling factors. `alpha` and `beta` are baked into the kernel
    /// at compile time — to use different values, build a different
    /// `JitGemm`.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        layout: Layout,
        transa: Transpose,
        transb: Transpose,
        m: usize,
        n: usize,
        k: usize,
        alpha: T,
        lda: usize,
        ldb: usize,
        beta: T,
        ldc: 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 lda_i: c_int = lda.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)?;

        let mut jitter: *mut core::ffi::c_void = ptr::null_mut();
        let raw_status = unsafe {
            T::jit_create(
                &mut jitter,
                map_layout(layout),
                map_transpose(transa),
                map_transpose(transb),
                m_i,
                n_i,
                k_i,
                alpha,
                lda_i,
                ldb_i,
                beta,
                ldc_i,
            )
        };
        let status = JitStatus::from_raw(raw_status)?;
        let kernel = unsafe { T::jit_get_kernel(jitter) }.ok_or(Error::InvalidArgument(
            "MKL returned a NULL kernel pointer for the JIT'd GEMM",
        ))?;
        Ok(Self {
            jitter,
            kernel,
            m,
            n,
            k,
            lda,
            ldb,
            ldc,
            transa,
            transb,
            layout,
            status,
            _marker: PhantomData,
        })
    }

    /// Whether the kernel was JIT-compiled or fell back to standard
    /// GEMM. Functional behavior is the same either way; this is
    /// informational for performance tuning.
    #[inline]
    #[must_use]
    pub fn status(&self) -> JitStatus {
        self.status
    }

    /// Execute the JIT'd kernel: `c ← alpha · op(a) · op(b) + beta · c`
    /// with the parameters baked in at construction time.
    pub fn execute(&self, a: &[T], b: &[T], c: &mut [T]) -> Result<()> {
        let (a_rows, a_cols) = match self.transa {
            Transpose::NoTrans => (self.m, self.k),
            _ => (self.k, self.m),
        };
        let (b_rows, b_cols) = match self.transb {
            Transpose::NoTrans => (self.k, self.n),
            _ => (self.n, self.k),
        };
        let needed_a = match self.layout {
            Layout::RowMajor => a_rows.saturating_mul(self.lda),
            Layout::ColMajor => a_cols.saturating_mul(self.lda),
        };
        let needed_b = match self.layout {
            Layout::RowMajor => b_rows.saturating_mul(self.ldb),
            Layout::ColMajor => b_cols.saturating_mul(self.ldb),
        };
        let needed_c = match self.layout {
            Layout::RowMajor => self.m.saturating_mul(self.ldc),
            Layout::ColMajor => self.n.saturating_mul(self.ldc),
        };
        if a.len() < needed_a {
            return Err(Error::InvalidArgument("A buffer too small for op(A) shape"));
        }
        if b.len() < needed_b {
            return Err(Error::InvalidArgument("B buffer too small for op(B) shape"));
        }
        if c.len() < needed_c {
            return Err(Error::InvalidArgument("C buffer too small for shape"));
        }
        // The kernel takes A and B as *mut even though they are inputs
        // — this matches MKL's C signature; the kernel does not
        // actually mutate them.
        unsafe {
            T::invoke_kernel(
                self.kernel,
                self.jitter,
                a.as_ptr() as *mut T,
                b.as_ptr() as *mut T,
                c.as_mut_ptr(),
            );
        }
        Ok(())
    }
}

impl<T: JitGemmScalar> Drop for JitGemm<T> {
    fn drop(&mut self) {
        if !self.jitter.is_null() {
            unsafe {
                let _ = sys::mkl_jit_destroy(self.jitter);
            }
        }
    }
}