fsci-conformance 0.3.0

Differential conformance testing harness for FrankenSciPy
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
#![forbid(unsafe_code)]
//! Live scipy.sparse parity for fsci_sparse basic ops:
//! sparse_add, sparse_scale, sparse_transpose, sparse_nnz,
//! sparse_is_symmetric.
//!
//! Resolves [frankenscipy-wf3yt]. All deterministic; 1e-12 abs.

use std::collections::{BTreeMap, HashMap};
use std::fs;
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use std::time::{Instant, SystemTime, UNIX_EPOCH};

use fsci_conformance::{ArmCounts, CompareLedger};
use fsci_sparse::{
    CooMatrix, CsrMatrix, FormatConvertible, Shape2D, sparse_add, sparse_is_symmetric, sparse_nnz,
    sparse_scale, sparse_transpose,
};
use serde::{Deserialize, Serialize};

const PACKET_ID: &str = "FSCI-P2C-007";
const ABS_TOL: f64 = 1.0e-12;
const REQUIRE_SCIPY_ENV: &str = "FSCI_REQUIRE_SCIPY_ORACLE";

#[derive(Debug, Clone, Serialize)]
struct Case {
    case_id: String,
    op: String, // "add" | "scale" | "transpose" | "nnz" | "is_sym"
    a_rows: usize,
    a_cols: usize,
    a_triplets: Vec<(usize, usize, f64)>,
    b_rows: usize,
    b_cols: usize,
    b_triplets: Vec<(usize, usize, f64)>,
    alpha: f64,
}

#[derive(Debug, Clone, Serialize)]
struct OracleQuery {
    points: Vec<Case>,
}

#[derive(Debug, Clone, Deserialize)]
struct PointArm {
    case_id: String,
    /// dense flatten for add/scale/transpose
    dense: Option<Vec<f64>>,
    #[allow(dead_code)]
    out_rows: Option<usize>,
    #[allow(dead_code)]
    out_cols: Option<usize>,
    /// scalar count for nnz
    nnz: Option<usize>,
    /// boolean for is_sym
    is_sym: Option<bool>,
}

#[derive(Debug, Clone, Deserialize)]
struct OracleResult {
    points: Vec<PointArm>,
}

#[derive(Debug, Clone, Serialize)]
struct CaseDiff {
    case_id: String,
    op: String,
    abs_diff: f64,
    pass: bool,
}

#[derive(Debug, Clone, Serialize)]
struct DiffLog {
    test_id: String,
    category: String,
    case_count: usize,
    compared: BTreeMap<String, ArmCounts>,
    max_abs_diff: f64,
    pass: bool,
    timestamp_ms: u128,
    duration_ns: u128,
    cases: Vec<CaseDiff>,
}

fn output_dir() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(format!("fixtures/artifacts/{PACKET_ID}/diff"))
}

fn ensure_output_dir() {
    fs::create_dir_all(output_dir()).expect("create sparse_basic diff dir");
}

fn timestamp_ms() -> u128 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_millis())
}

fn emit_log(log: &DiffLog) {
    ensure_output_dir();
    let path = output_dir().join(format!("{}.json", log.test_id));
    let json = serde_json::to_string_pretty(log).expect("serialize log");
    fs::write(path, json).expect("write log");
}

fn csr_to_dense(c: &CsrMatrix) -> Vec<f64> {
    let s = c.shape();
    let mut out = vec![0.0_f64; s.rows * s.cols];
    let indptr = c.indptr();
    let indices = c.indices();
    let data = c.data();
    for r in 0..s.rows {
        let start = indptr[r];
        let end = indptr[r + 1];
        for idx in start..end {
            out[r * s.cols + indices[idx]] += data[idx];
        }
    }
    out
}

fn build_csr(rows: usize, cols: usize, trips: &[(usize, usize, f64)]) -> Option<CsrMatrix> {
    let mut data = Vec::new();
    let mut rs = Vec::new();
    let mut cs = Vec::new();
    for &(r, c, v) in trips {
        data.push(v);
        rs.push(r);
        cs.push(c);
    }
    let coo = CooMatrix::from_triplets(Shape2D::new(rows, cols), data, rs, cs, true).ok()?;
    coo.to_csr().ok()
}

