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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! int4 GEMM plan.
//!
//! Phase 2 int4 surface — full 36-SKU matrix on `sm_89`:
//!
//!   `{S4, U4} × {RCR, RRR} × {Identity, Bias, BiasRelu, BiasGelu,
//!                              BiasSilu} × {f32 bias, i32 bias}`
//!
//! (The Identity epilogue ignores the bias-element generic, so the
//! full SKU count is `2 × 2 × (1 + 4 × 2) = 36`.) The plan-layer type
//! is parameterized on `T: IntElement` and `BT: BiasElement`; the
//! dispatcher routes on `(T::KIND, layout, epilogue, BT::KIND)` to the
//! matching bespoke kernel in `baracuda-kernels-sys`.
//!
//! All int4 SKUs are bespoke kernels in
//! [`baracuda-kernels-sys`](baracuda_kernels_sys) — CUTLASS 4.2.0 does
//! not ship int4 instantiations on the layouts / epilogues this crate
//! targets (and the int8 RRR rationale carries over: packed-storage
//! int kernels exceed CUTLASS template-vendoring friction past 8-bit).
//!
//! Plan-layer conventions:
//!
//! - Descriptor M / N / K are in **element** counts.
//! - `MatrixRef<S4>::ld` / `MatrixMut<S4>::ld` are in **storage-slot
//!   (= byte) counts**, not element counts. Each storage slot is a
//!   packed-pair byte (low nibble = even index, high nibble = odd
//!   index along the K axis for A/B operands and the N axis for the
//!   D output).
//! - `MatrixRef<S4>::cols` is in **element** counts for shape checks
//!   (= K for A and B, = N for D); the leading dimension `ld` is in
//!   bytes.
//! - `K` must be even (packing is byte-aligned).
//! - `N` must be even (the D output store is byte-granular at packed
//!   pairs along N).
//!
//! Bias element generic mirrors the int8 family: `<T, f32>` for
//! float-scaled bias, `<T, i32>` for TensorRT-style integer bias.

use core::ffi::c_void;
use core::marker::PhantomData;

use baracuda_cutlass::{Error, Result};
use baracuda_driver::Stream;
use baracuda_kernels_types::{
    ArchSku, BiasElement, BiasElementKind, ElementKind, EpilogueKind, IntElement, LayoutSku,
    MatrixMut, MatrixRef, PlanPreference, PrecisionGuarantee, S4, U4, VectorRef, Workspace,
};

// Reuse the SKU descriptor from baracuda-cutlass — it carries the same
// (arch, layout, epilogue, element, bias_element) tuple the int-GEMM
// and FP8 dispatchers use, so telemetry / autotuner caches can key off
// one shape across all GEMM backends.
pub use baracuda_cutlass::GemmSku;

/// Problem shape and configuration for [`Int4GemmPlan::select`].
#[derive(Copy, Clone, Debug)]
pub struct Int4GemmDescriptor {
    /// Output row count, in **elements**.
    pub m: i32,
    /// Output column count, in **elements** (must be even).
    pub n: i32,
    /// Reduction depth, in **elements** (must be even).
    pub k: i32,
    /// Layout SKU. Trailblazer SKU is [`LayoutSku::Rcr`]; the RRR
    /// variant joins in subsequent fanout commits.
    pub layout: LayoutSku,
    /// Epilogue kind. Trailblazer SKU is [`EpilogueKind::Identity`];
    /// the `Bias*` family joins in subsequent fanout commits.
    pub epilogue: EpilogueKind,
}

