caroli_green/precision.rs
1//! Reduced precision for transport (experimental), chosen by the user and checked against double
2//! precision.
3//!
4//! The nested-dissection solvers can run their fronts in complex f32 ([`Precision::Single`]).
5//! The root of the elimination (the lead self-energies, the delayed variables and the final
6//! solve) and the trace stay in f64. [`checked`] runs a batch of points in the chosen precision,
7//! recomputes a sample in double precision and falls back to double precision for the whole
8//! batch when the sample differs by more than the tolerance: every run reports the error it
9//! measured.
10//!
11//! Measured on Apple silicon (`ARCHITECTURE.md`, item 12), single precision is a preview tool:
12//! - 1.1–1.6× faster on one thread on the benchmark problems (less where the lead modes, always
13//! in f64, take most of the time: BHZ, graphene), 1.4–1.9× on all threads;
14//! - the median error stays near 10⁻⁵, but the largest grows with the width: on the spin blocks
15//! of the g2g1 ribbons, 3·10⁻² at W = 64, 6·10⁻² at W = 128, 0.4 at W = 256 (below 10⁻² on
16//! the conductance plateaus). Nested dissection eliminates closed subdomains at a real energy,
17//! and close to one of their eigenvalues a block keeps too few digits in f32.
18
19use crate::GreenError;
20use rayon::prelude::*;
21
22/// Floating-point precision of the eliminations of a nested-dissection solve.
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum Precision {
25 /// Complex f64 throughout (the default).
26 #[default]
27 Double,
28 /// Experimental: the fronts below the root in complex f32, the root and the trace in f64.
29 /// 1.1–1.9× faster, with errors up to 10⁻² and more in wide samples (see the module
30 /// documentation): for previews, checked with [`checked`].
31 Single,
32}
33
34/// How a batch of points runs in reduced precision (see [`checked`]).
35#[derive(Clone, Copy, Debug, PartialEq)]
36pub struct PrecisionOptions {
37 /// Precision the points run in; with [`Precision::Double`], nothing is checked.
38 pub precision: Precision,
39 /// Largest difference accepted between a point in `precision` and its double-precision value.
40 pub tolerance: f64,
41 /// One point in `every` (at least one) is recomputed in double precision.
42 pub every: usize,
43}
44
45impl PrecisionOptions {
46 /// Double precision: nothing to check.
47 pub fn double() -> Self {
48 Self { precision: Precision::Double, tolerance: 0.0, every: 0 }
49 }
50
51 /// Single precision for previews: one point in fifty recomputed in double precision,
52 /// differences up to 10⁻² accepted.
53 pub fn single() -> Self {
54 Self { precision: Precision::Single, tolerance: 1e-2, every: 50 }
55 }
56}
57
58impl Default for PrecisionOptions {
59 fn default() -> Self {
60 Self::double()
61 }
62}
63
64/// What a checked batch did.
65#[derive(Clone, Debug, Default, PartialEq)]
66pub struct PrecisionReport {
67 /// The precision of the results returned: `Double` after a fallback.
68 pub precision: Precision,
69 /// Points recomputed in double precision to check the batch, and the median and largest
70 /// difference found among them.
71 pub checked: usize,
72 /// Median of these differences (by the `distance` of [`checked`]); 0 when none was checked.
73 pub median: f64,
74 /// Largest of these differences; NaN when a point failed in double precision only, which
75 /// fails the check.
76 pub max: f64,
77 /// Points that failed in reduced precision (a singular front) and were computed in double
78 /// precision instead.
79 pub failed: usize,
80 /// Why the whole batch was recomputed in double precision.
81 pub fallback: Option<String>,
82}
83
84/// Runs `run(point, precision)` on every point, in parallel, in `options.precision`. In reduced
85/// precision, one point in `options.every` is recomputed in double precision and compared with
86/// `distance`; if one of them differs by more than `options.tolerance`, the whole batch is
87/// recomputed in double precision. Points that fail in reduced precision are computed in double
88/// precision. The checked points return their double-precision values.
89///
90/// ```ignore
91/// let (t, report) = checked(&energies, &PrecisionOptions::single(), |&e, p| {
92/// sys.transmission_with_precision(&sys.self_energies(e)?, p)
93/// }, |a, b| (a - b).abs());
94/// ```
95pub fn checked<P: Sync, O: Send>(
96 points: &[P],
97 options: &PrecisionOptions,
98 run: impl Fn(&P, Precision) -> Result<O, GreenError> + Sync,
99 distance: impl Fn(&O, &O) -> f64,
100) -> (Vec<Result<O, GreenError>>, PrecisionReport) {
101 let mut report = PrecisionReport { precision: options.precision, ..PrecisionReport::default() };
102 let mut out: Vec<Result<O, GreenError>> = points.par_iter().map(|p| run(p, options.precision)).collect();
103 if options.precision == Precision::Double || points.is_empty() {
104 return (out, report);
105 }
106 // Points that failed in reduced precision, and the sample, in double precision.
107 let every = options.every.max(1);
108 let redo: Vec<usize> = (0..points.len()).filter(|&i| out[i].is_err() || i % every == 0).collect();
109 let double: Vec<(usize, Result<O, GreenError>)> =
110 redo.par_iter().map(|&i| (i, run(&points[i], Precision::Double))).collect();
111 let mut differences = Vec::new();
112 for (i, d) in double {
113 match (&out[i], &d) {
114 (Ok(single), Ok(exact)) => differences.push(distance(single, exact)),
115 (Err(_), _) => report.failed += 1,
116 (Ok(_), Err(_)) => differences.push(f64::NAN),
117 }
118 out[i] = d;
119 }
120 report.checked = differences.len();
121 differences.sort_by(f64::total_cmp);
122 if let Some(&last) = differences.last() {
123 report.median = differences[differences.len() / 2];
124 report.max = if differences.iter().any(|d| d.is_nan()) { f64::NAN } else { last };
125 }
126 // A NaN (a point that failed in double precision only) fails the check too.
127 if report.max.is_nan() || report.max > options.tolerance {
128 report.fallback = Some(format!(
129 "largest difference {:.1e} above the tolerance {:.1e}: all {} points recomputed in double precision",
130 report.max,
131 options.tolerance,
132 points.len()
133 ));
134 report.precision = Precision::Double;
135 out = points.par_iter().map(|p| run(p, Precision::Double)).collect();
136 }
137 (out, report)
138}
139
140#[cfg(test)]
141mod tests {
142 use super::*;
143
144 /// A point "computed" in single precision is off by 1e-4 at index 7.
145 fn run(i: &usize, p: Precision) -> Result<f64, GreenError> {
146 let exact = *i as f64;
147 match (p, *i) {
148 (Precision::Single, 7) => Ok(exact + 1e-4),
149 (Precision::Single, 3) => Err(GreenError::Singular(0.0)),
150 _ => Ok(exact),
151 }
152 }
153
154 #[test]
155 fn sample_failures_and_fallback() {
156 let points: Vec<usize> = (0..10).collect();
157 let d = |a: &f64, b: &f64| (a - b).abs();
158 // Index 7 is not sampled (every 5): kept; the failed index 3 is redone in double.
159 let options = PrecisionOptions { precision: Precision::Single, tolerance: 1e-6, every: 5 };
160 let (out, report) = checked(&points, &options, run, d);
161 assert_eq!((report.checked, report.failed, report.fallback.is_none()), (2, 1, true));
162 assert_eq!(out[3].as_ref().ok(), Some(&3.0));
163 assert_eq!(out[7].as_ref().ok(), Some(&(7.0 + 1e-4)));
164 // Index 7 sampled (every 7): above the tolerance, everything redone in double.
165 let options = PrecisionOptions { every: 7, ..options };
166 let (out, report) = checked(&points, &options, run, d);
167 assert!(report.fallback.is_some() && report.precision == Precision::Double);
168 assert!(out.iter().enumerate().all(|(i, t)| t.as_ref().ok() == Some(&(i as f64))));
169 // Double precision: nothing checked.
170 let (_, report) = checked(&points, &PrecisionOptions::double(), run, d);
171 assert_eq!(report, PrecisionReport::default());
172 }
173}