onemkl 0.3.11

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
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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Compact BLAS — batched dense kernels packed for SIMD.
//!
//! When you need to apply the same small dense kernel (a 4×4 GEMM, a
//! 8×8 LU, etc.) to many independent matrices simultaneously, the
//! Compact BLAS API achieves better throughput than calling the
//! standard BLAS in a loop or even using the pointer-array batched
//! API. It packs `nm` matrices into a single buffer with SIMD-width
//! interleaving so each underlying instruction processes a
//! `pack-width`-sized batch in lockstep.
//!
//! Three pack widths are supported:
//!
//! | [`CompactFormat`] | SIMD width | Best on |
//! | --- | --- | --- |
//! | `Sse` | 4 (f32) / 2 (f64) | older Intel cores |
//! | `Avx` | 8 / 4 | most CPUs since Haswell |
//! | `Avx512` | 16 / 8 | Skylake-X, Sapphire Rapids, … |
//!
//! Typical flow:
//!
//! 1. Compute the packed-buffer size with [`get_size`].
//! 2. Pack a slice of `*const T` pointers into the buffer with
//!    [`gepack`].
//! 3. Run the desired compact kernel ([`gemm`], …) on the packed
//!    buffers.
//! 4. Unpack with [`geunpack`] when results are needed back as
//!    regular matrices.
//!
//! Compact BLAS is real-only for the full lifecycle (`f32` / `f64`).
//! Complex GEMM exists but lacks a matching pack / unpack pair, so
//! the Rust wrapper restricts this module to real types.

use core::ffi::c_int;

use onemkl_sys as sys;

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

/// SIMD pack width to use when laying out compact matrices.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CompactFormat {
    /// 128-bit SSE pack (4 f32 / 2 f64 lanes).
    Sse,
    /// 256-bit AVX pack (8 f32 / 4 f64 lanes).
    Avx,
    /// 512-bit AVX-512 pack (16 f32 / 8 f64 lanes).
    Avx512,
}

impl CompactFormat {
    #[inline]
    fn as_mkl(self) -> sys::MKL_COMPACT_PACK::Type {
        match self {
            Self::Sse => sys::MKL_COMPACT_PACK::MKL_COMPACT_SSE,
            Self::Avx => sys::MKL_COMPACT_PACK::MKL_COMPACT_AVX,
            Self::Avx512 => sys::MKL_COMPACT_PACK::MKL_COMPACT_AVX512,
        }
    }
}

#[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,
    }
}

/// Real scalar types supported by the Compact BLAS lifecycle.
#[allow(missing_docs)]
pub trait CompactScalar: Copy + 'static {
    unsafe fn get_size_compact(
        ld: c_int,
        sd: c_int,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: c_int,
    ) -> c_int;

    #[allow(clippy::too_many_arguments)]
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: c_int,
        cols: c_int,
        a: *const *const Self,
        lda: c_int,
        ap: *mut Self,
        ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: c_int,
    );

    #[allow(clippy::too_many_arguments)]
    unsafe fn geunpack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: c_int,
        cols: c_int,
        a: *const *mut Self,
        lda: c_int,
        ap: *const Self,
        ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: c_int,
    );

    #[allow(clippy::too_many_arguments)]
    unsafe fn gemm_compact(
        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,
        a: *const Self, ldap: c_int,
        b: *const Self, ldbp: c_int,
        beta: Self,
        c: *mut Self, ldcp: c_int,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: c_int,
    );
}

impl CompactScalar for f32 {
    unsafe fn get_size_compact(
        ld: c_int, sd: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) -> c_int {
        unsafe { sys::mkl_sget_size_compact(ld, sd, format, nm) }
    }
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type, rows: c_int, cols: c_int,
        a: *const *const Self, lda: c_int,
        ap: *mut Self, ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_sgepack_compact(layout, rows, cols, a, lda, ap, ldap, format, nm)
        }
    }
    unsafe fn geunpack_compact(
        layout: sys::MKL_LAYOUT::Type, rows: c_int, cols: c_int,
        a: *const *mut Self, lda: c_int,
        ap: *const Self, ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_sgeunpack_compact(layout, rows, cols, a, lda, ap, ldap, format, nm)
        }
    }
    unsafe fn gemm_compact(
        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,
        a: *const Self, ldap: c_int,
        b: *const Self, ldbp: c_int,
        beta: Self, c: *mut Self, ldcp: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_sgemm_compact(
                layout, transa, transb, m, n, k, alpha,
                a, ldap, b, ldbp, beta, c, ldcp, format, nm,
            )
        }
    }
}