/// Per-launch arguments for an [`Int4GemmPlan::run`] call.
///
/// `c` is optional: when `None`, `β` is forced to `0` at the safe
/// layer and the kernel computes `D = sat_cast_int4(α · A · B)`. The
/// kernel uses an S32 accumulator and saturating-casts back to s4
/// (clamp to `[-8, +7]`) or u4 (clamp to `[0, 15]`) on store.
///
/// `bias` is optional and required-vs-disallowed by the epilogue:
/// [`EpilogueKind::Identity`] must pass `None`; the `Bias*` variants
/// (later fanout) must pass `Some`. The bias element type follows the
/// `BT` plan generic — `f32` for the conventional float-scaled bias,
/// `i32` for the TensorRT-style integer bias convention.
///
/// Pointer / layout contracts (mirrors the FFI; see the
/// `baracuda-kernels-sys` doc comment on
/// `baracuda_kernels_gemm_s4_rcr_sm89_run` for the byte-level details):
///
/// - `a.data` storage holds packed-pair int4 bytes; `a.rows = M`,
///   `a.cols = K` (element counts), `a.ld` is the row stride in
///   **bytes** (≥ `K / 2`).
/// - `b.data` storage holds packed-pair int4 bytes; `b.rows = K`,
///   `b.cols = N`, `b.ld` is the column stride in **bytes** (≥ `K / 2`
///   for `LayoutSku::Rcr`; col-major).
/// - `c.data` / `d.data` storage holds packed-pair int4 bytes;
///   `c.rows = d.rows = M`, `c.cols = d.cols = N`, `c.ld = d.ld` are
///   row strides in **bytes** (≥ `N / 2`).
#[derive(Debug)]
pub struct Int4GemmArgs<'a, T: IntElement, BT: BiasElement = f32> {
    /// Left input. Row-major `[M, K]`. Packed-pair int4 storage; `ld`
    /// in bytes.
    pub a: MatrixRef<'a, T>,
    /// Right input. RCR: col-major `[K, N]` with column stride ≥ K/2
    /// bytes. RRR (later fanout): row-major `[K, N]` with row stride
    /// ≥ N/2 bytes.
    pub b: MatrixRef<'a, T>,
    /// Optional accumulation source. Row-major `[M, N]` packed-pair
    /// int4 storage. `None` skips the `β · C` term internally.
    pub c: Option<MatrixRef<'a, T>>,
    /// Output. Row-major `[M, N]` packed-pair int4 storage.
    pub d: MatrixMut<'a, T>,
    /// Optional bias vector. Required when the descriptor's epilogue
    /// is any `Bias*` variant (later fanout); must be `None` for
    /// [`EpilogueKind::Identity`]. Length-`N`, contiguous device
    /// memory; broadcast across rows of `D`.
    pub bias: Option<VectorRef<'a, BT>>,
    /// Multiplier on the matrix-multiply accumulator. F32 — the
    /// kernel accumulates in S32 and the epilogue scales to F32
    /// before quantizing back to int4.
    pub alpha: f32,
    /// Multiplier on `c`. Forced to `0` internally when `c` is `None`.
    pub beta: f32,
}

/// int4 GEMM plan.
///
/// Parameterized on `T: IntElement` ([`S4`] / [`U4`]; trailblazer SKU
/// is [`S4`] only) and `BT: BiasElement` (`f32` default, or `i32`,
/// matching the int8 family's bias-element convention).
pub struct Int4GemmPlan<T: IntElement, BT: BiasElement = f32> {
    desc: Int4GemmDescriptor,
    sku: GemmSku,
    _element: PhantomData<T>,
    _bias_element: PhantomData<BT>,
}

