sketch-spgemm 0.11.0

Adaptive SketchSpGEMM with low-overhead auto selection and fused residual fingerprints
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
use crate::error::{ArithmeticOperation, SpGemmError};
use crate::matrix::{CheckedSpGemmScalar, CsrInput, CsrMatrix, DenseMatrix, SpGemmScalar};
use std::collections::HashMap;

#[derive(Clone, Debug, Default)]
pub struct SpGemmStats {
    pub candidate_products: u128,
}

/// Resource limits for direct sparse multiplication.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SpGemmOptions {
    /// Maximum number of explicitly stored entries in the result.
    pub max_output_nnz: Option<usize>,
}

/// Algebra used by configurable sparse matrix multiplication.
pub trait Semiring<T> {
    /// Additive identity and implicit sparse value.
    fn zero(&self) -> T;
    /// Combine a new path contribution with an existing output value.
    fn add(&self, left: T, right: T) -> T;
    /// Combine values along one path.
    fn multiply(&self, left: T, right: T) -> T;
    /// Whether a value should be omitted from canonical sparse output.
    fn is_zero(&self, value: T) -> bool;
}

/// Ordinary sum-product arithmetic.
#[derive(Clone, Copy, Debug, Default)]
pub struct PlusTimes;

impl<T> Semiring<T> for PlusTimes
where
    T: SpGemmScalar,
{
    fn zero(&self) -> T {
        T::default()
    }

    fn add(&self, mut left: T, right: T) -> T {
        left += right;
        left
    }

    fn multiply(&self, left: T, right: T) -> T {
        left * right
    }

    fn is_zero(&self, value: T) -> bool {
        value == T::default()
    }
}

fn enforce_output_limit(
    current: usize,
    additional: usize,
    options: SpGemmOptions,
) -> Result<(), SpGemmError> {
    let attempted = current.saturating_add(additional);
    if options
        .max_output_nnz
        .is_some_and(|limit| attempted > limit)
    {
        return Err(SpGemmError::OutputNnzLimitExceeded {
            limit: options.max_output_nnz.expect("checked output limit"),
            attempted,
        });
    }
    Ok(())
}

/// Baseline row-wise hash-accumulator SpGEMM over any supported scalar.
/// This is intentionally simple: it is a correctness/baseline kernel, not a
/// replacement for SuiteSparse/Kokkos/cuSPARSE.
pub fn spgemm_hash<T, A, B>(a: &A, b: &B) -> (CsrMatrix<T>, SpGemmStats)
where
    T: SpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    assert_eq!(a.cols(), b.rows(), "incompatible matrix dimensions");

    let mut triplets = Vec::new();
    let mut stats = SpGemmStats::default();

    for i in 0..a.rows() {
        let mut acc: HashMap<usize, T> = HashMap::new();
        for (k, av) in a.row(i) {
            for (j, bv) in b.row(k) {
                stats.candidate_products += 1;
                *acc.entry(j).or_default() += av * bv;
            }
        }

        let zero = T::default();
        let mut row: Vec<(usize, T)> = acc.into_iter().filter(|&(_, v)| v != zero).collect();
        row.sort_unstable_by_key(|&(j, _)| j);
        triplets.extend(row.into_iter().map(|(j, v)| (i, j, v)));
    }

    (
        CsrMatrix::from_triplets(a.rows(), b.cols(), &triplets),
        stats,
    )
}

/// Fallible direct multiplication for arbitrary canonical CSR inputs.
pub fn try_spgemm_hash<T, A, B>(a: &A, b: &B) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: SpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    try_spgemm_hash_with_options(a, b, SpGemmOptions::default())
}

/// Fallible direct multiplication with an optional output-size budget.
pub fn try_spgemm_hash_with_options<T, A, B>(
    a: &A,
    b: &B,
    options: SpGemmOptions,
) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: SpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    if a.cols() != b.rows() {
        return Err(SpGemmError::DimensionMismatch {
            left: (a.rows(), a.cols()),
            right: (b.rows(), b.cols()),
        });
    }
    try_spgemm_semiring(a, b, PlusTimes, options)
}

