use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::cuda::kernels::launch_scalar_op_half;
use crate::runtime::cuda::kernels::{
launch_pow_scalar_int, launch_scalar_op_c64, launch_scalar_op_c128, launch_scalar_op_f32,
launch_scalar_op_f64, launch_scalar_op_int,
};
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::ensure_contiguous;
use crate::tensor::Tensor;
fn scalar_op_has_kernel(dtype: DType) -> bool {
match dtype {
DType::F32
| DType::F64
| DType::FP8E4M3
| DType::FP8E5M2
| DType::Complex64
| DType::Complex128 => true,
d if d.is_int() => true,
DType::F16 | DType::BF16 => cfg!(feature = "f16"),
_ => false,
}
}
pub(crate) fn native_scalar_op(
client: &CudaClient,
a: &Tensor<CudaRuntime>,
op: &'static str,
scalar: f64,
) -> Result<Tensor<CudaRuntime>> {
let dtype = a.dtype();
let a_contig = ensure_contiguous(a)?;
let out = Tensor::<CudaRuntime>::empty(a.shape(), dtype, &client.device)?;
if out.numel() == 0 && scalar_op_has_kernel(dtype) {
return Ok(out);
}
if op == "pow_scalar" && dtype.is_int() {
unsafe {
launch_pow_scalar_int(
&client.context,
&client.stream,
client.device.index,
dtype,
a_contig.ptr(),
scalar,
out.ptr(),
out.numel(),
)?;
}
return Ok(out);
}
unsafe {
match dtype {
DType::F32 => launch_scalar_op_f32(
&client.context,
&client.stream,
client.device.index,
op,
a_contig.ptr(),
scalar as f32,
out.ptr(),
out.numel(),
)?,
DType::F64 => launch_scalar_op_f64(
&client.context,
&client.stream,
client.device.index,
op,
a_contig.ptr(),
scalar,
out.ptr(),
out.numel(),
)?,
d if d.is_int() => launch_scalar_op_int(
&client.context,
&client.stream,
client.device.index,
op,
d,
a_contig.ptr(),
scalar,
out.ptr(),
out.numel(),
)?,
#[cfg(feature = "f16")]
DType::F16 | DType::BF16 => launch_scalar_op_half(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
a_contig.ptr(),
scalar as f32,
out.ptr(),
out.numel(),
)?,
DType::FP8E4M3 | DType::FP8E5M2 => launch_scalar_op_half(
&client.context,
&client.stream,
client.device.index,
op,
dtype,
a_contig.ptr(),
scalar as f32,
out.ptr(),
out.numel(),
)?,
DType::Complex64 => launch_scalar_op_c64(
&client.context,
&client.stream,
client.device.index,
op,
a_contig.ptr(),
scalar as f32,
out.ptr(),
out.numel(),
)?,
DType::Complex128 => launch_scalar_op_c128(
&client.context,
&client.stream,
client.device.index,
op,
a_contig.ptr(),
scalar,
out.ptr(),
out.numel(),
)?,
_ => {
return Err(Error::UnsupportedDType { dtype, op });
}
}
}
Ok(out)
}