fn generate_query() -> OracleQuery {
    let mut points = Vec::new();

    let a_3x3 = vec![
        (0, 0, 2.0_f64),
        (0, 2, -1.0),
        (1, 1, 3.0),
        (2, 0, 1.0),
        (2, 2, 4.0),
    ];
    let b_3x3 = vec![(0, 1, 1.0_f64), (1, 0, 0.5), (1, 2, -0.3), (2, 1, 2.0)];
    let a_5x4 = vec![
        (0, 0, 1.0_f64),
        (0, 2, 2.0),
        (1, 1, 3.0),
        (1, 3, -1.0),
        (2, 2, 4.0),
        (3, 0, 0.5),
        (4, 3, 1.5),
    ];
    let b_5x4 = vec![
        (0, 1, -0.5_f64),
        (1, 0, 0.7),
        (2, 3, 2.5),
        (3, 3, 1.0),
        (4, 0, 0.3),
    ];
    // symmetric
    let sym_3 = vec![
        (0, 0, 2.0_f64),
        (0, 1, 1.0),
        (0, 2, -0.5),
        (1, 0, 1.0),
        (1, 1, 3.0),
        (1, 2, 0.7),
        (2, 0, -0.5),
        (2, 1, 0.7),
        (2, 2, 4.0),
    ];
    // not symmetric
    let asym_3 = vec![(0, 1, 1.0_f64), (1, 0, -1.0), (1, 2, 2.0)];

    // sparse_add
    points.push(Case {
        case_id: "add_3x3".into(),
        op: "add".into(),
        a_rows: 3,
        a_cols: 3,
        a_triplets: a_3x3.clone(),
        b_rows: 3,
        b_cols: 3,
        b_triplets: b_3x3.clone(),
        alpha: 0.0,
    });
    points.push(Case {
        case_id: "add_5x4".into(),
        op: "add".into(),
        a_rows: 5,
        a_cols: 4,
        a_triplets: a_5x4.clone(),
        b_rows: 5,
        b_cols: 4,
        b_triplets: b_5x4.clone(),
        alpha: 0.0,
    });

    // sparse_scale
    for &alpha in &[0.0_f64, 1.0, -1.0, 2.5, 0.5] {
        points.push(Case {
            case_id: format!("scale_3x3_a{alpha}"),
            op: "scale".into(),
            a_rows: 3,
            a_cols: 3,
            a_triplets: a_3x3.clone(),
            b_rows: 0,
            b_cols: 0,
            b_triplets: vec![],
            alpha,
        });
    }

    // sparse_transpose
    points.push(Case {
        case_id: "transpose_3x3".into(),
        op: "transpose".into(),
        a_rows: 3,
        a_cols: 3,
        a_triplets: a_3x3.clone(),
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });
    points.push(Case {
        case_id: "transpose_5x4".into(),
        op: "transpose".into(),
        a_rows: 5,
        a_cols: 4,
        a_triplets: a_5x4.clone(),
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });

    // sparse_nnz
    points.push(Case {
        case_id: "nnz_3x3".into(),
        op: "nnz".into(),
        a_rows: 3,
        a_cols: 3,
        a_triplets: a_3x3.clone(),
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });
    points.push(Case {
        case_id: "nnz_5x4".into(),
        op: "nnz".into(),
        a_rows: 5,
        a_cols: 4,
        a_triplets: a_5x4.clone(),
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });
    points.push(Case {
        case_id: "nnz_explicit_zero_2x2".into(),
        op: "nnz".into(),
        a_rows: 2,
        a_cols: 2,
        a_triplets: vec![(0, 0, 0.0), (1, 1, 2.0)],
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });

    // is_symmetric
    points.push(Case {
        case_id: "is_sym_yes".into(),
        op: "is_sym".into(),
        a_rows: 3,
        a_cols: 3,
        a_triplets: sym_3,
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });
    points.push(Case {
        case_id: "is_sym_no".into(),
        op: "is_sym".into(),
        a_rows: 3,
        a_cols: 3,
        a_triplets: asym_3,
        b_rows: 0,
        b_cols: 0,
        b_triplets: vec![],
        alpha: 0.0,
    });

    OracleQuery { points }
}

