Skip to main content

baracuda_kernels/softmax/
sparsemax.rs

1//! Sparsemax forward plan — projection onto the probability simplex.
2//!
3//! `y = ProjSimplex(x)` via the standard sort-then-threshold closed
4//! form: sort logits descending, find the largest `k` such that
5//! `1 + (k+1) · x_sorted[k] > Σ_{i ≤ k} x_sorted[i]`, set
6//! `τ = (Σ_{i ≤ k_max} x_sorted[i] - 1) / (k_max + 1)`, and emit
7//! `y[i] = max(0, x[i] - τ)`.
8//!
9//! Wired today: `T ∈ {f32, f16, bf16, f64}`. Row extent (softmax axis
10//! size) limited to 1024 (Phase 11.6) — the kernel uses a
11//! `cub::BlockRadixSort` + `cub::BlockScan` block-cooperative
12//! algorithm: one CUDA thread block per row, 256 threads per block,
13//! and two compiled tile-size specializations
14//! (`ITEMS_PER_THREAD = 1` for extents ≤ 256, `ITEMS_PER_THREAD = 4`
15//! for extents 257..=1024). Larger extents return `Unsupported` at
16//! plan-select time.
17
18use core::ffi::c_void;
19use core::marker::PhantomData;
20
21use baracuda_cutlass::{Error, Result};
22use baracuda_driver::Stream;
23use baracuda_kernels_types::{
24    ArchSku, BackendKind, Element, ElementKind, KernelSku, MathPrecision, OpCategory,
25    PlanPreference, PrecisionGuarantee, SoftmaxKind, TensorMut, TensorRef, Workspace,
26};
27
28/// Maximum supported extent along the sparsemax axis. Phase 11.6 lifts
29/// this from the trailblazer 64 → 1024 by switching the forward kernel
30/// from a per-thread serial sort to a block-cooperative
31/// `cub::BlockRadixSort` + `cub::BlockScan`. Mirrors the C++ macro
32/// `BARACUDA_SPARSEMAX_MAX_EXTENT`.
33pub const SPARSEMAX_MAX_EXTENT: i32 = 1024;
34
35/// Descriptor for a Sparsemax forward op.
36#[derive(Copy, Clone, Debug)]
37pub struct SparsemaxDescriptor<const N: usize> {
38    /// Tensor shape (input and output share it).
39    pub input_shape: [i32; N],
40    /// Axis along which to apply sparsemax. Must be in `[0, N)`.
41    /// Extent along this axis must be `<= SPARSEMAX_MAX_EXTENT`.
42    pub softmax_axis: u8,
43    /// Element type.
44    pub element: ElementKind,
45}
46
47/// Args bundle for a Sparsemax forward launch.
48pub struct SparsemaxArgs<'a, T: Element, const N: usize> {
49    /// Input logits.
50    pub x: TensorRef<'a, T, N>,
51    /// Output tensor — same shape as input.
52    pub y: TensorMut<'a, T, N>,
53}
54
55/// Sparsemax forward plan.
56pub struct SparsemaxPlan<T: Element, const N: usize> {
57    desc: SparsemaxDescriptor<N>,
58    sku: KernelSku,
59    _marker: PhantomData<T>,
60}
61
62impl<T: Element, const N: usize> SparsemaxPlan<T, N> {
63    /// Pick a kernel.
64    pub fn select(
65        _stream: &Stream,
66        desc: &SparsemaxDescriptor<N>,
67        _pref: PlanPreference,
68    ) -> Result<Self> {
69        if desc.element != T::KIND {
70            return Err(Error::Unsupported(
71                "baracuda-kernels::SparsemaxPlan: descriptor element != T",
72            ));
73        }
74        if (desc.softmax_axis as usize) >= N {
75            return Err(Error::InvalidProblem(
76                "baracuda-kernels::SparsemaxPlan: softmax_axis out of range",
77            ));
78        }
79        for &d in desc.input_shape.iter() {
80            if d < 0 {
81                return Err(Error::InvalidProblem(
82                    "baracuda-kernels::SparsemaxPlan: shape dims must be non-negative",
83                ));
84            }
85        }
86        if N > 8 {
87            return Err(Error::Unsupported(
88                "baracuda-kernels::SparsemaxPlan: tensor rank > 8 not supported",
89            ));
90        }
91        let extent = desc.input_shape[desc.softmax_axis as usize];
92        if extent > SPARSEMAX_MAX_EXTENT {
93            return Err(Error::Unsupported(
94                "baracuda-kernels::SparsemaxPlan: extent along softmax_axis > 1024 \
95                 not supported (block-cooperative BlockRadixSort tile capped at 1024)",
96            ));
97        }
98        let dtype_in_fp_family = matches!(
99            T::KIND,
100            ElementKind::F32 | ElementKind::F16 | ElementKind::Bf16 | ElementKind::F64
101        );
102        if !dtype_in_fp_family {
103            return Err(Error::Unsupported(
104                "baracuda-kernels::SparsemaxPlan: wired today: {f32, f16, bf16, f64}",
105            ));
106        }
107
108        let math_precision = match T::KIND {
109            ElementKind::F64 => MathPrecision::F64,
110            _ => MathPrecision::F32,
111        };
112        let precision_guarantee = PrecisionGuarantee {
113            math_precision,
114            accumulator: match T::KIND {
115                ElementKind::F64 => ElementKind::F64,
116                _ => ElementKind::F32,
117            },
118            bit_stable_on_same_hardware: true,
119            deterministic: true,
120        };
121        let sku = KernelSku {
122            category: OpCategory::Softmax,
123            op: SoftmaxKind::Sparsemax as u16,
124            element: T::KIND,
125            aux_element: None,
126            layout: None,
127            epilogue: None,
128            arch: ArchSku::Sm80,
129            backend: BackendKind::Bespoke,
130            precision_guarantee,
131        };
132        Ok(Self {
133            desc: *desc,
134            sku,
135            _marker: PhantomData,
136        })
137    }
138
139    /// Validate args.
140    pub fn can_implement(&self, args: &SparsemaxArgs<'_, T, N>) -> Result<()> {
141        if args.x.shape != self.desc.input_shape {
142            return Err(Error::InvalidProblem(
143                "baracuda-kernels::SparsemaxPlan: x shape mismatch",
144            ));
145        }
146        if args.y.shape != self.desc.input_shape {
147            return Err(Error::InvalidProblem(
148                "baracuda-kernels::SparsemaxPlan: y shape mismatch",
149            ));
150        }
151        let numel = args.x.numel();
152        let x_len = args.x.data.len() as i64;
153        let y_len = args.y.data.len() as i64;
154        if x_len < numel || y_len < numel {
155            return Err(Error::BufferTooSmall {
156                needed: numel as usize,
157                got: x_len.min(y_len) as usize,
158            });
159        }
160        Ok(())
161    }
162
163    /// Workspace size in bytes.
164    #[inline]
165    pub fn workspace_size(&self) -> usize {
166        0
167    }
168
169    /// Kernel SKU identity.
170    #[inline]
171    pub fn sku(&self) -> KernelSku {
172        self.sku
173    }
174
175    /// Numerical guarantees.
176    #[inline]
177    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
178        self.sku.precision_guarantee
179    }
180
181    /// Launch.
182    pub fn run(
183        &self,
184        stream: &Stream,
185        _workspace: Workspace<'_>,
186        args: SparsemaxArgs<'_, T, N>,
187    ) -> Result<()> {
188        self.can_implement(&args)?;
189        let numel = args.x.numel();
190        if numel == 0 {
191            return Ok(());
192        }
193        let x_ptr = args.x.data.as_raw().0 as *const c_void;
194        let y_ptr = args.y.data.as_raw().0 as *mut c_void;
195        let stream_ptr = stream.as_raw() as *mut c_void;
196
197        let axis = self.desc.softmax_axis as usize;
198        let shape = self.desc.input_shape;
199        let stride_x = args.x.stride;
200        let stride_y = args.y.stride;
201        let rank = N as i32;
202        let extent = shape[axis];
203        let stride_x_axis = stride_x[axis];
204        let stride_y_axis = stride_y[axis];
205
206        macro_rules! dispatch {
207            ($sym:ident) => {
208                unsafe {
209                    baracuda_kernels_sys::$sym(
210                        numel,
211                        rank,
212                        shape.as_ptr(),
213                        stride_x.as_ptr(),
214                        stride_y.as_ptr(),
215                        axis as i32,
216                        extent,
217                        stride_x_axis,
218                        stride_y_axis,
219                        x_ptr,
220                        y_ptr,
221                        core::ptr::null_mut(),
222                        0,
223                        stream_ptr,
224                    )
225                }
226            };
227        }
228        let status = match T::KIND {
229            ElementKind::F32 => dispatch!(baracuda_kernels_sparsemax_f32_run),
230            ElementKind::F16 => dispatch!(baracuda_kernels_sparsemax_f16_run),
231            ElementKind::Bf16 => dispatch!(baracuda_kernels_sparsemax_bf16_run),
232            ElementKind::F64 => dispatch!(baracuda_kernels_sparsemax_f64_run),
233            _ => {
234                return Err(Error::Unsupported(
235                    "baracuda-kernels::SparsemaxPlan::run unimplemented dtype",
236                ));
237            }
238        };
239        map_status(status)
240    }
241}
242
243fn map_status(code: i32) -> Result<()> {
244    match code {
245        0 => Ok(()),
246        1 => Err(Error::MisalignedOperand),
247        2 => Err(Error::InvalidProblem(
248            "baracuda-kernels-sys reported invalid problem",
249        )),
250        3 => Err(Error::Unsupported(
251            "baracuda-kernels-sys reported unsupported configuration",
252        )),
253        4 => Err(Error::WorkspaceTooSmall { needed: 0, got: 0 }),
254        n => Err(Error::CutlassInternal(n)),
255    }
256}