onemkl 0.6.0

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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! BLAS-like extensions provided by oneMKL.
//!
//! This module covers Intel-specific routines beyond the standard BLAS:
//!
//! - [`axpby`] — generalization of `axpy` that scales `y`.
//! - [`imatcopy`], [`omatcopy`], [`omatcopy2`], [`omatadd`] — combined
//!   transposition and scaling.
//! - Batched routines: [`axpy_batch_strided`], [`copy_batch_strided`],
//!   [`gemv_batch_strided`], [`gemm_batch_strided`],
//!   [`trsm_batch_strided`], [`dgmm_batch_strided`], and (complex-only)
//!   [`gemm3m_batch_strided`].
//!
//! The pointer-array variants (`?gemm_batch`, `?trsm_batch`, etc.) and
//! the JIT / packed / mixed-precision GEMM APIs are wrapped in follow-up
//! modules.

use core::ffi::c_char;

use crate::blas::scalar::{BlasScalar, ComplexBlasScalar};
use crate::enums::{Diag, Layout, Side, Transpose, UpLo};
use crate::error::{Error, Result};
use crate::util::{check_two_vectors, dim_to_mkl_int, stride_to_mkl_int};

// =====================================================================
// axpby
// =====================================================================

/// `y ← alpha * x + beta * y`. Equivalent to `axpy` but also scales `y`.
pub fn axpby<T: BlasScalar>(alpha: T, x: &[T], beta: T, y: &mut [T]) -> Result<()> {
    axpby_inc(alpha, x, 1, beta, y, 1)
}

/// Strided variant of [`axpby`].
pub fn axpby_inc<T: BlasScalar>(
    alpha: T,
    x: &[T],
    incx: i64,
    beta: T,
    y: &mut [T],
    incy: i64,
) -> Result<()> {
    let n = check_two_vectors(x, incx, y, incy)?;
    let cn = dim_to_mkl_int(n)?;
    unsafe {
        T::cblas_axpby(
            cn,
            alpha,
            x.as_ptr(),
            stride_to_mkl_int(incx)?,
            beta,
            y.as_mut_ptr(),
            stride_to_mkl_int(incy)?,
        );
    }
    Ok(())
}

// =====================================================================
// imatcopy / omatcopy / omatcopy2 / omatadd
// =====================================================================

/// In-place matrix transposition with scaling: `A ← alpha * op(A)`.
///
/// `rows` × `cols` describes the input matrix. `lda` is the leading
/// dimension before the operation; `ldb` is the leading dimension after
/// (which differs when `trans` actually transposes).
///
/// The buffer must hold both layouts:
///
/// - For [`Layout::RowMajor`], a buffer of `max(rows * lda, post_rows * ldb)`
///   elements (where `post_rows` is `cols` if transposed, else `rows`).
/// - For [`Layout::ColMajor`], `max(cols * lda, post_cols * ldb)` similarly.
///
/// See the oneMKL reference for the exact buffer-size formula.
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 8 arguments; changing the signature breaks consumers"
)]
pub fn imatcopy<T: BlasScalar>(
    layout: Layout,
    trans: Transpose,
    rows: usize,
    cols: usize,
    alpha: T,
    ab: &mut [T],
    lda: usize,
    ldb: usize,
) -> Result<()> {
    check_imatcopy_buf(layout, trans, rows, cols, lda, ldb, ab.len())?;
    unsafe {
        T::mkl_imatcopy(
            layout.as_char() as c_char,
            trans.as_char() as c_char,
            rows,
            cols,
            alpha,
            ab.as_mut_ptr(),
            lda,
            ldb,
        );
    }
    Ok(())
}

