Skip to main content

caroli_walk/
scan.rs

1//! Many walks of one graph side by side, as in a scan of parameters: one walk per CPU thread
2//! and, optionally, a stream of walks on the GPU fed by one more thread, all taking the next walk
3//! from one queue. Each walk returns the probability of every half-edge summed over its steps
4//! (time averages, Kolmogorov–Smirnov distances).
5//!
6//! Walks run in reduced precision (f32 on the CPU or on the GPU) are checked: one in fifty, at
7//! least one, is recomputed in f64 on the CPU, and if the sums differ by more than the tolerance
8//! (relative to their total), all the walks of that kind are recomputed in f64.
9
10use crate::walk::{SpinWalk, to_single};
11use caroli_model::c64;
12use rayon::prelude::*;
13use std::sync::Mutex;
14use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
15
16/// How a scan runs.
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub struct ScanOptions {
19    /// f32 states on the CPU: half the memory traffic.
20    pub single: bool,
21    /// Also run walks on the GPU (f32), fed by one of the threads.
22    pub gpu: bool,
23    /// Largest deviation accepted between a reduced-precision walk and its f64 recomputation.
24    pub tolerance: f64,
25}
26
27impl Default for ScanOptions {
28    fn default() -> Self {
29        Self { single: false, gpu: false, tolerance: 1e-3 }
30    }
31}
32
33/// What a scan did.
34#[derive(Clone, Debug, Default, PartialEq)]
35pub struct ScanReport {
36    /// Walks run on the CPU and on the GPU.
37    pub cpu_walks: usize,
38    /// Walks run on the GPU (f32), counted even when a fallback recomputed them.
39    pub gpu_walks: usize,
40    /// The GPU, or why it was not used.
41    pub gpu: String,
42    /// Reduced-precision walks recomputed in f64, and the largest relative deviation found.
43    pub checked: usize,
44    /// Largest deviation `max_h |a_h − b_h| / Σ_h b_h` between the half-edge sums `a` of a checked
45    /// walk and `b` of its f64 recomputation.
46    pub deviation: f64,
47    /// Why the f64 CPU recomputed the reduced-precision walks.
48    pub fallback: Option<String>,
49}
50
51#[derive(Clone, Copy, PartialEq, Eq)]
52enum Kind {
53    Double,
54    Single,
55    Gpu,
56}
57
58/// The result of each walk, filled by the threads that run them.
59type Slots = [Mutex<Option<(Vec<f64>, Kind)>>];
60
61/// The sums over `steps` steps of the half-edge probabilities, on the calling thread.
62fn on_cpu(walk: &SpinWalk, psi: Vec<c64>, steps: usize, single: bool) -> Vec<f64> {
63    let mut acc = vec![0.0; walk.graph().half_edges()];
64    if single {
65        let mut psi = to_single(&psi);
66        for _ in 0..steps {
67            walk.step_serial_accumulate(&mut psi, &mut acc);
68        }
69    } else {
70        let mut psi = psi;
71        for _ in 0..steps {
72            walk.step_serial_accumulate(&mut psi, &mut acc);
73        }
74    }
75    acc
76}
77
78/// `max_h |a_h − b_h| / Σ b`, NaN if any entry is.
79fn deviation(a: &[f64], b: &[f64]) -> f64 {
80    let total: f64 = b.iter().sum();
81    a.iter().zip(b).map(|(x, y)| (x - y).abs()).fold(0.0, max_or_nan) / total
82}
83
84/// The larger of `a` and `b`, or NaN if either is: a NaN must fail the checks, and `f64::max`
85/// would hide it (it returns the other number).
86fn max_or_nan(a: f64, b: f64) -> f64 {
87    if a.is_nan() || b.is_nan() { f64::NAN } else { a.max(b) }
88}
89
90/// For each walk, the probability of every half-edge summed over `steps` steps from
91/// `initial(i)`. The walks must share their graph.
92pub fn scan(
93    walks: &[SpinWalk],
94    initial: impl Fn(usize) -> Vec<c64> + Sync,
95    steps: usize,
96    options: &ScanOptions,
97) -> (Vec<Vec<f64>>, ScanReport) {
98    let mut report = ScanReport::default();
99    if walks.is_empty() {
100        return (Vec::new(), report);
101    }
102    assert!(walks.iter().all(|w| w.graph() == walks[0].graph()), "the walks of a scan share their graph");
103    let results: Box<Slots> = walks.iter().map(|_| Mutex::new(None)).collect();
104    let next = AtomicUsize::new(0);
105    let threads = rayon::current_num_threads().max(1);
106    let gpu_name = Mutex::new(String::from("not used"));
107    // The CPU threads wait for the GPU to be ready (or to have failed), so that it gets its share.
108    let ready = AtomicBool::new(!options.gpu);
109    let cpu_kind = if options.single { Kind::Single } else { Kind::Double };
110    std::thread::scope(|s| {
111        if options.gpu {
112            s.spawn(|| {
113                *gpu_name.lock().unwrap() = gpu_worker(walks, &initial, steps, &next, &results, &ready);
114                ready.store(true, Ordering::Release);
115            });
116        }
117        let workers = if options.gpu { threads.saturating_sub(1).max(1) } else { threads };
118        for _ in 0..workers {
119            s.spawn(|| {
120                while !ready.load(Ordering::Acquire) {
121                    std::thread::yield_now();
122                }
123                loop {
124                    let i = next.fetch_add(1, Ordering::Relaxed);
125                    if i >= walks.len() {
126                        break;
127                    }
128                    let acc = on_cpu(&walks[i], initial(i), steps, options.single);
129                    *results[i].lock().unwrap() = Some((acc, cpu_kind));
130                }
131            });
132        }
133    });
134    report.gpu = gpu_name.into_inner().unwrap();
135    let mut out: Vec<(Vec<f64>, Kind)> =
136        results.into_iter().map(|m| m.into_inner().unwrap().expect("every walk ran")).collect();
137    report.gpu_walks = out.iter().filter(|r| r.1 == Kind::Gpu).count();
138    report.cpu_walks = out.len() - report.gpu_walks;
139    // Check the reduced-precision walks against f64, kind by kind.
140    for kind in [Kind::Single, Kind::Gpu] {
141        let indices: Vec<usize> = (0..out.len()).filter(|&i| out[i].1 == kind).collect();
142        if indices.is_empty() {
143            continue;
144        }
145        let picked: Vec<usize> = (0..indices.len().div_ceil(50)).map(|k| indices[k * 50]).collect();
146        let worst = picked
147            .par_iter()
148            .map(|&i| deviation(&out[i].0, &on_cpu(&walks[i], initial(i), steps, false)))
149            .reduce(|| 0.0, max_or_nan);
150        report.checked += picked.len();
151        report.deviation = max_or_nan(report.deviation, worst);
152        if worst.is_nan() || worst > options.tolerance {
153            let name = if kind == Kind::Gpu { "GPU" } else { "CPU f32" };
154            report.fallback = Some(format!(
155                "{name}: deviation {worst:.1e} above the tolerance {:.1e}; {} walks recomputed in f64",
156                options.tolerance,
157                indices.len()
158            ));
159            let redone: Vec<(usize, Vec<f64>)> =
160                indices.par_iter().map(|&i| (i, on_cpu(&walks[i], initial(i), steps, false))).collect();
161            for (i, acc) in redone {
162                out[i] = (acc, Kind::Double);
163            }
164        }
165    }
166    (out.into_iter().map(|r| r.0).collect(), report)
167}
168
169/// The GPU's share of a scan: walks taken from the queue until it is empty. Returns the GPU's
170/// name, or why it could not run; a walk it fails is run on the CPU by this thread.
171#[cfg(target_os = "macos")]
172fn gpu_worker(
173    walks: &[SpinWalk],
174    initial: &(impl Fn(usize) -> Vec<c64> + Sync),
175    steps: usize,
176    next: &AtomicUsize,
177    results: &Slots,
178    ready: &AtomicBool,
179) -> String {
180    use caroli_gpu::{MetalDevice, Precision};
181    let device = MetalDevice::new();
182    ready.store(true, Ordering::Release);
183    let device = match device {
184        Ok(d) => d,
185        Err(e) => return format!("no GPU: {e}"),
186    };
187    // Walks per batch: about 8 MB of f32 states, so that a batch stays in the GPU's cache (larger
188    // batches spill to memory and run slower per walk on an M5).
189    let per_walk = walks[0].dimension() * 8;
190    let size = ((8usize << 20) / per_walk).clamp(1, 64);
191    let rows = walks[0].graph().half_edges();
192    let mut failed = None;
193    loop {
194        let start = next.fetch_add(size, Ordering::Relaxed);
195        if start >= walks.len() {
196            break;
197        }
198        let picked: Vec<usize> = (start..(start + size).min(walks.len())).collect();
199        let tables: Vec<crate::gpu::Tables> =
200            picked.iter().map(|&i| crate::gpu::Tables::of(&walks[i])).collect();
201        let views: Vec<caroli_gpu::WalkTables> = tables.iter().map(|t| t.view()).collect();
202        let states: Vec<c64> = picked.iter().flat_map(|&i| initial(i)).collect();
203        let run = device.walks(&views, &states, Precision::Single).and_then(|mut w| {
204            w.steps_accumulate(steps)?;
205            Ok(w.accumulated())
206        });
207        match run {
208            Ok(acc) => {
209                for (k, &i) in picked.iter().enumerate() {
210                    *results[i].lock().unwrap() = Some((acc[k * rows..(k + 1) * rows].to_vec(), Kind::Gpu));
211                }
212            }
213            Err(e) => {
214                for &i in &picked {
215                    *results[i].lock().unwrap() =
216                        Some((on_cpu(&walks[i], initial(i), steps, false), Kind::Double));
217                }
218                failed = Some(format!("GPU failed ({e}); the CPU took over"));
219                break;
220            }
221        }
222    }
223    failed.unwrap_or_else(|| device.name())
224}
225
226#[cfg(not(target_os = "macos"))]
227fn gpu_worker(
228    _walks: &[SpinWalk],
229    _initial: &(impl Fn(usize) -> Vec<c64> + Sync),
230    _steps: usize,
231    _next: &AtomicUsize,
232    _results: &Slots,
233    _ready: &AtomicBool,
234) -> String {
235    "no GPU walk backend on this platform (Metal only)".into()
236}
237
238#[cfg(test)]
239mod tests {
240    use super::*;
241    use crate::walk::PLUS;
242
243    /// A NaN in a reduced-precision result fails the check: `f64::max` alone would skip it.
244    #[test]
245    fn nan_deviations_fail() {
246        assert!(deviation(&[f64::NAN, 0.5], &[0.5, 0.5]).is_nan());
247        assert!(max_or_nan(0.0, f64::NAN).is_nan() && max_or_nan(f64::NAN, 1.0).is_nan());
248        assert!((deviation(&[0.4, 0.5], &[0.5, 0.5]) - 0.1).abs() < 1e-15);
249    }
250
251    #[test]
252    fn scans_agree() {
253        let n = 9;
254        let walks: Vec<SpinWalk> =
255            (0..12).map(|k| SpinWalk::ring(n, 0.1 + 0.12 * k as f64, 0.3 + 0.2 * k as f64)).collect();
256        let initial = |i: usize| walks[i].product_state(&walks[i].localized(4, 0), &[PLUS; 9]);
257        let steps = 200;
258        let (exact, report) = scan(&walks, initial, steps, &ScanOptions::default());
259        assert_eq!((report.cpu_walks, report.gpu_walks, report.checked), (12, 0, 0));
260        let total: f64 = exact[0].iter().sum();
261        assert!((total - steps as f64).abs() < 1e-9, "the probabilities add up to one at each step");
262        for options in [
263            ScanOptions { single: true, ..ScanOptions::default() },
264            ScanOptions { gpu: true, ..ScanOptions::default() },
265            ScanOptions { single: true, gpu: true, ..ScanOptions::default() },
266        ] {
267            let (sums, report) = scan(&walks, initial, steps, &options);
268            assert!(report.fallback.is_none(), "{report:?}");
269            // Without a GPU (other platforms, virtual machines) the CPU runs every walk, and
270            // only the f32 ones need checking.
271            let reduced = options.single || report.gpu_walks > 0;
272            assert_eq!(report.checked >= 1, reduced, "{report:?}");
273            assert!(report.deviation < 1e-4, "{report:?}");
274            for (a, b) in sums.iter().zip(&exact) {
275                assert!(deviation(a, b) < 1e-4, "{options:?}");
276            }
277        }
278        // An impossible tolerance: the reduced-precision walks are redone in f64.
279        let strict = ScanOptions { single: true, gpu: false, tolerance: 1e-15 };
280        let (sums, report) = scan(&walks, initial, steps, &strict);
281        assert!(report.fallback.is_some());
282        assert_eq!(sums, exact);
283    }
284}