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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 OUTRAM PARK contributors
//
// This file is part of OUTRAM PARK. See `src/lib.rs` for the full licence
// notice.
//! Where a numerical kernel runs — serial, multi-CPU, or GPU.
//!
//! # What belongs in this module
//!
//! The **dispatch layer and nothing else**: the [`ComputeBackend`] enum, the
//! worker-count policy [`ThreadCount`], the named backend-selection policy
//! [`select_backend`], and the GPU adapter probe. It is deliberately free of
//! numerical code so that every kernel in the crate answers the question
//! "where do I run?" the same way.
//!
//! # What does NOT belong here
//!
//! Kernels. A root finder, a sparse matrix-vector product, a quadrature rule
//! or an ODE ensemble lives in its own module (`polynomial/`, `ldu_matrix/`,
//! `krylov/`, `math/`, `ode/`) and takes a [`ComputeBackend`] as a parameter.
//! If you find yourself writing physics or arithmetic in this file, it is in
//! the wrong file.
//!
//! # Hybrid means dispatch, not two APIs
//!
//! A kernel exposes **one** public entry point with the backend as a
//! parameter. It does not grow a `foo_parallel()` sibling beside `foo()`.
//! Callers that do not care let [`select_backend`] resolve one for them;
//! callers that do care name the backend explicitly and get exactly it, or a
//! documented fallback. There is no `Auto` variant — resolution is a function,
//! not a backend.
//!
//! # The serial path is the oracle
//!
//! [`ComputeBackend::Serial`] is always compiled, on every target, under every
//! feature combination, and is the `#[default]`. It is the reference
//! implementation that the other two are checked against, and it is the only
//! one guaranteed to be bit-for-bit reproducible run to run. Verification and
//! validation are judged against it. The other backends are *acceleration*.
//!
//! # Cargo features — both OFF by default
//!
//! | Feature | Adds | Backend enabled |
//! |---|---|---|
//! | *(none)* | — | [`ComputeBackend::Serial`] |
//! | `parallel` | `rayon` | [`ComputeBackend::CpuMulti`] |
//! | `gpu` | `wgpu` (non-Android only) | [`ComputeBackend::Gpu`] |
//!
//! A default build pulls neither dependency, which keeps the crate
//! dependency-light and Android/Termux clean. Requesting a backend whose
//! feature is off is **not an error**: it resolves down to the best available
//! one (see [`ComputeBackend::resolve`]). That way a caller written on a
//! desktop with `--features gpu` still runs, correctly and more slowly, on a
//! phone with no features at all.
//!
//! # Android / Termux
//!
//! `rayon` is pure Rust with no system component, so the `parallel` feature is
//! **not** target-gated — it works on Android. `wgpu` is target-gated off
//! Android in `Cargo.toml`, because Android has no system Vulkan/Metal loader
//! and the workspace Android rule forbids GPU dependencies in a library build.
//! Enabling `gpu` on an Android target therefore yields a build with no GPU
//! backend rather than a broken one.
//!
//! # Planned: hybrid CPU+GPU co-execution (NOT implemented)
//!
//! There is no `Hybrid` variant and no GPU kernel in this crate — see
//! [`gpu_adapter_present`] for the extent of the `wgpu` use. One policy
//! decision for it is nevertheless already settled, because it constrains how
//! the kernels are written.
//!
//! For the **iterative** kernels the shape is *coarse-to-fine*, not a split
//! batch: a GPU `f32` pass produces only the **initial guess**, and the CPU
//! converges it to the final answer at `f64`. The result is therefore entirely
//! `f64` and the `f32` accuracy floors govern the guess, not the answer. This
//! suits batched root finding especially well — [`RootProblem::guess`] already
//! guarantees that a bad guess is a performance problem and not a correctness
//! one, and Newton's quadratic convergence turns an `f32`-accurate start into
//! a `f64` answer in about two iterations.
//!
//! [`RootProblem::guess`]: crate::math::parallel::RootProblem::guess
//!
//! For the **elementwise** kernels, where a batch genuinely is split across the
//! two devices, the CPU half runs `f32` to match the GPU, so that precision is
//! uniform across one output array rather than varying with the split ratio.
//! Those kernels are an `f32`-class throughput path sitting roughly `1e-7`
//! relative from the [`ComputeBackend::Serial`] oracle.
//!
//! Numerical differentiation is excluded from both shapes: a finite difference
//! has no fixed point to converge to, so there is no guess to seed and the
//! `f32` floor would land directly on the answer.
//!
//! Full reasoning, the per-kernel floors at `f32`, the measured iteration
//! savings, and the caveats none of this resolves are in
//! `docs/hybrid-precision-policy.md`.
//!
//! # Units
//!
//! Nothing in this module carries a physical dimension. Sizes are counts of
//! independent work items, which is a pure number. `uom` typing belongs on the
//! kernels' own signatures and must not be stripped to get data onto a device —
//! convert at the buffer boundary and convert back.
//!
// The link definitions below are fully qualified on purpose. `lib.rs` carries
// an outer `///` summary on `pub mod compute;` while this file carries inner
// `//!` docs; rustdoc concatenates the two and resolves the merged block at the
// *crate root*, where the names below are not in scope. Bare `[`ComputeBackend`]`
// therefore fails here even though the type is declared in this very file.
//! [`ComputeBackend`]: crate::compute::ComputeBackend
//! [`ComputeBackend::Serial`]: crate::compute::ComputeBackend::Serial
//! [`ComputeBackend::CpuMulti`]: crate::compute::ComputeBackend::CpuMulti
//! [`ComputeBackend::Gpu`]: crate::compute::ComputeBackend::Gpu
//! [`ComputeBackend::resolve`]: crate::compute::ComputeBackend::resolve
//! [`ThreadCount`]: crate::compute::ThreadCount
//! [`select_backend`]: crate::compute::select_backend
//! [`gpu_adapter_present`]: crate::compute::gpu_adapter_present
use OnceLock;
/// Which execution backend a numerical kernel should use.
///
/// # Variants and what they cost
///
/// - [`Serial`](Self::Serial) — one thread, scalar. Always available. The
/// deterministic trusted reference; bit-for-bit reproducible run to run.
/// - [`CpuMulti`](Self::CpuMulti) — `rayon` across CPU cores. Requires the
/// `parallel` feature. Pays thread-pool overhead, so it loses on small
/// problems; see [`CPU_MULTI_MIN_WORK_ITEMS`]. Reduction order is not
/// generally reproducible unless a kernel says otherwise.
/// - [`Gpu`](Self::Gpu) — `wgpu` compute. Requires the `gpu` feature, a
/// non-Android target, and an actual adapter at run time. Pays a host-device
/// transfer per dispatch, so it needs a much larger problem to win; see
/// [`GPU_MIN_WORK_ITEMS`]. WGSL has no `f64`, so a GPU kernel that computes
/// in `f32` will NOT match the serial `f64` path to full precision — each
/// kernel must document its own measured deviation.
///
/// # Choosing one
///
/// Prefer [`select_backend`] over hand-picking. If you do name a backend,
/// route it through [`resolve`](Self::resolve) so an unavailable choice
/// degrades instead of failing.
///
/// # Units
///
/// Dimensionless — this is a mode selector, not a quantity.
/// The number of work items below which [`ComputeBackend::CpuMulti`] is not
/// worth its thread-pool overhead, and [`select_backend`] returns
/// [`ComputeBackend::Serial`] instead.
///
/// # How this number was chosen
///
/// **It is a placeholder, it has NOT been justified by measurement, and the
/// one kernel family that has since been measured found it far too low.**
/// Bead `op-yvj.4.7` covers the crossover benchmarks that will replace it.
///
/// The failure mode this guards is real and easy to reproduce: spawning
/// threads to add two 50-element vectors is slower than doing it serially.
///
/// # Measured counter-evidence — read before relying on this
///
/// [`crate::fields::parallel`] measured its own crossover on 2026-08-12 (4
/// logical cores, release, `--features parallel`) and found that **at exactly
/// this threshold the parallel path was about 6x SLOWER** — `0.17x` speedup at
/// `n = 4096`, and it lost 10 sweeps out of 10 at every size below 65 536.
/// Those kernels are memory-bandwidth bound at 1-2 flops per element, so
/// thread overhead dominates much further out than it would for compute-dense
/// work. That module therefore overrides this constant at 131 072 via
/// [`crate::fields::parallel::field_parallel_crossover`].
///
/// [`crate::ldu_matrix::parallel`] measured the same day and found the
/// opposite for *its* sparse matrix-vector product: 4096 cells is precisely
/// where that kernel breaks even, so `SPMV_MIN_CELLS` keeps this value. But
/// the vector operations in that same module want `VECOP_MIN_ELEMENTS =
/// 262 144`, because `axpy` at 4096 elements runs at `0.05x` — twenty times
/// slower.
///
/// [`crate::math::parallel`] then measured the opposite direction:
/// batched root finding crosses over at **256** problems, 16x *below* this
/// constant, because it is compute-dense per lane where the field kernels are
/// memory-bound.
///
/// Four kernel families have now been measured and they want **256, 4 096,
/// 131 072 and 262 144** — a 1024x spread, with this constant sitting in the
/// middle and wrong at both ends. That is the real finding: no single
/// crate-wide threshold can be right for all of them.
///
/// Worse for any hope of a universal number: the root-finding crossover
/// depends on the *caller's* residual cost, which this crate cannot know. A
/// cheap residual and an expensive one cross over at different sizes with
/// identical kernel code.
///
/// The honest reading: this constant is a *floor against absurdity*, not a
/// tuned value, and a kernel that has not measured its own crossover should
/// not assume this one is safe for it. Per-kernel overrides are expected, not
/// exceptional.
///
/// # Units
///
/// A count of independent work items (cells, faces, roots, quadrature points),
/// dimensionless.
pub const CPU_MULTI_MIN_WORK_ITEMS: usize = 4_096;
/// The number of work items below which [`ComputeBackend::Gpu`] is not worth
/// the host-device transfer, and [`select_backend`] falls back to the best
/// available CPU backend.
///
/// # How this number was chosen
///
/// **Placeholder awaiting measurement — see [`CPU_MULTI_MIN_WORK_ITEMS`].**
/// It is set an order of magnitude above the CPU-multi threshold because a GPU
/// dispatch pays for a round trip across the PCIe bus in addition to kernel
/// launch, so it needs correspondingly more work to amortise.
///
/// Note that this workspace's own experience argues for caution rather than
/// optimism about GPU wins: beads `op-u6s.8` and `op-u6s.9` record GPU
/// transport work struggling to beat a good multi-threaded CPU path, and
/// `op-u6s.9` is still open.
///
/// # Units
///
/// A count of independent work items, dimensionless.
pub const GPU_MIN_WORK_ITEMS: usize = 65_536;
/// **The** backend-selection policy — one named function, so a reader can find
/// the rule instead of hunting for scattered `if n > 1024` tests.
///
/// # The rule
///
/// Given `work_items`, the number of *independent* items a kernel will process:
///
/// 1. If `work_items >= ` [`GPU_MIN_WORK_ITEMS`] and the GPU is available, use
/// [`ComputeBackend::Gpu`].
/// 2. Otherwise if `work_items >= ` [`CPU_MULTI_MIN_WORK_ITEMS`] and the
/// `parallel` feature is on, use [`ComputeBackend::CpuMulti`].
/// 3. Otherwise use [`ComputeBackend::Serial`].
///
/// # Arguments
///
/// - `work_items` — count of independent work items (cells, faces, roots,
/// quadrature points). Dimensionless. Pass the honest count: passing a
/// matrix's row count when the kernel actually loops over its faces will
/// pick the wrong backend.
///
/// # Returns
///
/// A backend that is guaranteed available, so the caller may use it directly
/// without a further [`ComputeBackend::resolve`].
///
/// # Why a caller might not use this
///
/// Benchmarks and parity gates need to run a *named* backend regardless of
/// size — that is what [`ComputeBackend::resolve`] is for. This function is
/// for production callers that just want the fastest correct option.
///
/// # Example
///
/// ```
/// use outram_foam_basic_lib::compute::{select_backend, ComputeBackend};
///
/// // A tiny problem always runs serially, whatever features are enabled.
/// assert_eq!(select_backend(16), ComputeBackend::Serial);
///
/// // Whatever it picks for a large problem is guaranteed to be runnable.
/// assert!(select_backend(1_000_000).is_available());
/// ```
/// How many worker threads [`ComputeBackend::CpuMulti`] should use.
///
/// Mirrors the established shape in `boon-lay`'s and `outram-mc-libs`'s own
/// compute modules so the workspace has one vocabulary for this rather than
/// three.
///
/// # Units
///
/// Dimensionless counts. [`Fraction`](Self::Fraction) is a pure ratio.
/// Cached answer to "is there a usable GPU adapter on this machine?", so the
/// probe runs at most once per process.
static GPU_PRESENT: = new;
/// Whether a usable GPU compute adapter exists, probed once and cached.
///
/// # Behaviour
///
/// - Without the `gpu` feature, or on Android, this is `false` with no probe
/// attempted.
/// - Otherwise it asks `wgpu` for an adapter, once. `false` is a normal
/// outcome — headless CI, a container, a machine with no discrete GPU — and
/// is **not** an error. Nothing here panics or returns `Err`.
///
/// # Returns
///
/// `true` only if a GPU kernel could actually be dispatched.
/// The one-shot probe behind [`gpu_adapter_present`] — Android and
/// feature-disabled builds.
/// The one-shot probe behind [`gpu_adapter_present`] — desktop builds with the
/// `gpu` feature.
///
/// Requests a headless adapter (no surface, so no display handle is needed).
/// A failure is reported as `false`, never as a panic.
/// A minimal thread-parking executor, so probing for an adapter does not drag
/// an async runtime into this crate.
///
/// Mirrors the same device in `njoy-outram-park-fork`'s `gpu.rs`; kept private
/// because it exists only to make one `wgpu` call blocking.
/// Data-level co-execution: split one batch between the CPU and the GPU.
///
/// A selection policy over the existing backends, not a fourth backend. Always
/// compiled — with no GPU available it plans every lane onto the CPU, which is
/// the correct answer rather than a degraded one.
/// The `wgpu` device context and the shared kernel-dispatch helper.
///
/// Present only when the `gpu` feature is on and the target is not Android —
/// the same gate `wgpu` itself is under. Every GPU kernel in the crate reaches
/// the device through [`gpu::GpuContext::dispatch`].