fn scipy_oracle_or_skip(query: &OracleQuery) -> Option<OracleResult> {
    let script = r#"
import json
import math
import sys
import numpy as np
from scipy.sparse import csr_matrix

def build(rows, cols, trips):
    if not trips:
        return csr_matrix((rows, cols))
    rs = [int(t[0]) for t in trips]
    cs = [int(t[1]) for t in trips]
    vs = [float(t[2]) for t in trips]
    return csr_matrix((vs, (rs, cs)), shape=(rows, cols)).astype(float)

q = json.load(sys.stdin)
points = []
for case in q["points"]:
    cid = case["case_id"]; op = case["op"]
    a_rows = int(case["a_rows"]); a_cols = int(case["a_cols"])
    try:
        A = build(a_rows, a_cols, case["a_triplets"])
        if op == "add":
            B = build(int(case["b_rows"]), int(case["b_cols"]), case["b_triplets"])
            R = (A + B)
            D = np.asarray(R.todense())
            flat = [float(v) for v in D.flatten().tolist()]
            points.append({"case_id": cid, "dense": flat, "out_rows": int(D.shape[0]), "out_cols": int(D.shape[1]),
                           "nnz": None, "is_sym": None})
        elif op == "scale":
            alpha = float(case["alpha"])
            R = A.multiply(alpha)
            D = np.asarray(R.todense())
            flat = [float(v) for v in D.flatten().tolist()]
            points.append({"case_id": cid, "dense": flat, "out_rows": int(D.shape[0]), "out_cols": int(D.shape[1]),
                           "nnz": None, "is_sym": None})
        elif op == "transpose":
            R = A.T
            D = np.asarray(R.todense())
            flat = [float(v) for v in D.flatten().tolist()]
            points.append({"case_id": cid, "dense": flat, "out_rows": int(D.shape[0]), "out_cols": int(D.shape[1]),
                           "nnz": None, "is_sym": None})
        elif op == "nnz":
            n = int(A.nnz)
            points.append({"case_id": cid, "dense": None, "out_rows": None, "out_cols": None, "nnz": n, "is_sym": None})
        elif op == "is_sym":
            D = np.asarray(A.todense())
            sym = bool(np.allclose(D, D.T, atol=1e-12))
            points.append({"case_id": cid, "dense": None, "out_rows": None, "out_cols": None, "nnz": None, "is_sym": sym})
        else:
            points.append({"case_id": cid, "dense": None, "out_rows": None, "out_cols": None, "nnz": None, "is_sym": None})
    except Exception as e:
        sys.stderr.write(f"oracle {cid}: {e}\n")
        points.append({"case_id": cid, "dense": None, "out_rows": None, "out_cols": None, "nnz": None, "is_sym": None})
print(json.dumps({"points": points}))
"#;
    let query_json = serde_json::to_string(query).expect("serialize query");
    let mut child = match fsci_conformance::scipy_oracle_command()
        .arg("-c")
        .arg(script)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            assert!(
                std::env::var(REQUIRE_SCIPY_ENV).is_err(),
                "failed to spawn python3 for sparse_basic oracle: {e}"
            );
            eprintln!("skipping sparse_basic oracle: python3 not available ({e})");
            return None;
        }
    };
    {
        let stdin = child.stdin.as_mut().expect("open oracle stdin");
        if let Err(err) = stdin.write_all(query_json.as_bytes()) {
            let output = child.wait_with_output().expect("wait for failed oracle");
            let stderr = String::from_utf8_lossy(&output.stderr);
            assert!(
                std::env::var(REQUIRE_SCIPY_ENV).is_err(),
                "sparse_basic oracle stdin write failed: {err}; stderr: {stderr}"
            );
            eprintln!("skipping sparse_basic oracle: stdin write failed ({err})\n{stderr}");
            return None;
        }
    }
    let output = child
        .wait_with_output()
        .expect("wait for sparse_basic oracle");
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert!(
            std::env::var(REQUIRE_SCIPY_ENV).is_err(),
            "sparse_basic oracle failed: {stderr}"
        );
        eprintln!("skipping sparse_basic oracle: scipy not available\n{stderr}");
        return None;
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    Some(serde_json::from_str(&stdout).expect("parse sparse_basic oracle JSON"))
}