/// Sparse multiplication over a caller-provided semiring.
pub fn try_spgemm_semiring<T, A, B, S>(
    a: &A,
    b: &B,
    semiring: S,
    options: SpGemmOptions,
) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: Copy,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
    S: Semiring<T>,
{
    if a.cols() != b.rows() {
        return Err(SpGemmError::DimensionMismatch {
            left: (a.rows(), a.cols()),
            right: (b.rows(), b.cols()),
        });
    }

    let mut row_ptr = Vec::with_capacity(a.rows().saturating_add(1));
    let mut col_idx = Vec::new();
    let mut values = Vec::new();
    let mut stats = SpGemmStats::default();
    row_ptr.push(0);

    for row in 0..a.rows() {
        let mut acc: HashMap<usize, T> = HashMap::new();
        for (inner, left) in a.row(row) {
            for (column, right) in b.row(inner) {
                stats.candidate_products = stats.candidate_products.saturating_add(1);
                let product = semiring.multiply(left, right);
                let current = acc.get(&column).copied().unwrap_or_else(|| semiring.zero());
                acc.insert(column, semiring.add(current, product));
            }
        }
        let mut output_row: Vec<_> = acc
            .into_iter()
            .filter(|&(_, value)| !semiring.is_zero(value))
            .collect();
        output_row.sort_unstable_by_key(|&(column, _)| column);
        enforce_output_limit(values.len(), output_row.len(), options)?;
        for (column, value) in output_row {
            col_idx.push(column);
            values.push(value);
        }
        row_ptr.push(values.len());
    }

    Ok((
        CsrMatrix {
            rows: a.rows(),
            cols: b.cols(),
            row_ptr,
            col_idx,
            values,
        },
        stats,
    ))
}

/// Overflow-detecting row-wise hash-accumulator SpGEMM.
///
/// This exact direct kernel returns the first scalar multiplication or
/// accumulator addition that cannot be represented by `T`. It intentionally
/// does not enter the `i64` sketch pipeline, whose recovery arithmetic has
/// different bounds and remains available through [`crate::try_auto_spgemm`].
/// Accumulation is checked after every candidate product in canonical inner
/// index order; it does not use a wider temporary accumulator, so intermediate
/// overflow is reported even when later cancellation could fit in `T`.
pub fn try_spgemm_hash_checked<T, A, B>(
    a: &A,
    b: &B,
) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: CheckedSpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    try_spgemm_hash_checked_with_options(a, b, SpGemmOptions::default())
}

/// Checked direct multiplication with an optional output-size budget.
pub fn try_spgemm_hash_checked_with_options<T, A, B>(
    a: &A,
    b: &B,
    options: SpGemmOptions,
) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: CheckedSpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    if a.cols() != b.rows() {
        return Err(SpGemmError::DimensionMismatch {
            left: (a.rows(), a.cols()),
            right: (b.rows(), b.cols()),
        });
    }

    let zero = T::default();
    let mut row_ptr = Vec::with_capacity(a.rows().saturating_add(1));
    let mut col_idx = Vec::new();
    let mut values = Vec::new();
    let mut stats = SpGemmStats::default();
    row_ptr.push(0);

    for row in 0..a.rows() {
        let mut acc: HashMap<usize, T> = HashMap::new();
        for (inner, left) in a.row(row) {
            for (column, right) in b.row(inner) {
                stats.candidate_products = stats.candidate_products.saturating_add(1);
                let product =
                    left.checked_mul_value(right)
                        .ok_or(SpGemmError::ArithmeticOverflow {
                            operation: ArithmeticOperation::Multiply,
                            row,
                            inner,
                            column,
                        })?;
                let current = acc.get(&column).copied().unwrap_or(zero);
                let sum =
                    current
                        .checked_add_value(product)
                        .ok_or(SpGemmError::ArithmeticOverflow {
                            operation: ArithmeticOperation::Add,
                            row,
                            inner,
                            column,
                        })?;
                acc.insert(column, sum);
            }
        }

        let mut output_row: Vec<_> = acc
            .into_iter()
            .filter(|&(_, value)| value != zero)
            .collect();
        output_row.sort_unstable_by_key(|&(column, _)| column);
        enforce_output_limit(values.len(), output_row.len(), options)?;
        for (column, value) in output_row {
            col_idx.push(column);
            values.push(value);
        }
        row_ptr.push(values.len());
    }

    Ok((
        CsrMatrix {
            rows: a.rows(),
            cols: b.cols(),
            row_ptr,
            col_idx,
            values,
        },
        stats,
    ))
}

