scirs2-linalg 0.4.2

Linear algebra module for SciRS2 (scirs2-linalg)
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
//! Batch matrix operations for AI/ML workloads
//!
//! This module provides matrix operations optimized for processing batches of data,
//! which is especially useful for machine learning applications such as mini-batch
//! gradient descent, convolutional neural networks, and transformer models.

use scirs2_core::ndarray::{
    Array, Array2, Array3, ArrayView1, ArrayView2, ArrayView3, Axis, ScalarOperand,
};
use scirs2_core::numeric::{Float, NumAssign};
use std::iter::Sum;

use crate::error::{LinalgError, LinalgResult};

// Re-export batch attention operations
pub mod attention;
pub use attention::{
    batch_flash_attention, batch_multi_head_attention, batch_multi_query_attention,
};

// Batch BLAS-like operations
pub mod operations;
pub use operations::{
    batch_cholesky, batch_det, batch_frobenius_norm, batch_inverse, batch_matmul_pairwise,
    batch_solve, batch_solve_matrix, batch_trace, batch_transpose,
};

/// Perform matrix multiplication on a batch of matrices
///
/// Computes a batch multiplication where the input represents multiple matrices
/// that need to be multiplied with the same right-hand side matrix.
///
/// # Arguments
///
/// * `batch_a` - 3D array of shape (batchsize, m, k) representing the batch of matrices
/// * `b` - 2D array of shape (k, n) representing the right-hand side matrix
///
/// # Returns
///
/// * 3D array of shape (batchsize, m, n) containing the result of each batch multiplication
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array3};
/// use scirs2_linalg::batch::batch_matmul;
///
/// // Create a batch of 2 matrices, each 2x2
/// let batch_a = Array3::from_shape_vec((2, 2, 2), vec![
///     1.0, 2.0,  // First matrix: [[1.0, 2.0],
///     3.0, 4.0,  //               [3.0, 4.0]]
///     5.0, 6.0,  // Second matrix: [[5.0, 6.0],
///     7.0, 8.0   //                [7.0, 8.0]]
/// ]).expect("Operation failed");
///
/// // Create a 2x1 matrix to multiply with each batch matrix
/// let b = array![[10.0], [20.0]];
///
/// // Perform batch multiplication
/// let result = batch_matmul(&batch_a.view(), &b.view()).expect("Operation failed");
///
/// // Expected results:
/// // First result: [[1.0, 2.0], [3.0, 4.0]] × [[10.0], [20.0]] = [[50.0], [110.0]]
/// // Second result: [[5.0, 6.0], [7.0, 8.0]] × [[10.0], [20.0]] = [[170.0], [230.0]]
/// assert_eq!(result.shape(), &[2, 2, 1]);
/// assert_eq!(result[[0, 0, 0]], 50.0);
/// assert_eq!(result[[0, 1, 0]], 110.0);
/// assert_eq!(result[[1, 0, 0]], 170.0);
/// assert_eq!(result[[1, 1, 0]], 230.0);
/// ```
/// Threshold for using BLAS-accelerated matmul vs naive implementation.
/// For small matrices, naive implementation may be faster due to overhead.
const BATCH_MATMUL_SIMD_THRESHOLD: usize = 64;

#[allow(dead_code)]
pub fn batch_matmul<F>(batch_a: &ArrayView3<F>, b: &ArrayView2<F>) -> LinalgResult<Array3<F>>
where
    F: Float + NumAssign + Sum + Send + Sync + ScalarOperand + 'static,
{
    // Check dimensions compatibility
    let (batchsize, m, k1) = batch_a.dim();
    let (k2, n) = b.dim();

    if k1 != k2 {
        return Err(LinalgError::ShapeError(format!(
            "Inner dimensions mismatch for batch_matmul: {k1} vs {k2}"
        )));
    }

    // Initialize result array
    let mut result = Array::zeros((batchsize, m, n));

    // Use BLAS-accelerated path for larger matrices (Phase 35 optimization)
    let work_size = m * k1 * n;
    if work_size >= BATCH_MATMUL_SIMD_THRESHOLD {
        // BLAS-accelerated path: use matmul for each batch element
        for batch_idx in 0..batchsize {
            // Extract the batch element as a 2D view
            let a_slice = batch_a.slice(scirs2_core::ndarray::s![batch_idx, .., ..]);

            // Use BLAS-accelerated matmul (3-5x faster for large matrices)
            let batch_result = crate::blas_accelerated::matmul(&a_slice, b)?;

            // Copy result to output array
            result
                .slice_mut(scirs2_core::ndarray::s![batch_idx, .., ..])
                .assign(&batch_result);
        }
    } else {
        // Naive path for small matrices (overhead avoidance)
        for batch_idx in 0..batchsize {
            for i in 0..m {
                for j in 0..n {
                    let mut sum = F::zero();
                    for k in 0..k1 {
                        sum += batch_a[[batch_idx, i, k]] * b[[k, j]];
                    }
                    result[[batch_idx, i, j]] = sum;
                }
            }
        }
    }

    Ok(result)
}

