onemkl 0.6.1

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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
// SPDX-License-Identifier: MIT OR Apache-2.0
//! 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 onemkl_sys::{self as sys, MKL_INT};

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 {
    /// Raw `get_size_compact` call.
    ///
    /// # Safety
    ///
    /// `ld` is the leading dimension, `sd` the second dimension of one matrix, `format` a `MKL_COMPACT_*` constant, `nm >= 0` the number of matrices; there are no pointers. Returns the buffer size in **bytes** MKL needs for the matching compact buffer (**verified**: `mkl_dget_size_compact(100, 100, MKL_COMPACT_AVX, 10)` returned 960000 = 3 groups x 4 lanes x 8 bytes x 100 x 100, i.e. `nm` rounded up to whole SIMD groups; and 1600000 for `nm = 20`; oneMKL 2026.2, Linux x86_64). Callers must check it is non-negative and fits `usize`.
    /// The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    unsafe fn get_size_compact(
        ld: MKL_INT,
        sd: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    ) -> MKL_INT;

    /// Raw `gepack_compact` call.
    ///
    /// # Safety
    ///
    /// `a` must be valid for reads of `nm` matrix pointers; each pointer must be non-null and address a `rows x cols` matrix with leading dimension `lda` per `layout` (`lda >= rows` column-major, `>= cols` row-major), readable for `lda * cols` (column-major) or `lda * rows` (row-major) elements.
    /// `ap` must be valid for writes of a compact buffer for those `nm` matrices: A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `ap` must not overlap any matrix addressed through `a`. The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?gepack_compact argument for argument"
    )]
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: MKL_INT,
        cols: MKL_INT,
        a: *const *const Self,
        lda: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );

    /// Raw `geunpack_compact` call.
    ///
    /// # Safety
    ///
    /// `ap` must be valid for reads of a compact buffer that was packed with the same `rows`, `cols`, `format` and `nm`: A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `a` must be valid for reads of `nm` matrix pointers; each pointer must be non-null and address distinct writable storage for a `rows x cols` matrix with leading dimension `lda` per `layout`. No Rust reference to that storage may be live, and none may overlap `ap`. The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?geunpack_compact argument for argument"
    )]
    unsafe fn geunpack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: MKL_INT,
        cols: MKL_INT,
        a: *const *mut Self,
        lda: MKL_INT,
        ap: *const Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );

    /// Raw `gemm_compact` call.
    ///
    /// # Safety
    ///
    /// `a`, `b` and `c` are compact buffers (`ap`-style) for `nm` matrices in the same `format`; each must be valid per: A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed. with the per-matrix shapes `op(A): m x k`, `op(B): k x n`, `C: m x n` and leading dimensions `ldap`, `ldbp`, `ldcp`.
    /// `c` is read (when `beta != 0`) and written, and must not overlap `a` or `b`. `m`, `n`, `k` must be non-negative. The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?gemm_compact argument for argument"
    )]
    unsafe fn gemm_compact(
        layout: sys::MKL_LAYOUT::Type,
        transa: sys::MKL_TRANSPOSE::Type,
        transb: sys::MKL_TRANSPOSE::Type,
        m: MKL_INT,
        n: MKL_INT,
        k: MKL_INT,
        alpha: Self,
        a: *const Self,
        ldap: MKL_INT,
        b: *const Self,
        ldbp: MKL_INT,
        beta: Self,
        c: *mut Self,
        ldcp: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );
}

