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
//! Real-GPU smoke test for the Phase 3 trailblazer binary-add kernel
//! in `baracuda-kernels-sys`.
//!
//! Covers `BinaryPlan<f32, N> + BinaryKind::Add` over 1D / 2D / 3D
//! contiguous shapes. The kernel is a pure pointwise `a + b` SIMT
//! kernel (no tensor cores, no warp reduction), so the result is
//! **bit-exact** against the CPU reference — no tolerance.
//!
//! `#[ignore]` by default; run with
//! `cargo test -p baracuda-kernels --release --features sm89 -- --ignored`.

use baracuda_driver::{init, Context, Device, DeviceBuffer, Stream};
use baracuda_kernels::{
    contiguous_stride, BinaryArgs, BinaryDescriptor, BinaryKind, BinaryPlan, ElementKind,
    PlanPreference, TensorMut, TensorRef, Workspace,
};
use half::{bf16, f16};

// 1-ULP relative tolerance for f16 (mantissa = 10 bits → eps ≈ 2^-10).
// `|got - expected| <= max(|expected|, 1.0) * F16_EPS` accepts the
// single-rounding-step disagreement between the host `f16 + f16` path
// and the GPU `__hadd_rn` path, valid for non-subnormal values.
const F16_EPS: f32 = 9.77e-4;
// 1-ULP relative tolerance for bf16 (mantissa = 7 bits → eps ≈ 2^-7).
const BF16_EPS: f32 = 7.81e-3;

fn run_case<const N: usize>(shape: [i32; N]) {
    init().expect("driver init");
    let device = Device::get(0).expect("device 0");
    let ctx = Context::new(&device).expect("context");
    let stream = Stream::new(&ctx).expect("stream");

    let numel: usize = shape.iter().map(|&d| d as usize).product();
    assert!(numel > 0, "test shape must have non-zero element count");

    // Deterministic-but-non-pathological inputs. Mix in some half-
    // integer-ish values so a kernel that accidentally rounded would
    // show up.
    let host_a: Vec<f32> = (0..numel)
        .map(|i| (i as f32) * 0.5 - 17.25)
        .collect();
    let host_b: Vec<f32> = (0..numel)
        .map(|i| (i as f32) * 0.125 + 3.75)
        .collect();
    let host_expected: Vec<f32> = host_a
        .iter()
        .zip(host_b.iter())
        .map(|(a, b)| a + b)
        .collect();

    let dev_a = DeviceBuffer::from_slice(&ctx, &host_a).expect("upload A");
    let dev_b = DeviceBuffer::from_slice(&ctx, &host_b).expect("upload B");
    let mut dev_y: DeviceBuffer<f32> =
        DeviceBuffer::zeros(&ctx, numel).expect("alloc Y");

    let stride = contiguous_stride(shape);

    let desc = BinaryDescriptor {
        kind: BinaryKind::Add,
        shape,
        element: ElementKind::F32,
    };
    let plan = BinaryPlan::<f32, N>::select(&stream, &desc, PlanPreference::default())
        .expect("select BinaryPlan<f32, N>");

    let args = BinaryArgs::<f32, N> {
        a: TensorRef {
            data: dev_a.as_slice(),
            shape,
            stride,
        },
        b: TensorRef {
            data: dev_b.as_slice(),
            shape,
            stride,
        },
        y: TensorMut {
            data: dev_y.as_slice_mut(),
            shape,
            stride,
        },
    };
    plan.run(&stream, Workspace::None, args).expect("binary add run");
    stream.synchronize().expect("stream sync");

    let mut host_got = vec![0f32; numel];
    dev_y.copy_to_host(&mut host_got).expect("download Y");

    // Bit-exact comparison — the kernel is a pure SIMT a + b sweep
    // with no warp reduction or fma fusion, so each cell of the
    // result equals the f32 add of the corresponding cells in A and
    // B exactly.
    let mut mismatches = 0usize;
    let mut first: Option<(usize, f32, f32)> = None;
    for (i, (g, e)) in host_got.iter().zip(host_expected.iter()).enumerate() {
        if g.to_bits() != e.to_bits() {
            mismatches += 1;
            if first.is_none() {
                first = Some((i, *g, *e));
            }
        }
    }
    if mismatches > 0 {
        let (i, g, e) = first.unwrap();
        panic!(
            "binary add f32: {mismatches} mismatches over {numel} cells \
             for shape {shape:?}; first @ {i}: got {g} (bits {:#x}) \
             expected {e} (bits {:#x})",
            g.to_bits(),
            e.to_bits()
        );
    }
}