/// Batch matrix-vector multiplication
///
/// Performs matrix-vector multiplication for a batch of matrices with a single vector.
///
/// # Arguments
///
/// * `batch_a` - 3D array of shape (batchsize, m, n) representing the batch of matrices
/// * `x` - Vector of length n
///
/// # Returns
///
/// * 2D array of shape (batchsize, m) containing the result of each matrix-vector multiplication
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array3};
/// use scirs2_linalg::batch::batch_matvec;
///
/// // Create a batch of 2 matrices, each 2x2
/// let batch_a = Array3::from_shape_vec((2, 2, 2), vec![
///     1.0, 2.0,  // First matrix: [[1.0, 2.0],
///     3.0, 4.0,  //               [3.0, 4.0]]
///     5.0, 6.0,  // Second matrix: [[5.0, 6.0],
///     7.0, 8.0   //                [7.0, 8.0]]
/// ]).expect("Operation failed");
///
/// // Create a vector to multiply with each batch matrix
/// let x = array![10.0, 20.0];
///
/// // Perform batch matrix-vector multiplication
/// let result = batch_matvec(&batch_a.view(), &x.view()).expect("Operation failed");
///
/// // Expected results:
/// // First result: [[1.0, 2.0], [3.0, 4.0]] × [10.0, 20.0] = [50.0, 110.0]
/// // Second result: [[5.0, 6.0], [7.0, 8.0]] × [10.0, 20.0] = [170.0, 230.0]
/// assert_eq!(result.shape(), &[2, 2]);
/// assert_eq!(result[[0, 0]], 50.0);
/// assert_eq!(result[[0, 1]], 110.0);
/// assert_eq!(result[[1, 0]], 170.0);
/// assert_eq!(result[[1, 1]], 230.0);
/// ```
#[allow(dead_code)]
pub fn batch_matvec<F>(batch_a: &ArrayView3<F>, x: &ArrayView1<F>) -> LinalgResult<Array2<F>>
where
    F: Float
        + NumAssign
        + Sum
        + Send
        + Sync
        + ScalarOperand
        + scirs2_core::simd_ops::SimdUnifiedOps
        + 'static,
{
    // Check dimensions compatibility
    let (batchsize, m, n) = batch_a.dim();
    let x_len = x.len();

    if n != x_len {
        return Err(LinalgError::ShapeError(format!(
            "Dimension mismatch for batch_matvec: matrix width {n} does not match vector length {x_len}"
        )));
    }

    // Initialize result array
    let mut result = Array::zeros((batchsize, m));

    // Use SIMD-accelerated dot products (Phase 35 optimization)
    // For each batch element, compute matrix-vector product using SIMD dot
    if n >= 8 {
        // SIMD path: use simd_dot for each row
        for batch_idx in 0..batchsize {
            for i in 0..m {
                // Extract row as contiguous view
                let row = batch_a.slice(scirs2_core::ndarray::s![batch_idx, i, ..]);
                // Use SIMD-accelerated dot product
                result[[batch_idx, i]] = F::simd_dot(&row, x);
            }
        }
    } else {
        // Scalar fallback for small vectors (SIMD overhead not worth it)
        for batch_idx in 0..batchsize {
            for i in 0..m {
                let mut sum = F::zero();
                for j in 0..n {
                    sum += batch_a[[batch_idx, i, j]] * x[j];
                }
                result[[batch_idx, i]] = sum;
            }
        }
    }

    Ok(result)
}

