use super::super::CudaRuntime;
use crate::error::Result;
use crate::ops::matmul::matmul_batch_indices;
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
pub(crate) fn batch_count(shape: &[usize]) -> usize {
shape
.iter()
.take(shape.len().saturating_sub(2))
.product::<usize>()
.max(1)
}
fn modulo_indexing_is_correct(operand_shape: &[usize], out_shape: &[usize], is_lhs: bool) -> bool {
let operand_batch = &operand_shape[..operand_shape.len().saturating_sub(2)];
let out_batch = &out_shape[..out_shape.len().saturating_sub(2)];
if operand_batch == out_batch || batch_count(operand_shape) == 1 {
return true;
}
let (a_idx, b_idx) = if is_lhs {
matmul_batch_indices(operand_shape, out_shape, out_shape)
} else {
matmul_batch_indices(out_shape, operand_shape, out_shape)
};
let indices = if is_lhs { a_idx } else { b_idx };
let count = batch_count(operand_shape);
indices.iter().enumerate().all(|(i, &idx)| i % count == idx)
}
fn materialize_batch_broadcast(
operand: &Tensor<CudaRuntime>,
out_shape: &[usize],
is_lhs: bool,
) -> Result<Option<Tensor<CudaRuntime>>> {
if modulo_indexing_is_correct(operand.shape(), out_shape, is_lhs) {
return Ok(None);
}
let shape = operand.shape();
let mut target: Vec<usize> = out_shape[..out_shape.len().saturating_sub(2)].to_vec();
target.extend_from_slice(&shape[shape.len().saturating_sub(2)..]);
Ok(Some(operand.broadcast_to(&target)?.contiguous()?))
}
pub(crate) struct BatchedOperands {
pub a: Tensor<CudaRuntime>,
pub b: Tensor<CudaRuntime>,
pub a_batch: usize,
pub b_batch: usize,
}
pub(crate) fn resolve_batched_operands(
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
out_shape: &[usize],
) -> Result<BatchedOperands> {
let a = materialize_batch_broadcast(a, out_shape, true)?.unwrap_or_else(|| a.clone());
let b = materialize_batch_broadcast(b, out_shape, false)?.unwrap_or_else(|| b.clone());
let a_batch = batch_count(a.shape());
let b_batch = batch_count(b.shape());
Ok(BatchedOperands {
a,
b,
a_batch,
b_batch,
})
}
pub(crate) fn expand_batched_operands(
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
out_shape: &[usize],
) -> Result<(Tensor<CudaRuntime>, Tensor<CudaRuntime>)> {
let out_batch = &out_shape[..out_shape.len().saturating_sub(2)];
let expand = |t: &Tensor<CudaRuntime>| -> Result<Tensor<CudaRuntime>> {
let shape = t.shape();
let mat_start = shape.len().saturating_sub(2);
if &shape[..mat_start] == out_batch {
return ensure_contiguous(t);
}
let target: Vec<usize> = out_batch
.iter()
.chain(&shape[mat_start..])
.copied()
.collect();
t.broadcast_to(&target)?.contiguous()
};
Ok((expand(a)?, expand(b)?))
}
impl BatchedOperands {
pub(crate) fn contiguous(&self) -> Result<(Tensor<CudaRuntime>, Tensor<CudaRuntime>)> {
Ok((ensure_contiguous(&self.a)?, ensure_contiguous(&self.b)?))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_modulo_indexing_correct_for_leading_broadcast() {
assert!(modulo_indexing_is_correct(
&[1, 4, 2, 3],
&[2, 4, 3, 3],
false
));
}
#[test]
fn test_modulo_indexing_wrong_for_middle_broadcast() {
assert!(!modulo_indexing_is_correct(
&[2, 1, 2, 1],
&[2, 4, 3, 1],
false
));
}
#[test]
fn test_modulo_indexing_correct_for_equal_batches() {
assert!(modulo_indexing_is_correct(
&[2, 4, 3, 2],
&[2, 4, 3, 3],
true
));
}
#[test]
fn test_modulo_indexing_correct_for_unbatched() {
assert!(modulo_indexing_is_correct(&[3, 2], &[3, 4], true));
}
#[test]
fn test_fast_paths_agree_with_index_check() {
let cases: &[(&[usize], &[usize], bool)] = &[
(&[2, 4, 3, 2], &[2, 4, 3, 3], true),
(&[1, 4, 2, 3], &[2, 4, 3, 3], false),
(&[2, 1, 2, 1], &[2, 4, 3, 1], false),
(&[4, 2, 3], &[2, 4, 3, 3], false),
(&[2, 1, 3, 2], &[2, 4, 3, 3], true),
(&[3, 2], &[3, 4], true),
];
for &(operand, out, is_lhs) in cases {
let (a_idx, b_idx) = if is_lhs {
matmul_batch_indices(operand, out, out)
} else {
matmul_batch_indices(out, operand, out)
};
let indices = if is_lhs { a_idx } else { b_idx };
let count = batch_count(operand);
let expected = indices.iter().enumerate().all(|(i, &idx)| i % count == idx);
assert_eq!(
modulo_indexing_is_correct(operand, out, is_lhs),
expected,
"operand={operand:?} out={out:?} is_lhs={is_lhs}"
);
}
}
}