use crate::dtype::DType;
use crate::error::Result;
use crate::ops::conv_transpose_common::ConvTranspose1dParams;
use crate::ops::{MatmulOps, TypeConversionOps};
use crate::runtime::cuda::kernels::launch_col2im_transpose1d;
use crate::runtime::cuda::{CudaClient, CudaRuntime};
use crate::tensor::Tensor;
const MIN_C_IN: usize = 32;
const MAX_COL_ELEMENTS: usize = 1 << 27;
pub fn gemm_first_row_col_elements(params: &ConvTranspose1dParams) -> Option<usize> {
params
.length
.checked_mul(params.c_out)
.and_then(|v| v.checked_mul(params.kernel_size))
}
fn max_chunk_rows(params: &ConvTranspose1dParams) -> usize {
let per_row = gemm_first_row_col_elements(params)
.unwrap_or(usize::MAX)
.max(1);
(MAX_COL_ELEMENTS / per_row).max(1)
}
pub fn use_conv_transpose1d_gemm_first(params: &ConvTranspose1dParams, dtype: DType) -> bool {
if !matches!(dtype, DType::F32 | DType::F64 | DType::F16 | DType::BF16) || params.groups != 1 {
return false;
}
match gemm_first_row_col_elements(params) {
Some(n) if n <= MAX_COL_ELEMENTS => {}
_ => return false,
}
params.c_in >= MIN_C_IN
}
pub fn conv_transpose1d_gemm_first(
client: &CudaClient,
input: &Tensor<CudaRuntime>,
weight: &Tensor<CudaRuntime>,
bias: Option<&Tensor<CudaRuntime>>,
params: &ConvTranspose1dParams,
) -> Result<Tensor<CudaRuntime>> {
conv_transpose1d_gemm_first_chunked(client, input, weight, bias, params, max_chunk_rows(params))
}
pub(crate) fn conv_transpose1d_gemm_first_chunked(
client: &CudaClient,
input: &Tensor<CudaRuntime>,
weight: &Tensor<CudaRuntime>,
bias: Option<&Tensor<CudaRuntime>>,
params: &ConvTranspose1dParams,
chunk_max: usize,
) -> Result<Tensor<CudaRuntime>> {
let dtype = input.dtype();
let row = params.c_out * params.kernel_size;
let w_gemm = weight.reshape(&[1, params.c_in, row])?;
let out = Tensor::<CudaRuntime>::empty(
&[params.batch, params.c_out, params.output_length],
dtype,
&client.device,
)?;
let chunk_max = chunk_max.max(1);
let mut bias_col: Option<Tensor<CudaRuntime>> = None;
let mut start = 0usize;
while start < params.batch {
let rows = chunk_max.min(params.batch - start);
let x_t = input
.narrow(0, start, rows)?
.transpose(1, 2)?
.contiguous()?;
let col = client.matmul_wide(&x_t, &w_gemm)?;
let col_dtype = col.dtype();
if col_dtype != dtype && bias_col.is_none() {
bias_col = bias.map(|b| client.cast(b, col_dtype)).transpose()?;
}
let bias_ptr = bias_col.as_ref().or(bias).map(|b| b.ptr());
let out_chunk = out.narrow(0, start, rows)?;
unsafe {
launch_col2im_transpose1d(
&client.context,
&client.stream,
client.device.index,
col_dtype,
dtype,
col.ptr(),
bias_ptr,
out_chunk.ptr(),
rows,
params.length,
params.c_out,
params.kernel_size,
params.output_length,
params.stride,
params.pad_left,
params.dilation,
)?;
}
start += rows;
}
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ops::RandomOps;
use crate::ops::conv_transpose_common::validate_conv_transpose1d;
use crate::runtime::Runtime;
use crate::runtime::cuda::CudaDevice;
fn setup() -> Option<CudaClient> {
if !crate::runtime::cuda::is_cuda_available() {
return None;
}
let device = CudaDevice::new(0);
Some(CudaRuntime::default_client(&device))
}
#[test]
fn chunked_rows_match_one_chunk_bitwise() {
let Some(client) = setup() else {
return;
};
let (batch, c_in, c_out, k, len) = (5usize, 6usize, 8usize, 3usize, 11usize);
let input = client.rand(&[batch, c_in, len], DType::F32).expect("input");
let weight = client.rand(&[c_in, c_out, k], DType::F32).expect("weight");
let bias = client.rand(&[c_out], DType::F32).expect("bias");
let params = validate_conv_transpose1d(
input.shape(),
weight.shape(),
Some(bias.shape()),
2,
crate::ops::PaddingMode::Custom(1, 1, 0, 0),
1,
1,
1,
DType::F32,
DType::F32,
Some(DType::F32),
)
.expect("params");
let whole = conv_transpose1d_gemm_first_chunked(
&client,
&input,
&weight,
Some(&bias),
¶ms,
usize::MAX,
)
.expect("whole");
let chunked =
conv_transpose1d_gemm_first_chunked(&client, &input, &weight, Some(&bias), ¶ms, 2)
.expect("chunked");
assert_eq!(whole.shape(), chunked.shape());
let a: Vec<f32> = whole.to_vec();
let b: Vec<f32> = chunked.to_vec();
for (i, (x, y)) in a.iter().zip(&b).enumerate() {
assert_eq!(x.to_bits(), y.to_bits(), "element {i}: {x} vs {y}");
}
}
}