/// Add a vector to each matrix in a batch
///
/// Adds a vector to each row or column of each matrix in the batch,
/// supporting broadcasting.
///
/// # Arguments
///
/// * `batch_a` - 3D array of shape (batchsize, m, n) representing the batch of matrices
/// * `v` - Vector to add to each matrix in the batch
/// * `axis` - Axis along which to add the vector (0 for column-wise, 1 for row-wise)
///
/// # Returns
///
/// * 3D array of shape (batchsize, m, n) containing the result
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array3, Axis};
/// use scirs2_linalg::batch::batch_add;
///
/// // Create a batch of 2 matrices, each 2x2
/// let batch_a = Array3::from_shape_vec((2, 2, 2), vec![
///     1.0, 2.0,  // First matrix: [[1.0, 2.0],
///     3.0, 4.0,  //               [3.0, 4.0]]
///     5.0, 6.0,  // Second matrix: [[5.0, 6.0],
///     7.0, 8.0   //                [7.0, 8.0]]
/// ]).expect("Operation failed");
///
/// // Create a vector to add to each row of each matrix
/// let v = array![10.0, 20.0];
///
/// // Add to each row (axis=1)
/// let result = batch_add(&batch_a.view(), &v.view(), 1).expect("Operation failed");
///
/// // Expected results:
/// // First matrix: [[1.0+10.0, 2.0+20.0], [3.0+10.0, 4.0+20.0]] = [[11.0, 22.0], [13.0, 24.0]]
/// // Second matrix: [[5.0+10.0, 6.0+20.0], [7.0+10.0, 8.0+20.0]] = [[15.0, 26.0], [17.0, 28.0]]
/// assert_eq!(result.shape(), &[2, 2, 2]);
/// assert_eq!(result[[0, 0, 0]], 11.0);
/// assert_eq!(result[[0, 0, 1]], 22.0);
/// assert_eq!(result[[0, 1, 0]], 13.0);
/// assert_eq!(result[[0, 1, 1]], 24.0);
/// assert_eq!(result[[1, 0, 0]], 15.0);
/// assert_eq!(result[[1, 0, 1]], 26.0);
/// assert_eq!(result[[1, 1, 0]], 17.0);
/// assert_eq!(result[[1, 1, 1]], 28.0);
/// ```
#[allow(dead_code)]
pub fn batch_add<F>(
    batch_a: &ArrayView3<F>,
    v: &ArrayView1<F>,
    axis: usize,
) -> LinalgResult<Array3<F>>
where
    F: Float + NumAssign + Sum + Send + Sync + ScalarOperand + 'static,
{
    // Check dimensions compatibility
    let (batchsize, m, n) = batch_a.dim();

    // Check if vector dimension is compatible with the specified axis
    match axis {
        0 => {
            // Column-wise addition: vector length should match m
            if v.len() != m {
                return Err(LinalgError::ShapeError(format!(
                    "Column-wise batch_add requires vector length {} to match number of rows {}, got {}",
                    m, m, v.len()
                )));
            }
        }
        1 => {
            // Row-wise addition: vector length should match n
            if v.len() != n {
                return Err(LinalgError::ShapeError(format!(
                    "Row-wise batch_add requires vector length {} to match number of columns {}, got {}",
                    n, n, v.len()
                )));
            }
        }
        _ => {
            return Err(LinalgError::InvalidInputError(format!(
                "Invalid axis {axis}: must be 0 (column-wise) or 1 (row-wise)"
            )));
        }
    }

    // Initialize result array with _a copy of the input batch
    let mut result = batch_a.to_owned();

    // Perform batch addition
    match axis {
        0 => {
            // Column-wise addition (add to each column)
            for batch_idx in 0..batchsize {
                for i in 0..m {
                    for j in 0..n {
                        result[[batch_idx, i, j]] += v[i];
                    }
                }
            }
        }
        1 => {
            // Row-wise addition (add to each row)
            for batch_idx in 0..batchsize {
                for i in 0..m {
                    for j in 0..n {
                        result[[batch_idx, i, j]] += v[j];
                    }
                }
            }
        }
        _ => unreachable!(), // Already validated above
    }

    Ok(result)
}

/// Compute the sum of a batch of matrices
///
/// Sums the matrices in a batch along the batch dimension.
///
/// # Arguments
///
/// * `batch_a` - 3D array of shape (batchsize, m, n) representing the batch of matrices
///
/// # Returns
///
/// * 2D array of shape (m, n) containing the sum of all matrices in the batch
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::{array, Array3};
/// use scirs2_linalg::batch::batch_sum;
///
/// // Create a batch of 2 matrices, each 2x2
/// let batch_a = Array3::from_shape_vec((2, 2, 2), vec![
///     1.0, 2.0,  // First matrix: [[1.0, 2.0],
///     3.0, 4.0,  //               [3.0, 4.0]]
///     5.0, 6.0,  // Second matrix: [[5.0, 6.0],
///     7.0, 8.0   //                [7.0, 8.0]]
/// ]).expect("Operation failed");
///
/// // Compute the sum of all matrices in the batch
/// let result = batch_sum(&batch_a.view());
///
/// // Expected result: [[1.0, 2.0], [3.0, 4.0]] + [[5.0, 6.0], [7.0, 8.0]] = [[6.0, 8.0], [10.0, 12.0]]
/// assert_eq!(result.shape(), &[2, 2]);
/// assert_eq!(result[[0, 0]], 6.0);
/// assert_eq!(result[[0, 1]], 8.0);
/// assert_eq!(result[[1, 0]], 10.0);
/// assert_eq!(result[[1, 1]], 12.0);
/// ```
#[allow(dead_code)]
pub fn batch_sum<F>(batch_a: &ArrayView3<F>) -> Array2<F>
where
    F: Float + NumAssign + Sum + Send + Sync + ScalarOperand + 'static,
{
    batch_a.sum_axis(Axis(0))
}