impl<T: IntElement, BT: BiasElement> Int4GemmPlan<T, BT> {
    /// Pick an int4 GEMM kernel for `desc`.
    ///
    /// Returns [`Error::Unsupported`] for any `(T, layout, epilogue)`
    /// triple outside the shipped trailblazer SKU
    /// (`S4 × RCR × Identity`). The rest of the int4 matrix joins in
    /// subsequent fanout commits.
    pub fn select(
        _stream: &Stream,
        desc: &Int4GemmDescriptor,
        _pref: PlanPreference,
    ) -> Result<Self> {
        if desc.m <= 0 || desc.n <= 0 || desc.k <= 0 {
            return Err(Error::InvalidProblem(
                "int4 GEMM problem must have positive M, N, K",
            ));
        }
        if (desc.k & 1) != 0 {
            return Err(Error::InvalidProblem(
                "int4 GEMM requires K to be even (packed-pair storage along K)",
            ));
        }
        if (desc.n & 1) != 0 {
            return Err(Error::InvalidProblem(
                "int4 GEMM requires N to be even (packed-pair storage along N for D output)",
            ));
        }
        if !matches!(T::KIND, ElementKind::S4 | ElementKind::U4) {
            return Err(Error::Unsupported(
                "baracuda-kernels: int4 GEMM: only S4 / U4 elements are accepted",
            ));
        }
        // Shipped today: full {S4, U4} × {RCR, RRR} × {Identity, Bias,
        // BiasRelu, BiasGelu, BiasSilu} × {f32, i32} bias matrix. The
        // `select` accepts every combination; the dispatcher in `run`
        // routes to the matching `baracuda-kernels-sys` entry point.
        // (T::KIND guard above already rejected non-int4 elements.)
        let _ = desc.layout;
        let _ = desc.epilogue;

        let sku = GemmSku {
            arch: ArchSku::Sm89,
            layout: desc.layout,
            epilogue: desc.epilogue,
            element: T::KIND,
            bias_element: if desc.epilogue.requires_bias() {
                Some(BT::KIND)
            } else {
                None
            },
        };
        Ok(Self {
            desc: *desc,
            sku,
            _element: PhantomData,
            _bias_element: PhantomData,
        })
    }

    /// Validate that this plan can launch with `args`.
    pub fn can_implement(&self, args: &Int4GemmArgs<'_, T, BT>) -> Result<()> {
        if self.desc.m <= 0 || self.desc.n <= 0 || self.desc.k <= 0 {
            return Err(Error::InvalidProblem(
                "int4 GEMM problem must have positive M, N, K",
            ));
        }
        if args.a.rows != self.desc.m || args.a.cols != self.desc.k {
            return Err(Error::InvalidProblem(
                "A shape mismatch with descriptor (M, K in elements)",
            ));
        }
        if args.b.rows != self.desc.k || args.b.cols != self.desc.n {
            return Err(Error::InvalidProblem(
                "B shape mismatch with descriptor (K, N in elements)",
            ));
        }
        if args.d.rows != self.desc.m || args.d.cols != self.desc.n {
            return Err(Error::InvalidProblem(
                "D shape mismatch with descriptor (M, N in elements)",
            ));
        }
        // Leading dimensions are in BYTES — minimum is element-count / 2.
        let k_bytes_min = (self.desc.k / 2) as i64;
        let n_bytes_min = (self.desc.n / 2) as i64;
        match self.sku.layout {
            LayoutSku::Rcr => {
                if args.a.ld < k_bytes_min {
                    return Err(Error::InvalidProblem(
                        "A leading dimension (bytes) must be >= K/2 for row-major int4 A",
                    ));
                }
                if args.b.ld < k_bytes_min {
                    return Err(Error::InvalidProblem(
                        "B leading dimension (bytes) must be >= K/2 for col-major int4 B (RCR)",
                    ));
                }
            }
            LayoutSku::Rrr => {
                // Reserved for fanout; reaches here only via a
                // direct construction bypassing `select`.
                if args.a.ld < k_bytes_min {
                    return Err(Error::InvalidProblem(
                        "A leading dimension (bytes) must be >= K/2 for row-major int4 A",
                    ));
                }
                if args.b.ld < n_bytes_min {
                    return Err(Error::InvalidProblem(
                        "B leading dimension (bytes) must be >= N/2 for row-major int4 B (RRR)",
                    ));
                }
            }
        }
        if args.d.ld < n_bytes_min {
            return Err(Error::InvalidProblem(
                "D leading dimension (bytes) must be >= N/2 for row-major int4 D",
            ));
        }
        if let Some(c) = &args.c {
            if c.rows != self.desc.m || c.cols != self.desc.n {
                return Err(Error::InvalidProblem(
                    "C shape mismatch with descriptor (M, N in elements)",
                ));
            }
            if c.ld < n_bytes_min {
                return Err(Error::InvalidProblem(
                    "C leading dimension (bytes) must be >= N/2 for row-major int4 C",
                ));
            }
        }
        // Bias presence must match the epilogue family. Identity
        // (trailblazer) takes no bias.
        let needs_bias = self.sku.epilogue.requires_bias();
        match (needs_bias, &args.bias) {
            (true, None) => {
                return Err(Error::InvalidProblem(
                    "Bias* epilogue requires a bias vector",
                ));
            }
            (false, Some(_)) => {
                return Err(Error::InvalidProblem(
                    "Identity epilogue must not be supplied a bias vector",
                ));
            }
            _ => {}
        }
        if let Some(b) = &args.bias
            && b.len != self.desc.n
        {
            return Err(Error::InvalidProblem(
                "bias length must equal N",
            ));
        }
        Ok(())
    }

