tensorlogic-quantrs-hooks 0.1.1

Probabilistic graphical model and message-passing interoperability for QuantRS2
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
//! Benchmarks for inference algorithms comparison
//!
//! This benchmark suite compares the performance of different inference methods:
//! - Variable Elimination (exact)
//! - Junction Tree (exact)
//! - Sum-Product BP (exact for trees, approximate for loopy graphs)
//! - Mean-Field VI (approximate)
//! - Bethe Approximation (approximate)
//! - Tree-Reweighted BP (approximate with bounds)
//! - Expectation Propagation (approximate)
//! - Gibbs Sampling (MCMC)

use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion, Throughput};
use scirs2_core::ndarray::Array;
use std::hint::black_box;
use tensorlogic_quantrs_hooks::{
    BetheApproximation, ExpectationPropagation, Factor, FactorGraph, GibbsSampler, JunctionTree,
    MeanFieldInference, MessagePassingAlgorithm, SumProductAlgorithm, TreeReweightedBP,
    VariableElimination,
};

/// Create a Bayesian Network: Sprinkler example
/// Rain -> Sprinkler -> Wet Grass <- Rain
fn create_sprinkler_network() -> FactorGraph {
    let mut graph = FactorGraph::new();

    // Variables
    graph.add_variable_with_card("Rain".to_string(), "Weather".to_string(), 2);
    graph.add_variable_with_card("Sprinkler".to_string(), "Device".to_string(), 2);
    graph.add_variable_with_card("WetGrass".to_string(), "State".to_string(), 2);

    // P(Rain)
    let p_rain = Factor::new(
        "P(Rain)".to_string(),
        vec!["Rain".to_string()],
        Array::from_shape_vec(vec![2], vec![0.8, 0.2])
            .expect("create_sprinkler_network: Failed to create P(Rain) array")
            .into_dyn(),
    )
    .expect("create_sprinkler_network: Failed to create P(Rain) factor");
    graph
        .add_factor(p_rain)
        .expect("create_sprinkler_network: Failed to add P(Rain)");

    // P(Sprinkler | Rain)
    let p_sprinkler = Factor::new(
        "P(Sprinkler|Rain)".to_string(),
        vec!["Rain".to_string(), "Sprinkler".to_string()],
        Array::from_shape_vec(vec![2, 2], vec![0.6, 0.4, 0.99, 0.01])
            .expect("create_sprinkler_network: Failed to create P(Sprinkler|Rain) array")
            .into_dyn(),
    )
    .expect("create_sprinkler_network: Failed to create P(Sprinkler|Rain) factor");
    graph
        .add_factor(p_sprinkler)
        .expect("create_sprinkler_network: Failed to add P(Sprinkler|Rain)");

    // P(WetGrass | Sprinkler, Rain)
    let p_wet = Factor::new(
        "P(WetGrass|Sprinkler,Rain)".to_string(),
        vec![
            "Sprinkler".to_string(),
            "Rain".to_string(),
            "WetGrass".to_string(),
        ],
        Array::from_shape_vec(
            vec![2, 2, 2],
            vec![1.0, 0.0, 0.2, 0.8, 0.1, 0.9, 0.01, 0.99],
        )
        .expect("create_sprinkler_network: Failed to create P(WetGrass|...) array")
        .into_dyn(),
    )
    .expect("create_sprinkler_network: Failed to create P(WetGrass|...) factor");
    graph
        .add_factor(p_wet)
        .expect("create_sprinkler_network: Failed to add P(WetGrass|...)");

    graph
}

/// Create a chain MRF for benchmarking
fn create_chain_mrf(length: usize, card: usize) -> FactorGraph {
    let mut graph = FactorGraph::new();

    // Add variables
    for i in 0..length {
        graph.add_variable_with_card(format!("X_{}", i), "Domain".to_string(), card);
    }

    // Add pairwise potentials
    let size = card * card;
    let values: Vec<f64> = (0..size).map(|i| (i as f64 + 1.0) / size as f64).collect();
    let shape = vec![card, card];

    for i in 0..(length - 1) {
        let array = Array::from_shape_vec(shape.clone(), values.clone())
            .expect("create_chain_mrf: Failed to create factor array")
            .into_dyn();
        let factor = Factor::new(
            format!("psi_{}_{}", i, i + 1),
            vec![format!("X_{}", i), format!("X_{}", i + 1)],
            array,
        )
        .expect("create_chain_mrf: Failed to create factor");
        graph
            .add_factor(factor)
            .expect("create_chain_mrf: Failed to add factor");
    }

    graph
}

