aicad 1.0.0-rc.1

A library to solve Constraint satisfaction problems with Multi-valued decision diagrams and, optionnaly, neural networks
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! The ConsFormer-MDD loss: the weighted model count of each constraint, decomposed into its own
//! exact MDD.
//!
//! For a sample with constraints $c_1, \dots, c_m$ and network probabilities $p$, the loss is
//! $\frac{1}{m}\sum_j -\log(\mathrm{WMC}_{c_j}(p) + \varepsilon)$, where $\mathrm{WMC}_{c_j}$ is the
//! weighted model count of the MDD of $c_j$ with the probabilities of the network on its edges.
//! The loss of a batch is the mean over its samples.
//!
//! The gradient is computed by hand, by a sink-to-root pass over each diagram
//! ([`crate::mdd::wmc`]), and handed to Burn's autodiff with the stop-gradient identity described
//! at [`DecomposedMddLoss::wmc_loss`]. The diagrams depend only on the problems, so they are
//! compiled once, by [`Loss::prepare`], before training.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use std::time::Instant;

use burn::tensor::Tensor;
use burn::tensor::backend::Backend;

use indicatif::{ParallelProgressIterator, ProgressBar, ProgressStyle};
use rayon::prelude::*;

use crate::learning::Loss;
use crate::mdd::arena::{MddCompilationConfig, compile_constraints};
use crate::mdd::wmc::log_wmc_and_gradient;
use crate::mdd::{CompiledConstraint, MddArena};
use crate::modelling::Problem;

use super::utils::{blend_with_current, gumbel_softmax};
use crate::neural::consformer::ConsFormerBatch;

/// Added to a weighted model count before its log, to avoid `ln(0)`.
const WMC_EPS: f64 = 1e-6;

/// `ln(exp(a) + exp(b))` without overflow or underflow; `a` may be `-inf`, `b` must be finite.
fn log_add_exp(a: f64, b: f64) -> f64 {
    let largest = a.max(b);
    largest + ((a - largest).exp() + (b - largest).exp()).ln()
}

/// Builds `constraint`'s per-layer weights from the raw network probabilities, **masking out** every
/// raw domain value that isn't actually in `real_problem`'s (possibly narrowed -- e.g. a Sudoku
/// given, or a masked/destroyed variable) domain for that layer's variable.
fn layer_weights_from_probs(
    constraint: &CompiledConstraint,
    real_problem: &Problem,
    probs_for_sample: &[f32],
    domain_size: usize,
) -> Vec<Vec<f64>> {
    let num_layers = constraint.order.len();
    let mut weights: Vec<Vec<f64>> = Vec::with_capacity(num_layers);
    for layer in 0..num_layers {
        let variable = constraint.decision_at_layer(layer);
        let mut layer_weights = vec![0.0; domain_size];
        for (raw_value, w) in layer_weights.iter_mut().enumerate() {
            if real_problem[variable].in_domain(raw_value as isize) {
                *w = probs_for_sample[variable.0 * domain_size + raw_value] as f64;
            }
        }
        weights.push(layer_weights);
    }
    weights
}

/// One constraint MDD's contribution to a sample's loss and to `∂loss/∂probs_for_sample`, computed
/// by a plain sink-to-root chain-rule pass (`crate::mdd::wmc::wmc_and_gradient`) instead of
/// automatic differentiation.
/// `probs_for_sample` is that sample's flattened `(number_vars, domain_size)` probability slice,
/// indexed by each variable's *raw domain value*, not by `ValueIndex` position.
/// `grad` accumulates `∂(-log(wmc+eps))/∂probs_for_sample` into that same indexing.
fn mdd_loss_and_gradient(
    constraint: &CompiledConstraint,
    real_problem: &Problem,
    probs_for_sample: &[f32],
    domain_size: usize,
    grad: &mut [f32],
) -> f64 {
    let weights = layer_weights_from_probs(constraint, real_problem, probs_for_sample, domain_size);
    let (log_wmc, gradient) = log_wmc_and_gradient(constraint, &weights);
    // `ln(wmc + eps)` and `d(-ln(wmc + eps))/d(weight) = -wmc / (wmc + eps) * d(ln wmc)/d(weight)`,
    // computed from `ln wmc` so that a count below the smallest `f64` does not flatten the loss.
    let log_total = log_add_exp(log_wmc, WMC_EPS.ln());
    let chain = -(log_wmc - log_total).exp();

    for (layer, layer_gradient) in gradient.iter().enumerate() {
        let variable = constraint.decision_at_layer(layer);
        for (raw_value, &g) in layer_gradient.iter().enumerate() {
            // Masked the same way `layer_weights_from_probs` masked the forward weight: a raw
            // value outside `real_problem`'s actual domain has a *constant* (zero) weight,
            // independent of `probs_for_sample` -- so its contribution to d(loss)/d(probs) is
            // genuinely zero, not whatever d(wmc)/d(weight) the shared, unhinted structure
            // reports for that (structurally still-present, but never actually selectable) edge.
            if real_problem[variable].in_domain(raw_value as isize) {
                grad[variable.0 * domain_size + raw_value] += (chain * g) as f32;
            }
        }
    }

    -log_total
}

