use cudarc::driver::PushKernelArg;
use cudarc::driver::safe::CudaContext;
use std::sync::Arc;
use crate::dtype::DType;
use crate::error::{Error, Result};
use crate::runtime::Device;
use crate::runtime::cuda::CudaClient;
use crate::runtime::cuda::GuardedStream;
use super::launch_dims::{BLOCK_SIZE, LaunchConfig, MAX_GRID_DIM_YZ};
use super::matmul_f32_smallm_tune::smallm_max_waves;
use super::module_cache::{get_kernel_function, get_or_load_module};
use super::names::kernel_names;
pub const MAX_SMALL_M: usize = 64;
pub const MAX_SMALL_N: usize = 1024;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SmallmLimits {
pub sm_count: usize,
pub max_waves: usize,
}
impl SmallmLimits {
pub fn of(client: &CudaClient) -> Self {
Self {
sm_count: client.device.profile().compute_units as usize,
max_waves: smallm_max_waves(client),
}
}
#[inline]
fn max_blocks(self) -> usize {
self.max_waves * self.sm_count
}
}
const SMALLM_BLOCK: u32 = BLOCK_SIZE;
pub const SMALLM_ROWS_PER_BLOCK: u32 = 8;
#[inline]
fn smallm_launch_config(m: usize, n: usize, batch: usize) -> LaunchConfig {
LaunchConfig {
grid_dim: (
(n as u32).div_ceil(SMALLM_ROWS_PER_BLOCK),
m as u32,
batch as u32,
),
block_dim: (SMALLM_BLOCK, 1, 1),
shared_mem_bytes: 0,
}
}
#[inline]
pub fn smallm_block_count(m: usize, n: usize) -> usize {
n.div_ceil(SMALLM_ROWS_PER_BLOCK as usize) * m
}
#[inline]
pub fn smallm_applies(
dtype: DType,
m: usize,
n: usize,
batch: usize,
limits: SmallmLimits,
) -> bool {
dtype == DType::F32
&& (1..=MAX_SMALL_M).contains(&m)
&& (1..=MAX_SMALL_N).contains(&n)
&& smallm_block_count(m, n) <= limits.max_blocks()
&& (1..=MAX_GRID_DIM_YZ as usize).contains(&batch)
}
pub unsafe fn launch_matmul_smallm_bt_kernel(
client: &CudaClient,
dtype: DType,
a_ptr: u64,
b_ptr: u64,
c_ptr: u64,
m: usize,
n: usize,
k: usize,
) -> Result<bool> {
if !smallm_applies(dtype, m, n, 1, SmallmLimits::of(client)) {
return Ok(false);
}
unsafe {
launch_matmul_smallm_bt_f32_ungated(
client.context(),
client.stream(),
client.device.index,
a_ptr,
b_ptr,
c_ptr,
m,
n,
k,
)?;
}
Ok(true)
}
pub unsafe fn launch_matmul_smallm_bt_f32_ungated(
context: &Arc<CudaContext>,
stream: &GuardedStream,
device_index: usize,
a_ptr: u64,
b_ptr: u64,
c_ptr: u64,
m: usize,
n: usize,
k: usize,
) -> Result<()> {
let module = get_or_load_module(context, device_index, kernel_names::MATMUL_MODULE)?;
let func = get_kernel_function(&module, "matmul_f32_smallm_bt")?;
let cfg = smallm_launch_config(m, n, 1);
let m_u32 = m as u32;
let n_u32 = n as u32;
let k_u32 = k as u32;
unsafe {
let mut builder = stream.launch_builder(&func);
builder.arg(&a_ptr);
builder.arg(&b_ptr);
builder.arg(&c_ptr);
builder.arg(&m_u32);
builder.arg(&n_u32);
builder.arg(&k_u32);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA matmul F32 small-M kernel 'matmul_f32_smallm_bt' launch failed: {:?}",
e
))
})?;
}
Ok(())
}
pub unsafe fn launch_matmul_batched_smallm_bt_kernel(
client: &CudaClient,
dtype: DType,
a_ptr: u64,
b_ptr: u64,
c_ptr: u64,
batch: usize,
m: usize,
n: usize,
k: usize,
a_batch: usize,
b_batch: usize,
) -> Result<bool> {
if !smallm_applies(dtype, m, n, batch, SmallmLimits::of(client)) {
return Ok(false);
}
let context = client.context();
let stream = client.stream();
let module = get_or_load_module(context, client.device.index, kernel_names::MATMUL_MODULE)?;
let func = get_kernel_function(&module, "matmul_batched_f32_smallm_bt")?;
let cfg = smallm_launch_config(m, n, batch);
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);
builder.arg(&c_ptr);
builder.arg(&batch_u32);
builder.arg(&m_u32);
builder.arg(&n_u32);
builder.arg(&k_u32);
builder.arg(&a_batch_u32);
builder.arg(&b_batch_u32);
builder.launch(cfg).map_err(|e| {
Error::Internal(format!(
"CUDA batched matmul F32 small-M kernel 'matmul_batched_f32_smallm_bt' \
launch failed: {:?}",
e
))
})?;
}
Ok(true)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn launch_config_is_one_block_per_row_group_and_m_with_256_threads() {
let cfg = smallm_launch_config(4, 5120, 3);
assert_eq!(cfg.grid_dim, (640, 4, 3));
assert_eq!(cfg.block_dim, (256, 1, 1));
assert_eq!(cfg.shared_mem_bytes, 0);
}
#[test]
fn launch_config_rounds_a_partial_row_group_up() {
assert_eq!(smallm_launch_config(1, 48, 1).grid_dim, (6, 1, 1));
assert_eq!(smallm_launch_config(1, 49, 1).grid_dim, (7, 1, 1));
assert_eq!(smallm_launch_config(1, 1, 1).grid_dim, (1, 1, 1));
assert_eq!(
smallm_launch_config(1, MAX_SMALL_N, 1).grid_dim,
(128, 1, 1)
);
}
const LIMITS: SmallmLimits = SmallmLimits {
sm_count: 28,
max_waves: 12,
};
#[test]
fn applies_only_to_f32_at_one_to_max_rows() {
assert!(smallm_applies(DType::F32, 1, 48, 1, LIMITS));
assert!(smallm_applies(DType::F32, MAX_SMALL_M, 40, 1, LIMITS));
assert!(!smallm_applies(DType::F32, MAX_SMALL_M + 1, 1, 1, LIMITS));
assert!(!smallm_applies(DType::F32, 0, 48, 1, LIMITS));
assert!(!smallm_applies(DType::F32, 1, 0, 1, LIMITS));
assert!(smallm_applies(DType::F32, 1, MAX_SMALL_N, 1, LIMITS));
assert!(!smallm_applies(DType::F32, 1, MAX_SMALL_N + 1, 1, LIMITS));
assert!(!smallm_applies(DType::F16, 1, 48, 1, LIMITS));
assert!(!smallm_applies(DType::F64, 1, 48, 1, LIMITS));
}
#[test]
fn block_count_is_row_groups_times_m() {
assert_eq!(smallm_block_count(1, 48), 6);
assert_eq!(smallm_block_count(64, 41), 6 * 64);
assert_eq!(smallm_block_count(3, MAX_SMALL_N), 384);
}
#[test]
fn applies_only_within_the_wave_bound() {
assert!(smallm_applies(DType::F32, 2, MAX_SMALL_N, 1, LIMITS));
assert!(!smallm_applies(DType::F32, 3, MAX_SMALL_N, 1, LIMITS));
assert!(smallm_applies(DType::F32, MAX_SMALL_M, 40, 1, LIMITS));
assert!(!smallm_applies(DType::F32, MAX_SMALL_M, 48, 1, LIMITS));
assert!(!smallm_applies(DType::F32, MAX_SMALL_M, 41, 1, LIMITS));
let wider = SmallmLimits {
sm_count: 32,
..LIMITS
};
assert!(smallm_applies(DType::F32, MAX_SMALL_M, 48, 1, wider));
let deeper = SmallmLimits {
max_waves: 14,
..LIMITS
};
assert!(smallm_applies(DType::F32, MAX_SMALL_M, 48, 1, deeper));
let unread = SmallmLimits {
sm_count: 0,
..LIMITS
};
assert!(!smallm_applies(DType::F32, 1, 1, 1, unread));
}
#[test]
fn applies_only_when_the_batch_fits_grid_z() {
let z = MAX_GRID_DIM_YZ as usize;
assert!(smallm_applies(DType::F32, 1, 48, z, LIMITS));
assert!(!smallm_applies(DType::F32, 1, 48, z + 1, LIMITS));
assert!(!smallm_applies(DType::F32, 1, 48, 0, LIMITS));
}
}