use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::ops::ConvLayout;
use crate::runtime::cuda::GuardedStream;
use super::conv_implicit_gemm_staging::select_conv_staging;
use super::conv_implicit_gemm_tile::{
ConvWindow, conv_kernel_name, conv_launch_config, select_conv_tile,
};
use super::module_cache::{get_kernel_function, get_or_load_module};
use super::names::kernel_names;
#[derive(Copy, Clone, Debug, PartialEq)]
pub(crate) enum ConvEpilogueActivation {
None,
Relu,
LeakyRelu(f32),
Prelu,
}
impl ConvEpilogueActivation {
fn code_and_slope(self) -> (u32, f32) {
match self {
Self::None => (0, 0.0),
Self::Relu => (1, 0.0),
Self::LeakyRelu(slope) => (2, slope),
Self::Prelu => (3, 0.0),
}
}
}
pub(crate) const CONV_MAX_KERNEL_EXTENT: usize = 32;
pub(crate) type ConvStrides = [i64; 4];
#[derive(Copy, Clone, Debug)]
pub(crate) struct ConvImplicitGemmArgs {
pub input_ptr: u64,
pub weight_ptr: u64,
pub bias_ptr: u64,
pub prelu_ptr: u64,
pub residual_ptr: u64,
pub out_ptr: u64,
pub layout: ConvLayout,
pub batch: usize,
pub in_h: usize,
pub in_w: usize,
pub c_in: usize,
pub out_h: usize,
pub out_w: usize,
pub c_out: usize,
pub kernel_h: usize,
pub kernel_w: usize,
pub stride: (usize, usize),
pub pad_top: usize,
pub pad_left: usize,
pub dilation: (usize, usize),
pub input_strides: ConvStrides,
pub out_strides: ConvStrides,
pub residual_strides: ConvStrides,
pub activation: ConvEpilogueActivation,
pub prelu_len: usize,
pub residual_scale: f32,
pub half_accumulate: bool,
}
fn to_i32(value: usize, what: &str) -> Result<i32> {
i32::try_from(value).map_err(|_| {
Error::Internal(format!(
"conv2d implicit GEMM: {what} = {value} exceeds the kernel's i32 range; route this \
shape to the generic path"
))
})
}
pub(crate) unsafe fn launch_conv_implicit_gemm(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
dtype: DType,
args: &ConvImplicitGemmArgs,
) -> Result<()> {
let m = args
.batch
.checked_mul(args.out_h)
.and_then(|v| v.checked_mul(args.out_w))
.ok_or_else(|| {
Error::Internal(
"conv2d implicit GEMM: N*H_out*W_out overflows; route this shape to the generic path"
.into(),
)
})?;
let k = args
.kernel_h
.checked_mul(args.kernel_w)
.and_then(|v| v.checked_mul(args.c_in))
.ok_or_else(|| {
Error::Internal(
"conv2d implicit GEMM: Kh*Kw*C_in overflows; route this shape to the generic path"
.into(),
)
})?;
if m == 0 || args.c_out == 0 {
return Ok(());
}
if args.half_accumulate && dtype != DType::F16 {
return Err(Error::Internal(format!(
"conv2d implicit GEMM: half_accumulate is set for {dtype:?}, but only F16 has \
F16-accumulator kernels. Set half_accumulate only for F16 inputs"
)));
}
if k == 0 {
return Err(Error::Internal(
"conv2d implicit GEMM: Kh*Kw*C_in is 0; route this shape to the generic path".into(),
));
}
if args.kernel_h > CONV_MAX_KERNEL_EXTENT || args.kernel_w > CONV_MAX_KERNEL_EXTENT {
return Err(Error::Internal(format!(
"conv2d implicit GEMM: kernel {}x{} exceeds the {CONV_MAX_KERNEL_EXTENT}x\
{CONV_MAX_KERNEL_EXTENT} tap masks; route this shape to the generic path",
args.kernel_h, args.kernel_w
)));
}
let m_i32 = to_i32(m, "N*H_out*W_out")?;
to_i32(k, "Kh*Kw*C_in")?;
let in_h = to_i32(args.in_h, "H")?;
let in_w = to_i32(args.in_w, "W")?;
let c_in = to_i32(args.c_in, "C_in")?;
let out_h = to_i32(args.out_h, "H_out")?;
let out_w = to_i32(args.out_w, "W_out")?;
let c_out = to_i32(args.c_out, "C_out")?;
let kernel_h = to_i32(args.kernel_h, "Kh")?;
let kernel_w = to_i32(args.kernel_w, "Kw")?;
let stride_h = to_i32(args.stride.0, "stride_h")?;
let stride_w = to_i32(args.stride.1, "stride_w")?;
let pad_top = to_i32(args.pad_top, "pad_top")?;
let pad_left = to_i32(args.pad_left, "pad_left")?;
let dil_h = to_i32(args.dilation.0, "dilation_h")?;
let dil_w = to_i32(args.dilation.1, "dilation_w")?;
let prelu_len = to_i32(args.prelu_len, "prelu_len")?;
let (act, slope) = args.activation.code_and_slope();
let tile = select_conv_tile(args.c_out, args.half_accumulate);
let window = ConvWindow {
batch: args.batch,
out_h: args.out_h,
out_w: args.out_w,
kernel: (args.kernel_h, args.kernel_w),
stride: args.stride,
dilation: args.dilation,
pad_left: args.pad_left,
};
let staging = select_conv_staging(
args.layout,
args.c_in,
args.input_ptr,
args.input_strides,
args.weight_ptr,
tile,
&window,
);
let cfg = conv_launch_config(&window, args.c_out, tile, staging).ok_or_else(|| {
Error::Internal(format!(
"conv2d implicit GEMM: grid for M = {m}, C_out = {} exceeds the CUDA grid limit; \
route this shape to the generic path",
args.c_out
))
})?;
let module = get_or_load_module(
context,
device_index,
kernel_names::CONV_IMPLICIT_GEMM_MODULE,
)?;
let name = conv_kernel_name(dtype, args.half_accumulate, tile, staging);
let func = get_kernel_function(&module, &name)?;
let strides = [args.input_strides, args.out_strides, args.residual_strides];
let pushed: &[usize] = match args.layout {
ConvLayout::Nhwc => &[0, 2, 3],
ConvLayout::Nchw => &[0, 1, 2, 3],
};
unsafe {
let mut builder = stream.launch_builder(&func);
builder.arg(&args.input_ptr);
builder.arg(&args.weight_ptr);
builder.arg(&args.bias_ptr);
builder.arg(&args.prelu_ptr);
builder.arg(&args.residual_ptr);
builder.arg(&args.out_ptr);
builder.arg(&m_i32);
builder.arg(&in_h);
builder.arg(&in_w);
builder.arg(&c_in);
builder.arg(&out_h);
builder.arg(&out_w);
builder.arg(&c_out);
builder.arg(&kernel_h);
builder.arg(&kernel_w);
builder.arg(&stride_h);
builder.arg(&stride_w);
builder.arg(&pad_top);
builder.arg(&pad_left);
builder.arg(&dil_h);
builder.arg(&dil_w);
for tensor in &strides {
for &d in pushed {
builder.arg(&tensor[d]);
}
}
builder.arg(&act);
builder.arg(&slope);
builder.arg(&prelu_len);
builder.arg(&args.residual_scale);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA conv2d implicit GEMM: launch of {name} failed: {e:?}; check the \
device and driver state"
))
})?;
}
Ok(())
}