use super::common::should_fuse_multi_dim_reduction;
use super::multi_dim::reduce_multi_dim_fused;
use super::single_dim::reduce_single_dim;
use crate::dispatch_dtype;
use crate::error::{Error, Result};
use crate::ops::{AccumulationPrecision, Kernel, ReduceOp, reduce_output_shape};
use crate::runtime::cpu::{CpuClient, CpuRuntime};
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
pub fn reduce_impl(
client: &CpuClient,
op: ReduceOp,
a: &Tensor<CpuRuntime>,
dims: &[usize],
keepdim: bool,
op_name: &'static str,
) -> Result<Tensor<CpuRuntime>> {
let dtype = a.dtype();
let shape = a.shape();
let ndim = shape.len();
for &d in dims {
if d >= ndim {
return Err(Error::InvalidDimension {
dim: d as isize,
ndim,
});
}
}
if dims.len() == 1 && dims[0] == ndim - 1 && a.is_contiguous() {
let reduce_size = shape[ndim - 1];
let outer_size: usize = shape[..ndim - 1].iter().product();
let out_shape = reduce_output_shape(shape, dims, keepdim);
let out = Tensor::<CpuRuntime>::empty(&out_shape, dtype, &client.device)?;
let a_ptr = a.ptr();
let out_ptr = out.ptr();
dispatch_dtype!(dtype, T => {
unsafe {
<CpuClient as Kernel<CpuRuntime>>::reduce::<T>(
client,
op,
a_ptr as *const T,
out_ptr as *mut T,
reduce_size,
outer_size,
);
}
}, op_name);
Ok(out)
} else if dims.is_empty() && ndim == 0 {
ensure_contiguous(a)
} else if dims.is_empty() {
let all_dims: Vec<usize> = (0..ndim).collect();
return reduce_impl(client, op, a, &all_dims, keepdim, op_name);
} else if dtype.is_int() && dims.len() > 1 && matches!(op, ReduceOp::Mean) {
let a_contig = ensure_contiguous(a)?;
reduce_multi_dim_fused(
client,
op,
&a_contig,
dims,
keepdim,
AccumulationPrecision::Native,
op_name,
)
} else if should_fuse_multi_dim_reduction(a, dims) {
reduce_multi_dim_fused(
client,
op,
a,
dims,
keepdim,
AccumulationPrecision::Native,
op_name,
)
} else {
let a_contig = ensure_contiguous(a)?;
let mut sorted_dims: Vec<usize> = dims.to_vec();
sorted_dims.sort_unstable();
sorted_dims.reverse();
let mut current = a_contig;
for &dim in &sorted_dims {
current = reduce_single_dim(client, op, ¤t, dim, keepdim, op_name)?;
}
Ok(current)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ops::ReduceOps;
use crate::runtime::Runtime;
use crate::runtime::cpu::{CpuDevice, CpuRuntime};
#[test]
fn test_int_multi_dim_mean_matches_regardless_of_fusion() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<i32> = vec![0, 3, 0, 3, 0, 0];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[3, 2], &device).unwrap();
let fused: Vec<i32> = client.mean(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(fused, vec![1]);
let data_t: Vec<i32> = vec![0, 0, 0, 3, 3, 0];
let a_t = Tensor::<CpuRuntime>::from_slice(&data_t, &[2, 3], &device).unwrap();
let a_t = a_t.transpose(0, 1).unwrap();
assert!(!a_t.is_contiguous());
let non_contig: Vec<i32> = client.mean(&a_t, &[0, 1], false).unwrap().to_vec();
assert_eq!(non_contig, vec![1]);
let rows = 100_000;
let big_data: Vec<i32> = std::iter::repeat_n([0i32, 3, 0], rows).flatten().collect();
let big = Tensor::<CpuRuntime>::from_slice(&big_data, &[rows, 3], &device).unwrap();
let big_bytes = big.numel() * big.dtype().size_in_bytes();
assert!(big_bytes > (1 << 20));
let big_mean: Vec<i32> = client.mean(&big, &[0, 1], false).unwrap().to_vec();
assert_eq!(big_mean, vec![1]);
}
#[test]
fn test_fused_multi_dim_int_sum_saturates_on_overflow() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<i32> = vec![i32::MAX, i32::MAX, i32::MAX, i32::MAX];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 2], &device).unwrap();
let sum: Vec<i32> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum, vec![i32::MAX]);
let neg: Vec<i32> = vec![i32::MIN, i32::MIN, i32::MIN, i32::MIN];
let b = Tensor::<CpuRuntime>::from_slice(&neg, &[2, 2], &device).unwrap();
let sum_neg: Vec<i32> = client.sum(&b, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum_neg, vec![i32::MIN]);
}
#[test]
fn test_fused_multi_dim_int_prod_saturates_on_overflow() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<i32> = vec![100_000, 100_000, 100_000, 1];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 2], &device).unwrap();
let prod: Vec<i32> = client.prod(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(prod, vec![i32::MAX]);
let neg: Vec<i32> = vec![-100_000, 100_000, 100_000, 1];
let b = Tensor::<CpuRuntime>::from_slice(&neg, &[2, 2], &device).unwrap();
let prod_neg: Vec<i32> = client.prod(&b, &[0, 1], false).unwrap().to_vec();
assert_eq!(prod_neg, vec![i32::MIN]);
}
#[test]
fn test_fused_multi_dim_int_sum_prod_exact_when_not_overflowing() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<i32> = vec![1, 2, 3, 4, 5, 6];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[3, 2], &device).unwrap();
let sum: Vec<i32> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum, vec![21]);
let prod: Vec<i32> = client.prod(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(prod, vec![720]);
}
#[test]
fn test_non_last_dim_int_sum_prod_saturate_on_overflow() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<i32> = vec![i32::MAX, 100_000, 7, i32::MAX, 100_000, 8];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 3], &device).unwrap();
let sum: Vec<i32> = client.sum(&a, &[0], false).unwrap().to_vec();
assert_eq!(sum, vec![i32::MAX, 200_000, 15]);
let prod: Vec<i32> = client.prod(&a, &[0], false).unwrap().to_vec();
assert_eq!(prod, vec![i32::MAX, i32::MAX, 56]);
}
#[test]
fn test_fused_multi_dim_sum_matches_expected() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<f32> = (1..=24).map(|v| v as f32).collect();
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 3, 4], &device).unwrap();
let out = client.sum(&a, &[1, 2], false).unwrap();
let got: Vec<f32> = out.to_vec();
assert_eq!(got, vec![78.0, 222.0]);
}
#[test]
fn test_fused_multi_dim_mean_keepdim_matches_expected() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<f32> = (1..=24).map(|v| v as f32).collect();
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 3, 4], &device).unwrap();
let out = client.mean(&a, &[0, 2], true).unwrap();
assert_eq!(out.shape(), &[1, 3, 1]);
let got: Vec<f32> = out.to_vec();
assert_eq!(got, vec![8.5, 12.5, 16.5]);
}
#[test]
fn test_f32_fused_multi_dim_sum_is_bit_exact_sequential() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data = vec![0.1f32; 512];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[512, 1], &device).unwrap();
let sum: Vec<f32> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum[0].to_bits(), 0x424c_cc96, "got {}", sum[0]);
let mean: Vec<f32> = client.mean(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(mean[0].to_bits(), 0x3dcc_cc96, "got {}", mean[0]);
}
#[cfg(feature = "f16")]
#[test]
fn test_bf16_fused_multi_dim_mean_does_not_saturate() {
use half::bf16;
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data = vec![bf16::from_f32(11.761_783_5); 512];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[512, 1], &device).unwrap();
let sum: Vec<bf16> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum[0], bf16::from_f32(6016.0), "sum saturated: {}", sum[0]);
let mean: Vec<bf16> = client.mean(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(
mean[0],
bf16::from_f32(11.75),
"mean saturated: {}",
mean[0]
);
}
#[cfg(feature = "f16")]
#[test]
fn test_bf16_fused_multi_dim_mean_low_magnitude() {
use half::bf16;
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data = vec![bf16::from_f32(0.7); 512];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[512, 1], &device).unwrap();
let sum: Vec<bf16> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum[0], bf16::from_f32(358.0), "sum saturated: {}", sum[0]);
let mean: Vec<bf16> = client.mean(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(
mean[0],
bf16::from_f32(0.699_218_75),
"mean saturated: {}",
mean[0]
);
}
#[cfg(feature = "f16")]
#[test]
fn test_f16_fused_multi_dim_mean_does_not_saturate() {
use half::f16;
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data = vec![f16::from_f32(1.0); 4096];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[4096, 1], &device).unwrap();
let sum: Vec<f16> = client.sum(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(sum[0], f16::from_f32(4096.0), "sum saturated: {}", sum[0]);
let mean: Vec<f16> = client.mean(&a, &[0, 1], false).unwrap().to_vec();
assert_eq!(mean[0], f16::from_f32(1.0), "mean saturated: {}", mean[0]);
}
#[cfg(feature = "f16")]
#[test]
fn test_bf16_non_last_dim_sum_does_not_saturate() {
use half::bf16;
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data = vec![bf16::from_f32(11.761_783_5); 512 * 3];
let a = Tensor::<CpuRuntime>::from_slice(&data, &[512, 3], &device).unwrap();
let sum: Vec<bf16> = client.sum(&a, &[0], false).unwrap().to_vec();
assert_eq!(sum.len(), 3);
for (i, &v) in sum.iter().enumerate() {
assert_eq!(v, bf16::from_f32(6016.0), "column {i} saturated: {v}");
}
}
#[test]
fn test_fused_multi_dim_max_and_precision_sum() {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let data: Vec<f32> = (1..=24).map(|v| v as f32).collect();
let a = Tensor::<CpuRuntime>::from_slice(&data, &[2, 3, 4], &device).unwrap();
let max_out = client.max(&a, &[0, 1], false).unwrap();
let max_vals: Vec<f32> = max_out.to_vec();
assert_eq!(max_vals, vec![21.0, 22.0, 23.0, 24.0]);
let sum_prec = client
.sum_with_precision(&a, &[0, 2], false, AccumulationPrecision::FP64)
.unwrap();
let sum_vals: Vec<f32> = sum_prec.to_vec();
assert_eq!(sum_vals, vec![68.0, 100.0, 132.0]);
}
}