use crate::error::{Error, Result};
use crate::runtime::cuda::kernels::{launch_binary_op, launch_broadcast_binary_op};
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::{compute_broadcast_shape, ensure_contiguous, validate_binary_dtypes};
use crate::tensor::Tensor;
pub(crate) fn native_binary_op(
client: &CudaClient,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
op: &'static str,
) -> Result<Tensor<CudaRuntime>> {
let dtype = validate_binary_dtypes(a, b)?;
let out_shape = compute_broadcast_shape(a, b)?;
if out_shape.iter().product::<usize>() == 0 {
return Tensor::<CudaRuntime>::empty(&out_shape, dtype, &client.device);
}
if a.shape() == b.shape() {
let a_contig = ensure_contiguous(a)?;
let b_contig = ensure_contiguous(b)?;
let out = Tensor::<CudaRuntime>::empty(&out_shape, dtype, &client.device)?;
unsafe {
launch_binary_op(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
a_contig.ptr(),
b_contig.ptr(),
out.ptr(),
out.numel(),
)?;
}
return Ok(out);
}
let a_contig = ensure_contiguous(a)?;
let b_contig = ensure_contiguous(b)?;
let out = Tensor::<CudaRuntime>::empty(&out_shape, dtype, &client.device)?;
unsafe {
launch_broadcast_binary_op(
&client.context,
&client.stream,
client.device.index,
&client.device,
op,
dtype,
a_contig.ptr(),
b_contig.ptr(),
out.ptr(),
a.shape(),
b.shape(),
&out_shape,
)?;
}
Ok(out)
}
pub(crate) fn native_binary_op_into(
client: &CudaClient,
out: &Tensor<CudaRuntime>,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
op: &'static str,
) -> Result<()> {
let dtype = validate_binary_dtypes(a, b)?;
let out_shape = compute_broadcast_shape(a, b)?;
if out.dtype() != dtype {
return Err(Error::DTypeMismatch {
lhs: dtype,
rhs: out.dtype(),
});
}
if out.shape() != out_shape.as_slice() {
return Err(Error::ShapeMismatch {
expected: out_shape,
got: out.shape().to_vec(),
});
}
if !out.is_contiguous() {
return Err(Error::Backend(
"native_binary_op_into: destination tensor must be contiguous".into(),
));
}
if out.numel() == 0 {
return Ok(());
}
let a_contig = ensure_contiguous(a)?;
let b_contig = ensure_contiguous(b)?;
if a.shape() == b.shape() {
unsafe {
launch_binary_op(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
a_contig.ptr(),
b_contig.ptr(),
out.ptr(),
out.numel(),
)?;
}
} else {
unsafe {
launch_broadcast_binary_op(
&client.context,
&client.stream,
client.device.index,
&client.device,
op,
dtype,
a_contig.ptr(),
b_contig.ptr(),
out.ptr(),
a.shape(),
b.shape(),
&out_shape,
)?;
}
}
Ok(())
}