numr 0.5.2

High-performance numerical computing with multi-backend GPU acceleration (CPU/CUDA/WebGPU)
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
#![allow(dead_code)]

use fluxbench::{Bencher, flux};
use std::hint::black_box;

use numr::prelude::*;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn rand_numr(shape: &[usize], device: &CpuDevice) -> Tensor<CpuRuntime> {
    let client = CpuRuntime::default_client(device);
    client.rand(shape, DType::F32).unwrap()
}

fn rand_complex(n: usize, device: &CpuDevice) -> Tensor<CpuRuntime> {
    let client = CpuRuntime::default_client(device);
    let real = client.rand(&[n], DType::F64).unwrap();
    client.cast(&real, DType::Complex128).unwrap()
}

// ---------------------------------------------------------------------------
// Group 1: Matmul Thread Scaling (512x512 matrix)
// ---------------------------------------------------------------------------

#[flux::bench(group = "matmul_threads_512", args = [1, 2, 4, 8])]
fn matmul_512x512(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let a = rand_numr(&[512, 512], &device);
    let bm = rand_numr(&[512, 512], &device);
    b.iter(|| black_box(client.matmul(&a, &bm).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 2: Batched Matmul Thread Scaling (32 x 128x128)
// ---------------------------------------------------------------------------

#[flux::bench(group = "matmul_batch_threads", args = [1, 2, 4, 8])]
fn matmul_batched_32x128x128(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let a = rand_numr(&[32, 128, 128], &device);
    let bm = rand_numr(&[32, 128, 128], &device);
    b.iter(|| black_box(client.matmul(&a, &bm).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 3: Reduce Sum Thread Scaling (1M elements)
// ---------------------------------------------------------------------------

#[flux::bench(group = "reduce_sum_1m_threads", args = [1, 2, 4, 8])]
fn reduce_sum_1m(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let t = rand_numr(&[1_000_000], &device);
    b.iter(|| black_box(client.sum(&t, &[0], false).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 4: Reduce Sum Thread Scaling (10M elements)
// ---------------------------------------------------------------------------

#[flux::bench(group = "reduce_sum_10m_threads", args = [1, 2, 4, 8])]
fn reduce_sum_10m(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let t = rand_numr(&[10_000_000], &device);
    b.iter(|| black_box(client.sum(&t, &[0], false).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 5: Reduce Mean Thread Scaling (1M elements)
// ---------------------------------------------------------------------------

#[flux::bench(group = "reduce_mean_1m_threads", args = [1, 4])]
fn reduce_mean_1m(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let t = rand_numr(&[1_000_000], &device);
    b.iter(|| black_box(client.mean(&t, &[0], false).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 6: FFT Thread Scaling (16384 elements)
// ---------------------------------------------------------------------------

#[flux::bench(group = "fft_threads_16k", args = [1, 2, 4, 8])]
fn fft_16384(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let t = rand_complex(16384, &device);
    b.iter(|| {
        black_box(
            client
                .fft(&t, FftDirection::Forward, FftNormalization::Backward)
                .unwrap(),
        )
    });
}

// ---------------------------------------------------------------------------
// Group 7: Batched FFT Thread Scaling (64 x 1024)
// ---------------------------------------------------------------------------

#[flux::bench(group = "fft_batch_threads", args = [1, 2, 4, 8])]
fn fft_batched_64x1024(b: &mut Bencher, threads: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(threads), None));
    let real = client.rand(&[64, 1024], DType::F64).unwrap();
    let t = client.cast(&real, DType::Complex128).unwrap();
    b.iter(|| {
        black_box(
            client
                .fft(&t, FftDirection::Forward, FftNormalization::Backward)
                .unwrap(),
        )
    });
}

// ---------------------------------------------------------------------------
// Group 8: Chunk Size Sensitivity (4 threads, reduce sum 10M)
// ---------------------------------------------------------------------------

#[flux::bench(group = "reduce_sum_chunk_sensitivity", args = [256, 1024, 4096, 16384])]
fn reduce_sum_10m_chunk(b: &mut Bencher, chunk_size: usize) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device)
        .with_parallelism(ParallelismConfig::new(Some(4), Some(chunk_size)));
    let t = rand_numr(&[10_000_000], &device);
    b.iter(|| black_box(client.sum(&t, &[0], false).unwrap()));
}

// ---------------------------------------------------------------------------
// Group 9: Overhead Benchmarks (default vs custom config)
// ---------------------------------------------------------------------------

#[flux::bench(group = "overhead_matmul")]
fn matmul_512x512_default(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device);
    let a = rand_numr(&[512, 512], &device);
    let bm = rand_numr(&[512, 512], &device);
    b.iter(|| black_box(client.matmul(&a, &bm).unwrap()));
}

#[flux::bench(group = "overhead_matmul")]
fn matmul_512x512_custom_same(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client =
        CpuRuntime::default_client(&device).with_parallelism(ParallelismConfig::new(None, None));
    let a = rand_numr(&[512, 512], &device);
    let bm = rand_numr(&[512, 512], &device);
    b.iter(|| black_box(client.matmul(&a, &bm).unwrap()));
}

#[flux::bench(group = "overhead_reduce")]
fn reduce_sum_1m_default(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device);
    let t = rand_numr(&[1_000_000], &device);
    b.iter(|| black_box(client.sum(&t, &[0], false).unwrap()));
}

#[flux::bench(group = "overhead_reduce")]
fn reduce_sum_1m_custom_same(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client =
        CpuRuntime::default_client(&device).with_parallelism(ParallelismConfig::new(None, None));
    let t = rand_numr(&[1_000_000], &device);
    b.iter(|| black_box(client.sum(&t, &[0], false).unwrap()));
}

#[flux::bench(group = "overhead_fft")]
fn fft_1024_default(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client = CpuRuntime::default_client(&device);
    let t = rand_complex(1024, &device);
    b.iter(|| {
        black_box(
            client
                .fft(&t, FftDirection::Forward, FftNormalization::Backward)
                .unwrap(),
        )
    });
}

#[flux::bench(group = "overhead_fft")]
fn fft_1024_custom_same(b: &mut Bencher) {
    let device = CpuDevice::new();
    let client =
        CpuRuntime::default_client(&device).with_parallelism(ParallelismConfig::new(None, None));
    let t = rand_complex(1024, &device);
    b.iter(|| {
        black_box(
            client
                .fft(&t, FftDirection::Forward, FftNormalization::Backward)
                .unwrap(),
        )
    });
}

// ---------------------------------------------------------------------------
// Comparisons: Thread Scaling
// ---------------------------------------------------------------------------

#[flux::compare(
    id = "matmul_512_threads",
    title = "Matmul 512×512 Thread Scaling",
    benchmarks = [
        "matmul_512x512@1",
        "matmul_512x512@2",
        "matmul_512x512@4",
        "matmul_512x512@8"
    ],
    baseline = "matmul_512x512@1",
    metric = "mean"
)]
struct MatmulScaling512;

#[flux::compare(
    id = "matmul_batch_threads",
    title = "Matmul Batched 32×128×128 Thread Scaling",
    benchmarks = [
        "matmul_batched_32x128x128@1",
        "matmul_batched_32x128x128@2",
        "matmul_batched_32x128x128@4",
        "matmul_batched_32x128x128@8"
    ],
    baseline = "matmul_batched_32x128x128@1",
    metric = "mean"
)]
struct MatmulBatchScaling;

#[flux::compare(
    id = "reduce_sum_1m_threads",
    title = "Reduce Sum 1M Thread Scaling",
    benchmarks = [
        "reduce_sum_1m@1",
        "reduce_sum_1m@2",
        "reduce_sum_1m@4",
        "reduce_sum_1m@8"
    ],
    baseline = "reduce_sum_1m@1",
    metric = "mean"
)]
struct ReduceSum1MScaling;

#[flux::compare(
    id = "reduce_sum_10m_threads",
    title = "Reduce Sum 10M Thread Scaling",
    benchmarks = [
        "reduce_sum_10m@1",
        "reduce_sum_10m@2",
        "reduce_sum_10m@4",
        "reduce_sum_10m@8"
    ],
    baseline = "reduce_sum_10m@1",
    metric = "mean"
)]
struct ReduceSum10MScaling;

#[flux::compare(
    id = "fft_16k_threads",
    title = "FFT 16384 Thread Scaling",
    benchmarks = [
        "fft_16384@1",
        "fft_16384@2",
        "fft_16384@4",
        "fft_16384@8"
    ],
    baseline = "fft_16384@1",
    metric = "mean"
)]
struct FFT16KScaling;