/// Create a grid MRF
fn create_grid_mrf(rows: usize, cols: usize, card: usize) -> FactorGraph {
    let mut graph = FactorGraph::new();

    // Add variables
    for i in 0..rows {
        for j in 0..cols {
            graph.add_variable_with_card(format!("X_{}_{}", i, j), "Pixel".to_string(), card);
        }
    }

    // Add pairwise factors
    let size = card * card;
    let values: Vec<f64> = (0..size).map(|i| (i as f64 + 1.0) / size as f64).collect();
    let shape = vec![card, card];

    // Horizontal edges
    for i in 0..rows {
        for j in 0..(cols - 1) {
            let array = Array::from_shape_vec(shape.clone(), values.clone())
                .expect("create_grid_mrf: Failed to create horizontal edge array")
                .into_dyn();
            let factor = Factor::new(
                format!("h_{}_{}", i, j),
                vec![format!("X_{}_{}", i, j), format!("X_{}_{}", i, j + 1)],
                array,
            )
            .expect("create_grid_mrf: Failed to create horizontal edge factor");
            graph
                .add_factor(factor)
                .expect("create_grid_mrf: Failed to add horizontal edge factor");
        }
    }

    // Vertical edges
    for i in 0..(rows - 1) {
        for j in 0..cols {
            let array = Array::from_shape_vec(shape.clone(), values.clone())
                .expect("create_grid_mrf: Failed to create vertical edge array")
                .into_dyn();
            let factor = Factor::new(
                format!("v_{}_{}", i, j),
                vec![format!("X_{}_{}", i, j), format!("X_{}_{}", i + 1, j)],
                array,
            )
            .expect("create_grid_mrf: Failed to create vertical edge factor");
            graph
                .add_factor(factor)
                .expect("create_grid_mrf: Failed to add vertical edge factor");
        }
    }

    graph
}

/// Benchmark variable elimination
fn bench_variable_elimination(c: &mut Criterion) {
    let mut group = c.benchmark_group("variable_elimination");

    let graph = create_sprinkler_network();

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            let ve = VariableElimination::new();
            black_box(
                ve.marginalize(&graph, "WetGrass")
                    .expect("VE sprinkler_network marginalize failed"),
            );
        });
    });

    // Chain MRF
    for length in [5, 10, 15] {
        let chain = create_chain_mrf(length, 2);

        group.throughput(Throughput::Elements(length as u64));
        group.bench_with_input(BenchmarkId::new("chain_length", length), &chain, |b, g| {
            b.iter(|| {
                let ve = VariableElimination::new();
                black_box(
                    ve.marginalize(g, "X_0")
                        .expect("VE chain_length marginalize failed"),
                );
            });
        });
    }

    group.finish();
}

/// Benchmark junction tree
fn bench_junction_tree(c: &mut Criterion) {
    let mut group = c.benchmark_group("junction_tree");

    let graph = create_sprinkler_network();

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network_build", |b| {
        b.iter(|| {
            black_box(
                JunctionTree::from_factor_graph(&graph).expect("JT sprinkler_network_build failed"),
            );
        });
    });

    group.bench_function("sprinkler_network_calibrate", |b| {
        let mut tree = JunctionTree::from_factor_graph(&graph)
            .expect("JT sprinkler_network_calibrate: from_factor_graph failed");
        b.iter(|| {
            tree.calibrate()
                .expect("JT sprinkler_network_calibrate: calibrate failed");
            black_box(());
        });
    });

    group.bench_function("sprinkler_network_query", |b| {
        let mut tree = JunctionTree::from_factor_graph(&graph)
            .expect("JT sprinkler_network_query: from_factor_graph failed");
        tree.calibrate()
            .expect("JT sprinkler_network_query: calibrate failed");
        b.iter(|| {
            black_box(
                tree.query_marginal("WetGrass")
                    .expect("JT sprinkler_network_query: query_marginal failed"),
            );
        });
    });

    // Chain MRF
    for length in [5, 10, 15] {
        let chain = create_chain_mrf(length, 2);

        group.throughput(Throughput::Elements(length as u64));
        group.bench_with_input(BenchmarkId::new("chain_build", length), &chain, |b, g| {
            b.iter(|| {
                black_box(
                    JunctionTree::from_factor_graph(g)
                        .expect("JT chain_build: from_factor_graph failed"),
                );
            });
        });
    }

    group.finish();
}

