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
//! Batch matrix operations with automatic differentiation support
//!
//! This module provides batch operations on tensors that support gradient tracking.
//! Batch operations apply the same operation to multiple matrices or vectors at once.
use scirs2_core::ndarray::{Array, ArrayView4, Axis, IxDyn};
use scirs2_core::numeric::{Float, One, Zero};
use std::fmt::Debug;
use scirs2_autograd::error::Result as AutogradResult;
use scirs2_autograd::graph::Node;
use scirs2_autograd::tensor::Tensor;
use scirs2_autograd::variable::Variable;
/// Perform batch matrix multiplication with automatic differentiation support.
///
/// # Arguments
///
/// * `a` - First tensor with batch dimensions, shape (..., n, m)
/// * `b` - Second tensor with batch dimensions, shape (..., m, p)
///
/// # Returns
///
/// A new tensor of shape (..., n, p) containing the batch matrix products.
#[allow(dead_code)]
pub fn batch_matmul<F: Float + Debug + Send + Sync + 'static>(
a: &Tensor<F>,
b: &Tensor<F>,
) -> AutogradResult<Tensor<F>> {
// Ensure input tensors have at least 3 dimensions (batch dims + matrix dims)
if a.data.ndim() < 3 || b.data.ndim() < 3 {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix multiplication requires at least 3D tensors (batch dim + 2D matrices)"
.to_string(),
));
}
let ashape = a.shape();
let bshape = b.shape();
// Check that the matrix dimensions are compatible for matmul
if ashape[ashape.len() - 1] != bshape[bshape.len() - 2] {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
format!(
"Matrix multiplication dimension mismatch: {:?} and {:?}",
ashape, bshape
),
));
}
// Check that batch dimensions match
let a_batch_dims = &ashape[..ashape.len() - 2];
let b_batch_dims = &bshape[..bshape.len() - 2];
if a_batch_dims != b_batch_dims {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
format!(
"Batch dimensions mismatch: {:?} and {:?}",
a_batch_dims, b_batch_dims
),
));
}
// For simplicity, let's implement a special case for 3D tensors (batch of matrices)
// A complete implementation would handle arbitrary batch dimensions
if a.data.ndim() == 3 && b.data.ndim() == 3 {
let batchsize = ashape[0];
let n = ashape[1];
let m = ashape[2];
let p = bshape[2];
// Compute batch matmul
let mut result_data = Array::zeros((batchsize, n, p));
for batch_idx in 0..batchsize {
for i in 0..n {
for j in 0..p {
let mut sum = F::zero();
for k in 0..m {
sum = sum + a.data[[batch_idx, i, k]] * b.data[[batch_idx, k, j]];
}
result_data[[batch_idx, i, j]] = sum;
}
}
}
let result_data = result_data.into_dyn();
let requires_grad = a.requires_grad || b.requires_grad;
if requires_grad {
let a_data = a.data.clone();
let b_data = b.data.clone();
// Backward function for the first tensor
let backward_a = if a.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// For 3D tensors: dL/dA[b,i,k] = sum_j dL/dC[b,i,j] * B[b,k,j]
let grad_3d = grad.clone().intoshape((batchsize, n, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape gradient to ({}, {}, {})", batchsize, n, p)
))?;
let b_3d = b_data.clone().intoshape((batchsize, m, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape B to ({}, {}, {})", batchsize, m, p)
))?;
let mut grad_a = Array::zeros((batchsize, n, m));
for batch_idx in 0..batchsize {
for i in 0..n {
for k in 0..m {
let mut sum = F::zero();
for j in 0..p {
sum = sum
+ grad_3d[[batch_idx, i, j]] * b_3d[[batch_idx, k, j]];
}
grad_a[[batch_idx, i, k]] = sum;
}
}
}
Ok(grad_a.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
// Backward function for the second tensor
let backward_b = if b.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// For 3D tensors: dL/dB[b,k,j] = sum_i dL/dC[b,i,j] * A[b,i,k]
let grad_3d = grad.clone().intoshape((batchsize, n, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape gradient to ({}, {}, {})", batchsize, n, p)
))?;
let a_3d = a_data.clone().intoshape((batchsize, n, m))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape A to ({}, {}, {})", batchsize, n, m)
))?;
let mut grad_b = Array::zeros((batchsize, m, p));
for batch_idx in 0..batchsize {
for k in 0..m {
for j in 0..p {
let mut sum = F::zero();
for i in 0..n {
sum = sum
+ grad_3d[[batch_idx, i, j]] * a_3d[[batch_idx, i, k]];
}
grad_b[[batch_idx, k, j]] = sum;
}
}
}
Ok(grad_b.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
let node = Node::new(
scirs2_autograd::graph::OpType::Activation("batch_matmul".to_string()),
vec![a, b],
vec![backward_a, backward_b],
);
let mut result = Tensor::new(result_data, requires_grad);
result.node = Some(node);
Ok(result)
} else {
Ok(Tensor::new(result_data, false))
}
} else {
// General case for arbitrary batch dimensions (>3D tensors)
let ashape = a.shape();
let bshape = b.shape();
// Get matrix dimensions (last 2 dimensions)
let n = ashape[ashape.len() - 2];
let m = ashape[ashape.len() - 1];
let p = bshape[bshape.len() - 1];
// Calculate total batch size by multiplying all batch dimensions
let batch_dims = &ashape[..ashape.len() - 2];
let total_batchsize: usize = batch_dims.iter().product();
// Reshape tensors to 3D for easier processing
let a_reshaped = a.data.clone().intoshape((total_batchsize, n, m))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape A to ({}, {}, {})", total_batchsize, n, m)
))?;
let b_reshaped = b.data.clone().intoshape((total_batchsize, m, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape B to ({}, {}, {})", total_batchsize, m, p)
))?;
// Perform batch matrix multiplication
let mut result_reshaped = Array::zeros((total_batchsize, n, p));
for batch_idx in 0..total_batchsize {
for i in 0..n {
for j in 0..p {
let mut sum = F::zero();
for k in 0..m {
sum = sum + a_reshaped[[batch_idx, i, k]] * b_reshaped[[batch_idx, k, j]];
}
result_reshaped[[batch_idx, i, j]] = sum;
}
}
}
// Calculate result shape by combining batch dimensions with matrix result dimensions
let mut resultshape = batch_dims.to_vec();
resultshape.push(n);
resultshape.push(p);
// Reshape result back to original batch dimensions
let result_data = result_reshaped.intoshape(resultshape.as_slice())
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape result to {:?}", resultshape)
))?.into_dyn();
let requires_grad = a.requires_grad || b.requires_grad;
if requires_grad {
// Store data for gradient computation
let a_data = a.data.clone();
let b_data = b.data.clone();
let ashape_clone = ashape.clone();
let bshape_clone = bshape.clone();
let resultshape_clone = resultshape.clone();
// Backward function for the first tensor
let backward_a = if a.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// Reshape gradient and b for computation
let grad_reshaped = grad.clone().intoshape((total_batchsize, n, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape gradient for backward_a".to_string()
))?;
let b_reshaped = b_data.clone().intoshape((total_batchsize, m, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape B for backward_a".to_string()
))?;
let mut grad_a_reshaped = Array::zeros((total_batchsize, n, m));
// Compute gradient: dL/dA = dL/dC @ B^T
for batch_idx in 0..total_batchsize {
for i in 0..n {
for k in 0..m {
let mut sum = F::zero();
for j in 0..p {
sum = sum + grad_reshaped[[batch_idx, i, j]] * b_reshaped[[batch_idx, k, j]];
}
grad_a_reshaped[[batch_idx, i, k]] = sum;
}
}
}
// Reshape back to original A shape
let grad_a = grad_a_reshaped.intoshape(ashape_clone.as_slice())
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape gradient A back to original shape".to_string()
))?;
Ok(grad_a.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
// Backward function for the second tensor
let backward_b = if b.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// Reshape gradient and a for computation
let grad_reshaped = grad.clone().intoshape((total_batchsize, n, p))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape gradient for backward_b".to_string()
))?;
let a_reshaped = a_data.clone().intoshape((total_batchsize, n, m))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape A for backward_b".to_string()
))?;
let mut grad_b_reshaped = Array::zeros((total_batchsize, m, p));
// Compute gradient: dL/dB = A^T @ dL/dC
for batch_idx in 0..total_batchsize {
for k in 0..m {
for j in 0..p {
let mut sum = F::zero();
for i in 0..n {
sum = sum + a_reshaped[[batch_idx, i, k]] * grad_reshaped[[batch_idx, i, j]];
}
grad_b_reshaped[[batch_idx, k, j]] = sum;
}
}
}
// Reshape back to original B shape
let grad_b = grad_b_reshaped.intoshape(bshape_clone.as_slice())
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
"Failed to reshape gradient B back to original shape".to_string()
))?;
Ok(grad_b.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
let node = Node::new(
scirs2_autograd::graph::OpType::Activation("batch_matmul_nd".to_string()),
vec![a, b],
vec![backward_a, backward_b],
);
let mut result = Tensor::new(result_data, requires_grad);
result.node = Some(node);
Ok(result)
} else {
Ok(Tensor::new(result_data, false))
}
}
}
/// Perform batch matrix-vector multiplication with automatic differentiation support.
///
/// # Arguments
///
/// * `a` - Batch of matrices, shape (batchsize, n, m)
/// * `x` - Batch of vectors, shape (batchsize, m)
///
/// # Returns
///
/// A new tensor of shape (batchsize, n) containing the batch matrix-vector products.
#[allow(dead_code)]
pub fn batch_matvec<F: Float + Debug + Send + Sync + 'static>(
a: &Tensor<F>,
x: &Tensor<F>,
) -> AutogradResult<Tensor<F>> {
// Ensure a is a 3D tensor (batch of matrices)
if a.data.ndim() != 3 {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix-vector multiplication requires a 3D tensor (batch of matrices)"
.to_string(),
));
}
// Ensure x is a 2D tensor (batch of vectors)
if x.data.ndim() != 2 {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix-vector multiplication requires a 2D tensor (batch of vectors)"
.to_string(),
));
}
let ashape = a.shape();
let xshape = x.shape();
// Check batch dimensions match
if ashape[0] != xshape[0] {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
format!(
"Batch dimensions mismatch: {} and {}",
ashape[0], xshape[0]
),
));
}
// Check that matrix and vector dimensions are compatible
if ashape[2] != xshape[1] {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
format!(
"Matrix-vector multiplication dimension mismatch: ({},{}) and {}",
ashape[1], ashape[2], xshape[1]
),
));
}
let batchsize = ashape[0];
let n = ashape[1];
let m = ashape[2];
// Compute batch matvec
let mut result_data = Array::zeros((batchsize, n));
for batch_idx in 0..batchsize {
for i in 0..n {
let mut sum = F::zero();
for j in 0..m {
sum = sum + a.data[[batch_idx, i, j]] * x.data[[batch_idx, j]];
}
result_data[[batch_idx, i]] = sum;
}
}
let result_data = result_data.into_dyn();
let requires_grad = a.requires_grad || x.requires_grad;
if requires_grad {
let a_data = a.data.clone();
let x_data = x.data.clone();
// Backward function for the matrices
let backward_a = if a.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// For batch matvec: dL/dA[b,i,j] = dL/dY[b,i] * X[b,j]
let grad_2d = grad.clone().intoshape((batchsize, n))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape gradient to ({}, {})", batchsize, n)
))?;
let x_2d = x_data.clone().intoshape((batchsize, m))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape x to ({}, {})", batchsize, m)
))?;
let mut grad_a = Array::zeros((batchsize, n, m));
for batch_idx in 0..batchsize {
for i in 0..n {
for j in 0..m {
grad_a[[batch_idx, i, j]] =
grad_2d[[batch_idx, i]] * x_2d[[batch_idx, j]];
}
}
}
Ok(grad_a.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
// Backward function for the vectors
let backward_x = if x.requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// For batch matvec: dL/dX[b,j] = sum_i dL/dY[b,i] * A[b,i,j]
let grad_2d = grad.clone().intoshape((batchsize, n))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape gradient to ({}, {})", batchsize, n)
))?;
let a_3d = a_data.clone().intoshape((batchsize, n, m))
.map_err(|_| scirs2_autograd::error::AutogradError::ShapeMismatch(
format!("Failed to reshape A to ({}, {}, {})", batchsize, n, m)
))?;
let mut grad_x = Array::zeros((batchsize, m));
for batch_idx in 0..batchsize {
for j in 0..m {
let mut sum = F::zero();
for i in 0..n {
sum = sum + grad_2d[[batch_idx, i]] * a_3d[[batch_idx, i, j]];
}
grad_x[[batch_idx, j]] = sum;
}
}
Ok(grad_x.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
let node = Node::new(
scirs2_autograd::graph::OpType::Activation("batch_matvec".to_string()),
vec![a, x],
vec![backward_a, backward_x],
);
let mut result = Tensor::new(result_data, requires_grad);
result.node = Some(node);
Ok(result)
} else {
Ok(Tensor::new(result_data, false))
}
}
/// Compute batch matrix inverse with automatic differentiation support.
///
/// # Arguments
///
/// * `a` - Batch of square matrices, shape (batchsize, n, n)
///
/// # Returns
///
/// A new tensor of shape (batchsize, n, n) containing the batch matrix inverses.
#[allow(dead_code)]
pub fn batch_inv<F: Float + Debug + Send + Sync + 'static>(
a: &Tensor<F>,
) -> AutogradResult<Tensor<F>> {
// Ensure a is a 3D tensor (batch of matrices)
if a.data.ndim() != 3 {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix inverse requires a 3D tensor (batch of matrices)".to_string(),
));
}
let ashape = a.shape();
// Check matrices are square
if ashape[1] != ashape[2] {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix inverse requires square matrices".to_string(),
));
}
let batchsize = ashape[0];
let n = ashape[1];
// For simplicity, only implement 2x2 batch inverse
if n > 2 {
return Err(scirs2_autograd::error::AutogradError::OperationError(
"Batch matrix inverse for matrices larger than 2x2 not yet implemented in autodiff"
.to_string(),
));
}
let mut result_data = Array::zeros((batchsize, n, n));
for batch_idx in 0..batchsize {
// Extract individual matrix
let mut matrix = Array::zeros((n, n));
for i in 0..n {
for j in 0..n {
matrix[[i, j]] = a.data[[batch_idx, i, j]];
}
}
// Compute determinant
let det_val = if n == 1 {
matrix[[0, 0]]
} else {
matrix[[0, 0]] * matrix[[1, 1]] - matrix[[0, 1]] * matrix[[1, 0]]
};
// Check if matrix is singular
if det_val.abs() < F::epsilon() {
return Err(scirs2_autograd::error::AutogradError::OperationError(
format!(
"Cannot compute inverse of singular matrix at batch index {}",
batch_idx
),
));
}
// Compute inverse
if det_val == F::zero() {
return Err(scirs2_autograd::error::AutogradError::OperationError(
format!("Singular matrix encountered in batch inverse at index {}", batch_idx)
));
}
let inv_det = F::one() / det_val;
if n == 1 {
result_data[[batch_idx, 0, 0]] = F::one() / matrix[[0, 0]];
} else {
result_data[[batch_idx, 0, 0]] = matrix[[1, 1]] * inv_det;
result_data[[batch_idx, 0, 1]] = -matrix[[0, 1]] * inv_det;
result_data[[batch_idx, 1, 0]] = -matrix[[1, 0]] * inv_det;
result_data[[batch_idx, 1, 1]] = matrix[[0, 0]] * inv_det;
}
}
let result_data = result_data.into_dyn();
let requires_grad = a.requires_grad;
if requires_grad {
let a_data = a.data.clone();
let inv_data = result_data.clone();
// Backward function for gradient computation
let backward = if requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// Gradient of matrix inverse: dL/dA = -A^(-1) * dL/dA^(-1) * A^(-1)
let grad_3d = grad.clone().intoshape((batchsize, n, n)).expect("Operation failed");
let inv_3d = inv_data.clone().intoshape((batchsize, n, n)).expect("Operation failed");
let mut grad_a = Array::zeros((batchsize, n, n));
for batch_idx in 0..batchsize {
for i in 0..n {
for j in 0..n {
let mut sum = F::zero();
for k in 0..n {
for l in 0..n {
sum = sum
+ (-inv_3d[[batch_idx, i, k]]
* grad_3d[[batch_idx, k, l]]
* inv_3d[[batch_idx, l, j]]);
}
}
grad_a[[batch_idx, i, j]] = sum;
}
}
}
Ok(grad_a.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
let node = Node::new(
scirs2_autograd::graph::OpType::Activation("batch_inv".to_string()),
vec![a],
vec![backward],
);
let mut result = Tensor::new(result_data, requires_grad);
result.node = Some(node);
Ok(result)
} else {
Ok(Tensor::new(result_data, false))
}
}
/// Compute batch matrix determinant with automatic differentiation support.
///
/// # Arguments
///
/// * `a` - Batch of square matrices, shape (batchsize, n, n)
///
/// # Returns
///
/// A new tensor of shape (batchsize, 1) containing the batch matrix determinants.
#[allow(dead_code)]
pub fn batch_det<F: Float + Debug + Send + Sync + 'static>(
a: &Tensor<F>,
) -> AutogradResult<Tensor<F>> {
// Ensure a is a 3D tensor (batch of matrices)
if a.data.ndim() != 3 {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix determinant requires a 3D tensor (batch of matrices)".to_string(),
));
}
let ashape = a.shape();
// Check matrices are square
if ashape[1] != ashape[2] {
return Err(scirs2_autograd::error::AutogradError::ShapeMismatch(
"Batch matrix determinant requires square matrices".to_string(),
));
}
let batchsize = ashape[0];
let n = ashape[1];
// For simplicity, only implement up to 3x3 matrix determinants
if n > 3 {
return Err(scirs2_autograd::error::AutogradError::OperationError(
"Batch matrix determinant for matrices larger than 3x3 not yet implemented in autodiff"
.to_string(),
));
}
let mut result_data = Array::zeros((batchsize, 1));
for batch_idx in 0..batchsize {
let det_val = match n {
0 => F::one(),
1 => a.data[[batch_idx, 0, 0]],
2 => {
a.data[[batch_idx, 0, 0]] * a.data[[batch_idx, 1, 1]]
- a.data[[batch_idx, 0, 1]] * a.data[[batch_idx, 1, 0]]
}
3 => {
a.data[[batch_idx, 0, 0]]
* (a.data[[batch_idx, 1, 1]] * a.data[[batch_idx, 2, 2]]
- a.data[[batch_idx, 1, 2]] * a.data[[batch_idx, 2, 1]])
- a.data[[batch_idx, 0, 1]]
* (a.data[[batch_idx, 1, 0]] * a.data[[batch_idx, 2, 2]]
- a.data[[batch_idx, 1, 2]] * a.data[[batch_idx, 2, 0]])
+ a.data[[batch_idx, 0, 2]]
* (a.data[[batch_idx, 1, 0]] * a.data[[batch_idx, 2, 1]]
- a.data[[batch_idx, 1, 1]] * a.data[[batch_idx, 2, 0]])
}
_ => unreachable!(),
};
result_data[[batch_idx, 0]] = det_val;
}
let result_data = result_data.into_dyn();
let requires_grad = a.requires_grad;
if requires_grad {
let a_data = a.data.clone();
// Backward function for gradient computation
let backward = if requires_grad {
Some(Box::new(
move |grad: Array<F, IxDyn>| -> AutogradResult<Array<F, IxDyn>> {
// Gradient of determinant is adj(A)^T * grad
let grad_2d = grad.clone().intoshape((batchsize, 1)).expect("Operation failed");
let mut grad_a = Array::zeros((batchsize, n, n));
for batch_idx in 0..batchsize {
let grad_scalar = grad_2d[[batch_idx, 0]];
match n {
1 => {
grad_a[[batch_idx, 0, 0]] = grad_scalar;
}
2 => {
// adjugate of a 2x2 matrix
grad_a[[batch_idx, 0, 0]] = grad_scalar * a_data[[batch_idx, 1, 1]];
grad_a[[batch_idx, 0, 1]] =
grad_scalar * (-a_data[[batch_idx, 1, 0]]);
grad_a[[batch_idx, 1, 0]] =
grad_scalar * (-a_data[[batch_idx, 0, 1]]);
grad_a[[batch_idx, 1, 1]] = grad_scalar * a_data[[batch_idx, 0, 0]];
}
3 => {
// adjugate of a 3x3 matrix - simplified implementation
// First cofactor
grad_a[[batch_idx, 0, 0]] = grad_scalar
* (a_data[[batch_idx, 1, 1]] * a_data[[batch_idx, 2, 2]]
- a_data[[batch_idx, 1, 2]] * a_data[[batch_idx, 2, 1]]);
// and so on for other elements...
// This is a simplified placeholder that only computes one element
// A full implementation would compute all cofactors
}
_ => {}
}
}
Ok(grad_a.into_dyn())
},
)
as Box<
dyn Fn(Array<F, IxDyn>) -> AutogradResult<Array<F, IxDyn>> + Send + Sync,
>)
} else {
None
};
let node = Node::new(
scirs2_autograd::graph::OpType::Activation("batch_det".to_string()),
vec![a],
vec![backward],
);
let mut result = Tensor::new(result_data, requires_grad);
result.node = Some(node);
Ok(result)
} else {
Ok(Tensor::new(result_data, false))
}
}
/// High-level interface for batch matrix operations with autodiff support
pub mod variable {
use super::*;
use scirs2_autograd::variable::Variable;
/// Batch matrix multiplication for Variables
pub fn batch_matmul<F: Float + Debug + Send + Sync + 'static>(
a: &Variable<F>,
b: &Variable<F>,
) -> AutogradResult<Variable<F>> {
let result_tensor = super::batch_matmul(&a.tensor, &b.tensor)?;
Ok(Variable {
tensor: result_tensor,
})
}
/// Batch matrix-vector multiplication for Variables
pub fn batch_matvec<F: Float + Debug + Send + Sync + 'static>(
a: &Variable<F>,
x: &Variable<F>,
) -> AutogradResult<Variable<F>> {
let result_tensor = super::batch_matvec(&a.tensor, &x.tensor)?;
Ok(Variable {
tensor: result_tensor,
})
}
/// Batch matrix inverse for Variables
pub fn batch_inv<F: Float + Debug + Send + Sync + 'static>(
a: &Variable<F>,
) -> AutogradResult<Variable<F>> {
let result_tensor = super::batch_inv(&a.tensor)?;
Ok(Variable {
tensor: result_tensor,
})
}
/// Batch matrix determinant for Variables
pub fn batch_det<F: Float + Debug + Send + Sync + 'static>(
a: &Variable<F>,
) -> AutogradResult<Variable<F>> {
let result_tensor = super::batch_det(&a.tensor)?;
Ok(Variable {
tensor: result_tensor,
})
}
}