Skip to main content

lensbench_core/
par.rs

1//! 並列の制御: 呼び出しごとのスレッド数と、計算の文脈([`Ctx`]: 中断の印 [`CancelToken`]・まとめ追跡の切り替え・
2//! 拡張の表・ファイルの口)。
3//!
4//! 文脈は呼び出したスレッドに置き([`with_cancel`]・[`with_batch`])、このモジュールの並列は作業のスレッドへ引き継ぐ。
5//! プロセスの大域には置かないので、同じプロセスで同時に回る別の計算(GUI の下書き・serve の別の接続)に響かない。
6//!
7//! 追跡は光線ごとに独立に計算し、結果は入力の順に並べる。総和・統計は並列にせず決まった順で足すので、
8//! スレッド数によらず結果は同じビットになる(tests/determinism.rs)。
9//!
10//! 外側でプロセス並列にするときは `with_threads(Some(1), ..)` で中を逐次にする(スレッドを作らない)。
11
12use crate::LockExt;
13use std::cell::Cell;
14use std::collections::HashMap;
15use std::sync::atomic::{AtomicBool, Ordering};
16use std::sync::{Arc, Mutex, OnceLock};
17
18thread_local! {
19    static SEQUENTIAL: Cell<bool> = const { Cell::new(false) };
20}
21
22/// スレッドを作れない(スレッドなしの wasm)。rayon に触らず常に逐次にする
23const NO_THREADS: bool = cfg!(all(target_arch = "wasm32", not(target_feature = "atomics")));
24
25/// スレッドありの wasm: rayon の大域プールを Web Worker で作り終えたか([`set_pool_ready`])。
26/// 作る前(画面のスレッド・下書きの Worker など)は逐次にする(std のスレッドは作れない)
27#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
28static POOL_READY: AtomicBool = AtomicBool::new(false);
29
30/// スレッドありの wasm: rayon の大域プールを作り終えた(wasm-bindgen-rayon の initThreadPool の後に呼ぶ)
31#[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
32pub fn set_pool_ready() {
33    POOL_READY.store(true, Ordering::Relaxed);
34}
35
36fn no_threads() -> bool {
37    #[cfg(all(target_arch = "wasm32", target_feature = "atomics"))]
38    if !POOL_READY.load(Ordering::Relaxed) {
39        return true;
40    }
41    NO_THREADS
42}
43
44/// 呼び出し中のスレッドで逐次に計算するか(`with_threads(Some(1), ..)` の中、またはスレッドなしの wasm)
45pub fn sequential() -> bool {
46    no_threads() || SEQUENTIAL.with(|c| c.get())
47}
48
49/// スレッド数ごとのプール(作るのが重いので使い回す。系の状態は持たない)。
50/// 一度作ったプールとそのスレッドはプロセスの終わりまで解放しない(使うスレッド数の種類だけ残る)
51/// apart は [`with_threads_apart`] の別のプール
52fn pool(n: usize, apart: bool) -> Result<Arc<rayon::ThreadPool>, rayon::ThreadPoolBuildError> {
53    type Pools = HashMap<(usize, bool), Arc<rayon::ThreadPool>>;
54    static POOLS: OnceLock<Mutex<Pools>> = OnceLock::new();
55    let mut m = POOLS.get_or_init(Default::default).lock_ok();
56    if let Some(p) = m.get(&(n, apart)) {
57        return Ok(p.clone());
58    }
59    let p = Arc::new(rayon::ThreadPoolBuilder::new().num_threads(n).build()?);
60    m.insert((n, apart), p.clone());
61    Ok(p)
62}
63
64/// f を threads 本のスレッドで実行する。None は既定(外の指定を引き継ぐ: `with_threads(Some(1), ..)` の中なら逐次、
65/// 別の with_threads のプールの中ならそのプール。どちらでもなければ [`set_default_threads`] の数があればその数、
66/// なければ rayon の大域プールで RAYON_NUM_THREADS が効く)、
67/// Some(1) は呼び出したスレッドで逐次、Some(0) は外の逐次の指定を外して既定に戻す。
68/// Some(n)(n ≥ 2)のプールは n ごとに作って使い回し、解放しない。
69pub fn with_threads<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> R {
70    threads_in(threads, false, f)
71}
72
73/// [`with_threads`] で、n ≥ 2 のときは同じ数でも別のプールで回す(長い計算を、同時に回る短い計算のプールの
74/// 盗みに載せない。載ると短い計算が長い計算の終わりまで返らない)
75pub fn with_threads_apart<R: Send>(threads: Option<usize>, f: impl FnOnce() -> R + Send) -> R {
76    threads_in(threads, true, f)
77}
78
79fn threads_in<R: Send>(threads: Option<usize>, apart: bool, f: impl FnOnce() -> R + Send) -> R {
80    match threads {
81        // 既定は外の逐次の指定を打ち消さない(以前は with_threads_or_outer と分かれていた)
82        None if sequential() => f(),
83        // 既定の数(CLI・Python が起動時に決める)。別のプールの中ならそのプール
84        None if rayon::current_thread_index().is_none() && default_threads().is_some() => {
85            threads_in(default_threads(), apart, f)
86        }
87        None | Some(0) => with_flag(false, f),
88        Some(1) => with_flag(true, f),
89        // wasm はスレッドを足せない(使えるのは Web Worker で作った大域プールだけ)
90        Some(_) if cfg!(target_arch = "wasm32") => with_flag(false, f),
91        Some(n) => match pool(n, apart) {
92            Ok(p) => {
93                // プールのスレッドで回すので、中断の印を引き継ぐ
94                let c = current();
95                p.install(move || with_ctx(&c, f))
96            }
97            // スレッドを作れないときは逐次にする(結果は同じ)
98            Err(_) => with_flag(true, f),
99        },
100    }
101}
102
103/// 既定のスレッド数(0 は無し: rayon の大域プール)
104static DEFAULT_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
105
106/// `with_threads(None, ..)` の既定のスレッド数を決める(None・0 で rayon の大域プール)。フロントエンド
107/// (CLI の `--threads`・Python の読込)が起動時に呼ぶ。core は環境変数を読まない
108pub(crate) fn set_default_threads(n: Option<usize>) {
109    DEFAULT_THREADS.store(n.unwrap_or(0), Ordering::Relaxed);
110}
111
112/// 既定のスレッド数([`set_default_threads`])
113pub fn default_threads() -> Option<usize> {
114    Some(DEFAULT_THREADS.load(Ordering::Relaxed)).filter(|&n| n > 0)
115}
116
117/// 既定のスレッド数を環境変数 LENSBENCH_THREADS(1 以上の整数。`lensbench run --threads` がスクリプトに渡す)
118/// から決める。CLI の起動・Python の import で呼ぶ(`--threads`・`threads=` を省いたときの数)
119pub(crate) fn default_threads_from_env() {
120    let n = std::env::var("LENSBENCH_THREADS")
121        .ok()
122        .and_then(|s| s.trim().parse::<usize>().ok());
123    set_default_threads(n);
124}
125
126/// 呼び出したスレッドの逐次の指定を f の間だけ変える(panic でも戻す)
127fn with_flag<R>(seq: bool, f: impl FnOnce() -> R) -> R {
128    struct Restore(bool);
129    impl Drop for Restore {
130        fn drop(&mut self) {
131            SEQUENTIAL.with(|c| c.set(self.0));
132        }
133    }
134    let _g = Restore(SEQUENTIAL.with(|c| c.replace(seq)));
135    f()
136}
137
138/// いま f が動くプールのスレッド数(逐次の指定の中では 1)
139pub fn current_threads() -> usize {
140    if sequential() {
141        1
142    } else {
143        rayon::current_num_threads()
144    }
145}
146
147/// a を n 個ずつに分けた塊のそれぞれに f(番号, 塊) をかける(逐次の指定の中では逐次)。
148/// 塊ごとに独立に計算するので、スレッド数によらず結果は同じ
149#[doc(hidden)]
150pub fn for_each_chunk_mut<T: Send>(
151    a: &mut [T],
152    n: usize,
153    f: impl Fn(usize, &mut [T]) + Sync + Send,
154) {
155    use rayon::prelude::*;
156    if sequential() {
157        a.chunks_mut(n).enumerate().for_each(|(i, c)| f(i, c));
158    } else {
159        let cx = current();
160        a.par_chunks_mut(n)
161            .enumerate()
162            .for_each(|(i, c)| with_ctx(&cx, || f(i, c)));
163    }
164}
165
166/// items のそれぞれに f をかけ、結果を入力の順に返す(逐次の指定の中では逐次)。
167/// 要素ごとに独立に計算するので、スレッド数によらず結果は同じ
168pub fn map<T: Sync, R: Send>(items: &[T], f: impl Fn(&T) -> R + Sync + Send) -> Vec<R> {
169    use rayon::prelude::*;
170    if sequential() || items.len() < 2 {
171        items.iter().map(f).collect()
172    } else {
173        items.par_iter().with_max_len(1).map(scoped(f)).collect()
174    }
175}
176
177/// [`map`] の誤りを返す形: 誤りが出たら新しい要素を始めず、入力の順で最初に見つかった誤りを返す
178/// (並列では、誤りの後に始めなかった要素より前の要素の誤りが返ることもある)
179pub fn try_map<T: Sync, R: Send, E: Send>(
180    items: &[T],
181    f: impl Fn(&T) -> Result<R, E> + Sync + Send,
182) -> Result<Vec<R>, E> {
183    let failed = AtomicBool::new(false);
184    let out = map(items, |x| {
185        if failed.load(Ordering::Relaxed) {
186            return None;
187        }
188        let r = f(x);
189        if r.is_err() {
190            failed.store(true, Ordering::Relaxed);
191        }
192        Some(r)
193    });
194    let mut v = Vec::with_capacity(out.len());
195    let mut skipped = false;
196    for r in out {
197        match r {
198            Some(Ok(x)) => v.push(x),
199            Some(Err(e)) => return Err(e),
200            None => skipped = true,
201        }
202    }
203    debug_assert!(!skipped, "skipped only after an error");
204    Ok(v)
205}
206
207/// 計算の中断の印。計算(要求)ごとに作って [`with_cancel`] で渡し、別のスレッドから [`CancelToken::cancel`] で倒す。
208/// 印は計算ごとなので、同じプロセスで同時に回っている別の計算は止めない。
209/// [`CancelToken::child`] で作った子の印は、親が倒れても倒れたとみなす(serve の要求の中で回す最適化など)
210#[derive(Clone, Debug, Default)]
211pub struct CancelToken {
212    flag: Arc<AtomicBool>,
213    parent: Option<Arc<CancelToken>>,
214}
215
216impl CancelToken {
217    pub fn new() -> Self {
218        Self::default()
219    }
220
221    /// 子の印: 自分を倒しても親は倒れないが、親が倒れれば子も倒れたとみなす
222    pub fn child(&self) -> Self {
223        Self {
224            flag: Arc::default(),
225            parent: Some(Arc::new(self.clone())),
226        }
227    }
228
229    /// この印で回っている計算に、区切りのよい所でやめるよう頼む([`check_cancel`] が `Error::Cancelled` を返す)
230    pub fn cancel(&self) {
231        self.flag.store(true, Ordering::Relaxed);
232    }
233
234    /// 中断を頼まれたか(親の印も見る)
235    pub fn is_cancelled(&self) -> bool {
236        self.flag.load(Ordering::Relaxed) || self.parent.as_ref().is_some_and(|p| p.is_cancelled())
237    }
238
239    /// 同じ印か(写しも同じ印)
240    pub fn same(&self, o: &CancelToken) -> bool {
241        Arc::ptr_eq(&self.flag, &o.flag)
242    }
243}
244
245/// 長い計算の進み具合の知らせ([`report`])。受け手は [`with_progress`] で文脈に渡す
246#[derive(Clone, Debug, PartialEq)]
247pub enum Event {
248    /// 反復の計算(最適化)の 1 回が終わった
249    Iter(Iter),
250    /// 数で数えられる作業(公差の試行・runs のタスク・差し替え探索の組)が 1 つ終わった
251    Count(Count),
252}
253
254/// 反復の計算の進み具合([`Event::Iter`])
255#[derive(Clone, Debug, PartialEq)]
256pub struct Iter {
257    /// 終わった反復の番号(1 始まり)
258    pub iter: usize,
259    /// 評価関数の値
260    pub merit: f64,
261    /// 変数の値
262    pub x: Vec<f64>,
263    /// 減衰の係数
264    pub damping: f64,
265    /// 残差を評価した回数(ヤコビアンの分を除く)
266    pub evals: usize,
267}
268
269/// 数で数えられる作業の進み具合([`Event::Count`])
270#[derive(Clone, Copy, Debug, PartialEq)]
271pub struct Count {
272    /// 段の名前(`""` は段の無い作業。差し替え探索は `"screen"`・`"main"`)
273    pub stage: &'static str,
274    /// 終わった数(再開で飛ばした分を含む)
275    pub done: usize,
276    pub total: usize,
277    /// この実行で終えた数
278    pub ran: usize,
279    /// この実行の経過(秒)
280    pub elapsed: f64,
281    /// 残りの見込み(秒。この実行の速さから。まだ分からなければ None)
282    pub eta: Option<f64>,
283}
284
285/// 進み具合の受け手(別のスレッドから呼ばれる)
286pub type ProgressFn = Arc<dyn Fn(&Event) + Send + Sync>;
287
288/// 計算の文脈(呼び出したスレッドに置き、このモジュールの並列が作業のスレッドへ引き継ぐ)
289#[derive(Clone, Default)]
290pub struct Ctx {
291    /// 中断の印([`with_cancel`])。None は中断できない
292    pub cancel: Option<CancelToken>,
293    /// まとめ追跡(`batch`)を使わない([`with_batch`]。結果は同じビットなので切り分け・比較のためだけ)
294    pub no_batch: bool,
295    /// 拡張の表([`crate::ext::with`])。None はプロセスの既定
296    pub ext: Option<Arc<crate::ext::Ext>>,
297    /// ファイルの口([`crate::vfs::with`])。None はプロセスの既定
298    pub fs: Option<Arc<dyn crate::vfs::Fs>>,
299    /// 進み具合の受け手([`with_progress`])。None は知らせない
300    pub progress: Option<ProgressFn>,
301}
302
303impl std::fmt::Debug for Ctx {
304    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
305        f.debug_struct("Ctx")
306            .field("cancel", &self.cancel)
307            .field("no_batch", &self.no_batch)
308            .field("ext", &self.ext)
309            .field("fs", &self.fs.as_ref().map(|_| "..."))
310            .field("progress", &self.progress.as_ref().map(|_| "..."))
311            .finish()
312    }
313}
314
315thread_local! {
316    /// 呼び出し中のスレッドの計算の文脈
317    static CTX: std::cell::RefCell<Ctx> = std::cell::RefCell::new(Ctx::default());
318}
319
320/// f を文脈 c の下で回す(panic でも戻す)
321pub fn with_ctx<R>(c: &Ctx, f: impl FnOnce() -> R) -> R {
322    struct Restore(Option<Ctx>);
323    impl Drop for Restore {
324        fn drop(&mut self) {
325            if let Some(c) = self.0.take() {
326                CTX.with(|x| *x.borrow_mut() = c);
327            }
328        }
329    }
330    let _g = Restore(Some(CTX.with(|x| x.replace(c.clone()))));
331    f()
332}
333
334/// 呼び出し中のスレッドの文脈(rayon を直に使う所で、作業のスレッドへ [`with_ctx`] で引き継ぐ)
335pub fn current() -> Ctx {
336    CTX.with(|x| x.borrow().clone())
337}
338
339/// f を中断の印 t の下で回す(文脈のほかの項目は引き継ぐ)。この中の [`check_cancel`]・[`cancelled`] は t を見る
340pub fn with_cancel<R>(t: Option<&CancelToken>, f: impl FnOnce() -> R) -> R {
341    let c = Ctx {
342        cancel: t.cloned(),
343        ..current()
344    };
345    with_ctx(&c, f)
346}
347
348/// f を進み具合の受け手 p の下で回す(文脈のほかの項目は引き継ぐ)。この中の [`report`] は p を呼ぶ。
349/// 最適化([`Event::Iter`])・公差・runs・差し替え探索([`Event::Count`])が知らせる。中断は [`with_cancel`] の印で頼む
350pub fn with_progress<R>(p: Option<ProgressFn>, f: impl FnOnce() -> R) -> R {
351    let c = Ctx {
352        progress: p,
353        ..current()
354    };
355    with_ctx(&c, f)
356}
357
358/// 進み具合を文脈の受け手([`with_progress`])に知らせる(受け手が無ければ何もしない)
359pub fn report(e: &Event) {
360    let p = CTX.with(|x| x.borrow().progress.clone());
361    if let Some(p) = p {
362        p(e);
363    }
364}
365
366/// 文脈に進み具合の受け手があるか(知らせを作るのが重いとき、無ければ作らない)
367pub fn reporting() -> bool {
368    CTX.with(|x| x.borrow().progress.is_some())
369}
370
371/// f をまとめ追跡あり(on)・なしで回す(文脈のほかの項目は引き継ぐ)
372pub fn with_batch<R>(on: bool, f: impl FnOnce() -> R) -> R {
373    let c = Ctx {
374        no_batch: !on,
375        ..current()
376    };
377    with_ctx(&c, f)
378}
379
380/// f を拡張の表 e の下で回す([`crate::ext::with`])
381pub(crate) fn with_ext<R>(e: Arc<crate::ext::Ext>, f: impl FnOnce() -> R) -> R {
382    let c = Ctx {
383        ext: Some(e),
384        ..current()
385    };
386    with_ctx(&c, f)
387}
388
389/// 文脈で渡した拡張の表
390pub(crate) fn current_ext() -> Option<Arc<crate::ext::Ext>> {
391    CTX.with(|x| x.borrow().ext.clone())
392}
393
394/// f をファイルの口 fs の下で回す([`crate::vfs::with`])
395pub(crate) fn with_fs<R>(fs: Arc<dyn crate::vfs::Fs>, f: impl FnOnce() -> R) -> R {
396    let c = Ctx {
397        fs: Some(fs),
398        ..current()
399    };
400    with_ctx(&c, f)
401}
402
403/// 文脈で渡したファイルの口
404pub(crate) fn current_fs() -> Option<Arc<dyn crate::vfs::Fs>> {
405    CTX.with(|x| x.borrow().fs.clone())
406}
407
408/// まとめ追跡を使ってよいか([`with_batch`])
409pub(crate) fn batch_enabled() -> bool {
410    CTX.with(|x| !x.borrow().no_batch)
411}
412
413/// f を、今の文脈を引き継ぐ関数にする(`par_iter().map(scoped(f))` のように rayon に渡す)
414pub fn scoped<A, R>(f: impl Fn(A) -> R + Sync + Send) -> impl Fn(A) -> R + Sync + Send {
415    let c = current();
416    move |a| with_ctx(&c, || f(a))
417}
418
419/// 文脈の中断の印([`with_cancel`]。無ければ None)。長い計算の中で自分だけ止められる子の印を作るとき([`CancelToken::child`])
420pub fn current_cancel() -> Option<CancelToken> {
421    CTX.with(|x| x.borrow().cancel.clone())
422}
423
424/// 中断を頼まれているか(印の無い計算は頼まれない)
425pub fn cancelled() -> bool {
426    CTX.with(|x| {
427        x.borrow()
428            .cancel
429            .as_ref()
430            .is_some_and(CancelToken::is_cancelled)
431    })
432}
433
434/// 中断を頼まれていれば `Error::Cancelled`。重い解析のループ(MTF の周波数・Huygens の像の点など)で呼ぶ
435pub fn check_cancel() -> crate::Result<()> {
436    if cancelled() {
437        Err(crate::error::Error::Cancelled)
438    } else {
439        Ok(())
440    }
441}
442
443#[cfg(test)]
444mod cancel_tests {
445    use super::*;
446
447    /// 印は計算ごと: 倒した印の計算だけが止まり、並列の作業のスレッドにも引き継がれる
448    #[test]
449    fn token_is_per_computation_and_reaches_workers() {
450        let a = CancelToken::new();
451        let b = CancelToken::new();
452        a.cancel();
453        with_cancel(Some(&a), || {
454            assert!(check_cancel().is_err());
455            let v = with_threads(Some(3), || map(&[1, 2, 3, 4], |_| cancelled()));
456            assert!(v.iter().all(|&x| x));
457        });
458        with_cancel(Some(&b), || {
459            assert!(check_cancel().is_ok());
460            let v = with_threads(Some(3), || map(&[1, 2, 3, 4], |_| cancelled()));
461            assert!(v.iter().all(|&x| !x));
462        });
463        // 印の外は頼まれない
464        assert!(!cancelled());
465    }
466
467    /// 子の印は親が倒れると倒れ、子を倒しても親は倒れない。進み具合は作業のスレッドからも受け手に届く
468    #[test]
469    fn child_token_and_progress() {
470        let a = CancelToken::new();
471        let c = a.child();
472        assert!(!c.is_cancelled());
473        c.cancel();
474        assert!(c.is_cancelled() && !a.is_cancelled());
475        let c2 = a.child();
476        a.cancel();
477        assert!(c2.is_cancelled());
478        let n = Arc::new(std::sync::atomic::AtomicUsize::new(0));
479        let n2 = n.clone();
480        let p: ProgressFn = Arc::new(move |_| {
481            n2.fetch_add(1, Ordering::Relaxed);
482        });
483        with_progress(Some(p), || {
484            with_threads(Some(3), || {
485                map(&[1, 2, 3, 4], |_| {
486                    report(&Event::Count(Count {
487                        stage: "",
488                        done: 1,
489                        total: 4,
490                        ran: 1,
491                        elapsed: 0.0,
492                        eta: None,
493                    }))
494                })
495            })
496        });
497        assert_eq!(n.load(Ordering::Relaxed), 4);
498        assert!(!reporting());
499    }
500
501    /// try_map: 誤りが無ければ map と同じ順、誤りがあれば誤り
502    #[test]
503    fn try_map_order_and_error() {
504        let v: Vec<usize> = (0..50).collect();
505        let r = with_threads(Some(3), || try_map(&v, |&x| Ok::<_, String>(x * 2)));
506        assert_eq!(r.unwrap(), (0..50).map(|x| x * 2).collect::<Vec<_>>());
507        let r = with_threads(Some(3), || {
508            try_map(&v, |&x| if x == 7 { Err(x) } else { Ok(x) })
509        });
510        assert_eq!(r, Err(7));
511    }
512
513    /// まとめ追跡の切り替えも文脈で、作業のスレッドに引き継ぎ、外では既定(使う)に戻る
514    #[test]
515    fn batch_switch_is_scoped() {
516        assert!(batch_enabled());
517        let v = with_batch(false, || {
518            with_threads(Some(3), || map(&[1, 2, 3, 4], |_| batch_enabled()))
519        });
520        assert!(v.iter().all(|&x| !x));
521        assert!(batch_enabled());
522    }
523}