/// Checked multiplication after losslessly widening both inputs to `U`.
///
/// This is useful for storing inputs as `i64` while accumulating products in
/// `i128`. The returned matrix uses the wider type and is never narrowed
/// implicitly.
pub fn try_spgemm_checked_with_accumulator<T, U, A, B>(
    a: &A,
    b: &B,
    options: SpGemmOptions,
) -> Result<(CsrMatrix<U>, SpGemmStats), SpGemmError>
where
    T: Copy,
    U: CheckedSpGemmScalar + From<T>,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    if a.cols() != b.rows() {
        return Err(SpGemmError::DimensionMismatch {
            left: (a.rows(), a.cols()),
            right: (b.rows(), b.cols()),
        });
    }

    let zero = U::default();
    let mut row_ptr = Vec::with_capacity(a.rows().saturating_add(1));
    let mut col_idx = Vec::new();
    let mut values = Vec::new();
    let mut stats = SpGemmStats::default();
    row_ptr.push(0);
    for row in 0..a.rows() {
        let mut acc: HashMap<usize, U> = HashMap::new();
        for (inner, left) in a.row(row) {
            for (column, right) in b.row(inner) {
                stats.candidate_products = stats.candidate_products.saturating_add(1);
                let product = U::from(left).checked_mul_value(U::from(right)).ok_or(
                    SpGemmError::ArithmeticOverflow {
                        operation: ArithmeticOperation::Multiply,
                        row,
                        inner,
                        column,
                    },
                )?;
                let sum = acc
                    .get(&column)
                    .copied()
                    .unwrap_or(zero)
                    .checked_add_value(product)
                    .ok_or(SpGemmError::ArithmeticOverflow {
                        operation: ArithmeticOperation::Add,
                        row,
                        inner,
                        column,
                    })?;
                acc.insert(column, sum);
            }
        }
        let mut output_row: Vec<_> = acc
            .into_iter()
            .filter(|&(_, value)| value != zero)
            .collect();
        output_row.sort_unstable_by_key(|&(column, _)| column);
        enforce_output_limit(values.len(), output_row.len(), options)?;
        for (column, value) in output_row {
            col_idx.push(column);
            values.push(value);
        }
        row_ptr.push(values.len());
    }
    Ok((
        CsrMatrix {
            rows: a.rows(),
            cols: b.cols(),
            row_ptr,
            col_idx,
            values,
        },
        stats,
    ))
}

/// Overflow-detecting exact sparse matrix multiplication.
///
/// This convenience entry point currently uses the row-wise hash accumulator
/// and never enters the unchecked `i64` sketch pipeline.
pub fn try_spgemm_checked<T, A, B>(a: &A, b: &B) -> Result<(CsrMatrix<T>, SpGemmStats), SpGemmError>
where
    T: CheckedSpGemmScalar,
    A: CsrInput<Scalar = T> + ?Sized,
    B: CsrInput<Scalar = T> + ?Sized,
{
    try_spgemm_hash_checked(a, b)
}

/// Straightforward dense rectangular GEMM. The inner loop skips zero entries in
/// the left factor so that hashed sketches that remain sparse do not pay the full
/// m*n*g cost.
pub fn dense_matmul<T>(a: &DenseMatrix<T>, b: &DenseMatrix<T>) -> DenseMatrix<T>
where
    T: SpGemmScalar,
{
    assert_eq!(a.cols, b.rows);
    let mut out: DenseMatrix<T> = DenseMatrix::zeros(a.rows, b.cols);

    for i in 0..a.rows {
        for k in 0..a.cols {
            let av = a[(i, k)];
            if av == T::default() {
                continue;
            }
            let bbase = k * b.cols;
            let obase = i * out.cols;
            for j in 0..b.cols {
                out.data[obase + j] += av * b.data[bbase + j];
            }
        }
    }
    out
}