/// A sample's plain average of `-log(wmc+eps)` over its constraint MDDs, plus
/// `∂(that average)/∂probs` (`mdds` iterated sequentially -- parallelism is across samples, see
/// `mdd_wmc_loss`).
fn sample_loss_and_gradient(
    constraints: &[CompiledConstraint],
    real_problem: &Problem,
    probs_for_sample: &[f32],
    number_vars: usize,
    domain_size: usize,
) -> (f64, Vec<f32>) {
    let mut grad = vec![0.0f32; number_vars * domain_size];
    let mut loss_sum = 0.0;
    for constraint in constraints {
        loss_sum += mdd_loss_and_gradient(
            constraint,
            real_problem,
            probs_for_sample,
            domain_size,
            &mut grad,
        );
    }
    // `.max(1)` so a (degenerate) sample with zero constraints reads back as zero loss instead of
    // `0.0 / 0.0`, matching the previous floor-based behaviour's result in that case.
    let denom = constraints.len().max(1) as f64;
    let loss = loss_sum / denom;
    for g in &mut grad {
        *g /= denom as f32;
    }
    (loss, grad)
}

/// Plain (unweighted) per-constraint mean of `-log(wmc+eps)`, per-sample then per-batch -- see
/// `sample_loss_and_gradient`.
///
/// The loss decomposes each constraint of a problem into its own exact MDD, so it needs those
/// diagrams before it can score anything: [`Loss::prepare`] compiles them for every problem it
/// will be asked about, and keeps them (with the arena they were compiled in) until the next call.
pub struct DecomposedMddLoss {
    /// How the constraint MDDs are compiled. Always exact, whatever width the setting asked for.
    compilation: MddCompilationConfig,
    /// Number of values the network predicts per variable; the MDDs are compiled against it.
    domain_size: usize,
    /// Where the MDDs are compiled, so that constraints of the same shape share their structure.
    arena: MddArena,
    /// The problems compiled by the last `compile`; they keep alive the addresses `compiled` is
    /// keyed by.
    problems: Vec<Arc<Problem>>,
    /// The constraints of each problem, one `CompiledConstraint` per constraint, keyed by the
    /// address of the problem's `Arc`.
    compiled: HashMap<usize, Vec<CompiledConstraint>>,
}

impl DecomposedMddLoss {
    /// A loss for a network predicting `domain_size` values per variable. `compilation` chooses
    /// the variable ordering and the heuristics; its width bound is ignored, since the loss needs
    /// exact diagrams.
    pub fn new(compilation: MddCompilationConfig, domain_size: usize) -> Self {
        Self {
            compilation: MddCompilationConfig {
                max_width: usize::MAX,
                ..compilation
            },
            domain_size,
            arena: MddArena::new(),
            problems: Vec::new(),
            compiled: HashMap::new(),
        }
    }

    /// Compiles the constraints of `problems`, replacing those of the previous call. A problem
    /// given several times (the same `Arc`) is compiled once. Every problem the loss will score,
    /// training and validation alike, must be given.
    ///
    /// Problems are known by their identity: two equal problems held in different `Arc`s are
    /// compiled separately.
    fn compile(&mut self, problems: &[Arc<Problem>]) {
        let mut seen = HashSet::new();
        let unique: Vec<Arc<Problem>> = problems
            .iter()
            .filter(|problem| seen.insert(Self::key(problem)))
            .cloned()
            .collect();

        let progress = ProgressBar::new(unique.len() as u64);
        progress.set_style(
            ProgressStyle::with_template(
                "{msg} [{elapsed_precise}] [{bar:40.cyan/blue}] {pos}/{len} ({eta})",
            )
            .expect("hard-coded progress bar template should always be valid"),
        );
        progress.set_message("Compiling MDDs");

        let start = Instant::now();
        let compiled: Vec<Vec<CompiledConstraint>> = crate::utils::worker_pool().install(|| {
            unique
                .par_iter()
                .progress_with(progress.clone())
                .map(|problem| {
                    compile_constraints(problem, &self.arena, &self.compilation, self.domain_size)
                })
                .collect()
        });
        progress.finish_and_clear();
        crate::diagnostics::data_log!(
            "mdd_compilation",
            num_problems = unique.len(),
            elapsed_s = start.elapsed().as_secs_f64(),
        );

        self.compiled = unique.iter().map(Self::key).zip(compiled).collect();
        self.problems = unique;
    }

    /// Identifies a problem by the address of its `Arc`.
    fn key(problem: &Arc<Problem>) -> usize {
        Arc::as_ptr(problem) as usize
    }

    /// The compiled constraints of `problem`.
    ///
    /// # Panics
    ///
    /// If `problem` is not (the same `Arc` as) one of the problems of the last `compile`.
    fn compiled_for(&self, problem: &Arc<Problem>) -> &[CompiledConstraint] {
        match self.compiled.get(&Self::key(problem)) {
            Some(constraints) => constraints,
            None => panic!(
                "DecomposedMddLoss was given a problem it has not compiled: `prepare` must be \
                 called with every training and validation problem"
            ),
        }
    }
}

