use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::{ScalarOps, ScatterReduceOp};
use crate::runtime::RuntimeClient;
use crate::runtime::ensure_contiguous;
use crate::runtime::wgpu::WgpuClient;
use crate::runtime::wgpu::WgpuRuntime;
use crate::runtime::wgpu::ops::helpers::{
MeanDivParams, ScatterReduceParams, alloc_output, create_params_buffer, ensure_i32_indices,
get_tensor_buffer,
};
use crate::runtime::wgpu::ops::native::native_scatter_reduce_int_wide;
use crate::runtime::wgpu::shaders::{
launch_scatter_reduce, launch_scatter_reduce_count, launch_scatter_reduce_mean_div,
launch_scatter_reduce_prod,
};
use crate::tensor::Tensor;
pub(super) fn scatter_reduce(
client: &WgpuClient,
dst: &Tensor<WgpuRuntime>,
dim: usize,
index: &Tensor<WgpuRuntime>,
src: &Tensor<WgpuRuntime>,
op: ScatterReduceOp,
include_self: bool,
) -> Result<Tensor<WgpuRuntime>> {
let dtype = dst.dtype();
if !matches!(dtype, DType::F32 | DType::I32 | DType::U32) {
return Err(Error::UnsupportedDType {
dtype,
op: "scatter_reduce",
});
}
if !matches!(index.dtype(), DType::I32 | DType::I64) {
return Err(Error::InvalidArgument {
arg: "index",
reason: "scatter_reduce index must be I32 or I64".to_string(),
});
}
if index.shape() != src.shape() {
return Err(Error::ShapeMismatch {
expected: src.shape().to_vec(),
got: index.shape().to_vec(),
});
}
let dst = ensure_contiguous(dst)?;
let index_i32 = ensure_i32_indices(client, index)?;
let index = ensure_contiguous(&index_i32)?;
let src = ensure_contiguous(src)?;
let dst_shape = dst.shape();
let ndim = dst_shape.len();
if dim >= ndim {
return Err(Error::InvalidArgument {
arg: "dim",
reason: format!("dim {} out of bounds for tensor with {} dims", dim, ndim),
});
}
let outer_size: usize = dst_shape[..dim].iter().product();
let dim_size = dst_shape[dim];
let inner_size: usize = dst_shape[dim + 1..].iter().product();
let src_dim_size = src.shape().get(dim).copied().unwrap_or(1);
let total_src = src.numel();
if dst.numel() == 0 {
return alloc_output(client, dst_shape, dtype);
}
let identity = match op {
ScatterReduceOp::Sum | ScatterReduceOp::Mean => 0.0f64,
ScatterReduceOp::Max => f64::NEG_INFINITY,
ScatterReduceOp::Min => f64::INFINITY,
ScatterReduceOp::Prod => 1.0,
};
let output = if include_self {
client.add_scalar(&dst, 0.0)?
} else {
Tensor::full_scalar(dst_shape, dtype, identity, client.device())?
};
if total_src == 0 {
return Ok(output);
}
let params = ScatterReduceParams {
dim: dim as u32,
outer_size: outer_size as u32,
dim_size: dim_size as u32,
inner_size: inner_size as u32,
src_dim_size: src_dim_size as u32,
_pad0: 0,
_pad1: 0,
_pad2: 0,
};
let params_buf = create_params_buffer(client, ¶ms);
let src_buf = get_tensor_buffer(&src)?;
let index_buf = get_tensor_buffer(&index)?;
let output_buf = get_tensor_buffer(&output)?;
if dtype.is_int() && matches!(op, ScatterReduceOp::Sum | ScatterReduceOp::Mean) {
return native_scatter_reduce_int_wide(
client,
&output,
&src,
&index,
¶ms_buf,
total_src,
matches!(op, ScatterReduceOp::Mean),
include_self,
);
}
match op {
ScatterReduceOp::Prod => {
let items = if dtype.is_int() {
output.numel()
} else {
total_src
};
launch_scatter_reduce_prod(
client.pipeline_cache(),
client.wgpu_queue(),
&src_buf,
&index_buf,
&output_buf,
¶ms_buf,
items,
dtype,
)?;
Ok(output)
}
ScatterReduceOp::Mean => {
launch_scatter_reduce(
client.pipeline_cache(),
client.wgpu_queue(),
&src_buf,
&index_buf,
&output_buf,
¶ms_buf,
total_src,
dtype,
"sum",
)?;
let numel = dst.numel();
let count_init = if include_self { 1u32 } else { 0u32 };
let count_data = vec![count_init; numel];
let count_tensor =
Tensor::<WgpuRuntime>::from_slice(&count_data, dst_shape, client.device())?;
let count_buf = get_tensor_buffer(&count_tensor)?;
launch_scatter_reduce_count(
client.pipeline_cache(),
client.wgpu_queue(),
&index_buf,
&count_buf,
¶ms_buf,
total_src,
dtype,
)?;
let result = alloc_output(client, dst_shape, dtype)?;
let result_buf = get_tensor_buffer(&result)?;
let mean_params = MeanDivParams {
n: numel as u32,
_pad0: 0,
_pad1: 0,
_pad2: 0,
};
let mean_params_buf = create_params_buffer(client, &mean_params);
launch_scatter_reduce_mean_div(
client.pipeline_cache(),
client.wgpu_queue(),
&output_buf,
&count_buf,
&result_buf,
&mean_params_buf,
numel,
dtype,
)?;
Ok(result)
}
_ => {
let op_str = match op {
ScatterReduceOp::Sum => "sum",
ScatterReduceOp::Max => "max",
ScatterReduceOp::Min => "min",
_ => unreachable!(),
};
launch_scatter_reduce(
client.pipeline_cache(),
client.wgpu_queue(),
&src_buf,
&index_buf,
&output_buf,
¶ms_buf,
total_src,
dtype,
op_str,
)?;
Ok(output)
}
}
}