use super::super::super::WgpuRuntime;
use crate::error::Result;
use crate::ops::matmul::matmul_mkn;
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
pub(crate) fn promote_rank1_operands(
a: &Tensor<WgpuRuntime>,
b: &Tensor<WgpuRuntime>,
) -> Result<Option<(Tensor<WgpuRuntime>, Tensor<WgpuRuntime>)>> {
if a.shape().len() != 1 && b.shape().len() != 1 {
return Ok(None);
}
let a2 = if a.shape().len() == 1 {
ensure_contiguous(a)?.reshape(&[1, a.shape()[0]])?
} else {
a.clone()
};
let b2 = if b.shape().len() == 1 {
ensure_contiguous(b)?.reshape(&[b.shape()[0], 1])?
} else {
b.clone()
};
Ok(Some((a2, b2)))
}
pub(crate) fn flatten_batched_operands(
a: &Tensor<WgpuRuntime>,
b: &Tensor<WgpuRuntime>,
out_shape: &[usize],
) -> Result<Option<(Tensor<WgpuRuntime>, Tensor<WgpuRuntime>)>> {
if out_shape.len() <= 2 {
return Ok(None);
}
let a_shape = a.shape();
let b_shape = b.shape();
let out_batch = &out_shape[..out_shape.len() - 2];
let (m, k, n) = matmul_mkn(a_shape, b_shape);
let a_target: Vec<usize> = out_batch.iter().copied().chain([m, k]).collect();
let b_target: Vec<usize> = out_batch.iter().copied().chain([k, n]).collect();
if out_shape.len() == 3 && a_shape == a_target.as_slice() && b_shape == b_target.as_slice() {
return Ok(None);
}
let batch: usize = out_batch.iter().product();
let a3 = a
.broadcast_to(&a_target)?
.contiguous()?
.reshape(&[batch, m, k])?;
let b3 = b
.broadcast_to(&b_target)?
.contiguous()?
.reshape(&[batch, k, n])?;
Ok(Some((a3, b3)))
}