#[test]
#[ignore]
fn add_f32_1d() {
    run_case::<1>([2048]);
}

#[test]
#[ignore]
fn add_f32_1d_huge() {
    // Exercises the grid-cap loop (numel > 65535 * 256 elements would
    // overflow a single-grid launch; this stays under but well past
    // one block).
    run_case::<1>([1 << 20]);
}

#[test]
#[ignore]
fn add_f32_2d() {
    run_case::<2>([64, 64]);
}

#[test]
#[ignore]
fn add_f32_3d() {
    run_case::<3>([8, 128, 128]);
}

#[test]
#[ignore]
fn add_f32_4d() {
    // Realistic transformer activation shape [B, S, H, D].
    run_case::<4>([2, 32, 8, 64]);
}

#[test]
#[ignore]
fn add_f32_ragged_1d() {
    // Non-power-of-two; tail thread coverage.
    run_case::<1>([2049]);
}

// --- f16 / bf16 / f64 fanout ------------------------------------------------
//
// For f16 / bf16 the GPU does one rounding step (`__hadd_rn`) and the host
// `half::f16 + half::f16` path also does one rounding step, but the upcast
// to f32 in the CPU reference can introduce a separate, distinct rounding
// step depending on impl. Accept up to a 1-ULP relative disagreement.
//
// For f64 the kernel is a pure SIMT `a + b` so bit-exact compare holds.

fn run_case_f16_3d(shape: [i32; 3]) {
    init().expect("driver init");
    let device = Device::get(0).expect("device 0");
    let ctx = Context::new(&device).expect("context");
    let stream = Stream::new(&ctx).expect("stream");

    let numel: usize = shape.iter().map(|&d| d as usize).product();

    // Keep inputs in [-10, 10] so add/sub/mul intermediates stay well
    // within the f16 representable range (max-finite ≈ 65504).
    let host_a: Vec<f16> = (0..numel)
        .map(|i| f16::from_f32(((i % 41) as f32) * 0.5 - 10.0))
        .collect();
    let host_b: Vec<f16> = (0..numel)
        .map(|i| f16::from_f32(((i % 37) as f32) * 0.25 - 4.5))
        .collect();
    let host_expected: Vec<f16> = host_a
        .iter()
        .zip(host_b.iter())
        .map(|(a, b)| *a + *b)
        .collect();

    let dev_a = DeviceBuffer::from_slice(&ctx, &host_a).expect("upload A");
    let dev_b = DeviceBuffer::from_slice(&ctx, &host_b).expect("upload B");
    let mut dev_y: DeviceBuffer<f16> =
        DeviceBuffer::zeros(&ctx, numel).expect("alloc Y");

    let stride = contiguous_stride(shape);
    let desc = BinaryDescriptor {
        kind: BinaryKind::Add,
        shape,
        element: ElementKind::F16,
    };
    let plan = BinaryPlan::<f16, 3>::select(&stream, &desc, PlanPreference::default())
        .expect("select BinaryPlan<f16, 3>");
    let args = BinaryArgs::<f16, 3> {
        a: TensorRef { data: dev_a.as_slice(), shape, stride },
        b: TensorRef { data: dev_b.as_slice(), shape, stride },
        y: TensorMut { data: dev_y.as_slice_mut(), shape, stride },
    };
    plan.run(&stream, Workspace::None, args).expect("binary add f16 run");
    stream.synchronize().expect("stream sync");

    let mut host_got = vec![f16::from_f32(0.0); numel];
    dev_y.copy_to_host(&mut host_got).expect("download Y");

    let mut mismatches = 0usize;
    let mut first: Option<(usize, f16, f16)> = None;
    for (i, (g, e)) in host_got.iter().zip(host_expected.iter()).enumerate() {
        let gf = g.to_f32();
        let ef = e.to_f32();
        let tol = ef.abs().max(1.0) * F16_EPS;
        if !((gf - ef).abs() <= tol) {
            mismatches += 1;
            if first.is_none() {
                first = Some((i, *g, *e));
            }
        }
    }
    if mismatches > 0 {
        let (i, g, e) = first.unwrap();
        panic!(
            "binary add f16: {mismatches} mismatches over {numel} cells \
             for shape {shape:?}; first @ {i}: got {} (bits {:#x}) \
             expected {} (bits {:#x})",
            g.to_f32(), g.to_bits(),
            e.to_f32(), e.to_bits()
        );
    }
}

