use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;
use crate::algorithm::TileConfig;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::cuda::GuardedStream;
use super::launch_dims::LaunchConfig;
use super::module_cache::{get_kernel_function, get_or_load_module};
use super::names::{dtype_suffix, kernel_names};
#[inline]
pub fn int_matmul_has_kernel(dtype: DType) -> bool {
dtype.is_int()
}
#[inline]
pub fn int_matmul_output_dtype(dtype: DType) -> DType {
crate::ops::matmul_output_dtype(dtype)
}
const INT_TILE: TileConfig = TileConfig {
block_m: 64,
block_n: 64,
block_k: 8,
thread_m: 4,
thread_n: 4,
};
pub(super) unsafe fn launch_matmul_int_tiled(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
dtype: DType,
a_ptr: u64,
b_ptr: u64,
bias_ptr: Option<u64>,
c_ptr: u64,
batch: usize,
m: usize,
n: usize,
k: usize,
a_batch: usize,
b_batch: usize,
) -> Result<()> {
let plain = batch == 1 && a_batch == 1 && b_batch == 1;
if !int_matmul_has_kernel(dtype) {
return Err(Error::UnsupportedDType {
dtype,
op: "matmul_int_tiled",
});
}
let base = match (bias_ptr.is_some(), plain) {
(false, true) => "matmul",
(false, false) => "matmul_batched",
(true, true) => "matmul_bias",
(true, false) => "matmul_bias_batched",
};
let suffix = if dtype == DType::I8 {
"i8_i32"
} else {
dtype_suffix(dtype)
};
let kernel_fn_name = format!("{}_{}_tiled_64x64x8_4x4", base, suffix);
let module = get_or_load_module(context, device_index, kernel_names::MATMUL_INT_MODULE)?;
let func = get_kernel_function(&module, &kernel_fn_name)?;
let bm = INT_TILE.block_m as u32;
let bn = INT_TILE.block_n as u32;
let tm = INT_TILE.thread_m as u32;
let tn = INT_TILE.thread_n as u32;
let cfg = LaunchConfig {
grid_dim: (
((n as u32) + bn - 1) / bn,
((m as u32) + bm - 1) / bm,
batch as u32,
),
block_dim: (bn / tn, bm / tm, 1),
shared_mem_bytes: 0,
};
let batch_u32 = batch as u32;
let m_u32 = m as u32;
let n_u32 = n as u32;
let k_u32 = k as u32;
let a_batch_u32 = a_batch as u32;
let b_batch_u32 = b_batch as u32;
unsafe {
let mut builder = stream.launch_builder(&func);
builder.arg(&a_ptr);
builder.arg(&b_ptr);
if let Some(bias) = bias_ptr.as_ref() {
builder.arg(bias);
}
builder.arg(&c_ptr);
if !plain {
builder.arg(&batch_u32);
}
builder.arg(&m_u32);
builder.arg(&n_u32);
builder.arg(&k_u32);
if !plain {
builder.arg(&a_batch_u32);
builder.arg(&b_batch_u32);
}
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA integer matmul kernel '{}' launch failed: {:?}",
kernel_fn_name, e
))
})?;
}
Ok(())
}