use super::tensor_inputs::{check_ternary, materialize};
use crate::error::{Error, Result};
use crate::ops::BinaryOps;
use crate::runtime::cuda::kernels::{
launch_fused_add_mul, launch_fused_mul_add, launch_strided_copy_into,
};
use crate::runtime::cuda::ops::helpers::{native_binary_op, native_binary_op_into};
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::runtime::{CopyIntoPlan, Runtime, validate_copy_into};
use crate::tensor::Tensor;
impl BinaryOps<CudaRuntime> for CudaClient {
fn add(&self, a: &Tensor<CudaRuntime>, b: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "add")
}
fn sub(&self, a: &Tensor<CudaRuntime>, b: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "sub")
}
fn mul(&self, a: &Tensor<CudaRuntime>, b: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "mul")
}
fn div(&self, a: &Tensor<CudaRuntime>, b: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "div")
}
fn pow(&self, a: &Tensor<CudaRuntime>, b: &Tensor<CudaRuntime>) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "pow")
}
fn maximum(
&self,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "max")
}
fn minimum(
&self,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, a, b, "min")
}
fn atan2(
&self,
y: &Tensor<CudaRuntime>,
x: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
native_binary_op(self, y, x, "atan2")
}
fn fused_mul_add(
&self,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
c: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
let count = check_ternary(self, a, b, c, "fused_mul_add")?;
let dtype = a.dtype();
let out = Tensor::<CudaRuntime>::empty(a.shape(), dtype, &self.device)?;
if count == 0 {
return Ok(out);
}
let a_materialized = materialize(self, a, count)?;
let b_materialized = materialize(self, b, count)?;
let c_materialized = materialize(self, c, count)?;
let a_contig = a_materialized.as_ref().unwrap_or(a);
let b_contig = b_materialized.as_ref().unwrap_or(b);
let c_contig = c_materialized.as_ref().unwrap_or(c);
unsafe {
launch_fused_mul_add(
&self.context,
&self.stream,
self.device.index,
dtype,
a_contig.ptr(),
b_contig.ptr(),
c_contig.ptr(),
out.ptr(),
out.numel(),
)?;
}
Ok(out)
}
fn fused_add_mul(
&self,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
c: &Tensor<CudaRuntime>,
) -> Result<Tensor<CudaRuntime>> {
let count = check_ternary(self, a, b, c, "fused_add_mul")?;
let dtype = a.dtype();
let out = Tensor::<CudaRuntime>::empty(a.shape(), dtype, &self.device)?;
if count == 0 {
return Ok(out);
}
let a_materialized = materialize(self, a, count)?;
let b_materialized = materialize(self, b, count)?;
let c_materialized = materialize(self, c, count)?;
let a_contig = a_materialized.as_ref().unwrap_or(a);
let b_contig = b_materialized.as_ref().unwrap_or(b);
let c_contig = c_materialized.as_ref().unwrap_or(c);
unsafe {
launch_fused_add_mul(
&self.context,
&self.stream,
self.device.index,
dtype,
a_contig.ptr(),
b_contig.ptr(),
c_contig.ptr(),
out.ptr(),
out.numel(),
)?;
}
Ok(out)
}
fn add_into(
&self,
out: &Tensor<CudaRuntime>,
a: &Tensor<CudaRuntime>,
b: &Tensor<CudaRuntime>,
) -> Result<()> {
native_binary_op_into(self, out, a, b, "add")
}
fn copy_into(&self, out: &Tensor<CudaRuntime>, src: &Tensor<CudaRuntime>) -> Result<()> {
if validate_copy_into(out, src, "copy_into")? == CopyIntoPlan::Skip {
return Ok(());
}
let elem_size = src.dtype().size_in_bytes();
if !out.is_contiguous() {
return unsafe {
launch_strided_copy_into(
&self.context,
&self.stream,
self.device.index,
src.storage().ptr(),
out.storage().ptr(),
src.shape(),
src.strides(),
out.strides(),
elem_size,
src.offset() * elem_size,
out.offset() * elem_size,
)
};
}
if !src.is_contiguous() {
return CudaRuntime::copy_strided(
src.storage().ptr(),
src.offset() * elem_size,
out.ptr(),
src.shape(),
src.strides(),
elem_size,
src.device(),
);
}
let size_bytes = src.numel() * elem_size;
let result = {
let _permit = self
.stream
.enqueue_permit()
.map_err(crate::error::CudaDriverError::from_driver)?;
unsafe {
cudarc::driver::sys::cuMemcpyDtoDAsync_v2(
out.ptr(),
src.ptr(),
size_bytes,
self.stream.raw().cu_stream(),
)
}
};
if result != cudarc::driver::sys::CUresult::CUDA_SUCCESS {
return Err(Error::Backend(format!(
"copy_into: device-to-device copy of {size_bytes} bytes failed ({result:?})"
)));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dtype::DType;
use crate::runtime::RuntimeClient;
use crate::runtime::cuda::CudaDevice;
fn setup() -> Option<CudaClient> {
if !crate::runtime::cuda::is_cuda_available() {
return None;
}
Some(CudaRuntime::default_client(&CudaDevice::new(0)))
}
#[test]
fn copy_into_keeps_destination_address() {
let Some(client) = setup() else {
return;
};
let src =
Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], client.device())
.unwrap();
let out = Tensor::<CudaRuntime>::zeros(&[2, 2], DType::F32, client.device()).unwrap();
let before = out.ptr();
client.copy_into(&out, &src).unwrap();
assert_eq!(out.ptr(), before);
assert_eq!(out.to_vec::<f32>(), vec![1.0, 2.0, 3.0, 4.0]);
}
#[test]
fn copy_into_reads_strided_source() {
let Some(client) = setup() else {
return;
};
let src = Tensor::<CudaRuntime>::from_slice(
&[1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0],
&[2, 3],
client.device(),
)
.unwrap();
let transposed = src.transpose(0, 1).unwrap();
let out = Tensor::<CudaRuntime>::zeros(&[3, 2], DType::F32, client.device()).unwrap();
client.copy_into(&out, &transposed).unwrap();
assert_eq!(out.to_vec::<f32>(), vec![1.0, 4.0, 2.0, 5.0, 3.0, 6.0]);
}
#[test]
fn copy_into_writes_a_channel_slice_and_keeps_the_rest() {
let Some(client) = setup() else {
return;
};
let buf =
Tensor::<CudaRuntime>::from_slice(&[9.0f32; 8], &[2, 4], client.device()).unwrap();
let slice = buf.narrow(-1, 1, 2).unwrap();
let src =
Tensor::<CudaRuntime>::from_slice(&[1.0f32, 2.0, 3.0, 4.0], &[2, 2], client.device())
.unwrap();
client.copy_into(&slice, &src).unwrap();
assert_eq!(
buf.to_vec::<f32>(),
vec![9.0, 1.0, 2.0, 9.0, 9.0, 3.0, 4.0, 9.0]
);
}
}