fn run_case_bf16_3d(shape: [i32; 3]) {
    init().expect("driver init");
    let device = Device::get(0).expect("device 0");
    let ctx = Context::new(&device).expect("context");
    let stream = Stream::new(&ctx).expect("stream");

    let numel: usize = shape.iter().map(|&d| d as usize).product();

    let host_a: Vec<bf16> = (0..numel)
        .map(|i| bf16::from_f32(((i % 41) as f32) * 0.5 - 10.0))
        .collect();
    let host_b: Vec<bf16> = (0..numel)
        .map(|i| bf16::from_f32(((i % 37) as f32) * 0.25 - 4.5))
        .collect();
    let host_expected: Vec<bf16> = host_a
        .iter()
        .zip(host_b.iter())
        .map(|(a, b)| *a + *b)
        .collect();

    let dev_a = DeviceBuffer::from_slice(&ctx, &host_a).expect("upload A");
    let dev_b = DeviceBuffer::from_slice(&ctx, &host_b).expect("upload B");
    let mut dev_y: DeviceBuffer<bf16> =
        DeviceBuffer::zeros(&ctx, numel).expect("alloc Y");

    let stride = contiguous_stride(shape);
    let desc = BinaryDescriptor {
        kind: BinaryKind::Add,
        shape,
        element: ElementKind::Bf16,
    };
    let plan = BinaryPlan::<bf16, 3>::select(&stream, &desc, PlanPreference::default())
        .expect("select BinaryPlan<bf16, 3>");
    let args = BinaryArgs::<bf16, 3> {
        a: TensorRef { data: dev_a.as_slice(), shape, stride },
        b: TensorRef { data: dev_b.as_slice(), shape, stride },
        y: TensorMut { data: dev_y.as_slice_mut(), shape, stride },
    };
    plan.run(&stream, Workspace::None, args).expect("binary add bf16 run");
    stream.synchronize().expect("stream sync");

    let mut host_got = vec![bf16::from_f32(0.0); numel];
    dev_y.copy_to_host(&mut host_got).expect("download Y");

    let mut mismatches = 0usize;
    let mut first: Option<(usize, bf16, bf16)> = None;
    for (i, (g, e)) in host_got.iter().zip(host_expected.iter()).enumerate() {
        let gf = g.to_f32();
        let ef = e.to_f32();
        let tol = ef.abs().max(1.0) * BF16_EPS;
        if !((gf - ef).abs() <= tol) {
            mismatches += 1;
            if first.is_none() {
                first = Some((i, *g, *e));
            }
        }
    }
    if mismatches > 0 {
        let (i, g, e) = first.unwrap();
        panic!(
            "binary add bf16: {mismatches} mismatches over {numel} cells \
             for shape {shape:?}; first @ {i}: got {} (bits {:#x}) \
             expected {} (bits {:#x})",
            g.to_f32(), g.to_bits(),
            e.to_f32(), e.to_bits()
        );
    }
}