#[flux::compare(
    id = "fft_batch_threads",
    title = "FFT Batched 64×1024 Thread Scaling",
    benchmarks = [
        "fft_batched_64x1024@1",
        "fft_batched_64x1024@2",
        "fft_batched_64x1024@4",
        "fft_batched_64x1024@8"
    ],
    baseline = "fft_batched_64x1024@1",
    metric = "mean"
)]
struct FFTBatchScaling;

// ---------------------------------------------------------------------------
// Comparisons: Chunk Size Sensitivity
// ---------------------------------------------------------------------------

#[flux::compare(
    id = "chunk_size_reduce",
    title = "Reduce Sum 10M Chunk Size Sensitivity",
    benchmarks = [
        "reduce_sum_10m_chunk@256",
        "reduce_sum_10m_chunk@1024",
        "reduce_sum_10m_chunk@4096",
        "reduce_sum_10m_chunk@16384"
    ],
    baseline = "reduce_sum_10m_chunk@1024",
    metric = "mean"
)]
struct ChunkSizeReduce;

// ---------------------------------------------------------------------------
// Comparisons: Overhead
// ---------------------------------------------------------------------------

#[flux::compare(
    id = "overhead_matmul",
    title = "Matmul 512×512 Configuration Overhead",
    benchmarks = ["matmul_512x512_default", "matmul_512x512_custom_same"],
    baseline = "matmul_512x512_default",
    metric = "mean"
)]
struct OverheadMatmul;