impl CompactScalar for f32 {
    unsafe fn get_size_compact(
        ld: MKL_INT,
        sd: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    ) -> MKL_INT {
        unsafe { sys::mkl_sget_size_compact(ld, sd, format, nm) }
    }
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: MKL_INT,
        cols: MKL_INT,
        a: *const *const Self,
        lda: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
        cols: MKL_INT,
        a: *const *mut Self,
        lda: MKL_INT,
        ap: *const Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
        n: MKL_INT,
        k: MKL_INT,
        alpha: Self,
        a: *const Self,
        ldap: MKL_INT,
        b: *const Self,
        ldbp: MKL_INT,
        beta: Self,
        c: *mut Self,
        ldcp: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
        sd: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    ) -> MKL_INT {
        unsafe { sys::mkl_dget_size_compact(ld, sd, format, nm) }
    }
    unsafe fn gepack_compact(
        layout: sys::MKL_LAYOUT::Type,
        rows: MKL_INT,
        cols: MKL_INT,
        a: *const *const Self,
        lda: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
        cols: MKL_INT,
        a: *const *mut Self,
        lda: MKL_INT,
        ap: *const Self,
        ldap: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
        n: MKL_INT,
        k: MKL_INT,
        alpha: Self,
        a: *const Self,
        ldap: MKL_INT,
        b: *const Self,
        ldbp: MKL_INT,
        beta: Self,
        c: *mut Self,
        ldcp: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT = ld.try_into().map_err(|_| Error::DimensionOverflow)?;
    let sd_i: MKL_INT = sd.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: MKL_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: i32::try_from(bytes).unwrap_or(i32::MAX),
        });
    }
    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,
    reason = "stable public surface: published since v0.1.0 with 8 arguments; changing the signature breaks consumers"
)]
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: MKL_INT = rows.try_into().map_err(|_| Error::DimensionOverflow)?;
    let cols_i: MKL_INT = cols.try_into().map_err(|_| Error::DimensionOverflow)?;
    let lda_i: MKL_INT = lda.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldap_i: MKL_INT = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: MKL_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,
    reason = "stable public surface: published since v0.1.0 with 8 arguments; changing the signature breaks consumers"
)]
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: MKL_INT = rows.try_into().map_err(|_| Error::DimensionOverflow)?;
    let cols_i: MKL_INT = cols.try_into().map_err(|_| Error::DimensionOverflow)?;
    let lda_i: MKL_INT = lda.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldap_i: MKL_INT = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: MKL_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,
    reason = "stable public surface: published since v0.1.0 with 16 arguments; changing the signature breaks consumers"
)]
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: MKL_INT = m.try_into().map_err(|_| Error::DimensionOverflow)?;
    let n_i: MKL_INT = n.try_into().map_err(|_| Error::DimensionOverflow)?;
    let k_i: MKL_INT = k.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldap_i: MKL_INT = ldap.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldbp_i: MKL_INT = ldbp.try_into().map_err(|_| Error::DimensionOverflow)?;
    let ldcp_i: MKL_INT = ldcp.try_into().map_err(|_| Error::DimensionOverflow)?;
    let nm_i: MKL_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;
    /// Raw `trsm_compact` call.
    ///
    /// # Safety
    ///
    /// `a` and `b` are compact buffers for `nm` matrices in the same `format` (see below); `a` is the triangular `m x m` (side left) or `n x n` (side right) factor with leading dimension `ldap`, `b` the `m x n` right-hand side overwritten with the solution, leading dimension `ldbp`. Each must satisfy: A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `b` must not overlap `a`; the diagonal of `a` must be non-singular unless `diag` is unit. The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?trsm_compact argument for argument"
    )]
    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: MKL_INT,
        n: MKL_INT,
        alpha: Self,
        a: *const Self,
        ldap: MKL_INT,
        b: *mut Self,
        ldbp: MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );
    /// Raw `potrf_compact` call.
    ///
    /// # Safety
    ///
    /// `ap` must be a compact buffer for `nm` `n x n` matrices (updated in place with the Cholesky factor of the triangle given by `uplo`): A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `info` must be valid for writes of the per-matrix status array MKL defines for compact routines (one `MKL_INT` per matrix in the compact group set, `nm` in total); entries are written even on partial failure.
    /// The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?potrf_compact argument for argument"
    )]
    unsafe fn potrf_compact(
        layout: sys::MKL_LAYOUT::Type,
        uplo: sys::MKL_UPLO::Type,
        n: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        info: *mut MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );
    /// Raw `getrfnp_compact` call.
    ///
    /// # Safety
    ///
    /// `ap` must be a compact buffer for `nm` `m x n` matrices (updated in place with the LU factors; no pivoting is performed, so a zero pivot yields a non-zero `info` entry): A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `info` must be valid for writes of the per-matrix status array MKL defines for compact routines (one `MKL_INT` per matrix in the compact group set, `nm` in total); entries are written even on partial failure.
    /// The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?getrfnp_compact argument for argument"
    )]
    unsafe fn getrfnp_compact(
        layout: sys::MKL_LAYOUT::Type,
        m: MKL_INT,
        n: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        info: *mut MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );
    /// Raw `geqrf_compact` call.
    ///
    /// # Safety
    ///
    /// `ap` must be a compact buffer for `nm` `m x n` matrices (updated in place with the QR factors): A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `taup` must be a compact buffer holding `min(m, n)` scalars per matrix, in the same `format` and `nm`, writable for its full compact size.
    /// `work` must be valid for writes of `lwork` elements, and `lwork` must be at least the workspace MKL requires (`lwork = -1` is a size query writing only `work[0]`).
    /// `info` must be valid for writes of the per-matrix status array MKL defines for compact routines (one `MKL_INT` per matrix in the compact group set, `nm` in total); entries are written even on partial failure.
    /// The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?geqrf_compact argument for argument"
    )]
    unsafe fn geqrf_compact(
        layout: sys::MKL_LAYOUT::Type,
        m: MKL_INT,
        n: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        taup: *mut Self,
        work: *mut Self,
        lwork: MKL_INT,
        info: *mut MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_INT,
    );
    /// Raw `getrinp_compact` call.
    ///
    /// # Safety
    ///
    /// `ap` must be a compact buffer for `nm` `n x n` matrices previously LU-factorised without pivoting by `getrfnp_compact`; it is overwritten with the inverses: A compact buffer `ap` holds `nm` matrices interleaved in SIMD-width groups per `format`. It must be valid for the byte size returned by `get_size_compact(ldap, stored_cols, format, nm)` (column-major; `stored_rows` for row-major), where `ldap` is at least the stored row (column-major) or column (row-major) count times the group width and `stored_rows x stored_cols` is the per-matrix shape the routine defines for it, and `format` and `nm` must be the same values used when the buffer was packed.
    /// `work` must be valid for writes of `lwork` elements, and `lwork` at least the workspace MKL requires.
    /// `info` must be valid for writes of the per-matrix status array MKL defines for compact routines (one `MKL_INT` per matrix in the compact group set, `nm` in total); entries are written even on partial failure.
    /// The MKL library must be linked and usable; invalid arguments are reported through MKL's error handler, not by this wrapper.
    #[allow(
        clippy::too_many_arguments,
        reason = "mirrors the oneMKL C signature mkl_?getrinp_compact argument for argument"
    )]
    unsafe fn getrinp_compact(
        layout: sys::MKL_LAYOUT::Type,
        n: MKL_INT,
        ap: *mut Self,
        ldap: MKL_INT,
        work: *mut Self,
        lwork: MKL_INT,
        info: *mut MKL_INT,
        format: sys::MKL_COMPACT_PACK::Type,
        nm: MKL_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: MKL_INT,
                n: MKL_INT,
                alpha: Self,
                a: *const Self,
                ldap: MKL_INT,
                b: *mut Self,
                ldbp: MKL_INT,
                format: sys::MKL_COMPACT_PACK::Type,
                nm: MKL_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: MKL_INT,
                ap: *mut Self,
                ldap: MKL_INT,
                info: *mut MKL_INT,
                format: sys::MKL_COMPACT_PACK::Type,
                nm: MKL_INT,
            ) {
                unsafe { sys::$potrf(layout, uplo, n, ap, ldap, info, format, nm) }
            }
            unsafe fn getrfnp_compact(
                layout: sys::MKL_LAYOUT::Type,
                m: MKL_INT,
                n: MKL_INT,
                ap: *mut Self,
                ldap: MKL_INT,
                info: *mut MKL_INT,
                format: sys::MKL_COMPACT_PACK::Type,
                nm: MKL_INT,
            ) {
                unsafe { sys::$getrfnp(layout, m, n, ap, ldap, info, format, nm) }
            }
            unsafe fn geqrf_compact(
                layout: sys::MKL_LAYOUT::Type,
                m: MKL_INT,
                n: MKL_INT,
                ap: *mut Self,
                ldap: MKL_INT,
                taup: *mut Self,
                work: *mut Self,
                lwork: MKL_INT,
                info: *mut MKL_INT,
                format: sys::MKL_COMPACT_PACK::Type,
                nm: MKL_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: MKL_INT,
                ap: *mut Self,
                ldap: MKL_INT,
                work: *mut Self,
                lwork: MKL_INT,
                info: *mut MKL_INT,
                format: sys::MKL_COMPACT_PACK::Type,
                nm: MKL_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<MKL_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,
    reason = "stable public surface: published since v0.3.8 with 14 arguments; changing the signature breaks consumers"
)]
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<MKL_INT> {
    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: MKL_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<MKL_INT> {
    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: MKL_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`, whose
/// arguments it takes one for one (layout, m, n, ap, ldap, taup, format,
/// num_matrices).
#[allow(
    clippy::too_many_arguments,
    reason = "mirrors the oneMKL C signature mkl_?geqrf_compact argument for argument"
)]
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<MKL_INT> {
    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: MKL_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<MKL_INT> {
    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: MKL_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)
}