Skip to main content

sparse_ir/
gemm.rs

1//! Matrix multiplication utilities with pluggable BLAS backend
2//!
3//! This module provides thin wrappers around matrix multiplication operations,
4//! with support for runtime selection of BLAS implementations.
5//!
6//! # Design
7//! - **Default**: Pure Rust Faer backend (no external dependencies)
8//! - **Optional**: External BLAS via function pointer injection
9//! - **Thread-safe**: Global dispatcher protected by RwLock
10//!
11//! # Example
12//! ```
13//! use mdarray::tensor;
14//! use sparse_ir::gemm::{GemmBackendHandle, matmul_par};
15//!
16//! let a = tensor![[1.0, 2.0], [3.0, 4.0]];
17//! let b = tensor![[5.0, 6.0], [7.0, 8.0]];
18//!
19//! // `None` uses the global dispatcher: the Faer backend by default (system
20//! // BLAS with the `system-blas` feature, or a BLAS injected at runtime)
21//! let c = matmul_par(&a, &b, None);
22//! assert_eq!(c, tensor![[19.0, 22.0], [43.0, 50.0]]);
23//!
24//! // Or pass an explicit backend handle instead of relying on global state
25//! let faer = GemmBackendHandle::default();
26//! assert_eq!(matmul_par(&a, &b, Some(&faer)), c);
27//! ```
28//!
29//! A custom BLAS (e.g. from the C API) is injected at runtime with
30//! [`set_blas_backend`] (LP64) or [`set_ilp64_backend`] (ILP64); see their
31//! examples. [`clear_blas_backend`] restores the Faer backend.
32
33use mdarray::{DSlice, DTensor, DView, DViewMut, Layout};
34use once_cell::sync::Lazy;
35use std::sync::{Arc, RwLock};
36
37#[cfg(feature = "system-blas")]
38use blas_sys::dgemm_;
39
40//==============================================================================
41// BLAS Function Pointer Types
42//==============================================================================
43
44/// BLAS dgemm function pointer type (LP64: 32-bit integers)
45///
46/// Signature matches Fortran BLAS dgemm:
47/// ```c
48/// void dgemm_(char *transa, char *transb, int *m, int *n, int *k,
49///             double *alpha, double *a, int *lda, double *b, int *ldb,
50///             double *beta, double *c, int *ldc);
51/// ```
52/// Note: All parameters are passed by reference (pointers).
53/// Transpose options: 'N' (no transpose), 'T' (transpose), 'C' (conjugate transpose).
54pub type DgemmFnPtr = unsafe extern "C" fn(
55    transa: *const libc::c_char,
56    transb: *const libc::c_char,
57    m: *const libc::c_int,
58    n: *const libc::c_int,
59    k: *const libc::c_int,
60    alpha: *const libc::c_double,
61    a: *const libc::c_double,
62    lda: *const libc::c_int,
63    b: *const libc::c_double,
64    ldb: *const libc::c_int,
65    beta: *const libc::c_double,
66    c: *mut libc::c_double,
67    ldc: *const libc::c_int,
68);
69
70/// BLAS zgemm function pointer type (LP64: 32-bit integers)
71///
72/// Signature matches Fortran BLAS zgemm:
73/// ```c
74/// void zgemm_(char *transa, char *transb, int *m, int *n, int *k,
75///             void *alpha, void *a, int *lda, void *b, int *ldb,
76///             void *beta, void *c, int *ldc);
77/// ```
78/// Note: All parameters are passed by reference (pointers).
79/// Complex numbers are passed as void* (typically complex<double>*).
80/// Transpose options: 'N' (no transpose), 'T' (transpose), 'C' (conjugate transpose).
81pub type ZgemmFnPtr = unsafe extern "C" fn(
82    transa: *const libc::c_char,
83    transb: *const libc::c_char,
84    m: *const libc::c_int,
85    n: *const libc::c_int,
86    k: *const libc::c_int,
87    alpha: *const num_complex::Complex<f64>,
88    a: *const num_complex::Complex<f64>,
89    lda: *const libc::c_int,
90    b: *const num_complex::Complex<f64>,
91    ldb: *const libc::c_int,
92    beta: *const num_complex::Complex<f64>,
93    c: *mut num_complex::Complex<f64>,
94    ldc: *const libc::c_int,
95);
96
97// When using system BLAS via `blas-sys`, we need a small wrapper to adapt
98// `blas_sys::zgemm_` (which uses `c_double_complex = [f64; 2]`) to the
99// `ZgemmFnPtr` signature that takes `num_complex::Complex<f64>`.
100#[cfg(feature = "system-blas")]
101unsafe extern "C" fn zgemm_wrapper(
102    transa: *const libc::c_char,
103    transb: *const libc::c_char,
104    m: *const libc::c_int,
105    n: *const libc::c_int,
106    k: *const libc::c_int,
107    alpha: *const num_complex::Complex<f64>,
108    a: *const num_complex::Complex<f64>,
109    lda: *const libc::c_int,
110    b: *const num_complex::Complex<f64>,
111    ldb: *const libc::c_int,
112    beta: *const num_complex::Complex<f64>,
113    c: *mut num_complex::Complex<f64>,
114    ldc: *const libc::c_int,
115) {
116    // Safety: `blas_sys::c_double_complex` is defined as `[f64; 2]` and is
117    // layout-compatible with `num_complex::Complex<f64>` in memory, so we can
118    // cast between the two pointer types here.
119    unsafe {
120        blas_sys::zgemm_(
121            transa,
122            transb,
123            m,
124            n,
125            k,
126            alpha as *const _ as *const blas_sys::c_double_complex,
127            a as *const _ as *const blas_sys::c_double_complex,
128            lda,
129            b as *const _ as *const blas_sys::c_double_complex,
130            ldb,
131            beta as *const _ as *const blas_sys::c_double_complex,
132            c as *mut _ as *mut blas_sys::c_double_complex,
133            ldc,
134        );
135    }
136}
137
138/// BLAS dgemm function pointer type (ILP64: 64-bit integers)
139///
140/// Signature matches Fortran BLAS dgemm (ILP64):
141/// ```c
142/// void dgemm_(char *transa, char *transb, long long *m, long long *n, long long *k,
143///             double *alpha, double *a, long long *lda, double *b, long long *ldb,
144///             double *beta, double *c, long long *ldc);
145/// ```
146pub type Dgemm64FnPtr = unsafe extern "C" fn(
147    transa: *const libc::c_char,
148    transb: *const libc::c_char,
149    m: *const i64,
150    n: *const i64,
151    k: *const i64,
152    alpha: *const libc::c_double,
153    a: *const libc::c_double,
154    lda: *const i64,
155    b: *const libc::c_double,
156    ldb: *const i64,
157    beta: *const libc::c_double,
158    c: *mut libc::c_double,
159    ldc: *const i64,
160);
161
162/// BLAS zgemm function pointer type (ILP64: 64-bit integers)
163///
164/// Signature matches Fortran BLAS zgemm (ILP64):
165/// ```c
166/// void zgemm_(char *transa, char *transb, long long *m, long long *n, long long *k,
167///             void *alpha, void *a, long long *lda, void *b, long long *ldb,
168///             void *beta, void *c, long long *ldc);
169/// ```
170pub type Zgemm64FnPtr = unsafe extern "C" fn(
171    transa: *const libc::c_char,
172    transb: *const libc::c_char,
173    m: *const i64,
174    n: *const i64,
175    k: *const i64,
176    alpha: *const num_complex::Complex<f64>,
177    a: *const num_complex::Complex<f64>,
178    lda: *const i64,
179    b: *const num_complex::Complex<f64>,
180    ldb: *const i64,
181    beta: *const num_complex::Complex<f64>,
182    c: *mut num_complex::Complex<f64>,
183    ldc: *const i64,
184);
185
186//==============================================================================
187// Fortran BLAS Constants
188//==============================================================================
189
190// Fortran BLAS transpose characters
191
192//==============================================================================
193// GemmBackend Trait
194//==============================================================================
195
196/// GEMM backend trait for runtime dispatch
197pub trait GemmBackend: Send + Sync {
198    /// Matrix multiplication: C = A * B (f64)
199    ///
200    /// # Arguments
201    /// * `m`, `n`, `k` - Matrix dimensions (M x K) * (K x N) = (M x N)
202    /// * `a` - Pointer to matrix A (row-major, M x K)
203    /// * `b` - Pointer to matrix B (row-major, K x N)
204    /// * `c` - Pointer to output matrix C (row-major, M x N)
205    /// Note: Leading dimension is calculated internally based on row-major to column-major conversion
206    unsafe fn dgemm(&self, m: usize, n: usize, k: usize, a: *const f64, b: *const f64, c: *mut f64);
207
208    /// Matrix multiplication: C = A * B (Complex<f64>)
209    ///
210    /// # Arguments
211    /// * `m`, `n`, `k` - Matrix dimensions (M x K) * (K x N) = (M x N)
212    /// * `a` - Pointer to matrix A (row-major, M x K)
213    /// * `b` - Pointer to matrix B (row-major, K x N)
214    /// * `c` - Pointer to output matrix C (row-major, M x N)
215    /// Note: Leading dimension is calculated internally based on row-major to column-major conversion
216    unsafe fn zgemm(
217        &self,
218        m: usize,
219        n: usize,
220        k: usize,
221        a: *const num_complex::Complex<f64>,
222        b: *const num_complex::Complex<f64>,
223        c: *mut num_complex::Complex<f64>,
224    );
225
226    /// Returns true if this backend uses 64-bit integers (ILP64)
227    fn is_ilp64(&self) -> bool {
228        false
229    }
230
231    /// Returns backend name for debugging
232    fn name(&self) -> &'static str;
233}
234
235//==============================================================================
236// Faer Backend (Default, Pure Rust, Zero-Copy)
237//==============================================================================
238
239/// Default Faer backend (Pure Rust, no external dependencies)
240///
241/// This implementation uses faer's native API with raw pointer views,
242/// achieving zero-copy matrix multiplication without intermediate allocations.
243struct FaerBackend;
244
245impl GemmBackend for FaerBackend {
246    unsafe fn dgemm(
247        &self,
248        m: usize,
249        n: usize,
250        k: usize,
251        a: *const f64,
252        b: *const f64,
253        c: *mut f64,
254    ) {
255        use faer::linalg::matmul::matmul;
256        use faer::mat::{MatMut, MatRef};
257        use faer::{Accum, Par};
258
259        // Create views directly from raw pointers (zero-copy!)
260        // Row-major layout: row_stride = number of columns, col_stride = 1
261        let lhs = unsafe { MatRef::from_raw_parts(a, m, k, k as isize, 1) };
262        let rhs = unsafe { MatRef::from_raw_parts(b, k, n, n as isize, 1) };
263        let mut dst = unsafe { MatMut::from_raw_parts_mut(c, m, n, n as isize, 1) };
264
265        // In-place matrix multiplication (no intermediate allocations)
266        matmul(&mut dst, Accum::Replace, &lhs, &rhs, 1.0, Par::Seq);
267    }
268
269    unsafe fn zgemm(
270        &self,
271        m: usize,
272        n: usize,
273        k: usize,
274        a: *const num_complex::Complex<f64>,
275        b: *const num_complex::Complex<f64>,
276        c: *mut num_complex::Complex<f64>,
277    ) {
278        use faer::linalg::matmul::matmul;
279        use faer::mat::{MatMut, MatRef};
280        use faer::{Accum, Par};
281
282        // Create views directly from raw pointers (zero-copy!)
283        // Row-major layout: row_stride = number of columns, col_stride = 1
284        let lhs = unsafe { MatRef::from_raw_parts(a, m, k, k as isize, 1) };
285        let rhs = unsafe { MatRef::from_raw_parts(b, k, n, n as isize, 1) };
286        let mut dst = unsafe { MatMut::from_raw_parts_mut(c, m, n, n as isize, 1) };
287
288        // In-place matrix multiplication (no intermediate allocations)
289        matmul(
290            &mut dst,
291            Accum::Replace,
292            &lhs,
293            &rhs,
294            num_complex::Complex::new(1.0, 0.0),
295            Par::Seq,
296        );
297    }
298
299    fn name(&self) -> &'static str {
300        "Faer (Pure Rust)"
301    }
302}
303
304//==============================================================================
305// External BLAS Backends (LP64 and ILP64)
306//==============================================================================
307
308/// Conversion rules for row-major data to column-major BLAS:
309///
310/// **Goal**: Compute C = A * B where:
311///   - A is m×k (row-major)
312///   - B is k×n (row-major)
313///   - C is m×n (row-major)
314///
315/// **Row-major to column-major interpretation**:
316///   - Row-major A (m×k) appears as A^T (k×m) in column-major → call this At
317///   - Row-major B (k×n) appears as B^T (n×k) in column-major → call this Bt
318///   - Row-major C (m×n) appears as C^T (n×m) in column-major → call this Ct
319///   - To compute C = A * B, we need: C^T = (A * B)^T = B^T * A^T
320///   - So: Ct = Bt * At
321///
322/// **BLAS call transformation**:
323///   - Original: C = A * B (row-major world)
324///   - BLAS call: Ct = Bt * At (column-major world)
325///   - transa = 'N' (Bt is already transposed-looking, no transpose needed)
326///   - transb = 'N' (At is already transposed-looking, no transpose needed)
327///   - Call: dgemm('N', 'N', n, m, k, alpha, B, lda, A, ldb, beta, C, ldc)
328///
329/// **Dimension conversions**:
330///   - m_blas = n (Ct rows = Bt rows)
331///   - n_blas = m (Ct cols = At cols)
332///   - k_blas = k (common dimension)
333///   - lda = n (leading dimension of Bt: n×k in column-major, lda = n)
334///   - ldb = k (leading dimension of At: k×m in column-major, ldb = k)
335///   - ldc = n (leading dimension of Ct: n×m in column-major, ldc = n)
336
337/// External BLAS backend (LP64: 32-bit integers)
338pub struct ExternalBlasBackend {
339    dgemm: DgemmFnPtr,
340    zgemm: ZgemmFnPtr,
341}
342
343impl ExternalBlasBackend {
344    pub fn new(dgemm: DgemmFnPtr, zgemm: ZgemmFnPtr) -> Self {
345        Self { dgemm, zgemm }
346    }
347}
348
349impl GemmBackend for ExternalBlasBackend {
350    unsafe fn dgemm(
351        &self,
352        m: usize,
353        n: usize,
354        k: usize,
355        a: *const f64,
356        b: *const f64,
357        c: *mut f64,
358    ) {
359        // Validate dimensions fit in i32
360        assert!(
361            m <= i32::MAX as usize,
362            "Matrix dimension m too large for LP64 BLAS"
363        );
364        assert!(
365            n <= i32::MAX as usize,
366            "Matrix dimension n too large for LP64 BLAS"
367        );
368        assert!(
369            k <= i32::MAX as usize,
370            "Matrix dimension k too large for LP64 BLAS"
371        );
372
373        // Fortran BLAS requires all parameters passed by reference
374        // Apply row-major to column-major conversion (see conversion rules above)
375        let transa = b'N' as libc::c_char; // Bt is already transposed-looking
376        let transb = b'N' as libc::c_char; // At is already transposed-looking
377        let m_i32 = n as i32; // m_blas = n (Ct rows = Bt rows)
378        let n_i32 = m as i32; // n_blas = m (Ct cols = At cols)
379        let k_i32 = k as i32; // k_blas = k (common dimension)
380        let alpha = 1.0f64;
381        let lda = n as i32; // lda = n (leading dimension of Bt: n×k in column-major)
382        let ldb = k as i32; // ldb = k (leading dimension of At: k×m in column-major)
383        let beta = 0.0f64;
384        // For row-major C (m×n) viewed as column-major Ct (n×m):
385        // Leading dimension in column-major is the stride between rows
386        // In row-major, stride between rows = number of columns = n
387        // So ldc = n (the number of columns in the original row-major matrix)
388        let ldc_i32 = n as i32; // ldc = n (leading dimension of Ct: n×m in column-major)
389
390        unsafe {
391            (self.dgemm)(
392                &transa, &transb, &m_i32, &n_i32, &k_i32, &alpha, b, // B first (Bt)
393                &lda, a, // A second (At)
394                &ldb, &beta, c, &ldc_i32,
395            );
396        }
397    }
398
399    unsafe fn zgemm(
400        &self,
401        m: usize,
402        n: usize,
403        k: usize,
404        a: *const num_complex::Complex<f64>,
405        b: *const num_complex::Complex<f64>,
406        c: *mut num_complex::Complex<f64>,
407    ) {
408        assert!(
409            m <= i32::MAX as usize,
410            "Matrix dimension m too large for LP64 BLAS"
411        );
412        assert!(
413            n <= i32::MAX as usize,
414            "Matrix dimension n too large for LP64 BLAS"
415        );
416        assert!(
417            k <= i32::MAX as usize,
418            "Matrix dimension k too large for LP64 BLAS"
419        );
420
421        // Fortran BLAS requires all parameters passed by reference
422        // Apply row-major to column-major conversion (see conversion rules above)
423        let transa = b'N' as libc::c_char; // Bt is already transposed-looking
424        let transb = b'N' as libc::c_char; // At is already transposed-looking
425        let m_i32 = n as i32; // m_blas = n (Ct rows = Bt rows)
426        let n_i32 = m as i32; // n_blas = m (Ct cols = At cols)
427        let k_i32 = k as i32; // k_blas = k (common dimension)
428        let alpha = num_complex::Complex::new(1.0, 0.0);
429        let lda = n as i32; // lda = n (leading dimension of Bt: n×k in column-major)
430        let ldb = k as i32; // ldb = k (leading dimension of At: k×m in column-major)
431        let beta = num_complex::Complex::new(0.0, 0.0);
432        // For row-major C (m×n) viewed as column-major Ct (n×m):
433        // Leading dimension in column-major is the stride between rows = n
434        let ldc_i32 = n as i32; // ldc = n (leading dimension of Ct: n×m in column-major)
435
436        unsafe {
437            (self.zgemm)(
438                &transa,
439                &transb,
440                &m_i32,
441                &n_i32,
442                &k_i32,
443                &alpha,
444                b as *const _, // B first (Bt)
445                &lda,
446                a as *const _, // A second (At)
447                &ldb,
448                &beta,
449                c as *mut _,
450                &ldc_i32,
451            );
452        }
453    }
454
455    fn name(&self) -> &'static str {
456        "External BLAS (LP64)"
457    }
458}
459
460/// External BLAS backend (ILP64: 64-bit integers)
461pub struct ExternalBlas64Backend {
462    dgemm64: Dgemm64FnPtr,
463    zgemm64: Zgemm64FnPtr,
464}
465
466impl ExternalBlas64Backend {
467    pub fn new(dgemm64: Dgemm64FnPtr, zgemm64: Zgemm64FnPtr) -> Self {
468        Self { dgemm64, zgemm64 }
469    }
470}
471
472impl GemmBackend for ExternalBlas64Backend {
473    unsafe fn dgemm(
474        &self,
475        m: usize,
476        n: usize,
477        k: usize,
478        a: *const f64,
479        b: *const f64,
480        c: *mut f64,
481    ) {
482        // Fortran BLAS requires all parameters passed by reference
483        // Apply row-major to column-major conversion (see conversion rules above)
484        let transa = b'N' as libc::c_char; // Bt is already transposed-looking
485        let transb = b'N' as libc::c_char; // At is already transposed-looking
486        let m_i64 = n as i64; // m_blas = n (Ct rows = Bt rows)
487        let n_i64 = m as i64; // n_blas = m (Ct cols = At cols)
488        let k_i64 = k as i64; // k_blas = k (common dimension)
489        let alpha = 1.0f64;
490        let lda = n as i64; // lda = n (leading dimension of Bt: n×k in column-major)
491        let ldb = k as i64; // ldb = k (leading dimension of At: k×m in column-major)
492        let beta = 0.0f64;
493        // For row-major C (m×n) viewed as column-major Ct (n×m):
494        // Leading dimension in column-major is the stride between rows = n
495        let ldc_i64 = n as i64; // ldc = n (leading dimension of Ct: n×m in column-major)
496
497        unsafe {
498            (self.dgemm64)(
499                &transa, &transb, &m_i64, &n_i64, &k_i64, &alpha, b, // B first (Bt)
500                &lda, a, // A second (At)
501                &ldb, &beta, c, &ldc_i64,
502            );
503        }
504    }
505
506    unsafe fn zgemm(
507        &self,
508        m: usize,
509        n: usize,
510        k: usize,
511        a: *const num_complex::Complex<f64>,
512        b: *const num_complex::Complex<f64>,
513        c: *mut num_complex::Complex<f64>,
514    ) {
515        // Fortran BLAS requires all parameters passed by reference
516        // Apply row-major to column-major conversion (see conversion rules above)
517        let transa = b'N' as libc::c_char; // Bt is already transposed-looking
518        let transb = b'N' as libc::c_char; // At is already transposed-looking
519        let m_i64 = n as i64; // m_blas = n (Ct rows = Bt rows)
520        let n_i64 = m as i64; // n_blas = m (Ct cols = At cols)
521        let k_i64 = k as i64; // k_blas = k (common dimension)
522        let alpha = num_complex::Complex::new(1.0, 0.0);
523        let lda = n as i64; // lda = n (leading dimension of Bt: n×k in column-major)
524        let ldb = k as i64; // ldb = k (leading dimension of At: k×m in column-major)
525        let beta = num_complex::Complex::new(0.0, 0.0);
526        // For row-major C (m×n) viewed as column-major Ct (n×m):
527        // Leading dimension in column-major is the stride between rows = n
528        let ldc_i64 = n as i64; // ldc = n (leading dimension of Ct: n×m in column-major)
529
530        unsafe {
531            (self.zgemm64)(
532                &transa,
533                &transb,
534                &m_i64,
535                &n_i64,
536                &k_i64,
537                &alpha,
538                b as *const _, // B first (Bt)
539                &lda,
540                a as *const _, // A second (At)
541                &ldb,
542                &beta,
543                c as *mut _,
544                &ldc_i64,
545            );
546        }
547    }
548
549    fn is_ilp64(&self) -> bool {
550        true
551    }
552
553    fn name(&self) -> &'static str {
554        "External BLAS (ILP64)"
555    }
556}
557
558//==============================================================================
559// Backend Handle
560//==============================================================================
561
562/// Thread-safe handle to a GEMM backend
563///
564/// This type wraps an `Arc<dyn GemmBackend>` to allow sharing a backend
565/// across multiple function calls without global state.
566///
567/// # Example
568/// ```
569/// use mdarray::tensor;
570/// use sparse_ir::gemm::{GemmBackendHandle, matmul_par};
571///
572/// let a = tensor![[1.0, 2.0], [3.0, 4.0]];
573/// let b = tensor![[5.0, 6.0], [7.0, 8.0]];
574/// let backend = GemmBackendHandle::default();
575/// let result = matmul_par(&a, &b, Some(&backend));
576/// assert_eq!(result, tensor![[19.0, 22.0], [43.0, 50.0]]);
577/// ```
578#[derive(Clone)]
579pub struct GemmBackendHandle {
580    inner: Arc<dyn GemmBackend>,
581}
582
583impl GemmBackendHandle {
584    /// Create a new backend handle from a boxed backend
585    pub fn new(backend: Box<dyn GemmBackend>) -> Self {
586        Self {
587            inner: Arc::from(backend),
588        }
589    }
590
591    /// Create a default backend handle (Faer backend)
592    pub fn default() -> Self {
593        Self {
594            inner: Arc::new(FaerBackend),
595        }
596    }
597
598    /// Get a reference to the inner backend
599    pub(crate) fn as_ref(&self) -> &dyn GemmBackend {
600        self.inner.as_ref()
601    }
602}
603
604//==============================================================================
605// Global Dispatcher (for backward compatibility)
606//==============================================================================
607
608/// Global BLAS dispatcher (thread-safe)
609///
610/// This is kept for backward compatibility when `None` is passed as backend.
611/// New code should use `GemmBackendHandle` explicitly.
612static BLAS_DISPATCHER: Lazy<RwLock<Box<dyn GemmBackend>>> = Lazy::new(|| {
613    #[cfg(feature = "system-blas")]
614    {
615        // Use system BLAS (LP64) by default via `blas-sys`.
616        let backend = ExternalBlasBackend::new(dgemm_ as DgemmFnPtr, zgemm_wrapper as ZgemmFnPtr);
617        RwLock::new(Box::new(backend) as Box<dyn GemmBackend>)
618    }
619    #[cfg(not(feature = "system-blas"))]
620    {
621        // Default to the pure Rust Faer backend.
622        RwLock::new(Box::new(FaerBackend) as Box<dyn GemmBackend>)
623    }
624});
625
626/// Set BLAS backend (LP64: 32-bit integers)
627///
628/// # Safety
629/// - Function pointers must be valid and thread-safe
630/// - Must remain valid for the lifetime of the program
631/// - Must follow Fortran BLAS calling convention
632///
633/// # Example
634/// ```
635/// use mdarray::{DTensor, tensor};
636/// use num_complex::Complex;
637/// use sparse_ir::gemm::{clear_blas_backend, get_backend_info, matmul_par, set_blas_backend};
638/// # use std::ffi::{c_char, c_int};
639/// # use std::ops::{Add, Mul};
640/// #
641/// # // Naive column-major C = alpha * A * B + beta * C for transa = transb = 'N'
642/// # // (what sparse-ir passes), standing in for a BLAS library.
643/// # unsafe fn gemm_nn<T>(mnk: [usize; 3], alpha: T, a: *const T, lda: usize,
644/// #                    b: *const T, ldb: usize, beta: T, c: *mut T, ldc: usize)
645/// # where
646/// #     T: Copy + Default + PartialEq + Add<Output = T> + Mul<Output = T>,
647/// # {
648/// #     let [m, n, k] = mnk;
649/// #     for j in 0..n {
650/// #         for i in 0..m {
651/// #             let mut acc = T::default();
652/// #             for p in 0..k {
653/// #                 acc = acc + unsafe { *a.add(i + p * lda) * *b.add(p + j * ldb) };
654/// #             }
655/// #             let cij = unsafe { &mut *c.add(i + j * ldc) };
656/// #             *cij = if beta == T::default() { alpha * acc } else { alpha * acc + beta * *cij };
657/// #         }
658/// #     }
659/// # }
660/// # unsafe extern "C" fn my_dgemm(
661/// #     _transa: *const c_char, _transb: *const c_char,
662/// #     m: *const c_int, n: *const c_int, k: *const c_int,
663/// #     alpha: *const f64, a: *const f64, lda: *const c_int,
664/// #     b: *const f64, ldb: *const c_int,
665/// #     beta: *const f64, c: *mut f64, ldc: *const c_int,
666/// # ) {
667/// #     unsafe {
668/// #         let mnk = [*m as usize, *n as usize, *k as usize];
669/// #         gemm_nn(mnk, *alpha, a, *lda as usize, b, *ldb as usize, *beta, c, *ldc as usize);
670/// #     }
671/// # }
672/// # unsafe extern "C" fn my_zgemm(
673/// #     _transa: *const c_char, _transb: *const c_char,
674/// #     m: *const c_int, n: *const c_int, k: *const c_int,
675/// #     alpha: *const Complex<f64>, a: *const Complex<f64>, lda: *const c_int,
676/// #     b: *const Complex<f64>, ldb: *const c_int,
677/// #     beta: *const Complex<f64>, c: *mut Complex<f64>, ldc: *const c_int,
678/// # ) {
679/// #     unsafe {
680/// #         let mnk = [*m as usize, *n as usize, *k as usize];
681/// #         gemm_nn(mnk, *alpha, a, *lda as usize, b, *ldb as usize, *beta, c, *ldc as usize);
682/// #     }
683/// # }
684///
685/// // `my_dgemm` and `my_zgemm` are the LP64 Fortran BLAS `dgemm_` and `zgemm_`
686/// // to use, e.g. from OpenBLAS. (This example defines naive stand-ins in
687/// // hidden lines so that it runs without a BLAS library.)
688/// unsafe {
689///     set_blas_backend(my_dgemm, my_zgemm);
690/// }
691/// assert_eq!(get_backend_info(), ("External BLAS (LP64)", true, false));
692///
693/// // Calls without an explicit backend handle now go through the injected BLAS
694/// let a = tensor![[1.0, 2.0], [3.0, 4.0]];
695/// let b = tensor![[5.0, 6.0], [7.0, 8.0]];
696/// let c = matmul_par(&a, &b, None);
697/// assert_eq!(c, tensor![[19.0, 22.0], [43.0, 50.0]]);
698///
699/// // Complex matrices use `zgemm`: (i A) B = i (A B)
700/// let ia = DTensor::<Complex<f64>, 2>::from_fn([2, 2], |idx| Complex::new(0.0, a[idx]));
701/// let bz = DTensor::<Complex<f64>, 2>::from_fn([2, 2], |idx| Complex::new(b[idx], 0.0));
702/// let ic = DTensor::<Complex<f64>, 2>::from_fn([2, 2], |idx| Complex::new(0.0, c[idx]));
703/// assert_eq!(matmul_par(&ia, &bz, None), ic);
704///
705/// clear_blas_backend(); // back to the pure-Rust Faer backend
706/// assert!(!get_backend_info().1);
707/// ```
708pub unsafe fn set_blas_backend(dgemm: DgemmFnPtr, zgemm: ZgemmFnPtr) {
709    let backend = ExternalBlasBackend { dgemm, zgemm };
710    let mut dispatcher = BLAS_DISPATCHER.write().unwrap();
711    *dispatcher = Box::new(backend);
712}
713
714/// Set ILP64 BLAS backend (64-bit integers)
715///
716/// # Safety
717/// - Function pointers must be valid, thread-safe, and use 64-bit integers
718/// - Must remain valid for the lifetime of the program
719/// - Must follow Fortran BLAS calling convention with ILP64 interface
720///
721/// # Example
722/// ```
723/// use mdarray::tensor;
724/// use sparse_ir::gemm::{clear_blas_backend, get_backend_info, matmul_par, set_ilp64_backend};
725/// # use num_complex::Complex;
726/// # use std::ffi::c_char;
727/// # use std::ops::{Add, Mul};
728/// #
729/// # // Naive column-major C = alpha * A * B + beta * C for transa = transb = 'N'
730/// # // (what sparse-ir passes), standing in for a BLAS library.
731/// # unsafe fn gemm_nn<T>(mnk: [usize; 3], alpha: T, a: *const T, lda: usize,
732/// #                    b: *const T, ldb: usize, beta: T, c: *mut T, ldc: usize)
733/// # where
734/// #     T: Copy + Default + PartialEq + Add<Output = T> + Mul<Output = T>,
735/// # {
736/// #     let [m, n, k] = mnk;
737/// #     for j in 0..n {
738/// #         for i in 0..m {
739/// #             let mut acc = T::default();
740/// #             for p in 0..k {
741/// #                 acc = acc + unsafe { *a.add(i + p * lda) * *b.add(p + j * ldb) };
742/// #             }
743/// #             let cij = unsafe { &mut *c.add(i + j * ldc) };
744/// #             *cij = if beta == T::default() { alpha * acc } else { alpha * acc + beta * *cij };
745/// #         }
746/// #     }
747/// # }
748/// # unsafe extern "C" fn my_dgemm64(
749/// #     _transa: *const c_char, _transb: *const c_char,
750/// #     m: *const i64, n: *const i64, k: *const i64,
751/// #     alpha: *const f64, a: *const f64, lda: *const i64,
752/// #     b: *const f64, ldb: *const i64,
753/// #     beta: *const f64, c: *mut f64, ldc: *const i64,
754/// # ) {
755/// #     unsafe {
756/// #         let mnk = [*m as usize, *n as usize, *k as usize];
757/// #         gemm_nn(mnk, *alpha, a, *lda as usize, b, *ldb as usize, *beta, c, *ldc as usize);
758/// #     }
759/// # }
760/// # unsafe extern "C" fn my_zgemm64(
761/// #     _transa: *const c_char, _transb: *const c_char,
762/// #     m: *const i64, n: *const i64, k: *const i64,
763/// #     alpha: *const Complex<f64>, a: *const Complex<f64>, lda: *const i64,
764/// #     b: *const Complex<f64>, ldb: *const i64,
765/// #     beta: *const Complex<f64>, c: *mut Complex<f64>, ldc: *const i64,
766/// # ) {
767/// #     unsafe {
768/// #         let mnk = [*m as usize, *n as usize, *k as usize];
769/// #         gemm_nn(mnk, *alpha, a, *lda as usize, b, *ldb as usize, *beta, c, *ldc as usize);
770/// #     }
771/// # }
772///
773/// // `my_dgemm64` and `my_zgemm64` are the ILP64 (64-bit integer) Fortran BLAS
774/// // `dgemm_` and `zgemm_` to use. (This example defines naive stand-ins in
775/// // hidden lines so that it runs without an ILP64 BLAS library.)
776/// unsafe {
777///     set_ilp64_backend(my_dgemm64, my_zgemm64);
778/// }
779/// assert_eq!(get_backend_info(), ("External BLAS (ILP64)", true, true));
780///
781/// // Calls without an explicit backend handle now go through the injected BLAS
782/// let a = tensor![[1.0, 2.0], [3.0, 4.0]];
783/// let b = tensor![[5.0, 6.0], [7.0, 8.0]];
784/// assert_eq!(matmul_par(&a, &b, None), tensor![[19.0, 22.0], [43.0, 50.0]]);
785///
786/// clear_blas_backend(); // back to the pure-Rust Faer backend
787/// let (_, is_external, is_ilp64) = get_backend_info();
788/// assert!(!is_external && !is_ilp64);
789/// ```
790pub unsafe fn set_ilp64_backend(dgemm64: Dgemm64FnPtr, zgemm64: Zgemm64FnPtr) {
791    let backend = ExternalBlas64Backend { dgemm64, zgemm64 };
792    let mut dispatcher = BLAS_DISPATCHER.write().unwrap();
793    *dispatcher = Box::new(backend);
794}
795
796/// Clear BLAS backend (reset to default Faer)
797///
798/// This function resets the GEMM dispatcher to use the default Pure Rust Faer backend.
799pub fn clear_blas_backend() {
800    let mut dispatcher = BLAS_DISPATCHER.write().unwrap();
801    *dispatcher = Box::new(FaerBackend);
802}
803
804/// Get current BLAS backend information
805///
806/// Returns:
807/// - `(backend_name, is_external, is_ilp64)`
808pub fn get_backend_info() -> (&'static str, bool, bool) {
809    let dispatcher = BLAS_DISPATCHER.read().unwrap();
810    let name = dispatcher.name();
811    let is_external = !name.contains("Faer");
812    let is_ilp64 = dispatcher.is_ilp64();
813    (name, is_external, is_ilp64)
814}
815
816//==============================================================================
817// Public API
818//==============================================================================
819
820/// Parallel matrix multiplication: C = A * B
821///
822/// Dispatches to the provided backend, or the global dispatcher if `None`.
823///
824/// # Arguments
825/// * `a` - Left matrix (M x K)
826/// * `b` - Right matrix (K x N)
827/// * `backend` - Optional backend handle. If `None`, uses global dispatcher (for backward compatibility)
828///
829/// # Returns
830/// Result matrix (M x N)
831///
832/// # Panics
833/// Panics if matrix dimensions are incompatible (A.cols != B.rows)
834///
835/// # Example
836/// ```
837/// use mdarray::tensor;
838/// use sparse_ir::gemm::{GemmBackendHandle, matmul_par};
839///
840/// let a = tensor![[1.0, 2.0], [3.0, 4.0]];
841/// let b = tensor![[5.0, 6.0], [7.0, 8.0]];
842/// let backend = GemmBackendHandle::default();
843/// let c = matmul_par(&a, &b, Some(&backend));
844/// assert_eq!(c, tensor![[19.0, 22.0], [43.0, 50.0]]);
845/// ```
846pub fn matmul_par<T>(
847    a: &DTensor<T, 2>,
848    b: &DTensor<T, 2>,
849    backend: Option<&GemmBackendHandle>,
850) -> DTensor<T, 2>
851where
852    T: num_complex::ComplexFloat + faer_traits::ComplexField + num_traits::One + Copy + 'static,
853{
854    let (_m, k) = *a.shape();
855    let (k2, _n) = *b.shape();
856
857    // Validate dimensions
858    assert_eq!(
859        k, k2,
860        "Matrix dimension mismatch: A.cols ({}) != B.rows ({})",
861        k, k2
862    );
863
864    // Use Faer directly to avoid creating intermediate DTensors through backend
865    // create _m x _n result tensor
866    let mut result = DTensor::<T, 2>::from_elem([_m, _n], T::zero().into());
867    matmul_par_overwrite(a, b, &mut result, backend);
868    result
869}
870
871/// Parallel matrix multiplication accepting DView (assumes contiguous memory)
872///
873/// This function accepts `DView` instead of `DTensor`, allowing views of arrays
874/// to be used directly without copying. The view must have contiguous memory layout.
875///
876/// # Arguments
877/// * `a` - Left matrix view (M x K) - must be contiguous
878/// * `b` - Right matrix view (K x N) - must be contiguous
879/// * `backend` - Optional backend handle. If `None`, uses global dispatcher
880///
881/// # Panics
882/// Panics if:
883/// - Matrix dimensions are incompatible (A.cols != B.rows)
884/// - Views are not contiguous in memory
885///
886/// # Example
887/// ```
888/// use mdarray::{DView, tensor};
889/// use sparse_ir::gemm::matmul_par_view;
890///
891/// let a = tensor![[1.0, 2.0], [3.0, 4.0]];
892/// let b = tensor![[5.0, 6.0], [7.0, 8.0]];
893/// let a_view: DView<'_, f64, 2> = a.view(.., ..);
894/// let b_view: DView<'_, f64, 2> = b.view(.., ..);
895/// let c = matmul_par_view(&a_view, &b_view, None);
896/// assert_eq!(c, tensor![[19.0, 22.0], [43.0, 50.0]]);
897/// ```
898pub fn matmul_par_view<T>(
899    a: &DView<'_, T, 2>,
900    b: &DView<'_, T, 2>,
901    backend: Option<&GemmBackendHandle>,
902) -> DTensor<T, 2>
903where
904    T: num_complex::ComplexFloat + faer_traits::ComplexField + num_traits::One + Copy + 'static,
905{
906    // Check that views are contiguous (required for BLAS operations)
907    assert!(
908        a.is_contiguous(),
909        "Matrix A view must be contiguous in memory"
910    );
911    assert!(
912        b.is_contiguous(),
913        "Matrix B view must be contiguous in memory"
914    );
915
916    let (m, k) = *a.shape();
917    let (k2, n) = *b.shape();
918
919    // Validate dimensions
920    assert_eq!(
921        k, k2,
922        "Matrix dimension mismatch: A.cols ({}) != B.rows ({})",
923        k, k2
924    );
925
926    // Create result tensor
927    let mut result = DTensor::<T, 2>::from_elem([m, n], T::zero().into());
928    matmul_par_overwrite_view(a, b, &mut result, backend);
929    result
930}
931
932/// Parallel matrix multiplication with overwrite accepting DView (assumes contiguous memory)
933///
934/// This function writes the result directly into the provided buffer `c`,
935/// accepting `DView` inputs. The views must have contiguous memory layout.
936///
937/// # Arguments
938/// * `a` - Left matrix view (M x K) - must be contiguous
939/// * `b` - Right matrix view (K x N) - must be contiguous
940/// * `c` - Output matrix (M x N) - will be overwritten with result
941/// * `backend` - Optional backend handle. If `None`, uses global dispatcher
942///
943/// # Panics
944/// Panics if:
945/// - Matrix dimensions are incompatible
946/// - Views are not contiguous in memory
947pub fn matmul_par_overwrite_view<T>(
948    a: &DView<'_, T, 2>,
949    b: &DView<'_, T, 2>,
950    c: &mut DTensor<T, 2>,
951    backend: Option<&GemmBackendHandle>,
952) where
953    T: num_complex::ComplexFloat + faer_traits::ComplexField + num_traits::One + Copy + 'static,
954{
955    // Check that views are contiguous (required for BLAS operations)
956    assert!(
957        a.is_contiguous(),
958        "Matrix A view must be contiguous in memory"
959    );
960    assert!(
961        b.is_contiguous(),
962        "Matrix B view must be contiguous in memory"
963    );
964
965    let (m, k) = *a.shape();
966    let (k2, n) = *b.shape();
967    let (mc, nc) = *c.shape();
968
969    // Validate dimensions
970    assert_eq!(
971        k, k2,
972        "Matrix dimension mismatch: A.cols ({}) != B.rows ({})",
973        k, k2
974    );
975    assert_eq!(
976        m, mc,
977        "Output matrix dimension mismatch: C.rows ({}) != A.rows ({})",
978        mc, m
979    );
980    assert_eq!(
981        n, nc,
982        "Output matrix dimension mismatch: C.cols ({}) != B.cols ({})",
983        nc, n
984    );
985
986    // Type dispatch: f64 or Complex<f64>
987    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
988        // f64 case
989        // Get pointers from views (contiguous memory assumed)
990        let a_ptr = a.as_ptr() as *const f64;
991        let b_ptr = b.as_ptr() as *const f64;
992        let c_ptr = c.as_mut_ptr() as *mut f64;
993
994        // Get backend: use provided handle or fall back to global dispatcher
995        match backend {
996            Some(handle) => unsafe {
997                handle.as_ref().dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
998            },
999            None => {
1000                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1001                unsafe {
1002                    dispatcher.dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1003                }
1004            }
1005        }
1006    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<num_complex::Complex<f64>>() {
1007        // Complex<f64> case
1008        let a_ptr = a.as_ptr() as *const num_complex::Complex<f64>;
1009        let b_ptr = b.as_ptr() as *const num_complex::Complex<f64>;
1010        let c_ptr = c.as_mut_ptr() as *mut num_complex::Complex<f64>;
1011
1012        match backend {
1013            Some(handle) => unsafe {
1014                handle.as_ref().zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1015            },
1016            None => {
1017                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1018                unsafe {
1019                    dispatcher.zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1020                }
1021            }
1022        }
1023    } else {
1024        // Fallback to Faer for unsupported types
1025        // Convert views to DTensors for Faer (this will copy, but only for unsupported types)
1026        let a_tensor = DTensor::<T, 2>::from_fn(*a.shape(), |idx| a[idx]);
1027        let b_tensor = DTensor::<T, 2>::from_fn(*b.shape(), |idx| b[idx]);
1028        use mdarray_linalg::matmul::MatMulBuilder;
1029        use mdarray_linalg::prelude::MatMul;
1030        use mdarray_linalg_faer::Faer;
1031
1032        Faer.matmul(&a_tensor, &b_tensor).parallelize().overwrite(c);
1033    }
1034}
1035
1036/// Parallel matrix multiplication with overwrite to mutable view: C = A * B
1037///
1038/// This function writes the result directly into the provided mutable view `c`,
1039/// allowing zero-copy writes to pre-allocated buffers (e.g., C pointers via FFI).
1040///
1041/// # Arguments
1042/// * `a` - Left matrix view (M x K), must be contiguous
1043/// * `b` - Right matrix view (K x N), must be contiguous
1044/// * `c` - Output mutable view (M x N), must be contiguous - will be overwritten
1045/// * `backend` - Optional backend handle. If `None`, uses global dispatcher
1046///
1047/// # Panics
1048/// Panics if:
1049/// - Matrix dimensions are incompatible
1050/// - Views are not contiguous in memory
1051pub fn matmul_par_to_viewmut<T>(
1052    a: &DView<'_, T, 2>,
1053    b: &DView<'_, T, 2>,
1054    c: &mut DViewMut<'_, T, 2>,
1055    backend: Option<&GemmBackendHandle>,
1056) where
1057    T: num_complex::ComplexFloat + faer_traits::ComplexField + num_traits::One + Copy + 'static,
1058{
1059    // Check that views are contiguous (required for BLAS operations)
1060    assert!(
1061        a.is_contiguous(),
1062        "Matrix A view must be contiguous in memory"
1063    );
1064    assert!(
1065        b.is_contiguous(),
1066        "Matrix B view must be contiguous in memory"
1067    );
1068    assert!(
1069        c.is_contiguous(),
1070        "Matrix C view must be contiguous in memory"
1071    );
1072
1073    let (m, k) = *a.shape();
1074    let (k2, n) = *b.shape();
1075    let (mc, nc) = *c.shape();
1076
1077    // Validate dimensions
1078    assert_eq!(
1079        k, k2,
1080        "Matrix dimension mismatch: A.cols ({}) != B.rows ({})",
1081        k, k2
1082    );
1083    assert_eq!(
1084        m, mc,
1085        "Output matrix dimension mismatch: C.rows ({}) != A.rows ({})",
1086        mc, m
1087    );
1088    assert_eq!(
1089        n, nc,
1090        "Output matrix dimension mismatch: C.cols ({}) != B.cols ({})",
1091        nc, n
1092    );
1093
1094    // Type dispatch: f64 or Complex<f64>
1095    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
1096        // f64 case
1097        let a_ptr = a.as_ptr() as *const f64;
1098        let b_ptr = b.as_ptr() as *const f64;
1099        let c_ptr = c.as_mut_ptr() as *mut f64;
1100
1101        match backend {
1102            Some(handle) => unsafe {
1103                handle.as_ref().dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1104            },
1105            None => {
1106                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1107                unsafe {
1108                    dispatcher.dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1109                }
1110            }
1111        }
1112    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<num_complex::Complex<f64>>() {
1113        // Complex<f64> case
1114        let a_ptr = a.as_ptr() as *const num_complex::Complex<f64>;
1115        let b_ptr = b.as_ptr() as *const num_complex::Complex<f64>;
1116        let c_ptr = c.as_mut_ptr() as *mut num_complex::Complex<f64>;
1117
1118        match backend {
1119            Some(handle) => unsafe {
1120                handle.as_ref().zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1121            },
1122            None => {
1123                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1124                unsafe {
1125                    dispatcher.zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1126                }
1127            }
1128        }
1129    } else {
1130        // Fallback: convert to DTensor (will copy)
1131        let a_tensor = DTensor::<T, 2>::from_fn(*a.shape(), |idx| a[idx]);
1132        let b_tensor = DTensor::<T, 2>::from_fn(*b.shape(), |idx| b[idx]);
1133        let mut c_tensor = DTensor::<T, 2>::from_fn(*c.shape(), |_| T::zero());
1134        use mdarray_linalg::matmul::MatMulBuilder;
1135        use mdarray_linalg::prelude::MatMul;
1136        use mdarray_linalg_faer::Faer;
1137
1138        Faer.matmul(&a_tensor, &b_tensor)
1139            .parallelize()
1140            .overwrite(&mut c_tensor);
1141
1142        // Copy back to view
1143        for i in 0..mc {
1144            for j in 0..nc {
1145                c[[i, j]] = c_tensor[[i, j]];
1146            }
1147        }
1148    }
1149}
1150
1151/// Parallel matrix multiplication with overwrite: C = A * B (writes to existing buffer)
1152///
1153/// This function writes the result directly into the provided buffer `c`,
1154/// avoiding memory allocation. This is more memory-efficient for repeated operations.
1155///
1156/// # Arguments
1157/// * `a` - Left matrix (M x K)
1158/// * `b` - Right matrix (K x N)
1159/// * `c` - Output matrix (M x N) - will be overwritten with result
1160/// * `backend` - Optional backend handle. If `None`, uses global dispatcher (for backward compatibility)
1161///
1162/// # Panics
1163/// Panics if matrix dimensions are incompatible (A.cols != B.rows or C.shape != [M, N])
1164pub fn matmul_par_overwrite<T, Lc: Layout>(
1165    a: &DTensor<T, 2>,
1166    b: &DTensor<T, 2>,
1167    c: &mut DSlice<T, 2, Lc>,
1168    backend: Option<&GemmBackendHandle>,
1169) where
1170    T: num_complex::ComplexFloat + faer_traits::ComplexField + num_traits::One + Copy + 'static,
1171{
1172    let (m, k) = *a.shape();
1173    let (k2, n) = *b.shape();
1174    let (mc, nc) = *c.shape();
1175
1176    // Validate dimensions
1177    assert_eq!(
1178        k, k2,
1179        "Matrix dimension mismatch: A.cols ({}) != B.rows ({})",
1180        k, k2
1181    );
1182    assert_eq!(
1183        m, mc,
1184        "Output matrix dimension mismatch: C.rows ({}) != A.rows ({})",
1185        mc, m
1186    );
1187    assert_eq!(
1188        n, nc,
1189        "Output matrix dimension mismatch: C.cols ({}) != B.cols ({})",
1190        nc, n
1191    );
1192
1193    // Type dispatch: f64 or Complex<f64>
1194    if std::any::TypeId::of::<T>() == std::any::TypeId::of::<f64>() {
1195        // f64 case
1196        // Get pointers directly from DTensors (row-major order)
1197        let a_ptr = a.as_ptr() as *const f64;
1198        let b_ptr = b.as_ptr() as *const f64;
1199        let c_ptr = c.as_mut_ptr() as *mut f64;
1200
1201        // Get backend: use provided handle or fall back to global dispatcher
1202        match backend {
1203            Some(handle) => {
1204                // Call backend directly with pointers (no temporary buffer needed)
1205                // Leading dimension is calculated internally in the backend
1206                unsafe {
1207                    handle.as_ref().dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1208                }
1209            }
1210            None => {
1211                // Backward compatibility: use global dispatcher
1212                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1213                unsafe {
1214                    dispatcher.dgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1215                }
1216            }
1217        }
1218    } else if std::any::TypeId::of::<T>() == std::any::TypeId::of::<num_complex::Complex<f64>>() {
1219        // Complex<f64> case
1220        // Get pointers directly from DTensors (row-major order)
1221        let a_ptr = a.as_ptr() as *const num_complex::Complex<f64>;
1222        let b_ptr = b.as_ptr() as *const num_complex::Complex<f64>;
1223        let c_ptr = c.as_mut_ptr() as *mut num_complex::Complex<f64>;
1224
1225        // Get backend: use provided handle or fall back to global dispatcher
1226        match backend {
1227            Some(handle) => {
1228                // Call backend directly with pointers (no temporary buffer needed)
1229                // Leading dimension is calculated internally in the backend
1230                unsafe {
1231                    handle.as_ref().zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1232                }
1233            }
1234            None => {
1235                // Backward compatibility: use global dispatcher
1236                let dispatcher = BLAS_DISPATCHER.read().unwrap();
1237                unsafe {
1238                    dispatcher.zgemm(m, n, k, a_ptr, b_ptr, c_ptr);
1239                }
1240            }
1241        }
1242    } else {
1243        // Fallback to Faer for unsupported types
1244        use mdarray_linalg::matmul::MatMulBuilder;
1245        use mdarray_linalg::prelude::MatMul;
1246        use mdarray_linalg_faer::Faer;
1247
1248        Faer.matmul(a, b).parallelize().overwrite(c);
1249    }
1250}
1251
1252#[cfg(test)]
1253mod tests {
1254    use super::*;
1255    use mdarray::DView;
1256
1257    #[test]
1258    #[cfg(not(feature = "system-blas"))]
1259    fn test_default_backend_is_faer() {
1260        let (name, is_external, is_ilp64) = get_backend_info();
1261        assert_eq!(name, "Faer (Pure Rust)");
1262        assert!(!is_external);
1263        assert!(!is_ilp64);
1264    }
1265
1266    #[test]
1267    fn test_matmul_par_view() {
1268        // Test with f64
1269        let a = DTensor::<f64, 2>::from([[1.0, 2.0], [3.0, 4.0]]);
1270        let b = DTensor::<f64, 2>::from([[5.0, 6.0], [7.0, 8.0]]);
1271        let a_view: DView<'_, f64, 2> = a.view(.., ..);
1272        let b_view: DView<'_, f64, 2> = b.view(.., ..);
1273
1274        let c_view = matmul_par_view(&a_view, &b_view, None);
1275        let c_expected = matmul_par(&a, &b, None);
1276
1277        // Results should be identical
1278        assert_eq!(c_view.shape(), c_expected.shape());
1279        for i in 0..c_view.shape().0 {
1280            for j in 0..c_view.shape().1 {
1281                assert!((c_view[[i, j]] - c_expected[[i, j]]).abs() < 1e-10);
1282            }
1283        }
1284    }
1285
1286    #[test]
1287    fn test_matmul_par_overwrite_view() {
1288        // Test with Complex<f64>
1289        use num_complex::Complex;
1290        let a = DTensor::<Complex<f64>, 2>::from_fn([2, 2], |idx| {
1291            Complex::new((idx[0] * 2 + idx[1]) as f64, 0.0)
1292        });
1293        let b = DTensor::<Complex<f64>, 2>::from_fn([2, 2], |idx| {
1294            Complex::new((idx[0] * 2 + idx[1] + 10) as f64, 0.0)
1295        });
1296        let a_view: DView<'_, Complex<f64>, 2> = a.view(.., ..);
1297        let b_view: DView<'_, Complex<f64>, 2> = b.view(.., ..);
1298
1299        let mut c_view = DTensor::<Complex<f64>, 2>::from_elem([2, 2], Complex::new(0.0, 0.0));
1300        matmul_par_overwrite_view(&a_view, &b_view, &mut c_view, None);
1301
1302        let c_expected = matmul_par(&a, &b, None);
1303
1304        // Results should be identical
1305        assert_eq!(c_view.shape(), c_expected.shape());
1306        for i in 0..c_view.shape().0 {
1307            for j in 0..c_view.shape().1 {
1308                assert!((c_view[[i, j]] - c_expected[[i, j]]).norm() < 1e-10);
1309            }
1310        }
1311    }
1312
1313    #[test]
1314    fn test_clear_backend() {
1315        // Should not panic
1316        clear_blas_backend();
1317        let (name, _, _) = get_backend_info();
1318        assert_eq!(name, "Faer (Pure Rust)");
1319    }
1320
1321    #[test]
1322    fn test_matmul_f64() {
1323        let a_data = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
1324        let b_data = [7.0, 8.0, 9.0, 10.0, 11.0, 12.0];
1325
1326        let a = DTensor::<f64, 2>::from_fn([2, 3], |idx| a_data[idx[0] * 3 + idx[1]]);
1327        let b = DTensor::<f64, 2>::from_fn([3, 2], |idx| b_data[idx[0] * 2 + idx[1]]);
1328        let c = matmul_par(&a, &b, None);
1329
1330        assert_eq!(*c.shape(), (2, 2));
1331        // First row: [1*7+2*9+3*11, 1*8+2*10+3*12] = [58, 64]
1332        // Second row: [4*7+5*9+6*11, 4*8+5*10+6*12] = [139, 154]
1333        assert!((c[[0, 0]] - 58.0).abs() < 1e-10);
1334        assert!((c[[0, 1]] - 64.0).abs() < 1e-10);
1335        assert!((c[[1, 0]] - 139.0).abs() < 1e-10);
1336        assert!((c[[1, 1]] - 154.0).abs() < 1e-10);
1337    }
1338
1339    #[test]
1340    fn test_matmul_par_basic() {
1341        use mdarray::tensor;
1342        let a: DTensor<f64, 2> = tensor![[1.0, 2.0], [3.0, 4.0]];
1343        let b: DTensor<f64, 2> = tensor![[5.0, 6.0], [7.0, 8.0]];
1344        let c = matmul_par(&a, &b, None);
1345
1346        // Expected: [[1*5+2*7, 1*6+2*8], [3*5+4*7, 3*6+4*8]]
1347        //         = [[19, 22], [43, 50]]
1348        assert!((c[[0, 0]] - 19.0).abs() < 1e-10);
1349        assert!((c[[0, 1]] - 22.0).abs() < 1e-10);
1350        assert!((c[[1, 0]] - 43.0).abs() < 1e-10);
1351        assert!((c[[1, 1]] - 50.0).abs() < 1e-10);
1352    }
1353
1354    #[test]
1355    fn test_matmul_par_non_square() {
1356        use mdarray::tensor;
1357        let a: DTensor<f64, 2> = tensor![[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]; // 2x3
1358        let b: DTensor<f64, 2> = tensor![[7.0], [8.0], [9.0]]; // 3x1
1359        let c = matmul_par(&a, &b, None);
1360
1361        // Expected: [[1*7+2*8+3*9], [4*7+5*8+6*9]]
1362        //         = [[50], [122]]
1363        assert!((c[[0, 0]] - 50.0).abs() < 1e-10);
1364        assert!((c[[1, 0]] - 122.0).abs() < 1e-10);
1365    }
1366}