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
//! Process-wide randomness that can be seeded to make a whole run reproducible.
//!
//! # Meaning
//!
//! [`with_rng`] runs a closure against a random number generator. Until [`set_seed`] has been
//! called it is a fresh, entropy-seeded `rand::rng()`; after `set_seed(seed)`, every call on any
//! thread draws from one shared generator started from `seed`. Calling `set_seed` again restarts
//! the sequence, whatever was drawn before.
//!
//! Call sites that do not receive an explicit seed (the shuffle of the training set, the random
//! masks of the classical training recipe, the initial assignment drawn by `Variable::sample`)
//! use `with_rng` instead of `rand::rng()`. Everything that takes a `seed` argument, such as the
//! neural local search, keeps using its own generator.
//!
//! The network's backend has its own generator, which `crate::set_seed` seeds next to this one.
//!
//! # How it works
//!
//! The shared generator is a `StdRng` behind a mutex in a `OnceLock`. Before the first
//! `set_seed` the cell is empty and `with_rng` takes no lock.
//!
//! # Design notes
//!
//! - **Reproducible only if the order of draws is.** Threads that draw from the shared generator
//! concurrently get values in the order they happen to lock it. Parallel code therefore draws
//! what it needs sequentially first (for example one seed per task) and hands it to the tasks.
//! - **Unseeded behaviour is unchanged.** A process that never calls `set_seed` behaves as if
//! this module did not exist.
use ;
use StdRng;
use ;
/// The shared generator, empty until `set_seed` is first called.
static GLOBAL_RNG: = new;
/// (Re)seeds the process-wide RNG that `with_rng` draws from. Safe to call more than once (e.g.
/// between successive runs in the same process): each call replaces the shared state with a
/// fresh `StdRng::seed_from_u64(seed)`, so the next `with_rng` call after `set_seed` always starts
/// a new, deterministic sequence regardless of how much randomness a previous run consumed.
pub
/// Runs `f` against the process-wide RNG if `set_seed` has been called at least once, or a fresh
/// entropy-seeded `rand::rng()` otherwise -- i.e. this crate's behaviour before `set_seed`
/// existed. Every call site that wants its randomness to become reproducible under `set_seed`
/// should draw from here instead of calling `rand::rng()` directly.
pub