#[cfg(test)]
mod tests {
    use super::*;
    use approx::assert_relative_eq;
    use scirs2_core::ndarray::{array, Array3};

    #[test]
    fn test_batch_matmul() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Create a 2x2 matrix to multiply with each batch matrix
        let b = array![[1.0, 2.0], [3.0, 4.0]];

        // Perform batch multiplication
        let result = batch_matmul(&batch_a.view(), &b.view()).expect("Operation failed");

        // Expected results:
        // First result: [[1.0, 2.0], [3.0, 4.0]] × [[1.0, 2.0], [3.0, 4.0]] = [[7.0, 10.0], [15.0, 22.0]]
        // Second result: [[5.0, 6.0], [7.0, 8.0]] × [[1.0, 2.0], [3.0, 4.0]] = [[23.0, 34.0], [31.0, 46.0]]
        assert_eq!(result.shape(), &[2, 2, 2]);
        assert_relative_eq!(result[[0, 0, 0]], 7.0);
        assert_relative_eq!(result[[0, 0, 1]], 10.0);
        assert_relative_eq!(result[[0, 1, 0]], 15.0);
        assert_relative_eq!(result[[0, 1, 1]], 22.0);
        assert_relative_eq!(result[[1, 0, 0]], 23.0);
        assert_relative_eq!(result[[1, 0, 1]], 34.0);
        assert_relative_eq!(result[[1, 1, 0]], 31.0);
        assert_relative_eq!(result[[1, 1, 1]], 46.0);
    }

    #[test]
    fn test_batch_matvec() {
        // Create a batch of 2 matrices, each 2x3
        let batch_a = Array3::from_shape_vec(
            (2, 2, 3),
            vec![
                1.0, 2.0, 3.0, // First matrix: [[1.0, 2.0, 3.0],
                4.0, 5.0, 6.0, //               [4.0, 5.0, 6.0]]
                7.0, 8.0, 9.0, // Second matrix: [[7.0, 8.0, 9.0],
                10.0, 11.0, 12.0, //              [10.0, 11.0, 12.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector to multiply with each batch matrix
        let x = array![1.0, 2.0, 3.0];

        // Perform batch matrix-vector multiplication
        let result = batch_matvec(&batch_a.view(), &x.view()).expect("Operation failed");

        // Expected results:
        // First result: [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] × [1.0, 2.0, 3.0] = [14.0, 32.0]
        // Second result: [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]] × [1.0, 2.0, 3.0] = [50.0, 68.0]
        assert_eq!(result.shape(), &[2, 2]);
        assert_relative_eq!(result[[0, 0]], 14.0);
        assert_relative_eq!(result[[0, 1]], 32.0);
        assert_relative_eq!(result[[1, 0]], 50.0);
        assert_relative_eq!(result[[1, 1]], 68.0);
    }

    #[test]
    fn test_batch_add_row_wise() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector to add to each row of each matrix
        let v = array![10.0, 20.0];

        // Add to each row (axis=1)
        let result = batch_add(&batch_a.view(), &v.view(), 1).expect("Operation failed");

        // Expected results:
        // First matrix: [[1.0+10.0, 2.0+20.0], [3.0+10.0, 4.0+20.0]] = [[11.0, 22.0], [13.0, 24.0]]
        // Second matrix: [[5.0+10.0, 6.0+20.0], [7.0+10.0, 8.0+20.0]] = [[15.0, 26.0], [17.0, 28.0]]
        assert_eq!(result.shape(), &[2, 2, 2]);
        assert_relative_eq!(result[[0, 0, 0]], 11.0);
        assert_relative_eq!(result[[0, 0, 1]], 22.0);
        assert_relative_eq!(result[[0, 1, 0]], 13.0);
        assert_relative_eq!(result[[0, 1, 1]], 24.0);
        assert_relative_eq!(result[[1, 0, 0]], 15.0);
        assert_relative_eq!(result[[1, 0, 1]], 26.0);
        assert_relative_eq!(result[[1, 1, 0]], 17.0);
        assert_relative_eq!(result[[1, 1, 1]], 28.0);
    }

    #[test]
    fn test_batch_add_column_wise() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector to add to each column of each matrix
        let v = array![10.0, 20.0];

        // Add to each column (axis=0)
        let result = batch_add(&batch_a.view(), &v.view(), 0).expect("Operation failed");

        // Expected results:
        // First matrix: [[1.0+10.0, 2.0+10.0], [3.0+20.0, 4.0+20.0]] = [[11.0, 12.0], [23.0, 24.0]]
        // Second matrix: [[5.0+10.0, 6.0+10.0], [7.0+20.0, 8.0+20.0]] = [[15.0, 16.0], [27.0, 28.0]]
        assert_eq!(result.shape(), &[2, 2, 2]);
        assert_relative_eq!(result[[0, 0, 0]], 11.0);
        assert_relative_eq!(result[[0, 0, 1]], 12.0);
        assert_relative_eq!(result[[0, 1, 0]], 23.0);
        assert_relative_eq!(result[[0, 1, 1]], 24.0);
        assert_relative_eq!(result[[1, 0, 0]], 15.0);
        assert_relative_eq!(result[[1, 0, 1]], 16.0);
        assert_relative_eq!(result[[1, 1, 0]], 27.0);
        assert_relative_eq!(result[[1, 1, 1]], 28.0);
    }

    #[test]
    fn test_batch_sum() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Compute the sum of all matrices in the batch
        let result = batch_sum(&batch_a.view());

        // Expected result: [[1.0, 2.0], [3.0, 4.0]] + [[5.0, 6.0], [7.0, 8.0]] = [[6.0, 8.0], [10.0, 12.0]]
        assert_eq!(result.shape(), &[2, 2]);
        assert_relative_eq!(result[[0, 0]], 6.0);
        assert_relative_eq!(result[[0, 1]], 8.0);
        assert_relative_eq!(result[[1, 0]], 10.0);
        assert_relative_eq!(result[[1, 1]], 12.0);
    }

    #[test]
    fn test_batch_matmul_dimension_error() {
        // Create a batch of 2 matrices, each 2x3
        let batch_a = Array3::from_shape_vec(
            (2, 2, 3),
            vec![
                1.0, 2.0, 3.0, // First matrix: [[1.0, 2.0, 3.0],
                4.0, 5.0, 6.0, //               [4.0, 5.0, 6.0]]
                7.0, 8.0, 9.0, // Second matrix: [[7.0, 8.0, 9.0],
                10.0, 11.0, 12.0, //              [10.0, 11.0, 12.0]]
            ],
        )
        .expect("Operation failed");

        // Create a 2x2 matrix (incompatible dimensions)
        let b = array![[1.0, 2.0], [3.0, 4.0]];

        // Batch multiplication should fail with dimension error
        let result = batch_matmul(&batch_a.view(), &b.view());
        assert!(result.is_err());
    }

    #[test]
    fn test_batch_matvec_dimension_error() {
        // Create a batch of 2 matrices, each 2x3
        let batch_a = Array3::from_shape_vec(
            (2, 2, 3),
            vec![
                1.0, 2.0, 3.0, // First matrix: [[1.0, 2.0, 3.0],
                4.0, 5.0, 6.0, //               [4.0, 5.0, 6.0]]
                7.0, 8.0, 9.0, // Second matrix: [[7.0, 8.0, 9.0],
                10.0, 11.0, 12.0, //              [10.0, 11.0, 12.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector with incompatible dimension
        let x = array![1.0, 2.0];

        // Batch matrix-vector multiplication should fail with dimension error
        let result = batch_matvec(&batch_a.view(), &x.view());
        assert!(result.is_err());
    }

    #[test]
    fn test_batch_add_dimension_error() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector with incompatible dimension
        let v = array![10.0, 20.0, 30.0];

        // Batch addition should fail with dimension error
        let result = batch_add(&batch_a.view(), &v.view(), 1);
        assert!(result.is_err());
    }

    #[test]
    fn test_batch_add_invalid_axis() {
        // Create a batch of 2 matrices, each 2x2
        let batch_a = Array3::from_shape_vec(
            (2, 2, 2),
            vec![
                1.0, 2.0, // First matrix: [[1.0, 2.0],
                3.0, 4.0, //               [3.0, 4.0]]
                5.0, 6.0, // Second matrix: [[5.0, 6.0],
                7.0, 8.0, //                [7.0, 8.0]]
            ],
        )
        .expect("Operation failed");

        // Create a vector
        let v = array![10.0, 20.0];

        // Batch addition with invalid axis should fail
        let result = batch_add(&batch_a.view(), &v.view(), 2);
        assert!(result.is_err());
    }
}