    /// Workspace size in bytes. Zero across the shipped int4 SKUs —
    /// the kernel does all its work in smem + registers.
    pub fn workspace_size(&self) -> usize {
        0
    }

    /// Identity of the kernel this plan picked.
    #[inline]
    pub fn sku(&self) -> GemmSku {
        self.sku
    }

    /// Numerical guarantees for this plan's kernel. int4 → int32
    /// accumulator → f32 epilogue → saturating-cast back to int4
    /// (round-half-to-even, clamp). Bit-stable on the same hardware
    /// (integer MMA has no warp-reduction nondeterminism).
    #[inline]
    pub fn precision_guarantee(&self) -> PrecisionGuarantee {
        self.sku.precision_guarantee()
    }

    /// Launch.
    pub fn run(
        &self,
        stream: &Stream,
        workspace: Workspace<'_>,
        args: Int4GemmArgs<'_, T, BT>,
    ) -> Result<()> {
        let _ = workspace; // int4 kernels take no scratch

        let a_ptr = args.a.data.as_raw().0 as *const c_void;
        let b_ptr = args.b.data.as_raw().0 as *const c_void;
        let d_ptr = args.d.data.as_raw().0 as *mut c_void;
        let (c_ptr, ldc) = match &args.c {
            Some(c) => (c.data.as_raw().0 as *const c_void, c.ld),
            None => (core::ptr::null(), 0i64),
        };
        let bias_ptr: *const c_void = match &args.bias {
            Some(b) => b.data.as_raw().0 as *const c_void,
            None => core::ptr::null(),
        };

        let needs_bias = self.sku.epilogue.requires_bias();
        if needs_bias && bias_ptr.is_null() {
            return Err(Error::InvalidProblem(
                "Bias* epilogue requires a bias vector",
            ));
        }
        if !needs_bias && !bias_ptr.is_null() {
            return Err(Error::InvalidProblem(
                "Identity epilogue must not be supplied a bias vector",
            ));
        }

        let stream_ptr = stream.as_raw() as *mut c_void;
        let m = self.desc.m;
        let n = self.desc.n;
        let k = self.desc.k;
        let lda = args.a.ld;
        let ldb = args.b.ld;
        let ldd = args.d.ld;
        let alpha = args.alpha;
        let beta = if args.c.is_some() { args.beta } else { 0.0 };

        #[cfg(not(feature = "sm89"))]
        {
            let _ = (a_ptr, b_ptr, c_ptr, d_ptr, ldc, lda, ldb, ldd,
                     m, n, k, alpha, beta, stream_ptr);
            return Err(Error::Unsupported(
                "baracuda-kernels: int4 GEMM requires the `sm89` feature \
                 to be enabled in baracuda-kernels-sys",
            ));
        }

        // Identity launchers don't take a bias pointer in their
        // signature; the bias family does and additionally routes on
        // `BT::KIND` ∈ {F32, I32}. The 4-tuple key reflects this:
        // `(T::KIND, layout, epilogue)` for Identity (BT is meaningless)
        // and the same triple delegating to a `BT::KIND` inner match for
        // each bias variant.
        #[cfg(feature = "sm89")]
        let status = match (T::KIND, self.sku.layout, self.sku.epilogue) {
            // ---- Identity ----
            (ElementKind::S4, LayoutSku::Rcr, EpilogueKind::Identity) => unsafe {
                baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_run(
                    m, n, k,
                    a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                    alpha, beta,
                    core::ptr::null_mut(), 0,
                    stream_ptr,
                )
            },
            (ElementKind::U4, LayoutSku::Rcr, EpilogueKind::Identity) => unsafe {
                baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_run(
                    m, n, k,
                    a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                    alpha, beta,
                    core::ptr::null_mut(), 0,
                    stream_ptr,
                )
            },
            (ElementKind::S4, LayoutSku::Rrr, EpilogueKind::Identity) => unsafe {
                baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_run(
                    m, n, k,
                    a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                    alpha, beta,
                    core::ptr::null_mut(), 0,
                    stream_ptr,
                )
            },
            (ElementKind::U4, LayoutSku::Rrr, EpilogueKind::Identity) => unsafe {
                baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_run(
                    m, n, k,
                    a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                    alpha, beta,
                    core::ptr::null_mut(), 0,
                    stream_ptr,
                )
            },

            // ---- S4 × RCR × Bias family ----
            (ElementKind::S4, LayoutSku::Rcr, EpilogueKind::Bias) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rcr, EpilogueKind::BiasRelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_relu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_relu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rcr, EpilogueKind::BiasGelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_gelu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_gelu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rcr, EpilogueKind::BiasSilu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_silu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rcr_sm89_bias_silu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },

            // ---- U4 × RCR × Bias family ----
            (ElementKind::U4, LayoutSku::Rcr, EpilogueKind::Bias) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rcr, EpilogueKind::BiasRelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_relu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_relu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rcr, EpilogueKind::BiasGelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_gelu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_gelu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rcr, EpilogueKind::BiasSilu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_silu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rcr_sm89_bias_silu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },

            // ---- S4 × RRR × Bias family ----
            (ElementKind::S4, LayoutSku::Rrr, EpilogueKind::Bias) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rrr, EpilogueKind::BiasRelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_relu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_relu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rrr, EpilogueKind::BiasGelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_gelu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_gelu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::S4, LayoutSku::Rrr, EpilogueKind::BiasSilu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_silu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_s4_rrr_sm89_bias_silu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },

            // ---- U4 × RRR × Bias family ----
            (ElementKind::U4, LayoutSku::Rrr, EpilogueKind::Bias) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rrr, EpilogueKind::BiasRelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_relu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_relu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rrr, EpilogueKind::BiasGelu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_gelu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_gelu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },
            (ElementKind::U4, LayoutSku::Rrr, EpilogueKind::BiasSilu) => match BT::KIND {
                BiasElementKind::F32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_silu_f32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
                BiasElementKind::I32 => unsafe {
                    baracuda_kernels_sys::baracuda_kernels_gemm_u4_rrr_sm89_bias_silu_i32_run(
                        m, n, k,
                        a_ptr, lda, b_ptr, ldb, c_ptr, ldc, d_ptr, ldd,
                        bias_ptr, alpha, beta,
                        core::ptr::null_mut(), 0, stream_ptr,
                    )
                },
            },

            _ => {
                return Err(Error::Unsupported(
                    "baracuda-kernels: int4 GEMM dispatcher reached an \
                     unimplemented (element, layout, epilogue) triple \
                     (T must be S4 / U4)",
                ));
            }
        };

        #[cfg(feature = "sm89")]
        { map_status(status) }
        #[cfg(not(feature = "sm89"))]
        #[allow(unreachable_code)]
        { unreachable!("returned earlier under #[cfg(not(feature = \"sm89\"))]") }
    }
}

// Type-level guard that the int4 element re-exports are in scope.
#[allow(dead_code)]
fn _hold_int4_elements_in_scope() {
    let _ = S4(0);
    let _ = U4(0);
}

#[cfg(feature = "sm89")]
fn map_status(code: i32) -> Result<()> {
    match code {
        0 => Ok(()),
        1 => Err(Error::MisalignedOperand),
        2 => Err(Error::InvalidProblem(
            "baracuda-kernels-sys reported invalid problem",
        )),
        3 => Err(Error::Unsupported(
            "baracuda-kernels-sys reported unsupported configuration \
             (likely K or N odd — int4 packing requires both even)",
        )),
        4 => Err(Error::WorkspaceTooSmall { needed: 0, got: 0 }),
        n => Err(Error::CutlassInternal(n)),
    }
}