impl CompactScalar for f64 {
    unsafe fn get_size_compact(
        ld: c_int, sd: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) -> c_int {
        unsafe { sys::mkl_dget_size_compact(ld, sd, format, nm) }
    }
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type, rows: c_int, cols: c_int,
        a: *const *const Self, lda: c_int,
        ap: *mut Self, ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_dgepack_compact(layout, rows, cols, a, lda, ap, ldap, format, nm)
        }
    }
    unsafe fn geunpack_compact(
        layout: sys::MKL_LAYOUT::Type, rows: c_int, cols: c_int,
        a: *const *mut Self, lda: c_int,
        ap: *const Self, ldap: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_dgeunpack_compact(layout, rows, cols, a, lda, ap, ldap, format, nm)
        }
    }
    unsafe fn gemm_compact(
        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,
        a: *const Self, ldap: c_int,
        b: *const Self, ldbp: c_int,
        beta: Self, c: *mut Self, ldcp: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    ) {
        unsafe {
            sys::mkl_dgemm_compact(
                layout, transa, transb, m, n, k, alpha,
                a, ldap, b, ldbp, beta, c, ldcp, format, nm,
            )
        }
    }
}

/// Number of scalars needed to hold `num_matrices` compact-packed
/// matrices of shape `ld × sd` (leading dimension × short dimension)
/// in the given format. Wraps `mkl_*get_size_compact`.
pub fn get_size<T: CompactScalar>(
    ld: usize,
    sd: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<usize> {
    let ld_i: c_int = ld.try_into().map_err(|_| Error::DimensionOverflow)?;
    let sd_i: c_int = sd.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: c_int = num_matrices
        .try_into()
        .map_err(|_| Error::DimensionOverflow)?;
    let bytes = unsafe { T::get_size_compact(ld_i, sd_i, format.as_mkl(), nm_i) };
    if bytes < 0 {
        return Err(Error::LapackComputationFailure { info: bytes });
    }
    let elem_size = core::mem::size_of::<T>();
    if elem_size == 0 {
        return Err(Error::InvalidArgument("zero-sized scalar"));
    }
    Ok((bytes as usize).div_ceil(elem_size))
}

/// Pack `num_matrices` regular matrices (one per pointer in `a`)
/// into the compact buffer `ap`. Wraps `mkl_*gepack_compact`.
///
/// `ldap` is the leading dimension of the compact buffer (use the
/// value returned by [`get_size`] / `num_matrices` arithmetic, or
/// the value MKL's documentation specifies for the chosen format).
///
/// # Safety
///
/// Each pointer in `a` must point to a buffer of at least the
/// matrix's storage size and remain valid for the duration of this
/// call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn gepack<T: CompactScalar>(
    layout: Layout,
    rows: usize,
    cols: usize,
    a: &[*const T],
    lda: usize,
    ap: &mut [T],
    ldap: usize,
    format: CompactFormat,
) -> Result<()> {
    let rows_i: c_int = rows.try_into().map_err(|_| Error::DimensionOverflow)?;
    let cols_i: c_int = cols.try_into().map_err(|_| Error::DimensionOverflow)?;
    let lda_i: c_int = lda.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldap_i: c_int = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: c_int = a.len().try_into().map_err(|_| Error::DimensionOverflow)?;
    unsafe {
        T::gepack_compact(
            map_layout(layout),
            rows_i, cols_i,
            a.as_ptr(),
            lda_i,
            ap.as_mut_ptr(),
            ldap_i,
            format.as_mkl(),
            nm_i,
        );
    }
    Ok(())
}