/// Overflow-detecting dense matrix multiplication.
///
/// Accumulation is checked after every product in inner-index order. A
/// temporarily unrepresentable sum is therefore an error even if subsequent
/// terms would bring the mathematical result back into range.
pub fn try_dense_matmul_checked<T>(
    a: &DenseMatrix<T>,
    b: &DenseMatrix<T>,
) -> Result<DenseMatrix<T>, SpGemmError>
where
    T: CheckedSpGemmScalar,
{
    if a.cols != b.rows {
        return Err(SpGemmError::DimensionMismatch {
            left: (a.rows, a.cols),
            right: (b.rows, b.cols),
        });
    }

    let zero = T::default();
    let mut out: DenseMatrix<T> = DenseMatrix::zeros(a.rows, b.cols);
    for row in 0..a.rows {
        for inner in 0..a.cols {
            let left = a[(row, inner)];
            if left == zero {
                continue;
            }
            for column in 0..b.cols {
                let right = b[(inner, column)];
                let product =
                    left.checked_mul_value(right)
                        .ok_or(SpGemmError::ArithmeticOverflow {
                            operation: ArithmeticOperation::Multiply,
                            row,
                            inner,
                            column,
                        })?;
                out[(row, column)] = out[(row, column)].checked_add_value(product).ok_or(
                    SpGemmError::ArithmeticOverflow {
                        operation: ArithmeticOperation::Add,
                        row,
                        inner,
                        column,
                    },
                )?;
            }
        }
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tiny_spgemm() {
        let a = CsrMatrix::from_triplets(2, 2, &[(0, 0, 2), (0, 1, 3), (1, 1, 4)]);
        let b = CsrMatrix::from_triplets(2, 2, &[(0, 0, 5), (1, 0, 7), (1, 1, 11)]);
        let (c, stats) = spgemm_hash(&a, &b);
        assert_eq!(stats.candidate_products, 5);
        assert_eq!(c.to_dense().data, vec![31, 33, 28, 44]);
    }

    #[test]
    fn generic_i32_spgemm() {
        let a = CsrMatrix::<i32>::from_triplets(1, 2, &[(0, 0, 2), (0, 1, 3)]);
        let b = CsrMatrix::<i32>::from_triplets(2, 1, &[(0, 0, 5), (1, 0, 7)]);
        let (c, _) = try_spgemm_hash(&a, &b).unwrap();
        assert_eq!(c.values, vec![31]);
    }

    #[test]
    fn generic_f64_dense_and_sparse_kernels() {
        let a = CsrMatrix::<f64>::from_triplets(1, 2, &[(0, 0, 0.5), (0, 1, 2.0)]);
        let b = CsrMatrix::<f64>::from_triplets(2, 1, &[(0, 0, 4.0), (1, 0, 1.5)]);
        let (sparse, _) = try_spgemm_hash(&a, &b).unwrap();
        let dense = dense_matmul(&a.to_dense(), &b.to_dense());
        assert_eq!(sparse.values, vec![5.0]);
        assert_eq!(dense.data, vec![5.0]);
    }

    #[test]
    fn fallible_generic_api_reports_shape_mismatch() {
        let a = CsrMatrix::<u32>::zeros(1, 2);
        let b = CsrMatrix::<u32>::zeros(3, 1);
        assert!(matches!(
            try_spgemm_hash(&a, &b),
            Err(SpGemmError::DimensionMismatch { .. })
        ));
    }

    #[test]
    fn checked_sparse_kernel_reports_multiplication_overflow() {
        let a = CsrMatrix::<i8>::from_triplets(1, 1, &[(0, 0, 100)]);
        let b = CsrMatrix::<i8>::from_triplets(1, 1, &[(0, 0, 2)]);

        assert!(matches!(
            try_spgemm_hash_checked(&a, &b),
            Err(SpGemmError::ArithmeticOverflow {
                operation: ArithmeticOperation::Multiply,
                row: 0,
                inner: 0,
                column: 0,
            })
        ));
    }

    #[test]
    fn checked_sparse_kernel_reports_accumulator_overflow() {
        let a = CsrMatrix::<i8>::from_triplets(1, 2, &[(0, 0, 100), (0, 1, 100)]);
        let b = CsrMatrix::<i8>::from_triplets(2, 1, &[(0, 0, 1), (1, 0, 1)]);

        assert!(matches!(
            try_spgemm_hash_checked(&a, &b),
            Err(SpGemmError::ArithmeticOverflow {
                operation: ArithmeticOperation::Add,
                row: 0,
                inner: 1,
                column: 0,
            })
        ));
    }

    #[test]
    fn checked_sparse_and_dense_kernels_match_exact_result() {
        let a = CsrMatrix::<i32>::from_triplets(1, 2, &[(0, 0, 2), (0, 1, 3)]);
        let b = CsrMatrix::<i32>::from_triplets(2, 1, &[(0, 0, 5), (1, 0, 7)]);

        let (sparse, stats) = try_spgemm_hash_checked(&a, &b).unwrap();
        let dense = try_dense_matmul_checked(&a.to_dense(), &b.to_dense()).unwrap();
        assert_eq!(sparse.values, vec![31]);
        assert_eq!(dense.data, vec![31]);
        assert_eq!(stats.candidate_products, 2);
    }

    #[test]
    fn output_budget_stops_direct_and_checked_kernels() {
        let identity = CsrMatrix::from_triplets(2, 2, &[(0, 0, 1_i64), (1, 1, 1)]);
        let options = SpGemmOptions {
            max_output_nnz: Some(1),
        };
        assert!(matches!(
            try_spgemm_hash_with_options(&identity, &identity, options),
            Err(SpGemmError::OutputNnzLimitExceeded {
                limit: 1,
                attempted: 2
            })
        ));
        assert!(matches!(
            try_spgemm_hash_checked_with_options(&identity, &identity, options),
            Err(SpGemmError::OutputNnzLimitExceeded { .. })
        ));
    }

    #[test]
    fn wider_accumulator_handles_products_outside_input_type() {
        let matrix = CsrMatrix::from_triplets(1, 1, &[(0, 0, i64::MAX)]);
        let multiplier = CsrMatrix::from_triplets(1, 1, &[(0, 0, 2_i64)]);
        let (product, _) = try_spgemm_checked_with_accumulator::<i64, i128, _, _>(
            &matrix,
            &multiplier,
            SpGemmOptions::default(),
        )
        .unwrap();
        assert_eq!(product.values, vec![i128::from(i64::MAX) * 2]);
    }

    #[test]
    fn custom_boolean_semiring_computes_structural_reachability() {
        #[derive(Clone, Copy)]
        struct Boolean;

        impl Semiring<bool> for Boolean {
            fn zero(&self) -> bool {
                false
            }
            fn add(&self, left: bool, right: bool) -> bool {
                left || right
            }
            fn multiply(&self, left: bool, right: bool) -> bool {
                left && right
            }
            fn is_zero(&self, value: bool) -> bool {
                !value
            }
        }

        let left = CsrMatrix {
            rows: 1,
            cols: 2,
            row_ptr: vec![0, 1],
            col_idx: vec![0],
            values: vec![true],
        };
        let right = CsrMatrix {
            rows: 2,
            cols: 2,
            row_ptr: vec![0, 1, 2],
            col_idx: vec![1, 0],
            values: vec![true, true],
        };
        let (product, _) =
            try_spgemm_semiring(&left, &right, Boolean, SpGemmOptions::default()).unwrap();
        assert_eq!(product.col_idx, vec![1]);
        assert_eq!(product.values, vec![true]);
    }
}