/// Out-of-place matrix transposition with scaling: `B ← alpha * op(A)`.
///
/// `rows` × `cols` describes `A`. The output `B` has shape `op(rows × cols)`.
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 9 arguments; changing the signature breaks consumers"
)]
pub fn omatcopy<T: BlasScalar>(
    layout: Layout,
    trans: Transpose,
    rows: usize,
    cols: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    b: &mut [T],
    ldb: usize,
) -> Result<()> {
    check_matcopy_in(layout, rows, cols, lda, a.len(), "A")?;
    let (out_rows, out_cols) = match trans {
        Transpose::NoTrans => (rows, cols),
        Transpose::Trans | Transpose::ConjTrans => (cols, rows),
    };
    check_matcopy_in(layout, out_rows, out_cols, ldb, b.len(), "B")?;
    unsafe {
        T::mkl_omatcopy(
            layout.as_char() as c_char,
            trans.as_char() as c_char,
            rows,
            cols,
            alpha,
            a.as_ptr(),
            lda,
            b.as_mut_ptr(),
            ldb,
        );
    }
    Ok(())
}

/// Out-of-place 2-D strided transposition with scaling: like [`omatcopy`]
/// but accepts an extra inter-element stride along the contiguous
/// dimension (`stridea`/`strideb`).
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 11 arguments; changing the signature breaks consumers"
)]
pub fn omatcopy2<T: BlasScalar>(
    layout: Layout,
    trans: Transpose,
    rows: usize,
    cols: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    stridea: usize,
    b: &mut [T],
    ldb: usize,
    strideb: usize,
) -> Result<()> {
    if stridea == 0 || strideb == 0 {
        return Err(Error::InvalidArgument("matcopy2 strides must be non-zero"));
    }
    unsafe {
        T::mkl_omatcopy2(
            layout.as_char() as c_char,
            trans.as_char() as c_char,
            rows,
            cols,
            alpha,
            a.as_ptr(),
            lda,
            stridea,
            b.as_mut_ptr(),
            ldb,
            strideb,
        );
    }
    Ok(())
}

/// Out-of-place add: `C ← alpha * op(A) + beta * op(B)`. `op(A)` and
/// `op(B)` must have the same shape (which becomes the shape of `C`).
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 13 arguments; changing the signature breaks consumers"
)]
pub fn omatadd<T: BlasScalar>(
    layout: Layout,
    transa: Transpose,
    transb: Transpose,
    rows: usize,
    cols: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    beta: T,
    b: &[T],
    ldb: usize,
    c: &mut [T],
    ldc: usize,
) -> Result<()> {
    let (a_rows, a_cols) = pre_op_shape(transa, rows, cols);
    let (b_rows, b_cols) = pre_op_shape(transb, rows, cols);
    check_matcopy_in(layout, a_rows, a_cols, lda, a.len(), "A")?;
    check_matcopy_in(layout, b_rows, b_cols, ldb, b.len(), "B")?;
    check_matcopy_in(layout, rows, cols, ldc, c.len(), "C")?;
    unsafe {
        T::mkl_omatadd(
            layout.as_char() as c_char,
            transa.as_char() as c_char,
            transb.as_char() as c_char,
            rows,
            cols,
            alpha,
            a.as_ptr(),
            lda,
            beta,
            b.as_ptr(),
            ldb,
            c.as_mut_ptr(),
            ldc,
        );
    }
    Ok(())
}

// =====================================================================
// Helpers
// =====================================================================

#[inline]
fn pre_op_shape(t: Transpose, post_rows: usize, post_cols: usize) -> (usize, usize) {
    match t {
        Transpose::NoTrans => (post_rows, post_cols),
        Transpose::Trans | Transpose::ConjTrans => (post_cols, post_rows),
    }
}

fn check_matcopy_in(
    layout: Layout,
    rows: usize,
    cols: usize,
    ld: usize,
    buf_len: usize,
    name: &'static str,
) -> Result<()> {
    let (contiguous, strided) = match layout {
        Layout::RowMajor => (cols, rows),
        Layout::ColMajor => (rows, cols),
    };
    if ld < contiguous {
        return Err(invalid_arg_for(
            name,
            "leading dimension is smaller than the contiguous dimension",
        ));
    }
    if rows == 0 || cols == 0 {
        return Ok(());
    }
    let needed = (strided - 1)
        .checked_mul(ld)
        .and_then(|v| v.checked_add(contiguous))
        .ok_or(Error::DimensionOverflow)?;
    if buf_len < needed {
        return Err(invalid_arg_for(
            name,
            "buffer too small for declared dimensions",
        ));
    }
    Ok(())
}

