#[derive(Copy, Clone, Debug)]
pub struct MatmulParams {
pub m: usize,
pub k: usize,
pub n: usize,
pub trans_a: bool,
pub trans_b: bool,
pub batch: usize,
}
impl MatmulParams {
pub fn new(m: usize, k: usize, n: usize) -> Self {
Self {
m,
k,
n,
trans_a: false,
trans_b: false,
batch: 1,
}
}
pub fn batched(batch: usize, m: usize, k: usize, n: usize) -> Self {
Self {
m,
k,
n,
trans_a: false,
trans_b: false,
batch,
}
}
pub fn with_trans_a(mut self, trans: bool) -> Self {
self.trans_a = trans;
self
}
pub fn with_trans_b(mut self, trans: bool) -> Self {
self.trans_b = trans;
self
}
pub fn output_shape(&self) -> Vec<usize> {
if self.batch > 1 {
vec![self.batch, self.m, self.n]
} else {
vec![self.m, self.n]
}
}
}
pub fn validate_matmul_shapes(
a_shape: &[usize],
b_shape: &[usize],
) -> Option<(usize, usize, usize)> {
let (a_rows, a_cols) = match a_shape.len() {
0 => return None,
1 => (1, a_shape[0]),
_ => {
let ndim = a_shape.len();
(a_shape[ndim - 2], a_shape[ndim - 1])
}
};
let (b_rows, b_cols) = match b_shape.len() {
0 => return None,
1 => (b_shape[0], 1),
_ => {
let ndim = b_shape.len();
(b_shape[ndim - 2], b_shape[ndim - 1])
}
};
if a_cols != b_rows {
return None;
}
Some((a_rows, a_cols, b_cols))
}
pub fn matmul_output_shape(a_shape: &[usize], b_shape: &[usize]) -> Option<Vec<usize>> {
let (m, _k, n) = validate_matmul_shapes(a_shape, b_shape)?;
let a_batch: Vec<_> = a_shape
.iter()
.take(a_shape.len().saturating_sub(2))
.copied()
.collect();
let b_batch: Vec<_> = b_shape
.iter()
.take(b_shape.len().saturating_sub(2))
.copied()
.collect();
let batch = super::broadcast_shape(&a_batch, &b_batch)?;
let mut result = batch;
result.push(m);
result.push(n);
Some(result)
}
pub fn matmul_batch_indices(
a_shape: &[usize],
b_shape: &[usize],
out_shape: &[usize],
) -> (Vec<usize>, Vec<usize>) {
let out_batch = &out_shape[..out_shape.len().saturating_sub(2)];
let a_batch = &a_shape[..a_shape.len().saturating_sub(2)];
let b_batch = &b_shape[..b_shape.len().saturating_sub(2)];
let total: usize = out_batch.iter().product();
let mut a_indices = Vec::with_capacity(total);
let mut b_indices = Vec::with_capacity(total);
let mut coord = vec![0usize; out_batch.len()];
let project = |coord: &[usize], batch: &[usize]| -> usize {
let offset = coord.len() - batch.len();
let mut idx = 0;
for (d, &size) in batch.iter().enumerate() {
let c = if size == 1 { 0 } else { coord[offset + d] };
idx = idx * size + c;
}
idx
};
for flat in 0..total {
let mut rem = flat;
for d in (0..out_batch.len()).rev() {
coord[d] = rem % out_batch[d];
rem /= out_batch[d];
}
a_indices.push(project(&coord, a_batch));
b_indices.push(project(&coord, b_batch));
}
(a_indices, b_indices)
}
pub fn matmul_mkn(a_shape: &[usize], b_shape: &[usize]) -> (usize, usize, usize) {
let m = if a_shape.len() >= 2 {
a_shape[a_shape.len() - 2]
} else {
1
};
let k = a_shape[a_shape.len() - 1];
let n = if b_shape.len() >= 2 {
b_shape[b_shape.len() - 1]
} else {
1
};
(m, k, n)
}
pub fn matmul_dims_and_batches(
a_shape: &[usize],
b_shape: &[usize],
out_shape: &[usize],
) -> (usize, usize, usize, usize, Vec<usize>, Vec<usize>) {
let (m, k, n) = matmul_mkn(a_shape, b_shape);
let batch_size: usize = out_shape
.iter()
.take(out_shape.len().saturating_sub(2))
.product();
let (a_batch_idx, b_batch_idx) = matmul_batch_indices(a_shape, b_shape, out_shape);
(m, k, n, batch_size, a_batch_idx, b_batch_idx)
}
pub fn is_transposed_b(b_shape: &[usize], b_strides: &[isize], k: usize, n: usize) -> bool {
let ndim = b_shape.len();
if ndim < 2 || b_strides.len() != ndim || k == 0 || n == 0 {
return false;
}
if b_strides[ndim - 2] != 1 || b_strides[ndim - 1] != k as isize {
return false;
}
let mut expected = (n * k) as isize;
for d in (0..ndim - 2).rev() {
if b_shape[d] != 1 && b_strides[d] != expected {
return false;
}
expected *= b_shape[d] as isize;
}
true
}
pub fn validate_matmul_bias_shapes(
a_shape: &[usize],
b_shape: &[usize],
bias_shape: &[usize],
) -> Option<(usize, usize, usize)> {
let (m, k, n) = validate_matmul_shapes(a_shape, b_shape)?;
if bias_shape.len() != 1 {
return None;
}
if bias_shape[0] != n {
return None;
}
Some((m, k, n))
}
pub fn matmul_bias_output_shape(
a_shape: &[usize],
b_shape: &[usize],
bias_shape: &[usize],
) -> Option<Vec<usize>> {
validate_matmul_bias_shapes(a_shape, b_shape, bias_shape)?;
matmul_output_shape(a_shape, b_shape)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_matmul_mkn_rank1_operands() {
assert_eq!(matmul_mkn(&[5, 7], &[7]), (5, 7, 1));
assert_eq!(matmul_mkn(&[7], &[7, 3]), (1, 7, 3));
assert_eq!(matmul_mkn(&[7], &[7]), (1, 7, 1));
assert_eq!(matmul_output_shape(&[5, 7], &[7]), Some(vec![5, 1]));
assert_eq!(matmul_output_shape(&[3, 5, 7], &[7]), Some(vec![3, 5, 1]));
let (m, k, n, batch, a_idx, b_idx) = matmul_dims_and_batches(&[3, 5, 7], &[7], &[3, 5, 1]);
assert_eq!((m, k, n, batch), (5, 7, 1, 3));
assert_eq!(a_idx, vec![0, 1, 2]);
assert_eq!(b_idx, vec![0, 0, 0]);
}
#[test]
fn test_matmul_batch_indices_middle_broadcast() {
let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[2, 1, 2, 1], &[2, 4, 3, 1]);
assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(b, vec![0, 0, 0, 0, 1, 1, 1, 1]);
}
#[test]
fn test_matmul_batch_indices_leading_broadcast() {
let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[1, 4, 2, 3], &[2, 4, 3, 3]);
assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
}
#[test]
fn test_matmul_batch_indices_fewer_batch_dims() {
let (a, b) = matmul_batch_indices(&[2, 4, 3, 2], &[4, 2, 3], &[2, 4, 3, 3]);
assert_eq!(a, vec![0, 1, 2, 3, 4, 5, 6, 7]);
assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
}
#[test]
fn test_matmul_batch_indices_both_broadcast() {
let (a, b) = matmul_batch_indices(&[2, 1, 3, 2], &[1, 4, 2, 3], &[2, 4, 3, 3]);
assert_eq!(a, vec![0, 0, 0, 0, 1, 1, 1, 1]);
assert_eq!(b, vec![0, 1, 2, 3, 0, 1, 2, 3]);
}
#[test]
fn test_matmul_batch_indices_unbatched() {
let (a, b) = matmul_batch_indices(&[3, 2], &[2, 4], &[3, 4]);
assert_eq!(a, vec![0]);
assert_eq!(b, vec![0]);
}
#[test]
fn test_validate_matmul_shapes() {
assert_eq!(validate_matmul_shapes(&[2, 3], &[3, 4]), Some((2, 3, 4)));
assert_eq!(validate_matmul_shapes(&[2, 3], &[4, 5]), None);
assert_eq!(validate_matmul_shapes(&[3], &[3, 4]), Some((1, 3, 4)));
assert_eq!(validate_matmul_shapes(&[2, 3], &[3]), Some((2, 3, 1)));
}
#[test]
fn test_matmul_output_shape() {
assert_eq!(matmul_output_shape(&[2, 3], &[3, 4]), Some(vec![2, 4]));
assert_eq!(
matmul_output_shape(&[5, 2, 3], &[5, 3, 4]),
Some(vec![5, 2, 4])
);
assert_eq!(
matmul_output_shape(&[5, 2, 3], &[3, 4]),
Some(vec![5, 2, 4])
);
}
#[test]
fn test_validate_matmul_bias_shapes() {
assert_eq!(
validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[4]),
Some((2, 3, 4))
);
assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[4, 5], &[5]), None);
assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[2, 4]), None);
assert_eq!(validate_matmul_bias_shapes(&[2, 3], &[3, 4], &[3]), None);
assert_eq!(
validate_matmul_bias_shapes(&[5, 2, 3], &[5, 3, 4], &[4]),
Some((2, 3, 4))
);
}
#[test]
fn test_matmul_bias_output_shape() {
assert_eq!(
matmul_bias_output_shape(&[2, 3], &[3, 4], &[4]),
Some(vec![2, 4])
);
assert_eq!(
matmul_bias_output_shape(&[5, 2, 3], &[5, 3, 4], &[4]),
Some(vec![5, 2, 4])
);
assert_eq!(matmul_bias_output_shape(&[2, 3], &[3, 4], &[3]), None);
}
#[test]
fn test_is_transposed_b_simple_transpose() {
assert!(is_transposed_b(&[4, 3], &[1, 4], 4, 3));
}
#[test]
fn test_is_transposed_b_rejects_contiguous() {
assert!(!is_transposed_b(&[4, 3], &[3, 1], 4, 3));
}
#[test]
fn test_is_transposed_b_rejects_zero_and_negative_strides() {
assert!(!is_transposed_b(&[4, 3], &[0, 4], 4, 3));
assert!(!is_transposed_b(&[4, 3], &[1, -4], 4, 3));
assert!(!is_transposed_b(&[4, 3], &[-1, 4], 4, 3));
}
#[test]
fn test_is_transposed_b_rejects_degenerate_dims() {
assert!(!is_transposed_b(&[0, 3], &[1, 0], 0, 3));
assert!(!is_transposed_b(&[4, 0], &[1, 4], 4, 0));
assert!(!is_transposed_b(&[3], &[1], 3, 1));
}
#[test]
fn test_is_transposed_b_batched_dense() {
assert!(is_transposed_b(&[2, 4, 3], &[12, 1, 4], 4, 3));
assert!(is_transposed_b(&[5, 2, 4, 3], &[24, 12, 1, 4], 4, 3));
}
#[test]
fn test_is_transposed_b_rejects_sliced_batch() {
assert!(!is_transposed_b(&[2, 4, 3], &[24, 1, 4], 4, 3));
}
#[test]
fn test_is_transposed_b_ignores_size_one_batch_stride() {
assert!(is_transposed_b(&[1, 4, 3], &[999, 1, 4], 4, 3));
}
}