use core::ffi::c_void;
use core::marker::PhantomData;
use baracuda_cutlass::{Error, Result};
use baracuda_driver::Stream;
use baracuda_kernels_types::{
ArchSku, AttentionKind, BackendKind, Element, ElementKind, KernelSku, MathPrecision,
OpCategory, PlanPreference, PrecisionGuarantee, TensorMut, TensorRef, Workspace,
};
use super::map_status;
#[derive(Copy, Clone, Debug)]
pub struct RopeDescriptor {
pub batch_size: i32,
pub num_heads: i32,
pub seq_len: i32,
pub head_dim: i32,
pub base: f32,
pub element: ElementKind,
}
pub struct RopeArgs<'a, T: Element> {
pub x: TensorRef<'a, T, 4>,
pub positions: Option<TensorRef<'a, i64, 1>>,
pub y: TensorMut<'a, T, 4>,
}
pub struct RopePlan<T: Element> {
desc: RopeDescriptor,
sku: KernelSku,
_marker: PhantomData<T>,
}
impl<T: Element> RopePlan<T> {
pub fn select(_stream: &Stream, desc: &RopeDescriptor, _pref: PlanPreference) -> Result<Self> {
if desc.element != T::KIND {
return Err(Error::Unsupported(
"baracuda-kernels::RopePlan: descriptor element != T",
));
}
if desc.batch_size < 0
|| desc.num_heads < 0
|| desc.seq_len < 0
|| desc.head_dim < 0
{
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: extents must be non-negative",
));
}
if desc.head_dim % 2 != 0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: head_dim must be even (RoPE rotates pairs)",
));
}
if !desc.base.is_finite() || desc.base <= 0.0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: base must be finite and positive",
));
}
let dtype_in_scope = matches!(
T::KIND,
ElementKind::F32 | ElementKind::F16 | ElementKind::Bf16 | ElementKind::F64
);
if !dtype_in_scope {
return Err(Error::Unsupported(
"baracuda-kernels::RopePlan: wired today: `{f32, f16, bf16, f64}`",
));
}
let precision_guarantee = PrecisionGuarantee {
math_precision: MathPrecision::F32,
accumulator: ElementKind::F32,
bit_stable_on_same_hardware: true,
deterministic: true,
};
let sku = KernelSku {
category: OpCategory::Attention,
op: AttentionKind::Rope 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,
})
}
pub fn can_implement(&self, args: &RopeArgs<'_, T>) -> Result<()> {
let want_shape = [
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
];
if args.x.shape != want_shape {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: x shape mismatch with descriptor",
));
}
if args.y.shape != want_shape {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: y shape mismatch with descriptor",
));
}
if args.x.stride[3] != 1 || args.y.stride[3] != 1 {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: head_dim axis must have stride=1 \
(RoPE rotates adjacent pairs)",
));
}
if let Some(ref p) = args.positions {
if p.shape != [self.desc.seq_len] {
return Err(Error::InvalidProblem(
"baracuda-kernels::RopePlan: positions shape must be [seq_len]",
));
}
if (p.data.len() as i64) < self.desc.seq_len as i64 {
return Err(Error::BufferTooSmall {
needed: self.desc.seq_len as usize,
got: p.data.len(),
});
}
}
if args.x.is_contiguous() && args.y.is_contiguous() {
let numel = args.x.numel();
if (args.x.data.len() as i64) < numel || (args.y.data.len() as i64) < numel {
return Err(Error::BufferTooSmall {
needed: numel as usize,
got: args.x.data.len().min(args.y.data.len()),
});
}
}
Ok(())
}
#[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: RopeArgs<'_, T>,
) -> Result<()> {
self.can_implement(&args)?;
let numel = args.x.numel();
if numel == 0 {
return Ok(());
}
let stream_ptr = stream.as_raw() as *mut c_void;
let x_ptr = args.x.data.as_raw().0 as *const c_void;
let y_ptr = args.y.data.as_raw().0 as *mut c_void;
let (pos_ptr, pos_default_flag) = match &args.positions {
Some(p) => (p.data.as_raw().0 as *const c_void, 0i32),
None => (core::ptr::null::<c_void>(), 1i32),
};
let contig = args.x.is_contiguous() && args.y.is_contiguous();
let status = unsafe {
if contig {
match T::KIND {
ElementKind::F32 => baracuda_kernels_sys::baracuda_kernels_rope_f32_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F16 => baracuda_kernels_sys::baracuda_kernels_rope_f16_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::Bf16 => baracuda_kernels_sys::baracuda_kernels_rope_bf16_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F64 => baracuda_kernels_sys::baracuda_kernels_rope_f64_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::RopePlan::run reached an unimplemented dtype",
));
}
}
} else {
let sxb = args.x.stride[0];
let sxh = args.x.stride[1];
let sxs = args.x.stride[2];
let syb = args.y.stride[0];
let syh = args.y.stride[1];
let sys = args.y.stride[2];
match T::KIND {
ElementKind::F32 => baracuda_kernels_sys::baracuda_kernels_rope_f32_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sxb, sxh, sxs, syb, syh, sys,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F16 => baracuda_kernels_sys::baracuda_kernels_rope_f16_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sxb, sxh, sxs, syb, syh, sys,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::Bf16 => baracuda_kernels_sys::baracuda_kernels_rope_bf16_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sxb, sxh, sxs, syb, syh, sys,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
ElementKind::F64 => baracuda_kernels_sys::baracuda_kernels_rope_f64_strided_run(
self.desc.batch_size,
self.desc.num_heads,
self.desc.seq_len,
self.desc.head_dim,
sxb, sxh, sxs, syb, syh, sys,
self.desc.base,
pos_default_flag,
x_ptr,
pos_ptr,
y_ptr,
core::ptr::null_mut(),
0,
stream_ptr,
),
_ => {
return Err(Error::Unsupported(
"baracuda-kernels::RopePlan::run reached an unimplemented dtype",
));
}
}
}
};
map_status(status)
}
}