use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::reduce_output_shape;
use crate::runtime::cuda::kernels::{
AccumulationPrecision, launch_reduce_dim_op, reduce_dim_split_count,
};
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
pub(crate) fn native_reduce_op(
client: &CudaClient,
a: &Tensor<CudaRuntime>,
op: &'static str,
dims: &[usize],
keepdim: bool,
precision: Option<AccumulationPrecision>,
) -> Result<Tensor<CudaRuntime>> {
let dtype = a.dtype();
if dtype == DType::Bool {
return Err(Error::UnsupportedDType { dtype, op });
}
let out_shape = reduce_output_shape(a.shape(), dims, keepdim);
let acc_precision = precision.unwrap_or_default();
if dims.len() == 1 {
let dim = dims[0];
let shape = a.shape();
let outer_size: usize = shape[..dim].iter().product();
let reduce_size = shape[dim];
let inner_size: usize = shape[dim + 1..].iter().product();
let a_contig = ensure_contiguous(a)?;
let out = Tensor::<CudaRuntime>::empty(&out_shape, dtype, &client.device)?;
if out.numel() == 0 {
return Ok(out);
}
if let Some(splits) = reduce_dim_split_count(
client.device.index,
op,
dtype,
acc_precision,
outer_size,
reduce_size,
inner_size,
) {
two_stage_reduce_dim(
client,
op,
acc_precision,
&a_contig,
&out,
(outer_size, reduce_size, inner_size),
splits,
)?;
return Ok(out);
}
unsafe {
launch_reduce_dim_op(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
a_contig.ptr(),
out.ptr(),
outer_size,
reduce_size,
inner_size,
acc_precision,
)?;
}
return Ok(out);
}
let mut sorted_dims: Vec<usize> = dims.to_vec();
sorted_dims.sort_unstable();
sorted_dims.reverse();
let mut current = a.clone();
for &dim in &sorted_dims {
current = native_reduce_op(client, ¤t, op, &[dim], true, precision)?;
}
if current.shape() != out_shape.as_slice() {
current = current.reshape(&out_shape)?;
}
Ok(current)
}
fn two_stage_reduce_dim(
client: &CudaClient,
op: &'static str,
acc_precision: AccumulationPrecision,
input: &Tensor<CudaRuntime>,
out: &Tensor<CudaRuntime>,
extents: (usize, usize, usize),
splits: usize,
) -> Result<()> {
let (outer_size, reduce_size, inner_size) = extents;
let dtype = input.dtype();
let chunk = reduce_size / splits;
let partial =
Tensor::<CudaRuntime>::empty(&[outer_size, splits, inner_size], dtype, &client.device)?;
let stage1_outer = outer_size.saturating_mul(splits);
unsafe {
launch_reduce_dim_op(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
input.ptr(),
partial.ptr(),
stage1_outer,
chunk,
inner_size,
acc_precision,
)?;
launch_reduce_dim_op(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
partial.ptr(),
out.ptr(),
outer_size,
splits,
inner_size,
acc_precision,
)?;
}
Ok(())
}