impl DecomposedMddLoss {
    /// Computes the MDD-WMC loss and its exact gradient wrt `probs` by hand (see
    /// `mdd_loss_and_gradient`), then hands that gradient to Burn's autodiff via the standard
    /// stop-gradient identity `value + stop_gradient(desired_value - value)`, here as
    /// `grad_tensor * (probs - probs.detach())`: its *value* is always zero (`probs.clone()` and
    /// `probs.detach()` hold the same numbers), so the returned tensor's value is exactly
    /// `loss_value`, but its derivative wrt `probs` is exactly `grad_tensor`, since `grad_tensor` and
    /// `probs.detach()` are constants as far as autodiff is concerned. This keeps the whole hand-rolled
    /// backward pass outside Burn's graph -- nothing per-layer gets recorded or replayed -- while
    /// still letting `loss.backward()` reach every parameter upstream of `probs` normally.
    fn wmc_loss<B: Backend>(
        &self,
        probs: Tensor<B, 3>,
        batch: &ConsFormerBatch<B>,
    ) -> Tensor<B, 1> {
        let device = probs.device();
        let [batch_size, number_vars, domain_size] = probs.dims();

        let probs_data: Vec<f32> = probs
            .clone()
            .into_data()
            .to_vec::<f32>()
            .expect("probs should convert to f32");

        let compiled: Vec<&[CompiledConstraint]> = batch
            .problems
            .iter()
            .map(|problem| self.compiled_for(problem))
            .collect();

        let results: Vec<(f64, Vec<f32>)> = crate::utils::worker_pool().install(|| {
            compiled
                .par_iter()
                .zip(batch.problems.par_iter())
                .enumerate()
                .map(|(i, (constraints, real_problem))| {
                    let start = i * number_vars * domain_size;
                    let sample_probs = &probs_data[start..start + number_vars * domain_size];
                    sample_loss_and_gradient(
                        constraints,
                        real_problem,
                        sample_probs,
                        number_vars,
                        domain_size,
                    )
                })
                .collect()
        });

        let loss_value: f64 = results.iter().map(|(loss, _)| loss).sum::<f64>() / batch_size as f64;

        let mut grad_data = vec![0.0f32; batch_size * number_vars * domain_size];
        for (i, (_, grad)) in results.iter().enumerate() {
            let start = i * number_vars * domain_size;
            for (j, &g) in grad.iter().enumerate() {
                grad_data[start + j] = g / batch_size as f32;
            }
        }

        let grad_tensor: Tensor<B, 3> = Tensor::<B, 1>::from_data(grad_data.as_slice(), &device)
            .reshape([batch_size, number_vars, domain_size]);
        let loss_tensor: Tensor<B, 1> = Tensor::from_data([loss_value as f32].as_slice(), &device);

        (grad_tensor * (probs.clone() - probs.detach()))
            .sum()
            .reshape([1])
            + loss_tensor
    }
}

impl<B: Backend> Loss<B, ConsFormerBatch<B>> for DecomposedMddLoss {
    fn prepare(&mut self, problems: &[Arc<Problem>]) {
        self.compile(problems);
    }

    fn loss(&self, logits: Tensor<B, 3>, batch: &ConsFormerBatch<B>) -> Tensor<B, 1> {
        let probs = gumbel_softmax(logits);
        let probs = blend_with_current(probs, batch.assignments.clone(), batch.var_masks.clone());
        self.wmc_loss(probs, batch)
    }
}

#[cfg(test)]
mod compile_tests {
    use super::*;
    use crate::constraints::{all_different, among, not_equals, sum};

    /// `real_domain_size` is what `problem[variable].domain_size()` used to be before the arena
    /// split -- since the group's structure is now compiled against the full nominal
    /// `domain_size` regardless of any real narrowing, this builds the same masked weights
    /// `crate::learning::consformer::loss::layer_weights_from_probs` does (every real variable
    /// here has an unnarrowed `0..domain_size` domain, so the mask is a no-op, but this keeps the
    /// test helper honest about what production code actually builds).
    fn brute_force_wmc(
        constraint: &CompiledConstraint,
        real_problem: &Problem,
        probs: &[f64],
        domain_size: usize,
    ) -> f64 {
        let num_layers = constraint.order.len();
        let mut weights = Vec::with_capacity(num_layers);
        for layer in 0..num_layers {
            let variable = constraint.decision_at_layer(layer);
            let mut layer_weights = vec![0.0; domain_size];
            for (raw_value, w) in layer_weights.iter_mut().enumerate() {
                if real_problem[variable].in_domain(raw_value as isize) {
                    *w = probs[variable.0 * domain_size + raw_value];
                }
            }
            weights.push(layer_weights);
        }
        crate::mdd::wmc::wmc(constraint, &weights)
    }

