use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::{ReduceOps, ShapeOps, TypeConversionOps};
use crate::runtime::cuda::kernels::{launch_bincount_weighted, launch_fill_with_f64};
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
struct BincountPlan {
input_dtype: DType,
weights_dtype: Option<DType>,
out_dtype: DType,
}
fn bincount_validate(
input: &Tensor<CudaRuntime>,
weights: Option<&Tensor<CudaRuntime>>,
) -> Result<BincountPlan> {
if input.ndim() != 1 {
return Err(Error::ShapeMismatch {
expected: vec![input.numel()],
got: input.shape().to_vec(),
});
}
let input_dtype = input.dtype();
if !matches!(input_dtype, DType::I32 | DType::I64) {
return Err(Error::DTypeMismatch {
lhs: DType::I64,
rhs: input_dtype,
});
}
let weights_dtype = if let Some(w) = weights {
if w.shape() != input.shape() {
return Err(Error::ShapeMismatch {
expected: input.shape().to_vec(),
got: w.shape().to_vec(),
});
}
Some(w.dtype())
} else {
None
};
Ok(BincountPlan {
input_dtype,
weights_dtype,
out_dtype: weights_dtype.unwrap_or(DType::I64),
})
}
fn bincount_accumulate(
client: &CudaClient,
plan: &BincountPlan,
input: &Tensor<CudaRuntime>,
weights: Option<&Tensor<CudaRuntime>>,
output_len: usize,
) -> Result<Tensor<CudaRuntime>> {
let input_contig = ensure_contiguous(input)?;
let numel = input.numel();
let out = Tensor::<CudaRuntime>::empty(&[output_len], plan.out_dtype, &client.device)?;
if output_len == 0 {
return Ok(out);
}
unsafe {
launch_fill_with_f64(
&client.context,
&client.stream,
client.device.index,
plan.out_dtype,
0.0,
out.ptr(),
output_len,
)?;
}
let weights_contig = weights.map(ensure_contiguous).transpose()?;
let weights_ptr = weights_contig.as_ref().map(|w| w.ptr());
unsafe {
launch_bincount_weighted(
&client.context,
&client.stream,
client.device.index,
plan.input_dtype,
plan.weights_dtype,
input_contig.ptr(),
weights_ptr,
out.ptr(),
numel,
output_len,
)?;
}
Ok(out)
}
pub fn bincount(
client: &CudaClient,
input: &Tensor<CudaRuntime>,
weights: Option<&Tensor<CudaRuntime>>,
minlength: usize,
) -> Result<Tensor<CudaRuntime>> {
let plan = bincount_validate(input, weights)?;
if input.numel() == 0 {
return bincount_accumulate(client, &plan, input, weights, minlength);
}
let input_f64 = client.cast(input, DType::F64)?;
let min_tensor = client.min(&input_f64, &[0], true)?;
let max_tensor = client.max(&input_f64, &[0], true)?;
let bounds = client.cat(&[&min_tensor, &max_tensor], 0)?;
let bounds = bounds.to_vec::<f64>();
let (min_val, max_val) = match bounds.as_slice() {
[lo, hi] => (*lo as i64, *hi as i64),
other => {
return Err(Error::Internal(format!(
"bincount: the min/max readback returned {} values, expected 2",
other.len()
)));
}
};
if min_val < 0 {
return Err(Error::InvalidArgument {
arg: "input",
reason: "bincount requires non-negative values".to_string(),
});
}
let output_len = ((max_val as usize) + 1).max(minlength);
bincount_accumulate(client, &plan, input, weights, output_len)
}
pub fn bincount_with_len(
client: &CudaClient,
input: &Tensor<CudaRuntime>,
weights: Option<&Tensor<CudaRuntime>>,
len: usize,
) -> Result<Tensor<CudaRuntime>> {
let plan = bincount_validate(input, weights)?;
bincount_accumulate(client, &plan, input, weights, len)
}