fn check_imatcopy_buf(
    layout: Layout,
    trans: Transpose,
    rows: usize,
    cols: usize,
    lda: usize,
    ldb: usize,
    buf_len: usize,
) -> Result<()> {
    // Pre-op shape: rows × cols with leading lda.
    check_matcopy_in(layout, rows, cols, lda, buf_len, "AB")?;
    // Post-op shape: op(rows × cols) with leading ldb.
    let (post_rows, post_cols) = match trans {
        Transpose::NoTrans => (rows, cols),
        Transpose::Trans | Transpose::ConjTrans => (cols, rows),
    };
    check_matcopy_in(layout, post_rows, post_cols, ldb, buf_len, "AB")
}

// =====================================================================
// Batched (strided) routines
// =====================================================================

/// Batched [`super::level1::axpy`]. Performs `batch_size` independent
/// `axpy` operations: for `b in 0..batch_size`,
/// `y[b*stridey..] ← alpha * x[b*stridex..] + y[b*stridey..]`,
/// each addressing `n` elements at increment `incx` / `incy`.
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 9 arguments; changing the signature breaks consumers"
)]
pub fn axpy_batch_strided<T: BlasScalar>(
    n: usize,
    alpha: T,
    x: &[T],
    incx: i64,
    stridex: i64,
    y: &mut [T],
    incy: i64,
    stridey: i64,
    batch_size: usize,
) -> Result<()> {
    check_batch_buffers(x.len(), n, incx, stridex, batch_size, "x")?;
    check_batch_buffers(y.len(), n, incy, stridey, batch_size, "y")?;
    unsafe {
        T::cblas_axpy_batch_strided(
            dim_to_mkl_int(n)?,
            alpha,
            x.as_ptr(),
            stride_to_mkl_int(incx)?,
            stride_to_mkl_int(stridex)?,
            y.as_mut_ptr(),
            stride_to_mkl_int(incy)?,
            stride_to_mkl_int(stridey)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Batched [`super::level1::copy`].
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 8 arguments; changing the signature breaks consumers"
)]
pub fn copy_batch_strided<T: BlasScalar>(
    n: usize,
    x: &[T],
    incx: i64,
    stridex: i64,
    y: &mut [T],
    incy: i64,
    stridey: i64,
    batch_size: usize,
) -> Result<()> {
    check_batch_buffers(x.len(), n, incx, stridex, batch_size, "x")?;
    check_batch_buffers(y.len(), n, incy, stridey, batch_size, "y")?;
    unsafe {
        T::cblas_copy_batch_strided(
            dim_to_mkl_int(n)?,
            x.as_ptr(),
            stride_to_mkl_int(incx)?,
            stride_to_mkl_int(stridex)?,
            y.as_mut_ptr(),
            stride_to_mkl_int(incy)?,
            stride_to_mkl_int(stridey)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Batched [`super::level2::gemv`]. The same `m`, `n`, `lda`, `trans`,
/// and increments apply to every batch entry; only the buffer offsets
/// differ between entries.
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 16 arguments; changing the signature breaks consumers"
)]
pub fn gemv_batch_strided<T: BlasScalar>(
    layout: Layout,
    trans: Transpose,
    m: usize,
    n: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    stridea: i64,
    x: &[T],
    incx: i64,
    stridex: i64,
    beta: T,
    y: &mut [T],
    incy: i64,
    stridey: i64,
    batch_size: usize,
) -> Result<()> {
    let _ = (a.len(), x.len(), y.len()); // length checks deferred to MKL.
    if batch_size == 0 {
        return Ok(());
    }
    unsafe {
        T::cblas_gemv_batch_strided(
            layout.as_cblas(),
            trans.as_cblas(),
            dim_to_mkl_int(m)?,
            dim_to_mkl_int(n)?,
            alpha,
            a.as_ptr(),
            dim_to_mkl_int(lda)?,
            stride_to_mkl_int(stridea)?,
            x.as_ptr(),
            stride_to_mkl_int(incx)?,
            stride_to_mkl_int(stridex)?,
            beta,
            y.as_mut_ptr(),
            stride_to_mkl_int(incy)?,
            stride_to_mkl_int(stridey)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Batched [`super::level3::gemm`]. Performs `batch_size` independent
/// `gemm` operations sharing the same shapes and transpositions, with
/// element-strides `stridea`, `strideb`, `stridec` between adjacent
/// matrices in the `a`, `b`, `c` buffers.
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 18 arguments; changing the signature breaks consumers"
)]
pub fn gemm_batch_strided<T: BlasScalar>(
    layout: Layout,
    transa: Transpose,
    transb: Transpose,
    m: usize,
    n: usize,
    k: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    stridea: i64,
    b: &[T],
    ldb: usize,
    strideb: i64,
    beta: T,
    c: &mut [T],
    ldc: usize,
    stridec: i64,
    batch_size: usize,
) -> Result<()> {
    let _ = (a.len(), b.len(), c.len());
    if batch_size == 0 {
        return Ok(());
    }
    unsafe {
        T::cblas_gemm_batch_strided(
            layout.as_cblas(),
            transa.as_cblas(),
            transb.as_cblas(),
            dim_to_mkl_int(m)?,
            dim_to_mkl_int(n)?,
            dim_to_mkl_int(k)?,
            alpha,
            a.as_ptr(),
            dim_to_mkl_int(lda)?,
            stride_to_mkl_int(stridea)?,
            b.as_ptr(),
            dim_to_mkl_int(ldb)?,
            stride_to_mkl_int(strideb)?,
            beta,
            c.as_mut_ptr(),
            dim_to_mkl_int(ldc)?,
            stride_to_mkl_int(stridec)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Pointer-array batched GEMM. Performs many GEMMs whose matrix
/// shapes (and `alpha` / `beta`) vary across "groups". Each
/// `GemmBatchGroup` holds the parameters for one group plus the
/// pointer arrays for `A`, `B`, `C` of that group.
///
/// This is the canonical "batched GEMM" API used by ML/DL workloads
/// where the per-call matrix shape can differ. For uniform-shape
/// batches use [`gemm_batch_strided`] instead — it has a smaller
/// dispatch overhead.
///
/// # Safety
///
/// Each `A` pointer must point to at least `lda * (op==NoTrans ? K :
/// M)` (or appropriate) elements; same for `B` and `C`. The lifetime
/// of the underlying buffers must extend through the call.
pub fn gemm_batch<T: BlasScalar>(layout: Layout, groups: &mut [GemmBatchGroup<T>]) -> Result<()> {
    if groups.is_empty() {
        return Ok(());
    }
    // Validate: all the per-group pointer arrays must have length equal
    // to group_size.
    for g in groups.iter() {
        if g.a_array.len() != g.group_size
            || g.b_array.len() != g.group_size
            || g.c_array.len() != g.group_size
        {
            return Err(Error::InvalidArgument(
                "a_array / b_array / c_array length must equal group_size",
            ));
        }
    }

    // Build the parallel parameter arrays MKL expects.
    let group_count = groups.len();
    let mut transa = Vec::with_capacity(group_count);
    let mut transb = Vec::with_capacity(group_count);
    let mut m_arr = Vec::with_capacity(group_count);
    let mut n_arr = Vec::with_capacity(group_count);
    let mut k_arr = Vec::with_capacity(group_count);
    let mut alpha_arr = Vec::with_capacity(group_count);
    let mut lda_arr = Vec::with_capacity(group_count);
    let mut ldb_arr = Vec::with_capacity(group_count);
    let mut beta_arr = Vec::with_capacity(group_count);
    let mut ldc_arr = Vec::with_capacity(group_count);
    let mut group_sz = Vec::with_capacity(group_count);

    let total: usize = groups.iter().map(|g| g.group_size).sum();
    let mut a_ptrs: Vec<*const T> = Vec::with_capacity(total);
    let mut b_ptrs: Vec<*const T> = Vec::with_capacity(total);
    let mut c_ptrs: Vec<*mut T> = Vec::with_capacity(total);

    for g in groups.iter_mut() {
        transa.push(g.transa.as_cblas());
        transb.push(g.transb.as_cblas());
        m_arr.push(dim_to_mkl_int(g.m)?);
        n_arr.push(dim_to_mkl_int(g.n)?);
        k_arr.push(dim_to_mkl_int(g.k)?);
        alpha_arr.push(g.alpha);
        lda_arr.push(dim_to_mkl_int(g.lda)?);
        ldb_arr.push(dim_to_mkl_int(g.ldb)?);
        beta_arr.push(g.beta);
        ldc_arr.push(dim_to_mkl_int(g.ldc)?);
        group_sz.push(dim_to_mkl_int(g.group_size)?);
        a_ptrs.extend(g.a_array.iter().copied());
        b_ptrs.extend(g.b_array.iter().copied());
        c_ptrs.extend(g.c_array.iter().copied());
    }

    unsafe {
        T::cblas_gemm_batch(
            layout.as_cblas(),
            transa.as_ptr(),
            transb.as_ptr(),
            m_arr.as_ptr(),
            n_arr.as_ptr(),
            k_arr.as_ptr(),
            alpha_arr.as_ptr(),
            a_ptrs.as_mut_ptr(),
            lda_arr.as_ptr(),
            b_ptrs.as_mut_ptr(),
            ldb_arr.as_ptr(),
            beta_arr.as_ptr(),
            c_ptrs.as_mut_ptr(),
            ldc_arr.as_ptr(),
            dim_to_mkl_int(group_count)?,
            group_sz.as_ptr(),
        );
    }
    Ok(())
}

/// Pointer-array batched GEMV. Performs many GEMVs whose vector
/// shapes (and `alpha` / `beta`) vary across "groups". See
/// [`gemm_batch`] for the group-based dispatch model.
///
/// # Safety
///
/// Each pointer must point to a buffer of the appropriate size for
/// the operation; lifetimes must extend through the call.
pub fn gemv_batch<T: BlasScalar>(layout: Layout, groups: &mut [GemvBatchGroup<T>]) -> Result<()> {
    if groups.is_empty() {
        return Ok(());
    }
    for g in groups.iter() {
        if g.a_array.len() != g.group_size
            || g.x_array.len() != g.group_size
            || g.y_array.len() != g.group_size
        {
            return Err(Error::InvalidArgument(
                "a_array / x_array / y_array length must equal group_size",
            ));
        }
    }
    let group_count = groups.len();
    let mut trans = Vec::with_capacity(group_count);
    let mut m_arr = Vec::with_capacity(group_count);
    let mut n_arr = Vec::with_capacity(group_count);
    let mut alpha_arr = Vec::with_capacity(group_count);
    let mut lda_arr = Vec::with_capacity(group_count);
    let mut incx_arr = Vec::with_capacity(group_count);
    let mut beta_arr = Vec::with_capacity(group_count);
    let mut incy_arr = Vec::with_capacity(group_count);
    let mut group_sz = Vec::with_capacity(group_count);

    let total: usize = groups.iter().map(|g| g.group_size).sum();
    let mut a_ptrs: Vec<*const T> = Vec::with_capacity(total);
    let mut x_ptrs: Vec<*const T> = Vec::with_capacity(total);
    let mut y_ptrs: Vec<*mut T> = Vec::with_capacity(total);

    for g in groups.iter_mut() {
        trans.push(g.trans.as_cblas());
        m_arr.push(dim_to_mkl_int(g.m)?);
        n_arr.push(dim_to_mkl_int(g.n)?);
        alpha_arr.push(g.alpha);
        lda_arr.push(dim_to_mkl_int(g.lda)?);
        incx_arr.push(stride_to_mkl_int(g.incx)?);
        beta_arr.push(g.beta);
        incy_arr.push(stride_to_mkl_int(g.incy)?);
        group_sz.push(dim_to_mkl_int(g.group_size)?);
        a_ptrs.extend(g.a_array.iter().copied());
        x_ptrs.extend(g.x_array.iter().copied());
        y_ptrs.extend(g.y_array.iter().copied());
    }

    unsafe {
        T::cblas_gemv_batch(
            layout.as_cblas(),
            trans.as_ptr(),
            m_arr.as_ptr(),
            n_arr.as_ptr(),
            alpha_arr.as_ptr(),
            a_ptrs.as_mut_ptr(),
            lda_arr.as_ptr(),
            x_ptrs.as_mut_ptr(),
            incx_arr.as_ptr(),
            beta_arr.as_ptr(),
            y_ptrs.as_mut_ptr(),
            incy_arr.as_ptr(),
            dim_to_mkl_int(group_count)?,
            group_sz.as_ptr(),
        );
    }
    Ok(())
}

/// Pointer-array batched TRSM. Solves many triangular systems whose
/// shapes / sides / triangles can vary across groups.
///
/// # Safety
///
/// Each pointer must point to a buffer of the appropriate size for
/// the operation; lifetimes must extend through the call. Each `B`
/// matrix is overwritten with the solution `X`.
pub fn trsm_batch<T: BlasScalar>(layout: Layout, groups: &mut [TrsmBatchGroup<T>]) -> Result<()> {
    if groups.is_empty() {
        return Ok(());
    }
    for g in groups.iter() {
        if g.a_array.len() != g.group_size || g.b_array.len() != g.group_size {
            return Err(Error::InvalidArgument(
                "a_array / b_array length must equal group_size",
            ));
        }
    }
    let group_count = groups.len();
    let mut side = Vec::with_capacity(group_count);
    let mut uplo = Vec::with_capacity(group_count);
    let mut transa = Vec::with_capacity(group_count);
    let mut diag = Vec::with_capacity(group_count);
    let mut m_arr = Vec::with_capacity(group_count);
    let mut n_arr = Vec::with_capacity(group_count);
    let mut alpha_arr = Vec::with_capacity(group_count);
    let mut lda_arr = Vec::with_capacity(group_count);
    let mut ldb_arr = Vec::with_capacity(group_count);
    let mut group_sz = Vec::with_capacity(group_count);

    let total: usize = groups.iter().map(|g| g.group_size).sum();
    let mut a_ptrs: Vec<*const T> = Vec::with_capacity(total);
    let mut b_ptrs: Vec<*mut T> = Vec::with_capacity(total);

    for g in groups.iter_mut() {
        side.push(g.side.as_cblas());
        uplo.push(g.uplo.as_cblas());
        transa.push(g.transa.as_cblas());
        diag.push(g.diag.as_cblas());
        m_arr.push(dim_to_mkl_int(g.m)?);
        n_arr.push(dim_to_mkl_int(g.n)?);
        alpha_arr.push(g.alpha);
        lda_arr.push(dim_to_mkl_int(g.lda)?);
        ldb_arr.push(dim_to_mkl_int(g.ldb)?);
        group_sz.push(dim_to_mkl_int(g.group_size)?);
        a_ptrs.extend(g.a_array.iter().copied());
        b_ptrs.extend(g.b_array.iter().copied());
    }

    unsafe {
        T::cblas_trsm_batch(
            layout.as_cblas(),
            side.as_ptr(),
            uplo.as_ptr(),
            transa.as_ptr(),
            diag.as_ptr(),
            m_arr.as_ptr(),
            n_arr.as_ptr(),
            alpha_arr.as_ptr(),
            a_ptrs.as_mut_ptr(),
            lda_arr.as_ptr(),
            b_ptrs.as_mut_ptr(),
            ldb_arr.as_ptr(),
            dim_to_mkl_int(group_count)?,
            group_sz.as_ptr(),
        );
    }
    Ok(())
}

/// One group of uniform GEMVs for [`gemv_batch`].
#[derive(Debug)]
pub struct GemvBatchGroup<'a, T: BlasScalar> {
    /// Transpose flag for `A`.
    pub trans: Transpose,
    /// Number of rows of `A`.
    pub m: usize,
    /// Number of columns of `A`.
    pub n: usize,
    /// Scaling factor for `op(A) * x`.
    pub alpha: T,
    /// Leading dimension of each `A`.
    pub lda: usize,
    /// Stride between consecutive elements of each `x`.
    pub incx: i64,
    /// Scaling factor for `y`.
    pub beta: T,
    /// Stride between consecutive elements of each `y`.
    pub incy: i64,
    /// Number of GEMVs in this group.
    pub group_size: usize,
    /// `A` matrix pointers, one per GEMV.
    pub a_array: &'a [*const T],
    /// `x` vector pointers.
    pub x_array: &'a [*const T],
    /// `y` vector pointers (mutable).
    pub y_array: &'a [*mut T],
}

/// One group of uniform TRSMs for [`trsm_batch`]. All TRSMs in this
/// group share side / uplo / trans / diag / dimensions / `alpha`.
#[derive(Debug)]
pub struct TrsmBatchGroup<'a, T: BlasScalar> {
    /// Whether `op(A)` appears on the left or right.
    pub side: Side,
    /// Which triangle of `A` to use.
    pub uplo: UpLo,
    /// Transpose flag for `A`.
    pub transa: Transpose,
    /// Whether `A` has a unit diagonal.
    pub diag: Diag,
    /// Number of rows of `B`.
    pub m: usize,
    /// Number of columns of `B`.
    pub n: usize,
    /// Scaling factor.
    pub alpha: T,
    /// Leading dimension of each `A`.
    pub lda: usize,
    /// Leading dimension of each `B`.
    pub ldb: usize,
    /// Number of TRSMs in this group.
    pub group_size: usize,
    /// `A` matrix pointers.
    pub a_array: &'a [*const T],
    /// `B` matrix pointers (mutable; overwritten with the solution `X`).
    pub b_array: &'a [*mut T],
}

/// One group of uniform GEMMs for [`gemm_batch`]. All GEMMs in this
/// group share the transposes, dimensions, and scaling factors.
#[derive(Debug)]
pub struct GemmBatchGroup<'a, T: BlasScalar> {
    /// Transpose flag for `A`.
    pub transa: Transpose,
    /// Transpose flag for `B`.
    pub transb: Transpose,
    /// Number of rows of `op(A)` and `C`.
    pub m: usize,
    /// Number of columns of `op(B)` and `C`.
    pub n: usize,
    /// Number of columns of `op(A)` / rows of `op(B)`.
    pub k: usize,
    /// Scaling factor for `A * B`.
    pub alpha: T,
    /// Leading dimension of each `A` matrix in this group.
    pub lda: usize,
    /// Leading dimension of each `B` matrix in this group.
    pub ldb: usize,
    /// Scaling factor for `C`.
    pub beta: T,
    /// Leading dimension of each `C` matrix in this group.
    pub ldc: usize,
    /// Number of GEMMs in this group.
    pub group_size: usize,
    /// `A` matrix pointers, one per GEMM in this group. Length must
    /// equal `group_size`.
    pub a_array: &'a [*const T],
    /// `B` matrix pointers.
    pub b_array: &'a [*const T],
    /// `C` matrix pointers, one per GEMM (mutable).
    pub c_array: &'a [*mut T],
}

/// Batched [`super::level3::trsm`].
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 15 arguments; changing the signature breaks consumers"
)]
pub fn trsm_batch_strided<T: BlasScalar>(
    layout: Layout,
    side: Side,
    uplo: UpLo,
    trans: Transpose,
    diag: Diag,
    m: usize,
    n: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    stridea: i64,
    b: &mut [T],
    ldb: usize,
    strideb: i64,
    batch_size: usize,
) -> Result<()> {
    let _ = (a.len(), b.len());
    if batch_size == 0 {
        return Ok(());
    }
    unsafe {
        T::cblas_trsm_batch_strided(
            layout.as_cblas(),
            side.as_cblas(),
            uplo.as_cblas(),
            trans.as_cblas(),
            diag.as_cblas(),
            dim_to_mkl_int(m)?,
            dim_to_mkl_int(n)?,
            alpha,
            a.as_ptr(),
            dim_to_mkl_int(lda)?,
            stride_to_mkl_int(stridea)?,
            b.as_mut_ptr(),
            dim_to_mkl_int(ldb)?,
            stride_to_mkl_int(strideb)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Batched diagonal-matrix multiply: for each batch entry,
/// `C[i] ← A[i] * diag(x[i])` (`side == Right`) or
/// `C[i] ← diag(x[i]) * A[i]` (`side == Left`).
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 14 arguments; changing the signature breaks consumers"
)]
pub fn dgmm_batch_strided<T: BlasScalar>(
    layout: Layout,
    side: Side,
    m: usize,
    n: usize,
    a: &[T],
    lda: usize,
    stridea: i64,
    x: &[T],
    incx: i64,
    stridex: i64,
    c: &mut [T],
    ldc: usize,
    stridec: i64,
    batch_size: usize,
) -> Result<()> {
    let _ = (a.len(), x.len(), c.len());
    if batch_size == 0 {
        return Ok(());
    }
    unsafe {
        T::cblas_dgmm_batch_strided(
            layout.as_cblas(),
            side.as_cblas(),
            dim_to_mkl_int(m)?,
            dim_to_mkl_int(n)?,
            a.as_ptr(),
            dim_to_mkl_int(lda)?,
            stride_to_mkl_int(stridea)?,
            x.as_ptr(),
            stride_to_mkl_int(incx)?,
            stride_to_mkl_int(stridex)?,
            c.as_mut_ptr(),
            dim_to_mkl_int(ldc)?,
            stride_to_mkl_int(stridec)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

/// Batched complex `gemm3m`. Complex-only counterpart of
/// [`gemm_batch_strided`].
#[allow(
    clippy::too_many_arguments,
    reason = "stable public surface: published since v0.1.0 with 18 arguments; changing the signature breaks consumers"
)]
pub fn gemm3m_batch_strided<T: ComplexBlasScalar>(
    layout: Layout,
    transa: Transpose,
    transb: Transpose,
    m: usize,
    n: usize,
    k: usize,
    alpha: T,
    a: &[T],
    lda: usize,
    stridea: i64,
    b: &[T],
    ldb: usize,
    strideb: i64,
    beta: T,
    c: &mut [T],
    ldc: usize,
    stridec: i64,
    batch_size: usize,
) -> Result<()> {
    let _ = (a.len(), b.len(), c.len());
    if batch_size == 0 {
        return Ok(());
    }
    unsafe {
        T::cblas_gemm3m_batch_strided(
            layout.as_cblas(),
            transa.as_cblas(),
            transb.as_cblas(),
            dim_to_mkl_int(m)?,
            dim_to_mkl_int(n)?,
            dim_to_mkl_int(k)?,
            alpha,
            a.as_ptr(),
            dim_to_mkl_int(lda)?,
            stride_to_mkl_int(stridea)?,
            b.as_ptr(),
            dim_to_mkl_int(ldb)?,
            stride_to_mkl_int(strideb)?,
            beta,
            c.as_mut_ptr(),
            dim_to_mkl_int(ldc)?,
            stride_to_mkl_int(stridec)?,
            dim_to_mkl_int(batch_size)?,
        );
    }
    Ok(())
}

#[inline]
fn check_batch_buffers(
    buf_len: usize,
    n: usize,
    inc: i64,
    stride: i64,
    batch_size: usize,
    _name: &'static str,
) -> Result<()> {
    if inc == 0 {
        return Err(Error::InvalidArgument("vector stride must be non-zero"));
    }
    if batch_size == 0 || n == 0 {
        return Ok(());
    }
    let abs_stride = stride.unsigned_abs() as usize;
    let elem_span = 1 + (n - 1) * inc.unsigned_abs() as usize;
    let needed = (batch_size - 1) * abs_stride + elem_span;
    if buf_len < needed {
        return Err(Error::InvalidArgument(
            "batched buffer too short for n, inc, stride, and batch_size",
        ));
    }
    Ok(())
}

fn invalid_arg_for(name: &'static str, msg: &'static str) -> Error {
    let _ = msg;
    match name {
        "A" => Error::InvalidArgument("A buffer is invalid for declared dimensions"),
        "B" => Error::InvalidArgument("B buffer is invalid for declared dimensions"),
        "C" => Error::InvalidArgument("C buffer is invalid for declared dimensions"),
        "AB" => Error::InvalidArgument("AB buffer is invalid for declared dimensions"),
        _ => Error::InvalidArgument("matrix buffer is invalid for declared dimensions"),
    }
}