use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;
use super::loader::{
BLOCK_SIZE, MAX_GRID_DIM_X, get_kernel_function, get_or_load_module, launch_config,
};
use crate::error::{Error, Result};
use crate::runtime::cuda::GuardedStream;
pub const IMAGE_MODULE: &str = "image";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageKernel {
PixelShuffle,
PixelUnshuffle,
UpsampleNearest2d,
}
impl ImageKernel {
fn base_name(self) -> &'static str {
match self {
Self::PixelShuffle => "pixel_shuffle",
Self::PixelUnshuffle => "pixel_unshuffle",
Self::UpsampleNearest2d => "upsample_nearest2d",
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ImageLaunch {
pub kernel: ImageKernel,
pub elem_size: usize,
pub out_dims: [usize; 4],
pub src_strides: [isize; 4],
pub dst_strides: [isize; 4],
pub channels_last: bool,
pub factor: usize,
pub in_hw: [usize; 2],
pub nearest: [(u32, f32); 2],
}
pub unsafe fn launch_image(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
src_ptr: u64,
dst_ptr: u64,
launch: &ImageLaunch,
) -> Result<()> {
let total: usize = launch.out_dims.iter().product();
if total == 0 {
return Ok(());
}
if !matches!(launch.elem_size, 1 | 2 | 4 | 8 | 16) {
return Err(Error::Internal(format!(
"{}: element size {} has no CUDA gather kernel",
launch.kernel.base_name(),
launch.elem_size
)));
}
let module = get_or_load_module(context, device_index, IMAGE_MODULE)?;
let func_name = format!("{}_b{}", launch.kernel.base_name(), launch.elem_size);
let func = get_kernel_function(&module, &func_name)?;
let blocks = (total as u64).div_ceil(u64::from(BLOCK_SIZE));
let grid = (blocks.min(u64::from(MAX_GRID_DIM_X)) as u32, 1, 1);
let cfg = launch_config(grid, (BLOCK_SIZE, 1, 1), 0);
let total_u64 = total as u64;
let [_, dim_c, dim_h, dim_w] = launch.out_dims.map(|d| d as u64);
let ss = launch.src_strides.map(|s| s as i64);
let ds = launch.dst_strides.map(|s| s as i64);
let channels_last = u32::from(launch.channels_last);
let factor = launch.factor as u64;
let [in_h, in_w] = launch.in_hw.map(|d| d as u64);
let [(mode_h, scale_h), (mode_w, scale_w)] = launch.nearest;
unsafe {
let mut builder = stream.launch_builder(&func);
builder.arg(&src_ptr);
builder.arg(&dst_ptr);
builder.arg(&total_u64);
builder.arg(&dim_c);
builder.arg(&dim_h);
builder.arg(&dim_w);
for s in &ss {
builder.arg(s);
}
for s in &ds {
builder.arg(s);
}
builder.arg(&channels_last);
builder.arg(&factor);
builder.arg(&in_h);
builder.arg(&in_w);
builder.arg(&mode_h);
builder.arg(&mode_w);
builder.arg(&scale_h);
builder.arg(&scale_w);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!("CUDA kernel '{func_name}' launch failed: {e:?}"))
})?;
}
Ok(())
}