use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::{CudaContext, CudaStream};
use std::sync::Arc;
use crate::dtype::DType;
use crate::error::{Error, Result};
use super::launch_dims::{BLOCK_SIZE, elementwise_launch_config, launch_config};
use super::module_cache::{get_kernel_function, get_or_load_module};
use super::names::kernel_name;
pub unsafe fn launch_unary_kernel(
context: &Arc<CudaContext>,
stream: &CudaStream,
device_index: usize,
module_name: &'static str,
op: &str,
dtype: DType,
input_ptr: u64,
output_ptr: u64,
numel: usize,
) -> Result<()> {
unsafe {
let module = get_or_load_module(context, device_index, module_name)?;
let func_name = kernel_name(op, dtype);
let func = get_kernel_function(&module, &func_name)?;
let grid = elementwise_launch_config(numel);
let block = (BLOCK_SIZE, 1, 1);
let n = numel as u32;
let cfg = launch_config(grid, block, 0);
let mut builder = stream.launch_builder(&func);
builder.arg(&input_ptr);
builder.arg(&output_ptr);
builder.arg(&n);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA {} kernel '{}' launch failed: {:?}",
module_name, op, e
))
})?;
Ok(())
}
}
pub unsafe fn launch_binary_kernel(
context: &Arc<CudaContext>,
stream: &CudaStream,
device_index: usize,
module_name: &'static str,
op: &str,
dtype: DType,
a_ptr: u64,
b_ptr: u64,
output_ptr: u64,
numel: usize,
) -> Result<()> {
unsafe {
let module = get_or_load_module(context, device_index, module_name)?;
let func_name = kernel_name(op, dtype);
let func = get_kernel_function(&module, &func_name)?;
let grid = elementwise_launch_config(numel);
let block = (BLOCK_SIZE, 1, 1);
let n = numel as u32;
let cfg = launch_config(grid, block, 0);
let mut builder = stream.launch_builder(&func);
builder.arg(&a_ptr);
builder.arg(&b_ptr);
builder.arg(&output_ptr);
builder.arg(&n);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA {} kernel '{}' launch failed: {:?}",
module_name, op, e
))
})?;
Ok(())
}
}