Skip to main content

baracuda_kernels/shape_layout/
concat.rs

1//! 2-input `concat` plan — `y = cat(a, b, dim=k)`.
2//!
3//! Variable-arity (N-input) concat needs a separate plan shape with
4//! device-side packing of N pointers + N stride arrays — deferred to a
5//! later session. For real ML use cases the 2-input variant covers the
6//! majority (residual joins, key/value concat in attention KV-cache,
7//! etc.).
8//!
9//! Today `f32`, `f16`, `bf16`, and `f64` are wired (one INSTANTIATE per
10//! dtype in the .cu, one FFI block per dtype here, one match arm in
11//! `run`).
12
13use core::ffi::c_void;
14use core::marker::PhantomData;
15
16use baracuda_cutlass::{Error, Result};
17use baracuda_driver::Stream;
18use baracuda_kernels_types::{
19    ArchSku, BackendKind, Element, ElementKind, KernelSku, MathPrecision, OpCategory,
20    PlanPreference, PrecisionGuarantee, ShapeLayoutKind, TensorMut, TensorRef, Workspace,
21};
22
23/// Descriptor for a 2-input concat op.
24///
25/// `a_shape` and `b_shape` must match on every axis except `concat_dim`.
26/// Output shape is `a_shape` with `[concat_dim]` set to
27/// `a_shape[concat_dim] + b_shape[concat_dim]`.
28#[derive(Copy, Clone, Debug)]
29pub struct ConcatDescriptor<const N: usize> {
30    /// Shape of the first input.
31    pub a_shape: [i32; N],
32    /// Shape of the second input.
33    pub b_shape: [i32; N],
34    /// Axis to concatenate along. Must satisfy `0 <= concat_dim < N`.
35    pub concat_dim: u8,
36    /// Element type.
37    pub element: ElementKind,
38}
39
40impl<const N: usize> ConcatDescriptor<N> {
41    /// Compute the output shape (a_shape with `[concat_dim]` summed).
42    pub fn output_shape(&self) -> [i32; N] {
43        let mut out = self.a_shape;
44        let d = self.concat_dim as usize;
45        out[d] = self.a_shape[d] + self.b_shape[d];
46        out
47    }
48}
49
50/// Args bundle for a Concat launch.
51pub struct ConcatArgs<'a, T: Element, const N: usize> {
52    /// First input. `a.shape` must equal `desc.a_shape`.
53    pub a: TensorRef<'a, T, N>,
54    /// Second input. `b.shape` must equal `desc.b_shape`.
55    pub b: TensorRef<'a, T, N>,
56    /// Output — shape matches `desc.output_shape()`.
57    pub y: TensorMut<'a, T, N>,
58}
59
60/// 2-input `concat` plan.
61///
62/// `y = cat(a, b, dim=concat_dim)` (PyTorch `torch.cat`).
63///
64/// **When to use**: residual joins, KV-cache concat in attention, any
65/// 2-input concatenation. Variable-arity (N-input) concat needs a
66/// separate plan with device-side pointer arrays — deferred. Pair
67/// with [`ConcatBackwardPlan`](crate::ConcatBackwardPlan).
68///
69/// **Dtypes**: `{f32, f64, f16, bf16}`.
70///
71/// **Shape limits**: rank in `[1, 8]`; `a_shape` and `b_shape` must
72/// match on every axis except `concat_dim`; `concat_dim ∈ [0, N)`.
73///
74/// **Workspace**: none.
75///
76/// **Precision guarantee**: deterministic, bit-stable, bit-exact
77/// (pure load + store).
78pub struct ConcatPlan<T: Element, const N: usize> {
79    desc: ConcatDescriptor<N>,
80    sku: KernelSku,
81    _marker: PhantomData<T>,
82}
83
84impl<T: Element, const N: usize> ConcatPlan<T, N> {
85    /// Pick a kernel for `desc`.
86    pub fn select(
87        _stream: &Stream,
88        desc: &ConcatDescriptor<N>,
89        _pref: PlanPreference,
90    ) -> Result<Self> {
91        if desc.element != T::KIND {
92            return Err(Error::Unsupported(
93                "baracuda-kernels::ConcatPlan: descriptor element != type parameter T",
94            ));
95        }
96        if (desc.concat_dim as usize) >= N {
97            return Err(Error::InvalidProblem(
98                "baracuda-kernels::ConcatPlan: concat_dim must be < rank",
99            ));
100        }
101        // Shapes must match on every axis except concat_dim.
102        let cd = desc.concat_dim as usize;
103        for d in 0..N {
104            if desc.a_shape[d] < 0 || desc.b_shape[d] < 0 {
105                return Err(Error::InvalidProblem(
106                    "baracuda-kernels::ConcatPlan: input shape dims must be non-negative",
107                ));
108            }
109            if d != cd && desc.a_shape[d] != desc.b_shape[d] {
110                return Err(Error::InvalidProblem(
111                    "baracuda-kernels::ConcatPlan: input shapes must match on every \
112                     axis except concat_dim",
113                ));
114            }
115        }
116
117        let supported = matches!(
118            T::KIND,
119            ElementKind::F32 | ElementKind::F16 | ElementKind::Bf16 | ElementKind::F64
120        );
121        if !supported {
122            return Err(Error::Unsupported(
123                "baracuda-kernels::ConcatPlan: today only `f32`, `f16`, `bf16`, `f64` \
124                 are wired; other dtypes land in future fanout",
125            ));
126        }
127
128        let precision_guarantee = PrecisionGuarantee {
129            math_precision: MathPrecision::F32,
130            accumulator: ElementKind::F32,
131            // Concat does no arithmetic — pure element copy.
132            bit_stable_on_same_hardware: true,
133            deterministic: true,
134        };
135        let sku = KernelSku {
136            category: OpCategory::ShapeLayout,
137            op: ShapeLayoutKind::Concat as u16,
138            element: T::KIND,
139            aux_element: None,
140            layout: None,
141            epilogue: None,
142            arch: ArchSku::Sm80,
143            backend: BackendKind::Bespoke,
144            precision_guarantee,
145        };
146        Ok(Self {
147            desc: *desc,
148            sku,
149            _marker: PhantomData,
150        })
151    }
152
153    /// Validate args.
154    pub fn can_implement(&self, args: &ConcatArgs<'_, T, N>) -> Result<()> {
155        if args.a.shape != self.desc.a_shape {
156            return Err(Error::InvalidProblem(
157                "baracuda-kernels::ConcatPlan: A shape mismatch with descriptor a_shape",
158            ));
159        }
160        if args.b.shape != self.desc.b_shape {
161            return Err(Error::InvalidProblem(
162                "baracuda-kernels::ConcatPlan: B shape mismatch with descriptor b_shape",
163            ));
164        }
165        let expected_out = self.desc.output_shape();
166        if args.y.shape != expected_out {
167            return Err(Error::InvalidProblem(
168                "baracuda-kernels::ConcatPlan: Y shape mismatch with derived output \
169                 shape (= a_shape with [concat_dim] = a + b extents)",
170            ));
171        }
172        if N > 8 {
173            return Err(Error::Unsupported(
174                "baracuda-kernels::ConcatPlan: tensor rank > 8 not supported",
175            ));
176        }
177        let a_numel = args.a.numel();
178        let b_numel = args.b.numel();
179        let y_numel = args.y.numel();
180        let a_len = args.a.data.len() as i64;
181        let b_len = args.b.data.len() as i64;
182        let y_len = args.y.data.len() as i64;
183        if a_len < a_numel {
184            return Err(Error::BufferTooSmall {
185                needed: a_numel as usize,
186                got: a_len as usize,
187            });
188        }
189        if b_len < b_numel {
190            return Err(Error::BufferTooSmall {
191                needed: b_numel as usize,
192                got: b_len as usize,
193            });
194        }
195        if y_len < y_numel {
196            return Err(Error::BufferTooSmall {
197                needed: y_numel as usize,
198                got: y_len as usize,
199            });
200        }
201        Ok(())
202    }
203
204    /// Workspace size in bytes. Always `0` for the trailblazer.
205    #[inline]
206    pub fn workspace_size(&self) -> usize {
207        0
208    }
209
210    /// Identity of the kernel this plan picked.
211    #[inline]
212    pub fn sku(&self) -> KernelSku {
213        self.sku
214    }
215
216    /// Numerical guarantees.
217    #[inline]
218    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
219        self.sku.precision_guarantee
220    }
221
222    /// Launch.
223    pub fn run(
224        &self,
225        stream: &Stream,
226        _workspace: Workspace<'_>,
227        args: ConcatArgs<'_, T, N>,
228    ) -> Result<()> {
229        self.can_implement(&args)?;
230        let output_numel = args.y.numel();
231        if output_numel == 0 {
232            return Ok(());
233        }
234        let a_ptr = args.a.data.as_raw().0 as *const c_void;
235        let b_ptr = args.b.data.as_raw().0 as *const c_void;
236        let y_ptr = args.y.data.as_raw().0 as *mut c_void;
237        let stream_ptr = stream.as_raw() as *mut c_void;
238
239        let output_shape = self.desc.output_shape();
240        let stride_a = args.a.stride;
241        let stride_b = args.b.stride;
242        let stride_y = args.y.stride;
243        let rank = N as i32;
244        let concat_dim = self.desc.concat_dim as i32;
245        let split_offset = self.desc.a_shape[self.desc.concat_dim as usize];
246
247        let status = match T::KIND {
248            ElementKind::F32 => unsafe {
249                baracuda_kernels_sys::baracuda_kernels_concat2_f32_run(
250                    output_numel,
251                    rank,
252                    output_shape.as_ptr(),
253                    concat_dim,
254                    split_offset,
255                    stride_a.as_ptr(),
256                    stride_b.as_ptr(),
257                    stride_y.as_ptr(),
258                    a_ptr,
259                    b_ptr,
260                    y_ptr,
261                    core::ptr::null_mut(),
262                    0,
263                    stream_ptr,
264                )
265            },
266            ElementKind::F16 => unsafe {
267                baracuda_kernels_sys::baracuda_kernels_concat2_f16_run(
268                    output_numel,
269                    rank,
270                    output_shape.as_ptr(),
271                    concat_dim,
272                    split_offset,
273                    stride_a.as_ptr(),
274                    stride_b.as_ptr(),
275                    stride_y.as_ptr(),
276                    a_ptr,
277                    b_ptr,
278                    y_ptr,
279                    core::ptr::null_mut(),
280                    0,
281                    stream_ptr,
282                )
283            },
284            ElementKind::Bf16 => unsafe {
285                baracuda_kernels_sys::baracuda_kernels_concat2_bf16_run(
286                    output_numel,
287                    rank,
288                    output_shape.as_ptr(),
289                    concat_dim,
290                    split_offset,
291                    stride_a.as_ptr(),
292                    stride_b.as_ptr(),
293                    stride_y.as_ptr(),
294                    a_ptr,
295                    b_ptr,
296                    y_ptr,
297                    core::ptr::null_mut(),
298                    0,
299                    stream_ptr,
300                )
301            },
302            ElementKind::F64 => unsafe {
303                baracuda_kernels_sys::baracuda_kernels_concat2_f64_run(
304                    output_numel,
305                    rank,
306                    output_shape.as_ptr(),
307                    concat_dim,
308                    split_offset,
309                    stride_a.as_ptr(),
310                    stride_b.as_ptr(),
311                    stride_y.as_ptr(),
312                    a_ptr,
313                    b_ptr,
314                    y_ptr,
315                    core::ptr::null_mut(),
316                    0,
317                    stream_ptr,
318                )
319            },
320            _ => {
321                return Err(Error::Unsupported(
322                    "baracuda-kernels::ConcatPlan::run: only `f32`, `f16`, `bf16`, `f64` \
323                     wired today",
324                ));
325            }
326        };
327        map_status(status)
328    }
329}
330
331fn map_status(code: i32) -> Result<()> {
332    match code {
333        0 => Ok(()),
334        1 => Err(Error::MisalignedOperand),
335        2 => Err(Error::InvalidProblem(
336            "baracuda-kernels-sys reported invalid problem",
337        )),
338        3 => Err(Error::Unsupported(
339            "baracuda-kernels-sys reported unsupported configuration",
340        )),
341        4 => Err(Error::WorkspaceTooSmall { needed: 0, got: 0 }),
342        n => Err(Error::CutlassInternal(n)),
343    }
344}