/// Unpack a compact buffer into individual matrices addressed by
/// `a` (one `*mut T` per matrix). Wraps `mkl_*geunpack_compact`.
///
/// # Safety
///
/// Each pointer in `a` must point to a buffer of at least the
/// matrix's storage size and remain valid for the duration of this
/// call.
#[allow(clippy::too_many_arguments)]
pub unsafe fn geunpack<T: CompactScalar>(
    layout: Layout,
    rows: usize,
    cols: usize,
    a: &[*mut T],
    lda: usize,
    ap: &[T],
    ldap: usize,
    format: CompactFormat,
) -> Result<()> {
    let rows_i: c_int = rows.try_into().map_err(|_| Error::DimensionOverflow)?;
    let cols_i: c_int = cols.try_into().map_err(|_| Error::DimensionOverflow)?;
    let lda_i: c_int = lda.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldap_i: c_int = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: c_int = a.len().try_into().map_err(|_| Error::DimensionOverflow)?;
    unsafe {
        T::geunpack_compact(
            map_layout(layout),
            rows_i, cols_i,
            a.as_ptr(),
            lda_i,
            ap.as_ptr(),
            ldap_i,
            format.as_mkl(),
            nm_i,
        );
    }
    Ok(())
}

/// Compact GEMM: perform `num_matrices` GEMMs `C ← α · op(A) · op(B)
/// + β · C` in lockstep on packed buffers. Wraps `mkl_*gemm_compact`.
#[allow(clippy::too_many_arguments)]
pub fn gemm<T: CompactScalar>(
    layout: Layout,
    transa: Transpose,
    transb: Transpose,
    m: usize,
    n: usize,
    k: usize,
    alpha: T,
    ap: &[T],
    ldap: usize,
    bp: &[T],
    ldbp: usize,
    beta: T,
    cp: &mut [T],
    ldcp: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<()> {
    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 ldap_i: c_int = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldbp_i: c_int = ldbp.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldcp_i: c_int = ldcp.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: c_int = num_matrices
        .try_into()
        .map_err(|_| Error::DimensionOverflow)?;
    unsafe {
        T::gemm_compact(
            map_layout(layout),
            map_transpose(transa),
            map_transpose(transb),
            m_i, n_i, k_i, alpha,
            ap.as_ptr(), ldap_i,
            bp.as_ptr(), ldbp_i,
            beta,
            cp.as_mut_ptr(), ldcp_i,
            format.as_mkl(),
            nm_i,
        );
    }
    Ok(())
}


#[inline]
fn map_side(s: Side) -> sys::MKL_SIDE::Type {
    match s {
        Side::Left => sys::MKL_SIDE::MKL_LEFT,
        Side::Right => sys::MKL_SIDE::MKL_RIGHT,
    }
}

#[inline]
fn map_uplo(u: UpLo) -> sys::MKL_UPLO::Type {
    match u {
        UpLo::Upper => sys::MKL_UPLO::MKL_UPPER,
        UpLo::Lower => sys::MKL_UPLO::MKL_LOWER,
    }
}

#[inline]
fn map_diag(d: Diag) -> sys::MKL_DIAG::Type {
    match d {
        Diag::NonUnit => sys::MKL_DIAG::MKL_NONUNIT,
        Diag::Unit => sys::MKL_DIAG::MKL_UNIT,
    }
}

/// Factorisation / solve kernels beyond GEMM (`f32` / `f64`).
#[allow(missing_docs)]
pub trait CompactFactorScalar: CompactScalar {
    fn zero() -> Self;
    fn to_workspace_len(self) -> usize;
    #[allow(clippy::too_many_arguments)]
    unsafe fn trsm_compact(
        layout: sys::MKL_LAYOUT::Type,
        side: sys::MKL_SIDE::Type,
        uplo: sys::MKL_UPLO::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        diag: sys::MKL_DIAG::Type,
        m: c_int, n: c_int,
        alpha: Self,
        a: *const Self, ldap: c_int,
        b: *mut Self, ldbp: c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    );
    #[allow(clippy::too_many_arguments)]
    unsafe fn potrf_compact(
        layout: sys::MKL_LAYOUT::Type,
        uplo: sys::MKL_UPLO::Type,
        n: c_int,
        ap: *mut Self, ldap: c_int,
        info: *mut c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    );
    #[allow(clippy::too_many_arguments)]
    unsafe fn getrfnp_compact(
        layout: sys::MKL_LAYOUT::Type,
        m: c_int, n: c_int,
        ap: *mut Self, ldap: c_int,
        info: *mut c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    );
    #[allow(clippy::too_many_arguments)]
    unsafe fn geqrf_compact(
        layout: sys::MKL_LAYOUT::Type,
        m: c_int, n: c_int,
        ap: *mut Self, ldap: c_int,
        taup: *mut Self,
        work: *mut Self, lwork: c_int,
        info: *mut c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    );
    #[allow(clippy::too_many_arguments)]
    unsafe fn getrinp_compact(
        layout: sys::MKL_LAYOUT::Type,
        n: c_int,
        ap: *mut Self, ldap: c_int,
        work: *mut Self, lwork: c_int,
        info: *mut c_int,
        format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
    );
}

macro_rules! impl_compact_factor {
    ($t:ty, $trsm:ident, $potrf:ident, $getrfnp:ident, $geqrf:ident, $getrinp:ident) => {
        impl CompactFactorScalar for $t {
            fn zero() -> Self { 0.0 }
            fn to_workspace_len(self) -> usize { self.ceil() as usize }
            unsafe fn trsm_compact(
                layout: sys::MKL_LAYOUT::Type,
                side: sys::MKL_SIDE::Type,
                uplo: sys::MKL_UPLO::Type,
                transa: sys::MKL_TRANSPOSE::Type,
                diag: sys::MKL_DIAG::Type,
                m: c_int, n: c_int,
                alpha: Self,
                a: *const Self, ldap: c_int,
                b: *mut Self, ldbp: c_int,
                format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
            ) {
                unsafe {
                    sys::$trsm(
                        layout, side, uplo, transa, diag, m, n, alpha,
                        a, ldap, b, ldbp, format, nm,
                    )
                }
            }
            unsafe fn potrf_compact(
                layout: sys::MKL_LAYOUT::Type,
                uplo: sys::MKL_UPLO::Type,
                n: c_int,
                ap: *mut Self, ldap: c_int,
                info: *mut c_int,
                format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
            ) {
                unsafe { sys::$potrf(layout, uplo, n, ap, ldap, info, format, nm) }
            }
            unsafe fn getrfnp_compact(
                layout: sys::MKL_LAYOUT::Type,
                m: c_int, n: c_int,
                ap: *mut Self, ldap: c_int,
                info: *mut c_int,
                format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
            ) {
                unsafe { sys::$getrfnp(layout, m, n, ap, ldap, info, format, nm) }
            }
            unsafe fn geqrf_compact(
                layout: sys::MKL_LAYOUT::Type,
                m: c_int, n: c_int,
                ap: *mut Self, ldap: c_int,
                taup: *mut Self,
                work: *mut Self, lwork: c_int,
                info: *mut c_int,
                format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
            ) {
                unsafe {
                    sys::$geqrf(layout, m, n, ap, ldap, taup, work, lwork, info, format, nm)
                }
            }
            unsafe fn getrinp_compact(
                layout: sys::MKL_LAYOUT::Type,
                n: c_int,
                ap: *mut Self, ldap: c_int,
                work: *mut Self, lwork: c_int,
                info: *mut c_int,
                format: sys::MKL_COMPACT_PACK::Type, nm: c_int,
            ) {
                unsafe { sys::$getrinp(layout, n, ap, ldap, work, lwork, info, format, nm) }
            }
        }
    };
}
impl_compact_factor!(f32, mkl_strsm_compact, mkl_spotrf_compact, mkl_sgetrfnp_compact, mkl_sgeqrf_compact, mkl_sgetrinp_compact);
impl_compact_factor!(f64, mkl_dtrsm_compact, mkl_dpotrf_compact, mkl_dgetrfnp_compact, mkl_dgeqrf_compact, mkl_dgetrinp_compact);

/// Packed buffer length needed for a `rows x cols` matrix in `layout`
/// with packed leading dimension `ldap`, or an error if `ldap` is smaller
/// than the matrix's leading dimension.
fn packed_len<T: CompactScalar>(
    layout: Layout,
    rows: usize,
    cols: usize,
    ldap: usize,
    format: CompactFormat,
    nm: usize,
) -> Result<usize> {
    let (ld, sd) = match layout {
        Layout::ColMajor => (rows, cols),
        Layout::RowMajor => (cols, rows),
    };
    if ldap < ld {
        return Err(Error::InvalidArgument("ldap is smaller than the matrix's leading dimension"));
    }
    get_size::<T>(ldap, sd, format, nm)
}

fn to_c(v: usize) -> Result<c_int> {
    v.try_into().map_err(|_| Error::DimensionOverflow)
}

/// Compact TRSM: solve `op(A) X = alpha B` (or `X op(A) = alpha B`) for
/// `num_matrices` triangular systems in lockstep; `B` is overwritten by
/// `X`. `A` is `m x m` for `Side::Left`, `n x n` for `Side::Right`; `B` is
/// `m x n`. Both are in the compact layout of `format`. Buffer lengths are
/// checked against [`get_size`]. Wraps `mkl_*trsm_compact`.
#[allow(clippy::too_many_arguments)]
pub fn trsm<T: CompactFactorScalar>(
    layout: Layout,
    side: Side,
    uplo: UpLo,
    transa: Transpose,
    diag: Diag,
    m: usize,
    n: usize,
    alpha: T,
    ap: &[T],
    ldap: usize,
    bp: &mut [T],
    ldbp: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<()> {
    let k = match side {
        Side::Left => m,
        Side::Right => n,
    };
    if ap.len() < packed_len::<T>(layout, k, k, ldap, format, num_matrices)? {
        return Err(Error::InvalidArgument("ap is smaller than the compact size of A"));
    }
    if bp.len() < packed_len::<T>(layout, m, n, ldbp, format, num_matrices)? {
        return Err(Error::InvalidArgument("bp is smaller than the compact size of B"));
    }
    let (m_i, n_i, ldap_i, ldbp_i, nm_i) =
        (to_c(m)?, to_c(n)?, to_c(ldap)?, to_c(ldbp)?, to_c(num_matrices)?);
    unsafe {
        T::trsm_compact(
            map_layout(layout), map_side(side), map_uplo(uplo),
            map_transpose(transa), map_diag(diag),
            m_i, n_i, alpha,
            ap.as_ptr(), ldap_i,
            bp.as_mut_ptr(), ldbp_i,
            format.as_mkl(), nm_i,
        );
    }
    Ok(())
}

/// Compact Cholesky: factor `num_matrices` symmetric positive-definite
/// `n x n` matrices in place (`uplo` selects the stored triangle). Returns
/// MKL's `info` (0 on success; MKL's compact interface reports one value
/// for the whole batch). Wraps `mkl_*potrf_compact`.
pub fn potrf<T: CompactFactorScalar>(
    layout: Layout,
    uplo: UpLo,
    n: usize,
    ap: &mut [T],
    ldap: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<i32> {
    if ap.len() < packed_len::<T>(layout, n, n, ldap, format, num_matrices)? {
        return Err(Error::InvalidArgument("ap is smaller than the compact size of A"));
    }
    let (n_i, ldap_i, nm_i) = (to_c(n)?, to_c(ldap)?, to_c(num_matrices)?);
    let mut info: c_int = 0;
    unsafe {
        T::potrf_compact(
            map_layout(layout), map_uplo(uplo), n_i,
            ap.as_mut_ptr(), ldap_i, &mut info,
            format.as_mkl(), nm_i,
        );
    }
    Ok(info)
}

/// Compact LU without pivoting: factor `num_matrices` `m x n` matrices in
/// place (`L` unit-lower and `U` share the buffer). Returns MKL's `info`.
/// No pivoting means the result is only meaningful for matrices whose
/// leading minors are non-singular. Wraps `mkl_*getrfnp_compact`.
pub fn getrfnp<T: CompactFactorScalar>(
    layout: Layout,
    m: usize,
    n: usize,
    ap: &mut [T],
    ldap: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<i32> {
    if ap.len() < packed_len::<T>(layout, m, n, ldap, format, num_matrices)? {
        return Err(Error::InvalidArgument("ap is smaller than the compact size of A"));
    }
    let (m_i, n_i, ldap_i, nm_i) = (to_c(m)?, to_c(n)?, to_c(ldap)?, to_c(num_matrices)?);
    let mut info: c_int = 0;
    unsafe {
        T::getrfnp_compact(
            map_layout(layout), m_i, n_i,
            ap.as_mut_ptr(), ldap_i, &mut info,
            format.as_mkl(), nm_i,
        );
    }
    Ok(info)
}

/// Compact QR: factor `num_matrices` `m x n` matrices in place (`R` in the
/// upper triangle, Householder vectors below). `taup` receives the
/// Householder scalars as a compact buffer of `min(m, n) x 1` vectors with
/// leading dimension `min(m, n)`; its length is checked against
/// [`get_size`]. The workspace is allocated internally from MKL's
/// workspace query. Returns MKL's `info`. Wraps `mkl_*geqrf_compact`.
pub fn geqrf<T: CompactFactorScalar>(
    layout: Layout,
    m: usize,
    n: usize,
    ap: &mut [T],
    ldap: usize,
    taup: &mut [T],
    format: CompactFormat,
    num_matrices: usize,
) -> Result<i32> {
    if ap.len() < packed_len::<T>(layout, m, n, ldap, format, num_matrices)? {
        return Err(Error::InvalidArgument("ap is smaller than the compact size of A"));
    }
    let k = m.min(n);
    if k > 0 && taup.len() < get_size::<T>(k, 1, format, num_matrices)? {
        return Err(Error::InvalidArgument("taup is smaller than the compact size of tau"));
    }
    let (m_i, n_i, ldap_i, nm_i) = (to_c(m)?, to_c(n)?, to_c(ldap)?, to_c(num_matrices)?);
    let mut info: c_int = 0;
    // Workspace query (lwork = -1): MKL writes the required size to work[0].
    let mut query = [T::zero()];
    unsafe {
        T::geqrf_compact(
            map_layout(layout), m_i, n_i,
            ap.as_mut_ptr(), ldap_i, taup.as_mut_ptr(),
            query.as_mut_ptr(), -1, &mut info,
            format.as_mkl(), nm_i,
        );
    }
    let lwork = query[0].to_workspace_len().max(1);
    let mut work = vec![T::zero(); lwork];
    unsafe {
        T::geqrf_compact(
            map_layout(layout), m_i, n_i,
            ap.as_mut_ptr(), ldap_i, taup.as_mut_ptr(),
            work.as_mut_ptr(), to_c(lwork)?, &mut info,
            format.as_mkl(), nm_i,
        );
    }
    Ok(info)
}

/// Compact in-place inverse of `num_matrices` `n x n` matrices that were
/// factored by [`getrfnp`] (no pivoting): on exit `ap` holds `A⁻¹`. The
/// workspace is allocated internally from MKL's workspace query. Returns
/// MKL's `info`. Wraps `mkl_*getrinp_compact`.
pub fn getrinp<T: CompactFactorScalar>(
    layout: Layout,
    n: usize,
    ap: &mut [T],
    ldap: usize,
    format: CompactFormat,
    num_matrices: usize,
) -> Result<i32> {
    if ap.len() < packed_len::<T>(layout, n, n, ldap, format, num_matrices)? {
        return Err(Error::InvalidArgument("ap is smaller than the compact size of A"));
    }
    let (n_i, ldap_i, nm_i) = (to_c(n)?, to_c(ldap)?, to_c(num_matrices)?);
    let mut info: c_int = 0;
    // Workspace query (lwork = -1): MKL writes the required size to work[0].
    let mut query = [T::zero()];
    unsafe {
        T::getrinp_compact(
            map_layout(layout), n_i, ap.as_mut_ptr(), ldap_i,
            query.as_mut_ptr(), -1, &mut info, format.as_mkl(), nm_i,
        );
    }
    let lwork = query[0].to_workspace_len().max(1);
    let mut work = vec![T::zero(); lwork];
    unsafe {
        T::getrinp_compact(
            map_layout(layout), n_i, ap.as_mut_ptr(), ldap_i,
            work.as_mut_ptr(), to_c(lwork)?, &mut info, format.as_mkl(), nm_i,
        );
    }
    Ok(info)
}