    #[test]
    fn compile_constraints_matches_brute_force_for_not_equals() {
        let mut problem = Problem::default();
        let x = problem.add_variable(vec![0, 1, 2]);
        let y = problem.add_variable(vec![0, 1, 2]);
        not_equals(&mut problem, x, y);
        let problem = Arc::new(problem);

        let domain_size = 3;
        let arena = MddArena::new();
        let mdds = compile_constraints(
            &problem,
            &arena,
            &MddCompilationConfig::default(),
            domain_size,
        );
        assert_eq!(mdds.len(), 1);
        assert_eq!(mdds[0].number_layers() - 1, 2);

        let probs: Vec<f64> = vec![
            0.2, 0.5, 0.3, // x
            0.1, 0.3, 0.6, // y
        ];
        let wmc = brute_force_wmc(&mdds[0], &problem, &probs, domain_size);

        let mut brute = 0.0;
        for xv in 0..domain_size {
            for yv in 0..domain_size {
                if xv != yv {
                    brute += probs[xv] * probs[domain_size + yv];
                }
            }
        }
        assert!((wmc - brute).abs() < 1e-9, "wmc={wmc} brute={brute}");
    }

    #[test]
    fn compile_constraints_matches_brute_force_for_all_different_permutation() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        all_different(&mut problem, vars.clone());
        let problem = Arc::new(problem);

        let domain_size = 3;
        let arena = MddArena::new();
        let mdds = compile_constraints(
            &problem,
            &arena,
            &MddCompilationConfig::default(),
            domain_size,
        );
        assert_eq!(mdds.len(), 1);
        assert_eq!(mdds[0].number_layers() - 1, 3);

        let probs: Vec<f64> = vec![
            0.5, 0.3, 0.2, // var 0
            0.2, 0.2, 0.6, // var 1
            0.1, 0.4, 0.5, // var 2
        ];
        let wmc = brute_force_wmc(&mdds[0], &problem, &probs, domain_size);

        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                for c in 0..domain_size {
                    if a != b && b != c && a != c {
                        brute += probs[a] * probs[domain_size + b] * probs[2 * domain_size + c];
                    }
                }
            }
        }
        assert!((wmc - brute).abs() < 1e-9, "wmc={wmc} brute={brute}");
    }

    #[test]
    fn compile_constraints_matches_brute_force_for_sum() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        sum(&mut problem, vars.clone(), 3);
        let problem = Arc::new(problem);

        let domain_size = 3;
        let arena = MddArena::new();
        let mdds = compile_constraints(
            &problem,
            &arena,
            &MddCompilationConfig::default(),
            domain_size,
        );

        let probs: Vec<f64> = vec![
            0.5, 0.3, 0.2, // var 0
            0.2, 0.2, 0.6, // var 1
            0.1, 0.4, 0.5, // var 2
        ];
        let wmc = brute_force_wmc(&mdds[0], &problem, &probs, domain_size);

        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                for c in 0..domain_size {
                    if a + b + c == 3 {
                        brute += probs[a] * probs[domain_size + b] * probs[2 * domain_size + c];
                    }
                }
            }
        }
        assert!((wmc - brute).abs() < 1e-9, "wmc={wmc} brute={brute}");
    }

    #[test]
    fn compile_constraints_matches_brute_force_for_among() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        among(&mut problem, vars.clone(), vec![1, 2], 1, 2);
        let problem = Arc::new(problem);

        let domain_size = 3;
        let arena = MddArena::new();
        let mdds = compile_constraints(
            &problem,
            &arena,
            &MddCompilationConfig::default(),
            domain_size,
        );

        let probs: Vec<f64> = vec![
            0.5, 0.3, 0.2, // var 0
            0.2, 0.2, 0.6, // var 1
            0.1, 0.4, 0.5, // var 2
        ];
        let wmc = brute_force_wmc(&mdds[0], &problem, &probs, domain_size);

        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                for c in 0..domain_size {
                    let count = [a, b, c].iter().filter(|&&v| v == 1 || v == 2).count();
                    if (1..=2).contains(&count) {
                        brute += probs[a] * probs[domain_size + b] * probs[2 * domain_size + c];
                    }
                }
            }
        }
        assert!((wmc - brute).abs() < 1e-9, "wmc={wmc} brute={brute}");
    }

    #[test]
    fn unsat_constraint_gets_zero_wmc() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1]);
        all_different(&mut problem, vars.clone());
        let problem = Arc::new(problem);

        let domain_size = 2;
        let arena = MddArena::new();
        let mdds = compile_constraints(
            &problem,
            &arena,
            &MddCompilationConfig::default(),
            domain_size,
        );
        let probs: Vec<f64> = vec![0.5, 0.5, 0.5, 0.5, 0.5, 0.5];
        assert_eq!(
            brute_force_wmc(&mdds[0], &problem, &probs, domain_size),
            0.0
        );
    }

    #[test]
    #[should_panic(expected = "out of the nominal")]
    fn compile_constraints_panics_when_domain_size_is_too_small() {
        let mut problem = Problem::default();
        let x = problem.add_variable(vec![0, 1, 2]);
        let y = problem.add_variable(vec![0, 1, 2]);
        not_equals(&mut problem, x, y);
        let problem = Arc::new(problem);

        let arena = MddArena::new();
        compile_constraints(&problem, &arena, &MddCompilationConfig::default(), 2);
    }

    #[test]
    fn compiling_many_problems_matches_compiling_each_alone() {
        let mut problems = Vec::new();
        for domain_max in 0isize..40 {
            let mut problem = Problem::default();
            let domain: Vec<isize> = (0..=(domain_max % 5 + 2)).collect();
            let vars = problem.add_variables(3, domain);
            all_different(&mut problem, vars.clone());
            not_equals(&mut problem, vars[0], vars[1]);
            problems.push(Arc::new(problem));
        }
        let domain_size = 7;

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), domain_size);
        loss_fn.compile(&problems);

        assert_eq!(loss_fn.compiled.len(), problems.len());
        for problem in &problems {
            let expected = compile_constraints(
                problem,
                &MddArena::new(),
                &MddCompilationConfig::default(),
                domain_size,
            );
            let actual = loss_fn.compiled_for(problem);
            assert_eq!(actual.len(), expected.len());
            for (a, e) in actual.iter().zip(expected.iter()) {
                assert_eq!(a.number_layers(), e.number_layers());
                assert_eq!(a.number_nodes(), e.number_nodes());
                assert_eq!(a.number_edges(), e.number_edges());
            }
        }
    }

    #[test]
    fn a_problem_given_twice_is_compiled_once() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        all_different(&mut problem, vars);
        let problem = Arc::new(problem);

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&[Arc::clone(&problem), Arc::clone(&problem)]);
        assert_eq!(loss_fn.compiled.len(), 1);
        assert_eq!(loss_fn.compiled_for(&problem).len(), 1);
    }

    #[test]
    #[should_panic(expected = "has not compiled")]
    fn scoring_a_problem_that_was_not_prepared_panics() {
        let build = || {
            let mut problem = Problem::default();
            let x = problem.add_variable(vec![0, 1, 2]);
            let y = problem.add_variable(vec![0, 1, 2]);
            not_equals(&mut problem, x, y);
            Arc::new(problem)
        };
        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&[build()]);
        // Equal to the compiled problem, but another `Arc`.
        loss_fn.compiled_for(&build());
    }
}

