baracuda-kernels 0.0.1-alpha.68

Unified ML op facade for the baracuda CUDA ecosystem. Exposes every primitive an ML framework would expect (union of PyTorch torch.* + nn.functional and JAX lax.* / numpy ops) through a single Plan-based Rust surface, internally dispatching to baracuda-cutlass, the baracuda-* NVIDIA-library wrappers, or bespoke baracuda-kernels-sys kernels.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! Rotary Position Embedding (RoPE) forward plan.
//!
//! For a Q/K tensor `x` of shape `[batch, num_heads, seq_len, head_dim]`,
//! RoPE rotates consecutive feature pairs `(2i, 2i+1)` by position-
//! dependent angles `θ_i = pos · base^(-2i/head_dim)`:
//!
//! ```text
//! y[2i]   = x[2i]   · cos(θ_i) - x[2i+1] · sin(θ_i)
//! y[2i+1] = x[2i+1] · cos(θ_i) + x[2i]   · sin(θ_i)
//! ```
//!
//! `head_dim` must be even. `base` defaults to `10000.0`. `positions` is
//! an optional `[seq_len]` `i64` tensor; when absent, the kernel uses
//! the sequence index as the position (canonical "no prefix-cache" case).
//!
//! Wired today: `{f32, f16, bf16, f64}`.

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;

/// Descriptor for a RoPE forward op.
///
/// All sizes are `i32` to match the kernel ABI (which uses int32 for
/// per-axis extents to keep param-block size bounded).
#[derive(Copy, Clone, Debug)]
pub struct RopeDescriptor {
    /// Batch size (`B`).
    pub batch_size: i32,
    /// Number of attention heads (`H`).
    pub num_heads: i32,
    /// Sequence length (`S`).
    pub seq_len: i32,
    /// Head dimension (`D`). **Must be even** — RoPE rotates feature
    /// pairs.
    pub head_dim: i32,
    /// Rotary base; default `10000.0`. Pass a different value for
    /// extended-context recipes (e.g. NTK-aware scaling uses
    /// `base * scaling_factor`).
    pub base: f32,
    /// Element type — must match the plan's type parameter.
    pub element: ElementKind,
}

/// Args bundle for a RoPE forward launch.
pub struct RopeArgs<'a, T: Element> {
    /// Input Q or K tensor — shape `[B, H, S, D]`, contiguous row-major.
    pub x: TensorRef<'a, T, 4>,
    /// Optional explicit `[S]` `i64` position indices. `None` means the
    /// kernel uses `positions[s] = s` (canonical case).
    pub positions: Option<TensorRef<'a, i64, 1>>,
    /// Output tensor — same shape as `x`.
    pub y: TensorMut<'a, T, 4>,
}

/// Rotary Position Embedding forward plan.
///
/// Rotates consecutive feature pairs `(2i, 2i+1)` of a `[B, H, S, D]`
/// Q or K tensor by per-position angles `θ_i = pos · base^(-2i/D)`.
///
/// **When to use**: dominant positional encoding in modern LLMs (Llama,
/// Mistral, Gemma, Qwen, Phi). Apply once per Q and once per K before
/// the attention matmul. Pair with [`super::RopeBackwardPlan`] for
/// autograd.
///
/// **Dtypes**: `f32`, `f64`, `f16`, `bf16`. `f16` / `bf16` detour
/// through `f32` for the trig + multiply; `f64` uses native double.
///
/// **Shape limits**: rank-4, contiguous, row-major. `head_dim` must
/// be even (RoPE rotates pairs). Optional `positions: i64[S]` override
/// — when absent the kernel uses `positions[s] = s`.
///
/// **Workspace**: zero.
///
/// **Precision guarantee**: deterministic; bit-stable on the same
/// hardware. Per-cell write, no atomics.
pub struct RopePlan<T: Element> {
    desc: RopeDescriptor,
    sku: KernelSku,
    _marker: PhantomData<T>,
}

impl<T: Element> RopePlan<T> {
    /// Pick a kernel.
    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,
            // Per-cell deterministic — no atomic ops.
            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,
        })
    }

    /// Validate args.
    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",
            ));
        }
        // Phase 14.4: strided variant supports arbitrary outer strides
        // but the innermost head_dim axis MUST remain stride=1 because
        // RoPE rotates adjacent pairs (2i, 2i+1).
        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(),
                });
            }
        }
        // Buffer size check: only meaningful for contiguous tensors —
        // strided views may legitimately read every-other element of a
        // larger backing buffer (and the kernel's last accessed offset
        // is at most max-over-coords of dot(coord, stride)). For the
        // trailblazer we only assert for contig; strided is caller's
        // responsibility (same convention as other Phase 14 strided
        // siblings).
        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(())
    }

    /// Workspace size in bytes.
    #[inline]
    pub fn workspace_size(&self) -> usize {
        0
    }

    /// SKU identity.
    #[inline]
    pub fn sku(&self) -> KernelSku {
        self.sku
    }

    /// Numerical guarantees.
    #[inline]
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee
    }

    /// Launch.
    ///
    /// Phase 14.4: dispatches between the contig fast path (all dims
    /// canonical row-major contig) and the strided sibling FFI (any
    /// outer-dim stride differs from canonical). The innermost
    /// `head_dim` axis must be stride=1 either way; non-unit stride
    /// is rejected at `can_implement`.
    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 {
                // Strided sibling. Pass per-outer-dim strides for x and y.
                // head_dim axis stride is implicitly 1 (enforced above).
                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)
    }
}