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,
};
#[derive(Copy, Clone, Debug)]
pub struct HyperConnectionDescriptor {
pub batch: i32,
pub hidden_dim: i32,
pub n_streams: i32,
pub sinkhorn_iters: i32,
pub eps: f32,
pub element: ElementKind,
}
pub struct HyperConnectionArgs<'a, T: Element> {
pub x_expanded: TensorRef<'a, T, 3>,
pub rmsnorm_weight: TensorRef<'a, half::bf16, 1>,
pub h_pre: TensorRef<'a, f32, 1>,
pub h_post: TensorRef<'a, f32, 1>,
pub h_res: TensorRef<'a, f32, 2>,
pub out: TensorMut<'a, T, 3>,
}
pub struct HyperConnectionPlan<T: Element> {
desc: HyperConnectionDescriptor,
sku: KernelSku,
#[cfg(feature = "mhc")]
handle: *mut c_void,
_marker: PhantomData<T>,
}
unsafe impl<T: Element> Send for HyperConnectionPlan<T> {}
unsafe impl<T: Element> Sync for HyperConnectionPlan<T> {}
impl<T: Element> HyperConnectionPlan<T> {
pub fn select(
_stream: &Stream,
desc: &HyperConnectionDescriptor,
_pref: PlanPreference,
) -> Result<Self> {
if desc.element != T::KIND {
return Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: descriptor element != T",
));
}
if !matches!(T::KIND, ElementKind::F32) {
return Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: Tier 1 wired today: `{f32}` only \
(f16 / bf16 deferred to Tier 3)",
));
}
if desc.batch <= 0 || desc.hidden_dim <= 0 || desc.n_streams <= 0 {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: batch / hidden_dim / n_streams must be positive",
));
}
if desc.n_streams >= 32 {
return Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: n_streams >= 32 not yet supported \
(would activate the cuBLAS-Lt tensor-core mix path)",
));
}
if desc.hidden_dim < desc.n_streams {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: hidden_dim < n_streams (need at least \
one channel per stream for the aggregate kernel)",
));
}
if desc.sinkhorn_iters <= 0 || desc.sinkhorn_iters > 1000 {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: sinkhorn_iters must be in 1..=1000",
));
}
if !(desc.eps.is_finite() && desc.eps > 0.0 && desc.eps < 1.0) {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: eps must be finite and in (0, 1)",
));
}
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::HyperConnection as u16,
element: T::KIND,
aux_element: Some(ElementKind::Bf16), layout: None,
epilogue: None,
arch: ArchSku::Sm80,
backend: BackendKind::Bespoke,
precision_guarantee,
};
#[cfg(feature = "mhc")]
{
let probe = unsafe {
baracuda_kernels_sys::baracuda_kernels_mhc_layer_static_bf16_can_implement(
desc.batch,
desc.hidden_dim,
desc.n_streams,
)
};
super::map_status(probe)?;
let handle = unsafe {
baracuda_kernels_sys::baracuda_kernels_mhc_layer_static_bf16_create(
desc.batch,
desc.hidden_dim,
desc.n_streams,
desc.sinkhorn_iters,
desc.eps,
)
};
if handle.is_null() {
return Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: native MHCLayer init failed",
));
}
Ok(Self {
desc: *desc,
sku,
handle,
_marker: PhantomData,
})
}
#[cfg(not(feature = "mhc"))]
{
let _ = sku; Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: build with the `mhc` cargo feature",
))
}
}
pub fn can_implement(&self, args: &HyperConnectionArgs<'_, T>) -> Result<()> {
let b = self.desc.batch;
let n = self.desc.n_streams;
let c = self.desc.hidden_dim;
if args.x_expanded.shape != [b, n, c] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: x_expanded shape mismatch with [B, n, C]",
));
}
if args.out.shape != [b, n, c] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: out shape mismatch with [B, n, C]",
));
}
if args.rmsnorm_weight.shape != [c] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: rmsnorm_weight shape mismatch with [C]",
));
}
if args.h_pre.shape != [n] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: h_pre shape mismatch with [n]",
));
}
if args.h_post.shape != [n] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: h_post shape mismatch with [n]",
));
}
if args.h_res.shape != [n, n] {
return Err(Error::InvalidProblem(
"baracuda-kernels::HyperConnectionPlan: h_res shape mismatch with [n, n]",
));
}
let bnc = (b as i64) * (n as i64) * (c as i64);
if (args.x_expanded.data.len() as i64) < bnc {
return Err(Error::BufferTooSmall {
needed: bnc as usize,
got: args.x_expanded.data.len(),
});
}
if (args.out.data.len() as i64) < bnc {
return Err(Error::BufferTooSmall {
needed: bnc as usize,
got: args.out.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: HyperConnectionArgs<'_, T>,
) -> Result<()> {
self.can_implement(&args)?;
#[cfg(feature = "mhc")]
{
let stream_ptr = stream.as_raw() as *mut c_void;
let status = unsafe {
baracuda_kernels_sys::baracuda_kernels_mhc_layer_static_bf16_run(
self.handle,
args.x_expanded.data.as_raw().0 as *const c_void,
args.rmsnorm_weight.data.as_raw().0 as *const c_void,
args.h_pre.data.as_raw().0 as *const c_void,
args.h_post.data.as_raw().0 as *const c_void,
args.h_res.data.as_raw().0 as *const c_void,
args.out.data.as_raw().0 as *mut c_void,
self.desc.batch,
self.desc.hidden_dim,
self.desc.n_streams,
core::ptr::null_mut(),
0,
stream_ptr,
)
};
super::map_status(status)
}
#[cfg(not(feature = "mhc"))]
{
let _ = stream;
Err(Error::Unsupported(
"baracuda-kernels::HyperConnectionPlan: build with the `mhc` cargo feature",
))
}
}
}
impl<T: Element> Drop for HyperConnectionPlan<T> {
fn drop(&mut self) {
#[cfg(feature = "mhc")]
{
if !self.handle.is_null() {
unsafe {
baracuda_kernels_sys::baracuda_kernels_mhc_layer_static_bf16_destroy(
self.handle,
);
}
self.handle = core::ptr::null_mut();
}
}
}
}