#[cfg(test)]
mod loss_tests {
    use std::sync::Arc;

    use burn::backend::ndarray::{NdArray, NdArrayDevice};
    use burn::data::dataloader::batcher::Batcher;
    use burn::data::dataset::Dataset;

    use crate::constraints::{all_different, not_equals};
    use crate::mdd::MddArena;
    use crate::mdd::arena::MddCompilationConfig;
    use crate::modelling::Problem;

    use burn::tensor::Int;

    use super::*;
    use crate::neural::consformer::{ConsFormerBatcher, ConsFormerDataset};

    /// Every problem is 3 variables, domain `{0,1,2}`, with an `AllDifferent` over all three and
    /// a `NotEquals` over the first two. Generic over the backend so the same builder can be used
    /// both with plain `NdArray` (the WMC/loss correctness tests) and `Autodiff<NdArray>` (the
    /// gradient-flow tests).
    fn two_sample_batch<B: Backend>(
        device: &B::Device,
        mask_fraction: f64,
    ) -> (ConsFormerBatch<B>, DecomposedMddLoss) {
        let mut problems = Vec::new();
        for _ in 0..2 {
            let mut problem = Problem::default();
            let vars = problem.add_variables(3, vec![0, 1, 2]);
            all_different(&mut problem, vars.clone());
            not_equals(&mut problem, vars[0], vars[1]);
            problems.push(Arc::new(problem));
        }

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&problems);
        let dataset = ConsFormerDataset::<B>::new(problems, device);
        let samples: Vec<_> = (0..dataset.len())
            .map(|i| dataset.get(i).unwrap())
            .collect();

