use core::ffi::c_void;
use core::marker::PhantomData;
use baracuda_cutlass::{Error, Result};
use baracuda_driver::Stream;
use baracuda_kernels_types::{
ArchSku, BackendKind, Element, ElementKind, KernelSku, LossKind, LossReduction, MathPrecision,
OpCategory, PlanPreference, PrecisionGuarantee, TensorMut, TensorRef, Workspace,
};
use super::common::{check_supported_dtype, map_status, unpack_workspace};
#[derive(Copy, Clone, Debug)]
pub struct CtcLossDescriptor {
pub max_time: i32,
pub batch_size: i32,
pub num_classes: i32,
pub max_target_len: i32,
pub blank: i32,
pub reduction: LossReduction,
pub zero_infinity: bool,
pub element: ElementKind,
}
pub struct CtcLossArgs<'a, T: Element> {
pub log_probs: TensorRef<'a, T, 3>,
pub targets: TensorRef<'a, i64, 2>,
pub input_lengths: TensorRef<'a, i64, 1>,
pub target_lengths: TensorRef<'a, i64, 1>,
pub loss: TensorMut<'a, T, 1>,
pub alpha: TensorMut<'a, u8, 1>,
}
pub struct CtcLossPlan<T: Element> {
desc: CtcLossDescriptor,
sku: KernelSku,
_marker: PhantomData<T>,
}
impl<T: Element> CtcLossPlan<T> {
pub fn select(
_stream: &Stream,
desc: &CtcLossDescriptor,
_pref: PlanPreference,
) -> Result<Self> {
if desc.element != T::KIND {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossPlan: descriptor element != T",
));
}
check_supported_dtype::<T>()?;
if desc.max_time < 0
|| desc.batch_size < 0
|| desc.num_classes < 0
|| desc.max_target_len < 0
{
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: dimensions must be non-negative",
));
}
if desc.num_classes > 32 {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossPlan: num_classes > 32 not supported \
(trailblazer cap)",
));
}
if desc.max_target_len > 256 {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossPlan: max_target_len > 256 not \
supported (trailblazer cap)",
));
}
if desc.num_classes > 0 && (desc.blank < 0 || desc.blank >= desc.num_classes) {
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: blank must be in [0, num_classes)",
));
}
let precision_guarantee = PrecisionGuarantee {
math_precision: MathPrecision::F32,
accumulator: if T::KIND == ElementKind::F64 {
ElementKind::F64
} else {
ElementKind::F32
},
bit_stable_on_same_hardware: true,
deterministic: true,
};
let sku = KernelSku {
category: OpCategory::Loss,
op: LossKind::Ctc as u16,
element: T::KIND,
aux_element: None,
layout: None,
epilogue: None,
arch: ArchSku::Sm80,
backend: BackendKind::Bespoke,
precision_guarantee,
};
Ok(Self {
desc: *desc,
sku,
_marker: PhantomData,
})
}
#[inline]
pub fn alpha_workspace_size(&self) -> usize {
let acc_size = if T::KIND == ElementKind::F64 { 8usize } else { 4usize };
let l_max = (2 * self.desc.max_target_len as i64 + 1).max(1);
(self.desc.max_time as usize)
.saturating_mul(self.desc.batch_size as usize)
.saturating_mul(l_max as usize)
.saturating_mul(acc_size)
}
#[inline]
pub fn workspace_size(&self) -> usize {
let acc_size = if T::KIND == ElementKind::F64 { 8usize } else { 4usize };
(self.desc.batch_size as usize).saturating_mul(acc_size)
}
#[inline]
pub fn sku(&self) -> KernelSku {
self.sku
}
#[inline]
pub fn precision_guarantee(&self) -> PrecisionGuarantee {
self.sku.precision_guarantee
}
pub fn run(
&self,
stream: &Stream,
workspace: Workspace<'_>,
args: CtcLossArgs<'_, T>,
) -> Result<()> {
if self.desc.batch_size == 0 || self.desc.max_time == 0 {
return Ok(());
}
if args.log_probs.shape
!= [self.desc.max_time, self.desc.batch_size, self.desc.num_classes]
{
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: log_probs shape must be \
[max_time, batch_size, num_classes]",
));
}
if args.targets.shape != [self.desc.batch_size, self.desc.max_target_len] {
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: targets shape must be \
[batch_size, max_target_len]",
));
}
if args.input_lengths.shape != [self.desc.batch_size] {
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: input_lengths shape must be [batch_size]",
));
}
if args.target_lengths.shape != [self.desc.batch_size] {
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossPlan: target_lengths shape must be [batch_size]",
));
}
let needed_alpha = self.alpha_workspace_size();
if (args.alpha.data.len()) < needed_alpha {
return Err(Error::WorkspaceTooSmall {
needed: needed_alpha,
got: args.alpha.data.len(),
});
}
let (ws_ptr, ws_bytes) = unpack_workspace(workspace, self.workspace_size())?;
let stream_ptr = stream.as_raw() as *mut c_void;
let log_probs_ptr = args.log_probs.data.as_raw().0 as *const c_void;
let targets_ptr = args.targets.data.as_raw().0 as *const c_void;
let input_lengths_ptr = args.input_lengths.data.as_raw().0 as *const c_void;
let target_lengths_ptr = args.target_lengths.data.as_raw().0 as *const c_void;
let alpha_ptr = args.alpha.data.as_raw().0 as *mut c_void;
let out_ptr = args.loss.data.as_raw().0 as *mut c_void;
let mode = self.desc.reduction as i32;
let zinf = if self.desc.zero_infinity { 1 } else { 0 };
let status = match T::KIND {
ElementKind::F32 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_f32_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
out_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::F16 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_f16_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
out_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::Bf16 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_bf16_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
out_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::F64 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_f64_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
out_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossPlan::run unwired dtype",
));
}
};
map_status(status)
}
}
#[derive(Copy, Clone, Debug)]
pub struct CtcLossBackwardDescriptor {
pub max_time: i32,
pub batch_size: i32,
pub num_classes: i32,
pub max_target_len: i32,
pub blank: i32,
pub reduction: LossReduction,
pub zero_infinity: bool,
pub element: ElementKind,
}
pub struct CtcLossBackwardArgs<'a, T: Element> {
pub log_probs: TensorRef<'a, T, 3>,
pub targets: TensorRef<'a, i64, 2>,
pub input_lengths: TensorRef<'a, i64, 1>,
pub target_lengths: TensorRef<'a, i64, 1>,
pub per_sample_loss: TensorRef<'a, u8, 1>,
pub alpha: TensorRef<'a, u8, 1>,
pub dloss: TensorRef<'a, T, 1>,
pub dlog_probs: TensorMut<'a, T, 3>,
pub mean_denom: i64,
}
pub struct CtcLossBackwardPlan<T: Element> {
desc: CtcLossBackwardDescriptor,
sku: KernelSku,
_marker: PhantomData<T>,
}
impl<T: Element> CtcLossBackwardPlan<T> {
pub fn select(
_stream: &Stream,
desc: &CtcLossBackwardDescriptor,
_pref: PlanPreference,
) -> Result<Self> {
if desc.element != T::KIND {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossBackwardPlan: descriptor element != T",
));
}
check_supported_dtype::<T>()?;
if desc.max_time < 0
|| desc.batch_size < 0
|| desc.num_classes < 0
|| desc.max_target_len < 0
{
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossBackwardPlan: dimensions must be non-negative",
));
}
if desc.num_classes > 32 {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossBackwardPlan: num_classes > 32 not supported",
));
}
if desc.max_target_len > 256 {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossBackwardPlan: max_target_len > 256 not supported",
));
}
if desc.num_classes > 0 && (desc.blank < 0 || desc.blank >= desc.num_classes) {
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossBackwardPlan: blank must be in [0, num_classes)",
));
}
let precision_guarantee = PrecisionGuarantee {
math_precision: MathPrecision::F32,
accumulator: if T::KIND == ElementKind::F64 {
ElementKind::F64
} else {
ElementKind::F32
},
bit_stable_on_same_hardware: true,
deterministic: false, };
let sku = KernelSku {
category: OpCategory::Loss,
op: LossKind::Ctc as u16,
element: T::KIND,
aux_element: None,
layout: None,
epilogue: None,
arch: ArchSku::Sm80,
backend: BackendKind::Bespoke,
precision_guarantee,
};
Ok(Self {
desc: *desc,
sku,
_marker: PhantomData,
})
}
#[inline]
pub fn workspace_size(&self) -> usize {
let acc_size = if T::KIND == ElementKind::F64 { 8usize } else { 4usize };
let l_max = (2 * self.desc.max_target_len as i64 + 1).max(1);
(self.desc.batch_size as usize)
.saturating_mul(l_max as usize)
.saturating_mul(acc_size)
}
#[inline]
pub fn sku(&self) -> KernelSku {
self.sku
}
#[inline]
pub fn precision_guarantee(&self) -> PrecisionGuarantee {
self.sku.precision_guarantee
}
pub fn run(
&self,
stream: &Stream,
workspace: Workspace<'_>,
args: CtcLossBackwardArgs<'_, T>,
) -> Result<()> {
if self.desc.batch_size == 0 || self.desc.max_time == 0 {
return Ok(());
}
if args.dlog_probs.shape
!= [self.desc.max_time, self.desc.batch_size, self.desc.num_classes]
{
return Err(Error::InvalidProblem(
"baracuda-kernels::CtcLossBackwardPlan: dlog_probs shape must be \
[max_time, batch_size, num_classes]",
));
}
let (ws_ptr, ws_bytes) = unpack_workspace(workspace, self.workspace_size())?;
let stream_ptr = stream.as_raw() as *mut c_void;
let log_probs_ptr = args.log_probs.data.as_raw().0 as *const c_void;
let targets_ptr = args.targets.data.as_raw().0 as *const c_void;
let input_lengths_ptr = args.input_lengths.data.as_raw().0 as *const c_void;
let target_lengths_ptr = args.target_lengths.data.as_raw().0 as *const c_void;
let alpha_ptr = args.alpha.data.as_raw().0 as *const c_void;
let per_sample_loss_ptr = args.per_sample_loss.data.as_raw().0 as *const c_void;
let dloss_ptr = args.dloss.data.as_raw().0 as *const c_void;
let dlog_probs_ptr = args.dlog_probs.data.as_raw().0 as *mut c_void;
let mode = self.desc.reduction as i32;
let zinf = if self.desc.zero_infinity { 1 } else { 0 };
let inv_denom = match self.desc.reduction {
LossReduction::Mean => {
let d = args.mean_denom.max(1);
1.0_f32 / (d as f32)
}
LossReduction::Sum | LossReduction::None => 1.0_f32,
};
let status = match T::KIND {
ElementKind::F32 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_backward_f32_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
inv_denom,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
per_sample_loss_ptr,
dloss_ptr,
dlog_probs_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::F16 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_backward_f16_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
inv_denom,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
per_sample_loss_ptr,
dloss_ptr,
dlog_probs_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::Bf16 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_backward_bf16_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
inv_denom,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
per_sample_loss_ptr,
dloss_ptr,
dlog_probs_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
ElementKind::F64 => unsafe {
baracuda_kernels_sys::baracuda_kernels_loss_ctc_backward_f64_run(
self.desc.max_time,
self.desc.batch_size,
self.desc.num_classes,
self.desc.max_target_len,
self.desc.blank,
mode,
zinf,
inv_denom,
log_probs_ptr,
targets_ptr,
input_lengths_ptr,
target_lengths_ptr,
alpha_ptr,
per_sample_loss_ptr,
dloss_ptr,
dlog_probs_ptr,
ws_ptr,
ws_bytes,
stream_ptr,
)
},
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::CtcLossBackwardPlan::run unwired dtype",
));
}
};
map_status(status)
}
}