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
//! Python binding for machine-aware gate-parallelism calibration.
//!
//! `polypus.calibrate_parallel_threshold(force=False)` measures the qubit count
//! at which the native statevector simulator's gate kernels should switch to the
//! rayon parallel path on *this* machine, caches it on disk keyed by the rayon
//! thread count *and* a CPU fingerprint (so nodes sharing one `$HOME` keep
//! separate entries; see `polypus_sim::calibration`), and returns what it
//! decided. It mirrors `polypus.init_logger`:
//! a one-shot, process-level setup call, meant to run once — the first line of a
//! SLURM script, or inside `install.sh` — **before** any circuits are simulated,
//! because the per-process resolver reads the cache once and memoises it.
//!
//! Like every other library diagnostic, its `log::*` output stays silent until
//! `polypus.init_logger()` installs a sink.
//!
//! ## Default-visible fallback warning
//!
//! When a process runs the native statevector path against a cache calibrated
//! for *different* hardware (`FallbackReason::HardwareChanged`), `polypus-sim`
//! emits a `log::warn!` — but that is silent unless the user installed a logger,
//! which most do not. So [`warn_if_using_default_threshold`] additionally raises
//! a Python `UserWarning`, which the interpreter prints to stderr **by default**
//! with no setup. This does not break the "the pure Rust core never prints, only
//! logs" rule (that binds `polypus-sim`/`polypus-circuit`): this lives in the
//! bindings layer, which already talks to the interpreter directly.
//!
//! Since issue #176 the first native statevector run of a process auto-calibrates
//! the machine (lazily since #351; see [`prepare_native_threshold`]), so the
//! `FallbackReason::NotCalibrated` case no longer raises a `UserWarning` (it
//! would only nag on a read-only cache dir, where the result is still correct);
//! it is demoted to a logger-only `info!`. See [`warn_if_using_default_threshold`].
//!
//! ## Lazy auto-calibration
//!
//! A `pip install` of a published wheel has no post-install hook, and the CI
//! machine that builds the wheel is not the one that runs it, so the threshold
//! is measured on the runtime hardware, once per machine (#176). It used to run
//! at `import polypus`, which cost CPU and a cache write on every cold import,
//! even in processes that never simulate (#351). It now runs on the first call
//! that resolves the threshold — `polypus.statevector`, and `run_quantum_circuit`
//! or `train` on the native backend — just before the simulator reads the cache.
//! `import polypus` measures nothing and writes nothing.
use ;
use Once;
use *;
use ;
use FallbackReason;
/// Guards the one-per-process Python fallback warning. An explicit guard — the
/// same pattern as `LOGGER_INSTALLED` in `logging.rs` — rather than relying on
/// Python's own duplicate-warning filter, whose behaviour a caller can
/// reconfigure (`warnings.simplefilter("always")`, `-W`, pytest) and which we do
/// not want to depend on guessing right.
static THRESHOLD_WARNING_EMITTED: AtomicBool = new;
/// Guards the once-per-process implicit calibration (see
/// [`autocalibrate_once`]).
static AUTOCALIBRATION: Once = new;
/// Opt-out for the implicit calibration (CI, containers, runs that must pin the
/// static default threshold).
const OPTOUT_VAR: &str = "POLYPUS_NO_AUTOCALIBRATE";
/// Launcher rank variables: a non-zero rank skips the implicit calibration
/// (issue #214).
const RANK_VARS: = ;
/// Whether the implicit calibration may run, given an environment lookup.
///
/// `false` when `POLYPUS_NO_AUTOCALIBRATE` is `1`/`true`/`yes`/`on` (any case),
/// or when `SLURM_PROCID` or `OMPI_COMM_WORLD_RANK` is set to anything other
/// than empty or `0`: otherwise every rank of a large `srun`/`mpirun` would
/// measure at once, contending for the CPUs being timed and for the shared
/// cache file. Rank 0, or no launcher at all, calibrates. Pure, so the policy
/// is unit-tested without touching the process environment.
/// Calibrate (or reuse) this machine's gate-parallel threshold, at most once per
/// process and only when [`autocalibration_allowed`] permits it.
///
/// `force = false`: a cache entry valid for this hardware is reused in ~0s; a
/// cold or hardware-changed cache is measured (<1s) and persisted. A read-only
/// cache dir is not an error (the result is just not persisted). Calibration is
/// a pure performance optimisation — the parallel and sequential paths are
/// numerically identical — so a panic inside it is contained and the simulator
/// falls back to the static default. The GIL is released for the measurement,
/// including while another thread waits for it to finish.
/// Prepare the gate-parallel threshold before a native statevector run: run the
/// implicit calibration on the first such call of the process, then raise the
/// fallback warning if the threshold still resolved to the static default
/// because of a stale cache.
///
/// Must run before the run builds its simulator: the simulator resolves the
/// threshold from the cache once per process, so a calibration after that
/// point would not be seen until the next process.
pub
/// Raise a one-time, default-visible `UserWarning` if this process resolved the
/// gate-parallel threshold to the static default *because the cache was
/// calibrated for different hardware* (`FallbackReason::HardwareChanged`). The
/// `NotCalibrated` case is handled quietly (a logger-only `info!`) since the
/// first native run auto-calibrates the machine (issue #176) — see the module
/// docs.
///
/// Called through [`prepare_native_threshold`] at the entry points that actually
/// run the native statevector backend (`polypus.statevector`, and
/// `run_quantum_circuit`/`train` only when they select the native backend). No-op — and cheap — when the threshold came from a valid
/// cache, or after the first warning in a process. The message is actionable: it
/// names `polypus.calibrate_parallel_threshold()` so a user can fix it, matching
/// the `log` records `polypus-sim` emits for the same conditions.
///
/// Uses `polypus_sim::resolved_fallback_reason()`, which shares the one
/// per-process resolution the simulator uses, so the warning can never disagree
/// with the threshold actually in force.
/// Calibrate (or reuse) the gate-parallelism threshold for this machine.
///
/// With `force=False` (default) a cache entry already valid for the current
/// hardware (same CPU fingerprint *and* rayon thread count) is reused unchanged
/// and nothing is measured; with `force=True` the crossover is re-measured and
/// that one entry replaced — entries for other thread counts or other nodes are
/// preserved. The write is atomic and lock-protected, so concurrent calls (e.g.
/// several ranks or nodes on a shared `$HOME`) never tear the file. Unlike the
/// implicit calibration of the first native run, this explicit call runs on every
/// rank it is invoked on, secondary SLURM/OpenMPI ranks included, and ignores
/// `POLYPUS_NO_AUTOCALIBRATE`.
///
/// Returns a `dict` describing the outcome:
/// * `threshold` (int) — qubit count at/above which gates go parallel;
/// * `num_threads` (int) — rayon threads detected (one half of the cache key,
/// alongside the CPU fingerprint, which is not returned);
/// * `duration_secs` (float) — measurement time (`0.0` when reused);
/// * `reused_cache` (bool) — whether a valid cache was reused as-is;
/// * `cache_path` (str | None) — where the cache lives / would live;
/// * `cache_written` (bool) — whether this call persisted a fresh result.
///
/// A cache that cannot be written (read-only container/CI) is **not** an error:
/// the measured threshold is still returned with `cache_written=False`, so the
/// call is safe to run unconditionally from an installer. Diagnostics require
/// `polypus.init_logger()` to be visible.