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, MathPrecision, OpCategory,
PlanPreference, PrecisionGuarantee, SortKind, TensorMut, TensorRef, Workspace,
};
use super::{map_status, SORT_MAX_ROW};
#[derive(Copy, Clone, Debug)]
pub struct SortDescriptor {
pub batch: i32,
pub row_len: i32,
pub descending: bool,
pub element: ElementKind,
}
pub struct SortArgs<'a, T: Element> {
pub input: TensorRef<'a, T, 2>,
pub values: TensorMut<'a, T, 2>,
pub indices: TensorMut<'a, i32, 2>,
}
pub struct SortPlan<T: Element> {
desc: SortDescriptor,
sku: KernelSku,
_marker: PhantomData<T>,
}
impl<T: Element> SortPlan<T> {
pub fn select(
_stream: &Stream,
desc: &SortDescriptor,
_pref: PlanPreference,
) -> Result<Self> {
validate_sort_desc(desc.batch, desc.row_len, desc.element, T::KIND, "SortPlan")?;
let sku = build_sku::<T>(SortKind::Sort);
Ok(Self {
desc: *desc,
sku,
_marker: PhantomData,
})
}
pub fn can_implement(&self, args: &SortArgs<'_, T>) -> Result<()> {
validate_sort_args_2(
self.desc.batch,
self.desc.row_len,
args.input.shape,
args.values.shape,
args.indices.shape,
"SortPlan",
)
}
#[inline]
pub fn workspace_size(&self) -> usize {
0
}
#[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: SortArgs<'_, T>,
) -> Result<()> {
self.can_implement(&args)?;
if self.desc.batch == 0 || self.desc.row_len == 0 {
return Ok(());
}
let in_ptr = args.input.data.as_raw().0 as *const c_void;
let vals_ptr = args.values.data.as_raw().0 as *mut c_void;
let idx_ptr = args.indices.data.as_raw().0 as *mut c_void;
let stream_ptr = stream.as_raw() as *mut c_void;
let desc_flag = if self.desc.descending { 1 } else { 0 };
let status = match T::KIND {
ElementKind::F32 => unsafe {
baracuda_kernels_sys::baracuda_kernels_sort_f32_run(
self.desc.batch,
self.desc.row_len,
desc_flag,
in_ptr,
vals_ptr,
idx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
)
},
ElementKind::F64 => unsafe {
baracuda_kernels_sys::baracuda_kernels_sort_f64_run(
self.desc.batch,
self.desc.row_len,
desc_flag,
in_ptr,
vals_ptr,
idx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
)
},
ElementKind::I32 => unsafe {
baracuda_kernels_sys::baracuda_kernels_sort_i32_run(
self.desc.batch,
self.desc.row_len,
desc_flag,
in_ptr,
vals_ptr,
idx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
)
},
ElementKind::I64 => unsafe {
baracuda_kernels_sys::baracuda_kernels_sort_i64_run(
self.desc.batch,
self.desc.row_len,
desc_flag,
in_ptr,
vals_ptr,
idx_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
)
},
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::SortPlan::run reached an unimplemented dtype \
— select() should have caught this",
));
}
};
map_status(status)
}
}
pub(crate) fn validate_sort_desc(
batch: i32,
row_len: i32,
descriptor_element: ElementKind,
expected_element: ElementKind,
_plan_name: &'static str,
) -> Result<()> {
if descriptor_element != expected_element {
return Err(Error::Unsupported(
"baracuda-kernels::sort: descriptor element != type parameter T",
));
}
if batch < 0 || row_len < 0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::sort: batch / row_len must be non-negative",
));
}
if row_len > SORT_MAX_ROW {
return Err(Error::Unsupported(
"baracuda-kernels::sort: row_len > 1024 not supported in the \
block-bitonic trailblazer (tile-radix follow-up reserved)",
));
}
if !matches!(
descriptor_element,
ElementKind::F32 | ElementKind::F64 | ElementKind::I32 | ElementKind::I64
) {
return Err(Error::Unsupported(
"baracuda-kernels::sort: today only f32 / f64 / i32 / i64 wired",
));
}
Ok(())
}
pub(crate) fn validate_sort_args_2(
batch: i32,
row_len: i32,
in_shape: [i32; 2],
vals_shape: [i32; 2],
idx_shape: [i32; 2],
_plan_name: &'static str,
) -> Result<()> {
let expected = [batch, row_len];
if in_shape != expected {
return Err(Error::InvalidProblem(
"baracuda-kernels::sort: input shape != [batch, row_len]",
));
}
if vals_shape != expected {
return Err(Error::InvalidProblem(
"baracuda-kernels::sort: values shape != [batch, row_len]",
));
}
if idx_shape != expected {
return Err(Error::InvalidProblem(
"baracuda-kernels::sort: indices shape != [batch, row_len]",
));
}
Ok(())
}
pub(crate) fn build_sku<T: Element>(op: SortKind) -> KernelSku {
let precision_guarantee = PrecisionGuarantee {
math_precision: if T::KIND == ElementKind::F64 {
MathPrecision::F64
} else {
MathPrecision::F32
},
accumulator: T::KIND,
bit_stable_on_same_hardware: true,
deterministic: true,
};
KernelSku {
category: OpCategory::Sorting,
op: op as u16,
element: T::KIND,
aux_element: Some(ElementKind::I32),
layout: None,
epilogue: None,
arch: ArchSku::Sm80,
backend: BackendKind::Bespoke,
precision_guarantee,
}
}