#[flux::compare(
    id = "overhead_reduce",
    title = "Reduce Sum 1M Configuration Overhead",
    benchmarks = ["reduce_sum_1m_default", "reduce_sum_1m_custom_same"],
    baseline = "reduce_sum_1m_default",
    metric = "mean"
)]
struct OverheadReduce;

#[flux::compare(
    id = "overhead_fft",
    title = "FFT 1024 Configuration Overhead",
    benchmarks = ["fft_1024_default", "fft_1024_custom_same"],
    baseline = "fft_1024_default",
    metric = "mean"
)]
struct OverheadFFT;

// ---------------------------------------------------------------------------
// Synthetic Metrics: Scaling Efficiency
// ---------------------------------------------------------------------------

#[flux::synthetic(
    id = "matmul_512_4t_speedup",
    formula = "matmul_512x512@1 / matmul_512x512@4",
    unit = "x"
)]
struct Matmul512SpeedupRatio;

#[flux::synthetic(
    id = "reduce_sum_1m_4t_speedup",
    formula = "reduce_sum_1m@1 / reduce_sum_1m@4",
    unit = "x"
)]
struct ReduceSum1M4tSpeedup;

#[flux::synthetic(
    id = "reduce_sum_10m_4t_speedup",
    formula = "reduce_sum_10m@1 / reduce_sum_10m@4",
    unit = "x"
)]
struct ReduceSum10M4tSpeedup;

#[flux::synthetic(
    id = "fft_16k_4t_speedup",
    formula = "fft_16384@1 / fft_16384@4",
    unit = "x"
)]
struct FFT16K4tSpeedup;

// ---------------------------------------------------------------------------
// Synthetic Metrics: Configuration Overhead
// ---------------------------------------------------------------------------

#[flux::synthetic(
    id = "matmul_overhead_ratio",
    formula = "matmul_512x512_custom_same / matmul_512x512_default",
    unit = "x"
)]
struct MatmulOverheadRatio;

#[flux::synthetic(
    id = "reduce_overhead_ratio",
    formula = "reduce_sum_1m_custom_same / reduce_sum_1m_default",
    unit = "x"
)]
struct ReduceOverheadRatio;

#[flux::synthetic(
    id = "fft_overhead_ratio",
    formula = "fft_1024_custom_same / fft_1024_default",
    unit = "x"
)]
struct FFTOverheadRatio;

// ---------------------------------------------------------------------------
// Verification Gates: No Regression from Threading
// ---------------------------------------------------------------------------
// Single-operation kernels (batch_size=1) are inherently sequential.
// Threading only helps batched workloads. Verify that enabling threads
// doesn't cause regression (overhead must stay within 15%).

#[flux::verify(
    expr = "matmul_512x512@4 / matmul_512x512@1 < 1.15",
    severity = "warning"
)]
struct VerifyMatmul512NoRegression;

#[flux::verify(
    expr = "reduce_sum_10m@4 / reduce_sum_10m@1 < 1.15",
    severity = "warning"
)]
struct VerifyReduceSum10MNoRegression;

#[flux::verify(expr = "fft_16384@4 / fft_16384@1 < 1.15", severity = "warning")]
struct VerifyFFT16KNoRegression;

// ---------------------------------------------------------------------------
// Verification Gates: Configuration Overhead (must be strict)
// ---------------------------------------------------------------------------

#[flux::verify(
    expr = "matmul_512x512_custom_same / matmul_512x512_default < 1.10",
    severity = "warning"
)]
struct VerifyMatmulOverhead;

#[flux::verify(
    expr = "reduce_sum_1m_custom_same / reduce_sum_1m_default < 1.10",
    severity = "warning"
)]
struct VerifyReduceOverhead;

#[flux::verify(
    expr = "fft_1024_custom_same / fft_1024_default < 1.10",
    severity = "warning"
)]
struct VerifyFFTOverhead;