fn run_case_f64_3d(shape: [i32; 3]) {
    init().expect("driver init");
    let device = Device::get(0).expect("device 0");
    let ctx = Context::new(&device).expect("context");
    let stream = Stream::new(&ctx).expect("stream");

    let numel: usize = shape.iter().map(|&d| d as usize).product();

    let host_a: Vec<f64> = (0..numel)
        .map(|i| (i as f64) * 0.5 - 17.25)
        .collect();
    let host_b: Vec<f64> = (0..numel)
        .map(|i| (i as f64) * 0.125 + 3.75)
        .collect();
    let host_expected: Vec<f64> = host_a
        .iter()
        .zip(host_b.iter())
        .map(|(a, b)| a + b)
        .collect();

    let dev_a = DeviceBuffer::from_slice(&ctx, &host_a).expect("upload A");
    let dev_b = DeviceBuffer::from_slice(&ctx, &host_b).expect("upload B");
    let mut dev_y: DeviceBuffer<f64> =
        DeviceBuffer::zeros(&ctx, numel).expect("alloc Y");

    let stride = contiguous_stride(shape);
    let desc = BinaryDescriptor {
        kind: BinaryKind::Add,
        shape,
        element: ElementKind::F64,
    };
    let plan = BinaryPlan::<f64, 3>::select(&stream, &desc, PlanPreference::default())
        .expect("select BinaryPlan<f64, 3>");
    let args = BinaryArgs::<f64, 3> {
        a: TensorRef { data: dev_a.as_slice(), shape, stride },
        b: TensorRef { data: dev_b.as_slice(), shape, stride },
        y: TensorMut { data: dev_y.as_slice_mut(), shape, stride },
    };
    plan.run(&stream, Workspace::None, args).expect("binary add f64 run");
    stream.synchronize().expect("stream sync");

    let mut host_got = vec![0f64; numel];
    dev_y.copy_to_host(&mut host_got).expect("download Y");

    let mut mismatches = 0usize;
    let mut first: Option<(usize, f64, f64)> = None;
    for (i, (g, e)) in host_got.iter().zip(host_expected.iter()).enumerate() {
        if g.to_bits() != e.to_bits() {
            mismatches += 1;
            if first.is_none() {
                first = Some((i, *g, *e));
            }
        }
    }
    if mismatches > 0 {
        let (i, g, e) = first.unwrap();
        panic!(
            "binary add f64: {mismatches} mismatches over {numel} cells \
             for shape {shape:?}; first @ {i}: got {g} (bits {:#x}) \
             expected {e} (bits {:#x})",
            g.to_bits(),
            e.to_bits()
        );
    }
}

#[test]
#[ignore]
fn add_f16_3d() {
    run_case_f16_3d([8, 128, 128]);
}

#[test]
#[ignore]
fn add_bf16_3d() {
    run_case_bf16_3d([8, 128, 128]);
}

#[test]
#[ignore]
fn add_f64_3d() {
    run_case_f64_3d([8, 128, 128]);
}

#[test]
fn select_rejects_non_f32_today() {
    // No GPU needed for this — just confirm select() rejects the
    // unsupported (kind, dtype) pairs as the trailblazer scope
    // promises. Pow was the original sentinel; after the Pow fanout
    // landed, Lerp stands in as the documented reserved-but-deferred
    // discriminant (it takes a scalar `weight: f32` alongside its
    // two tensor inputs, which doesn't fit `BinaryArgs<a, b, y>`).
    let desc = BinaryDescriptor {
        kind: BinaryKind::Lerp,
        shape: [4],
        element: ElementKind::F32,
    };
    init().expect("driver init");
    let device = Device::get(0).expect("device 0");
    let ctx = Context::new(&device).expect("context");
    let stream = Stream::new(&ctx).expect("stream");
    let err = BinaryPlan::<f32, 1>::select(&stream, &desc, PlanPreference::default());
    assert!(
        err.is_err(),
        "Lerp is reserved-but-deferred today; select must reject"
    );
}