#[test]
fn diff_sparse_basic_ops() {
    let query = generate_query();
    let Some(oracle) = scipy_oracle_or_skip(&query) else {
        return;
    };

    let pmap: HashMap<String, PointArm> = oracle
        .points
        .into_iter()
        .map(|d| (d.case_id.clone(), d))
        .collect();

    let start = Instant::now();
    let mut diffs = Vec::new();
    let mut max_overall = 0.0_f64;
    let ops = ["add", "scale", "transpose", "nnz", "is_sym"];
    let mut ledger = CompareLedger::new("diff_sparse_basic_ops", &ops);

    for case in &query.points {
        let scipy_arm = pmap.get(&case.case_id);
        let csr_a = build_csr(case.a_rows, case.a_cols, &case.a_triplets);
        let abs_d = match case.op.as_str() {
            "add" => {
                let fsci_dense = csr_a.as_ref().and_then(|a| {
                    let csr_b = build_csr(case.b_rows, case.b_cols, &case.b_triplets)?;
                    Some(csr_to_dense(&sparse_add(a, &csr_b)))
                });
                let Some((expected, d)) = ledger.slices(
                    "add",
                    &case.case_id,
                    scipy_arm.and_then(|a| a.dense.as_deref()),
                    fsci_dense.as_deref(),
                ) else {
                    continue;
                };
                d.iter()
                    .zip(expected.iter())
                    .map(|(a, b)| (a - b).abs())
                    .fold(0.0_f64, f64::max)
            }
            "scale" => {
                let fsci_dense = csr_a
                    .as_ref()
                    .map(|a| csr_to_dense(&sparse_scale(a, case.alpha)));
                let Some((expected, d)) = ledger.slices(
                    "scale",
                    &case.case_id,
                    scipy_arm.and_then(|a| a.dense.as_deref()),
                    fsci_dense.as_deref(),
                ) else {
                    continue;
                };
                d.iter()
                    .zip(expected.iter())
                    .map(|(a, b)| (a - b).abs())
                    .fold(0.0_f64, f64::max)
            }
            "transpose" => {
                let fsci_dense = csr_a.as_ref().map(|a| csr_to_dense(&sparse_transpose(a)));
                let Some((expected, d)) = ledger.slices(
                    "transpose",
                    &case.case_id,
                    scipy_arm.and_then(|a| a.dense.as_deref()),
                    fsci_dense.as_deref(),
                ) else {
                    continue;
                };
                d.iter()
                    .zip(expected.iter())
                    .map(|(a, b)| (a - b).abs())
                    .fold(0.0_f64, f64::max)
            }
            "nnz" => {
                let Some((expected, actual)) = ledger.both(
                    "nnz",
                    &case.case_id,
                    scipy_arm.and_then(|a| a.nnz),
                    csr_a.as_ref().map(sparse_nnz),
                ) else {
                    continue;
                };
                if actual == expected {
                    0.0
                } else {
                    (actual as i64 - expected as i64).abs() as f64
                }
            }
            "is_sym" => {
                let Some((expected, actual)) = ledger.both(
                    "is_sym",
                    &case.case_id,
                    scipy_arm.and_then(|a| a.is_sym),
                    csr_a.as_ref().map(|a| sparse_is_symmetric(a, 1e-12)),
                ) else {
                    continue;
                };
                if actual == expected { 0.0 } else { 1.0 }
            }
            other => panic!("diff_sparse_basic_ops: unhandled op `{other}`"),
        };
        max_overall = max_overall.max(abs_d);
        ledger.compared(&case.op, &case.case_id, abs_d <= ABS_TOL);
        diffs.push(CaseDiff {
            case_id: case.case_id.clone(),
            op: case.op.clone(),
            abs_diff: abs_d,
            pass: abs_d <= ABS_TOL,
        });
    }

    let all_pass = diffs.iter().all(|d| d.pass);

    let log = DiffLog {
        test_id: "diff_sparse_basic_ops".into(),
        category: "fsci_sparse::{add, scale, transpose, nnz, is_symmetric} vs scipy.sparse".into(),
        case_count: diffs.len(),
        compared: ledger.counts().clone(),
        max_abs_diff: max_overall,
        pass: all_pass,
        timestamp_ms: timestamp_ms(),
        duration_ns: start.elapsed().as_nanos(),
        cases: diffs.clone(),
    };
    emit_log(&log);

    for d in &diffs {
        if !d.pass {
            eprintln!("{} mismatch: {} abs_diff={}", d.op, d.case_id, d.abs_diff);
        }
    }

    assert!(
        all_pass,
        "sparse_basic_ops conformance failed: {} cases, max_diff={}",
        diffs.len(),
        max_overall
    );
    ledger.finish(
        ops.iter()
            .map(|op| query.points.iter().filter(|c| c.op == *op).count())
            .min()
            .unwrap_or(0),
    );
}