fn main() {
    fluxbench::run().unwrap();
}

// ---------------------------------------------------------------------------
// Unit Tests: Numerical Parity
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    #[allow(unused_imports)]
    use numr::prelude::*;

    /// Matmul must produce bit-identical results regardless of thread count.
    /// Verifies that work partitioning doesn't affect floating-point accumulation order.
    #[test]
    fn test_matmul_parallelism_numerical_parity() {
        let device = CpuDevice::new();
        let client = CpuRuntime::default_client(&device);

        let a = client.rand(&[512, 512], DType::F32).unwrap();
        let b = client.rand(&[512, 512], DType::F32).unwrap();

        let result_1t = client
            .with_parallelism(ParallelismConfig::new(Some(1), None))
            .matmul(&a, &b)
            .unwrap()
            .to_vec::<f32>();

        let result_4t = client
            .with_parallelism(ParallelismConfig::new(Some(4), None))
            .matmul(&a, &b)
            .unwrap()
            .to_vec::<f32>();

        let result_8t = client
            .with_parallelism(ParallelismConfig::new(Some(8), None))
            .matmul(&a, &b)
            .unwrap()
            .to_vec::<f32>();

        assert_eq!(
            result_1t, result_4t,
            "Matmul results differ between 1-thread and 4-thread"
        );
        assert_eq!(
            result_1t, result_8t,
            "Matmul results differ between 1-thread and 8-thread"
        );
    }

    /// Reduction sum must produce bit-identical results regardless of thread count.
    /// Verifies that parallel chunk boundaries don't affect accumulation.
    #[test]
    fn test_reduce_sum_parallelism_numerical_parity() {
        let device = CpuDevice::new();
        let client = CpuRuntime::default_client(&device);

        let t = client.rand(&[1_000_000], DType::F32).unwrap();

        let result_1t = client
            .with_parallelism(ParallelismConfig::new(Some(1), None))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        let result_4t = client
            .with_parallelism(ParallelismConfig::new(Some(4), None))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        let result_8t = client
            .with_parallelism(ParallelismConfig::new(Some(8), None))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        assert_eq!(
            result_1t, result_4t,
            "Sum results differ between 1-thread and 4-thread"
        );
        assert_eq!(
            result_1t, result_8t,
            "Sum results differ between 1-thread and 8-thread"
        );
    }

    /// FFT must produce bit-identical results regardless of thread count.
    /// Single-batch FFTs are sequential, but batched FFTs split across threads.
    #[test]
    fn test_fft_parallelism_numerical_parity() {
        let device = CpuDevice::new();
        let client = CpuRuntime::default_client(&device);

        let real = client.rand(&[16384], DType::F64).unwrap();
        let t = client.cast(&real, DType::Complex128).unwrap();

        let result_1t = client
            .with_parallelism(ParallelismConfig::new(Some(1), None))
            .fft(&t, FftDirection::Forward, FftNormalization::Backward)
            .unwrap()
            .to_vec::<f64>();

        let result_4t = client
            .with_parallelism(ParallelismConfig::new(Some(4), None))
            .fft(&t, FftDirection::Forward, FftNormalization::Backward)
            .unwrap()
            .to_vec::<f64>();

        let result_8t = client
            .with_parallelism(ParallelismConfig::new(Some(8), None))
            .fft(&t, FftDirection::Forward, FftNormalization::Backward)
            .unwrap()
            .to_vec::<f64>();

        assert_eq!(
            result_1t, result_4t,
            "FFT results differ between 1-thread and 4-thread"
        );
        assert_eq!(
            result_1t, result_8t,
            "FFT results differ between 1-thread and 8-thread"
        );
    }

    #[test]
    fn test_chunk_size_numerical_parity() {
        let device = CpuDevice::new();
        let client = CpuRuntime::default_client(&device);

        let t = client.rand(&[10_000_000], DType::F32).unwrap();

        let result_chunk_256 = client
            .with_parallelism(ParallelismConfig::new(Some(4), Some(256)))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        let result_chunk_1024 = client
            .with_parallelism(ParallelismConfig::new(Some(4), Some(1024)))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        let result_chunk_4096 = client
            .with_parallelism(ParallelismConfig::new(Some(4), Some(4096)))
            .sum(&t, &[0], false)
            .unwrap()
            .to_vec::<f32>();

        assert_eq!(
            result_chunk_256, result_chunk_1024,
            "Sum results differ between chunk_size=256 and chunk_size=1024"
        );
        assert_eq!(
            result_chunk_1024, result_chunk_4096,
            "Sum results differ between chunk_size=1024 and chunk_size=4096"
        );
    }
}