/// Benchmark belief propagation
fn bench_belief_propagation(c: &mut Criterion) {
    let mut group = c.benchmark_group("belief_propagation");

    let graph = create_sprinkler_network();
    let algorithm = SumProductAlgorithm::default();

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            black_box(
                algorithm
                    .run(&graph)
                    .expect("BP sprinkler_network run failed"),
            );
        });
    });

    // Chain (tree structure - exact)
    for length in [5, 10, 20] {
        let chain = create_chain_mrf(length, 2);

        group.throughput(Throughput::Elements(length as u64));
        group.bench_with_input(BenchmarkId::new("chain_length", length), &chain, |b, g| {
            b.iter(|| {
                black_box(algorithm.run(g).expect("BP chain_length run failed"));
            });
        });
    }

    // Grid (loopy - approximate)
    for (rows, cols) in [(2, 2), (3, 3), (4, 4)] {
        let grid = create_grid_mrf(rows, cols, 2);
        let loopy_bp = SumProductAlgorithm::new(20, 1e-4, 0.0);

        let num_vars = rows * cols;
        group.throughput(Throughput::Elements(num_vars as u64));
        group.bench_with_input(
            BenchmarkId::new("grid_loopy", format!("{}x{}", rows, cols)),
            &grid,
            |b, g| {
                b.iter(|| {
                    black_box(loopy_bp.run(g).expect("BP grid_loopy run failed"));
                });
            },
        );
    }

    group.finish();
}

/// Benchmark mean-field variational inference
fn bench_mean_field(c: &mut Criterion) {
    let mut group = c.benchmark_group("mean_field");

    let graph = create_sprinkler_network();
    let mf = MeanFieldInference::new(100, 1e-4);

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            black_box(mf.run(&graph).expect("MF sprinkler_network run failed"));
        });
    });

    // Grid MRF
    for (rows, cols) in [(2, 2), (3, 3), (4, 4)] {
        let grid = create_grid_mrf(rows, cols, 2);

        let num_vars = rows * cols;
        group.throughput(Throughput::Elements(num_vars as u64));
        group.bench_with_input(
            BenchmarkId::new("grid_size", format!("{}x{}", rows, cols)),
            &grid,
            |b, g| {
                b.iter(|| {
                    black_box(mf.run(g).expect("MF grid_size run failed"));
                });
            },
        );
    }

    group.finish();
}

/// Benchmark Bethe approximation
fn bench_bethe(c: &mut Criterion) {
    let mut group = c.benchmark_group("bethe_approximation");

    let graph = create_sprinkler_network();
    let bethe = BetheApproximation::new(50, 1e-4, 0.0);

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            black_box(
                bethe
                    .run(&graph)
                    .expect("Bethe sprinkler_network run failed"),
            );
        });
    });

    // Grid MRF
    for (rows, cols) in [(2, 2), (3, 3)] {
        let grid = create_grid_mrf(rows, cols, 2);

        let num_vars = rows * cols;
        group.throughput(Throughput::Elements(num_vars as u64));
        group.bench_with_input(
            BenchmarkId::new("grid_size", format!("{}x{}", rows, cols)),
            &grid,
            |b, g| {
                b.iter(|| {
                    black_box(bethe.run(g).expect("Bethe grid_size run failed"));
                });
            },
        );
    }

    group.finish();
}