        let batcher = ConsFormerBatcher {
            mask_fraction,
            destroy: None,
        };
        (batcher.batch(samples, device), loss_fn)
    }

    fn brute_force_not_equals(probs: &[f64], domain_size: usize) -> f64 {
        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                if a != b {
                    brute += probs[a] * probs[domain_size + b];
                }
            }
        }
        brute
    }

    fn brute_force_all_different_permutation(probs: &[f64], domain_size: usize) -> f64 {
        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                for c in 0..domain_size {
                    if a != b && b != c && a != c {
                        brute += probs[a] * probs[domain_size + b] * probs[2 * domain_size + c];
                    }
                }
            }
        }
        brute
    }

    /// Plain per-constraint mean of `-log(wmc+eps)`, matching `sample_loss_and_gradient`'s (now
    /// unweighted) reduction -- used by the tests below to build an independently-derived expected
    /// value from brute-force/hand-computed `wmc`s.
    fn plain_average(wmcs: &[f64]) -> f64 {
        let loss_sum: f64 = wmcs.iter().map(|&wmc| -(wmc + WMC_EPS).ln()).sum();
        loss_sum / (wmcs.len().max(1) as f64)
    }

    #[test]
    fn sample_loss_and_gradient_matches_brute_force_average() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        all_different(&mut problem, vars.clone());
        not_equals(&mut problem, vars[0], vars[1]);
        let problem = Arc::new(problem);

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&[Arc::clone(&problem)]);
        let mdds = loss_fn.compiled_for(&problem);

        let probs: Vec<f32> = vec![0.2, 0.5, 0.3, 0.1, 0.3, 0.6, 0.4, 0.4, 0.2];
        let (loss, _grad) = sample_loss_and_gradient(mdds, &problem, &probs, 3, 3);

        let probs_f64: Vec<f64> = probs.iter().map(|&v| v as f64).collect();
        let not_equals_wmc = brute_force_not_equals(&probs_f64, 3);
        let all_different_wmc = brute_force_all_different_permutation(&probs_f64, 3);
        let expected = plain_average(&[not_equals_wmc, all_different_wmc]);

        assert!(
            (loss - expected).abs() < 1e-6,
            "got {loss} expected {expected}"
        );
    }

    #[test]
    fn sample_loss_and_gradient_matches_finite_differences() {
        let mut problem = Problem::default();
        let vars = problem.add_variables(3, vec![0, 1, 2]);
        all_different(&mut problem, vars.clone());
        not_equals(&mut problem, vars[0], vars[1]);
        let problem = Arc::new(problem);

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&[Arc::clone(&problem)]);
        let mdds = loss_fn.compiled_for(&problem);

        let probs: Vec<f32> = vec![0.2, 0.5, 0.3, 0.1, 0.3, 0.6, 0.4, 0.4, 0.2];
        let (base_loss, grad) = sample_loss_and_gradient(mdds, &problem, &probs, 3, 3);

        let eps = 1e-4f32;
        for i in 0..probs.len() {
            let mut bumped = probs.clone();
            bumped[i] += eps;
            let (bumped_loss, _) = sample_loss_and_gradient(mdds, &problem, &bumped, 3, 3);
            let finite_diff = (bumped_loss - base_loss) / eps as f64;
            assert!(
                (finite_diff - grad[i] as f64).abs() < 1e-2,
                "index {i}: analytic={} finite_diff={finite_diff}",
                grad[i],
            );
        }
    }

    #[test]
    fn mdd_wmc_loss_averages_per_sample_then_per_batch() {
        let device = NdArrayDevice::default();
        let domain_size = 3;
        let (batch, loss_fn) = two_sample_batch::<NdArray>(&device, 0.0);

        let per_sample_probs: Vec<Vec<f64>> = vec![
            vec![0.2, 0.5, 0.3, 0.1, 0.3, 0.6, 0.4, 0.4, 0.2],
            vec![0.6, 0.3, 0.1, 0.2, 0.2, 0.6, 0.5, 0.25, 0.25],
        ];
        let flat: Vec<f32> = per_sample_probs
            .iter()
            .flatten()
            .map(|&v| v as f32)
            .collect();
        let probs: Tensor<NdArray, 3> =
            Tensor::<NdArray, 1>::from_data(flat.as_slice(), &device).reshape([2, 3, domain_size]);

        let loss = loss_fn.wmc_loss(probs, &batch);
        let loss_value: f32 = loss.into_data().to_vec::<f32>().unwrap()[0];

        let mut expected_per_sample = Vec::new();
        for probs in &per_sample_probs {
            let not_equals_wmc = brute_force_not_equals(probs, domain_size);
            let all_different_wmc = brute_force_all_different_permutation(probs, domain_size);
            expected_per_sample.push(plain_average(&[not_equals_wmc, all_different_wmc]));
        }
        let expected = expected_per_sample.iter().sum::<f64>() / expected_per_sample.len() as f64;

        assert!(
            (loss_value as f64 - expected).abs() < 1e-4,
            "got {loss_value} expected {expected}"
        );
    }

    /// The custom gradient this loss hands to Burn's autodiff (`mdd_loss_and_gradient`'s
    /// sink-to-root chain rule) bypasses Burn's own backward machinery entirely, so this checks it
    /// against finite differences of `mdd_wmc_loss` itself -- computed on a plain, non-autodiff
    /// `NdArray` backend at perturbed `probs` -- rather than against a second differentiation path
    /// through Burn. `mdd_wmc_loss` is deterministic (no `gumbel_softmax` involved -- that's called
    /// only by `Loss::loss`, above this function), so this is an exact check, not just a
    /// finite/non-zero sanity check.
    #[test]
    fn mdd_wmc_loss_gradient_matches_finite_differences_via_autodiff() {
        use burn::backend::Autodiff;

        type ADBackend = Autodiff<NdArray>;
        let ad_device = NdArrayDevice::default();
        let plain_device = NdArrayDevice::default();
        let domain_size = 3;

        let (batch_ad, loss_ad) = two_sample_batch::<ADBackend>(&ad_device, 0.0);
        let (batch_plain, loss_plain) = two_sample_batch::<NdArray>(&plain_device, 0.0);

        let flat: Vec<f32> = vec![
            0.2, 0.5, 0.3, 0.1, 0.3, 0.6, 0.4, 0.4, 0.2, 0.6, 0.3, 0.1, 0.2, 0.2, 0.6, 0.5, 0.25,
            0.25,
        ];

        let probs_ad: Tensor<ADBackend, 3> =
            Tensor::<ADBackend, 1>::from_data(flat.as_slice(), &ad_device)
                .reshape([2, 3, domain_size])
                .require_grad();
        let loss = loss_ad.wmc_loss(probs_ad.clone(), &batch_ad);
        let grads = loss.backward();
        let grad = probs_ad
            .grad(&grads)
            .expect("probs should have a gradient after backward()");
        let grad_values: Vec<f32> = grad.into_data().to_vec::<f32>().unwrap();

        let base_tensor: Tensor<NdArray, 3> =
            Tensor::<NdArray, 1>::from_data(flat.as_slice(), &plain_device).reshape([
                2,
                3,
                domain_size,
            ]);
        let base_loss_tensor = loss_plain.wmc_loss(base_tensor, &batch_plain);
        let base_loss: f64 = base_loss_tensor.into_data().to_vec::<f32>().unwrap()[0] as f64;

        let eps = 1e-4f32;
        for i in 0..flat.len() {
            let mut bumped = flat.clone();
            bumped[i] += eps;
            let bumped_tensor: Tensor<NdArray, 3> =
                Tensor::<NdArray, 1>::from_data(bumped.as_slice(), &plain_device).reshape([
                    2,
                    3,
                    domain_size,
                ]);
            let bumped_loss_tensor = loss_plain.wmc_loss(bumped_tensor, &batch_plain);
            let bumped_loss: f64 =
                bumped_loss_tensor.into_data().to_vec::<f32>().unwrap()[0] as f64;
            let finite_diff = (bumped_loss - base_loss) / eps as f64;
            assert!(
                (finite_diff - grad_values[i] as f64).abs() < 1e-2,
                "index {i}: analytic={} finite_diff={finite_diff}",
                grad_values[i],
            );
        }
    }

    /// End-to-end through the full `Loss::loss` path (`gumbel_softmax` + `blend_with_current` +
    /// `mdd_wmc_loss`): with `logits` requiring grad, `.backward()` should reach `logits` with a
    /// finite, non-all-zero gradient of the expected shape. Unlike the test above, this can't be
    /// checked against an exact finite-difference value -- `gumbel_softmax` draws fresh noise on
    /// every call -- so it's a sanity check that the gradient actually flows end to end, not a
    /// correctness check on the custom gradient math itself (that's covered above).
    #[test]
    fn loss_backpropagates_through_gumbel_and_blend() {
        use burn::backend::Autodiff;
        use burn::tensor::Distribution;

        type ADBackend = Autodiff<NdArray>;

        let device = NdArrayDevice::default();
        let (batch, loss_fn) = two_sample_batch::<ADBackend>(&device, 1.0);

        let logits: Tensor<ADBackend, 3> =
            Tensor::random([2, 3, 3], Distribution::Uniform(-1.0, 1.0), &device).require_grad();

        let loss = loss_fn.loss(logits.clone(), &batch);
        let loss_value: f32 = loss.clone().into_data().to_vec::<f32>().unwrap()[0];
        assert!(
            loss_value.is_finite(),
            "loss should be finite, got {loss_value}"
        );

        let grads = loss.backward();
        let grad = logits
            .grad(&grads)
            .expect("logits should have a gradient after backward()");
        assert_eq!(grad.dims(), [2, 3, 3]);

        let grad_values: Vec<f32> = grad.into_data().to_vec::<f32>().unwrap();
        assert!(
            grad_values.iter().all(|v| v.is_finite()),
            "every gradient entry should be finite"
        );
        assert!(
            grad_values.iter().any(|&v| v != 0.0),
            "gradient should not be identically zero"
        );
    }

    /// A `NotEquals` constraint both of whose variables are pinned (`var_masks` all false) to the
    /// *same* value is unconditionally violated: `wmc = 0` for that MDD regardless of what the
    /// network predicts, so `mdd_loss_and_gradient`'s `-log(wmc+eps)`/`-1/(wmc+eps)` genuinely hit
    /// their `WMC_EPS` floor rather than some comfortably-nonzero value. This checks the loss and
    /// its gradient both stay finite in that regime -- the case `WMC_EPS` exists for.
    #[test]
    fn loss_stays_finite_when_a_pinned_assignment_violates_a_constraint() {
        use burn::backend::Autodiff;

        type ADBackend = Autodiff<NdArray>;
        let device = NdArrayDevice::default();

        let mut problem = Problem::default();
        let x = problem.add_variable(vec![0, 1, 2]);
        let y = problem.add_variable(vec![0, 1, 2]);
        not_equals(&mut problem, x, y);
        let problem = Arc::new(problem);

        let mut loss_fn = DecomposedMddLoss::new(MddCompilationConfig::default(), 3);
        loss_fn.compile(&[Arc::clone(&problem)]);
        let dataset = ConsFormerDataset::<ADBackend>::new(vec![problem], &device);
        let samples: Vec<_> = (0..dataset.len())
            .map(|i| dataset.get(i).unwrap())
            .collect();
        let batcher = ConsFormerBatcher {
            mask_fraction: 0.0,
            destroy: None,
        };
        let batch = batcher.batch(samples, &device);

        // `mask_fraction = 0.0` above means `var_masks` is all-false, so `blend_with_current`
        // pins every variable to `batch.assignments` regardless of `logits` -- setting both
        // assignments to 0 violates `not_equals(x, y)` unconditionally.
        let assignments: Tensor<ADBackend, 2, Int> =
            Tensor::<ADBackend, 1, Int>::from_data([0i64, 0i64].as_slice(), &device)
                .reshape([1, 2]);
        let batch = ConsFormerBatch {
            assignments,
            ..batch
        };

        let logits: Tensor<ADBackend, 3> = Tensor::zeros([1, 2, 3], &device).require_grad();

        let loss = loss_fn.loss(logits.clone(), &batch);
        let loss_value: f32 = loss.clone().into_data().to_vec::<f32>().unwrap()[0];
        assert!(
            loss_value.is_finite(),
            "loss should be finite, got {loss_value}"
        );
        assert!(
            (loss_value as f64 - (-(WMC_EPS).ln())).abs() < 1e-3,
            "an unconditionally-violated constraint should read back as -log(WMC_EPS), got {loss_value}",
        );

        let grads = loss.backward();
        let grad = logits
            .grad(&grads)
            .expect("logits should have a gradient after backward()");
        let grad_values: Vec<f32> = grad.into_data().to_vec::<f32>().unwrap();
        assert!(
            grad_values.iter().all(|v| v.is_finite()),
            "every gradient entry should be finite even when a constraint is unconditionally violated -- got {:?}",
            grad_values,
        );
    }

    /// Direct correctness check for the weight-masking fix `layer_weights_from_probs` needs now
    /// that `constraint.structure` is compiled with no per-instance domain restriction (see
    /// `crate::mdd::arena`'s module doc): a real "given" position (its domain narrowed to a
    /// single value, e.g. a Sudoku clue) must have every *other* raw value's weight forced to
    /// zero, even though the shared, un-hinted `AllDifferent` structure has a real edge for each
    /// of them. Checks both that the masked weight vector itself is a one-hot at the given value,
    /// and that `wmc` over those masked weights exactly matches a brute-force count restricted to
    /// assignments honouring the given -- i.e. sampling/`wmc`/gradient never actually credits an
    /// assignment that uses a masked-out value at the given position.
    #[test]
    fn layer_weights_from_probs_masks_out_a_given_values_forbidden_domain() {
        let domain_size = 4;
        let mut problem = Problem::default();
        let vars = problem.add_variables(4, (0..domain_size as isize).collect());
        all_different(&mut problem, vars.clone());
        // `vars[0]` is a "given": its real domain is narrowed to a single value, but the shared
        // template below is still compiled over the full nominal domain (no hint baked in).
        crate::modelling::equal(&mut problem, vars[0], 2);
        let problem = Arc::new(problem);

        let arena = MddArena::new();
        let constraint = problem
            .iter_constraints()
            .next()
            .expect("problem must have exactly one constraint");
        let constraint = crate::mdd::arena::compile_constraint(
            &arena,
            &problem,
            constraint,
            &crate::mdd::heuristics::OrderingHeuristic::MinDomMaxLinked,
            &crate::mdd::arena::nominal_domain(domain_size),
            usize::MAX,
        );

        // Uniform raw probabilities everywhere -- if masking didn't happen, every position
        // (including the given's 3 forbidden values) would carry equal, nonzero weight.
        let probs_for_sample: Vec<f32> = vec![0.25; 4 * domain_size];
        let weights =
            layer_weights_from_probs(&constraint, &problem, &probs_for_sample, domain_size);

        let given_layer = (0..constraint.order.len())
            .find(|&l| constraint.decision_at_layer(l) == vars[0])
            .expect("vars[0] must be in the compiled constraint's scope");
        assert_eq!(
            weights[given_layer],
            vec![0.0, 0.0, 0.25, 0.0],
            "a given position's weight vector must be zero everywhere but its one allowed value"
        );

        let wmc = crate::mdd::wmc::wmc(&constraint, &weights);

        // Brute force: every permutation of {0,1,2,3} over the 4 variables with vars[0] fixed to
        // 2, each weighted 0.25^4 (uniform raw probability at every position).
        let mut brute = 0.0;
        for a in 0..domain_size {
            for b in 0..domain_size {
                for c in 0..domain_size {
                    let full = [2usize, a, b, c];
                    let vals: std::collections::HashSet<usize> = full.iter().copied().collect();
                    if vals.len() == 4 {
                        brute += 0.25f64.powi(4);
                    }
                }
            }
        }
        assert!(
            (wmc - brute).abs() < 1e-9,
            "wmc={wmc} brute={brute} -- masked wmc must match assignments honouring the given"
        );
    }
    #[test]
    fn log_add_exp_matches_the_direct_sum_and_survives_extremes() {
        assert!((log_add_exp(0.3f64.ln(), 0.2f64.ln()) - 0.5f64.ln()).abs() < 1e-12);
        // A count of exp(-2000) next to the epsilon: the direct sum is just the epsilon.
        assert!((log_add_exp(-2000.0, 1e-6f64.ln()) - 1e-6f64.ln()).abs() < 1e-12);
        assert_eq!(log_add_exp(f64::NEG_INFINITY, 1e-6f64.ln()), 1e-6f64.ln());
    }
}