/// Benchmark Tree-Reweighted BP
fn bench_trw_bp(c: &mut Criterion) {
    let mut group = c.benchmark_group("trw_bp");

    let graph = create_sprinkler_network();
    let mut trw = TreeReweightedBP::new(50, 1e-4);
    trw.initialize_uniform_weights(&graph);

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            black_box(trw.run(&graph).expect("TRW sprinkler_network run failed"));
        });
    });

    // Grid MRF
    for (rows, cols) in [(2, 2), (3, 3)] {
        let grid = create_grid_mrf(rows, cols, 2);
        let mut trw_grid = TreeReweightedBP::new(20, 1e-4);
        trw_grid.initialize_uniform_weights(&grid);

        let num_vars = rows * cols;
        group.throughput(Throughput::Elements(num_vars as u64));
        group.bench_with_input(
            BenchmarkId::new("grid_size", format!("{}x{}", rows, cols)),
            &grid,
            |b, g| {
                b.iter(|| {
                    black_box(trw_grid.run(g).expect("TRW grid_size run failed"));
                });
            },
        );
    }

    group.finish();
}

/// Benchmark Expectation Propagation
fn bench_expectation_propagation(c: &mut Criterion) {
    let mut group = c.benchmark_group("expectation_propagation");

    let graph = create_sprinkler_network();
    let ep = ExpectationPropagation::new(50, 1e-4, 0.0);

    group.throughput(Throughput::Elements(3));
    group.bench_function("sprinkler_network", |b| {
        b.iter(|| {
            black_box(ep.run(&graph).expect("EP sprinkler_network run failed"));
        });
    });

    // Chain MRF
    for length in [5, 10] {
        let chain = create_chain_mrf(length, 2);

        group.throughput(Throughput::Elements(length as u64));
        group.bench_with_input(BenchmarkId::new("chain_length", length), &chain, |b, g| {
            b.iter(|| {
                black_box(ep.run(g).expect("EP chain_length run failed"));
            });
        });
    }

    group.finish();
}

/// Benchmark Gibbs sampling
fn bench_gibbs_sampling(c: &mut Criterion) {
    let mut group = c.benchmark_group("gibbs_sampling");

    let graph = create_sprinkler_network();

    for num_samples in [100, 500, 1000] {
        let sampler = GibbsSampler::new(50, num_samples, 5);

        group.throughput(Throughput::Elements(num_samples as u64));
        group.bench_with_input(
            BenchmarkId::new("num_samples", num_samples),
            &graph,
            |b, g| {
                b.iter(|| {
                    black_box(sampler.run(g).expect("Gibbs num_samples run failed"));
                });
            },
        );
    }

    group.finish();
}

/// Benchmark algorithm comparison on the same graph
fn bench_algorithm_comparison(c: &mut Criterion) {
    let mut group = c.benchmark_group("algorithm_comparison");

    let graph = create_chain_mrf(8, 2);

    // Variable Elimination
    group.bench_function("ve_chain8", |b| {
        b.iter(|| {
            let ve = VariableElimination::new();
            black_box(
                ve.marginalize(&graph, "X_0")
                    .expect("VE ve_chain8 marginalize failed"),
            );
        });
    });

    // Junction Tree
    group.bench_function("jt_chain8", |b| {
        b.iter(|| {
            let mut tree = JunctionTree::from_factor_graph(&graph)
                .expect("JT jt_chain8: from_factor_graph failed");
            tree.calibrate().expect("JT jt_chain8: calibrate failed");
            black_box(
                tree.query_marginal("X_0")
                    .expect("JT jt_chain8: query_marginal failed"),
            );
        });
    });

    // Sum-Product BP
    group.bench_function("bp_chain8", |b| {
        let bp = SumProductAlgorithm::default();
        b.iter(|| {
            black_box(bp.run(&graph).expect("BP bp_chain8 run failed"));
        });
    });

    // Mean-Field
    group.bench_function("mf_chain8", |b| {
        let mf = MeanFieldInference::new(100, 1e-4);
        b.iter(|| {
            black_box(mf.run(&graph).expect("MF mf_chain8 run failed"));
        });
    });

    // Bethe
    group.bench_function("bethe_chain8", |b| {
        let bethe = BetheApproximation::new(50, 1e-4, 0.0);
        b.iter(|| {
            black_box(bethe.run(&graph).expect("Bethe bethe_chain8 run failed"));
        });
    });

    group.finish();
}

criterion_group!(
    benches,
    bench_variable_elimination,
    bench_junction_tree,
    bench_belief_propagation,
    bench_mean_field,
    bench_bethe,
    bench_trw_bp,
    bench_expectation_propagation,
    bench_gibbs_sampling,
    bench_algorithm_comparison,
);
criterion_main!(benches);