diff --git a/.github/workflows/benchmark-pr.yml b/.github/workflows/benchmark-pr.yml index 1dfb4fd..4a6c06f 100644 --- a/.github/workflows/benchmark-pr.yml +++ b/.github/workflows/benchmark-pr.yml @@ -11,15 +11,25 @@ jobs: bench: runs-on: ubuntu-latest strategy: + fail-fast: false matrix: julia-version: ["1.10", "1.11", "1.12"] steps: - uses: actions/checkout@v4 + with: + fetch-depth: 2 + + - name: Identify the tested baseline + id: revisions + # The merge parent is the actual PR baseline, even for develop targets. + run: echo "base=$(git rev-parse HEAD^1)" >> "$GITHUB_OUTPUT" - name: Run AirspeedVelocity benchmark uses: MilesCranmer/AirspeedVelocity.jl@action-v1 with: julia-version: ${{ matrix.julia-version }} - bench-on: "head" # keep if you already had it + rev: "${{ steps.revisions.outputs.base }},${{ github.event.pull_request.head.sha }}" + bench-on: "head" script: "benchmark/benchmarks.jl" - extra-pkgs: "JSON,SimpleChains,OrdinaryDiffEqTsit5,Integrals,ADTypes,DataInterpolations,DifferentiationInterface,FastGaussQuadrature,ForwardDiff,Mooncake,Zygote,SciMLSensitivity" + # AirspeedVelocity creates its own environment, not benchmark/Project.toml. + extra-pkgs: "JSON,SimpleChains,OrdinaryDiffEqTsit5,Integrals,ADTypes,DataInterpolations,DifferentiationInterface,FastGaussQuadrature,ForwardDiff,Mooncake,Zygote,SciMLSensitivity,Reactant" diff --git a/BENCHMARK_BSPLINE_CANDIDATE.md b/BENCHMARK_BSPLINE_CANDIDATE.md new file mode 100644 index 0000000..841b1e7 --- /dev/null +++ b/BENCHMARK_BSPLINE_CANDIDATE.md @@ -0,0 +1,87 @@ +# ACE coefficient candidate: Narval paired benchmark + +2026-10-20. **Performance evidence, not implementation acceptance.** +Independent numerical/AD and full-suite regression review is complete; two +harness/provenance findings remain in `REVIEW_BSPLINE_STAGE_AB.md`. The main reviewer independently +reran all **5,718 focused tests successfully**, with four Julia threads and +`--check-bounds=yes` (48.8 seconds). These include prepared Mooncake/ForwardDiff, +live geometry, nonfinite fallback, malformed factors and concurrent plan use. +The implementer's full suite had +7,706 passes and the same five Reactant Akima failures seen in its baseline; +the main reviewer's full `Pkg.test()` independently reproduced 7,706 passes, +the same five Reactant Akima failures, and zero errors in 15m22.5s. All B-spline +test groups passed. This is not a green full package suite. + +## Provenance and coverage + +Warm setup 6581055 and measurement job **6581056** both completed with exit 0. +All measured cases ran on **nc10439**, one CPU thread, using candidate source +SHA256 `3cda5698898ca8eefa7437d937f266a8a325dd081450ff515d4788cc824b7af0`. +The loaded ACE path and source hash were asserted inside the job. + +The existing candidate benchmark freezes the original af79449 band solver +under separate functions; that reference does not call optimized helpers. +Each case runs baseline/new/new/baseline, 30 BenchmarkTools samples per trial, +evals=1, up to five seconds. Public new coefficient timings include structural +classification, allocation, copying and nonfinite guards. Preparation excluded. +Transpose timings are factor-transpose solves, **not full prepared gradients**. + +Independent dense forward/transpose checks passed at all six production counts +before timing, and each batch was also checked against the frozen old solver. +Post-run verification confirmed all four result files marked complete, expected +case coverage, **80 paired trials each with 30 finite samples**, plus two +30-sample Chebyshev-161 references. Campaign metadata is marked complete. + +## Float64 forward, 8,192 RHS columns + +Minimum milliseconds over the two repetitions of each algorithm: + +| N | Old ms | New ms | Speedup | +|---:|---:|---:|---:| +| 33 | 4.70050 | 2.16578 | 2.170× | +| 49 | 7.05966 | 3.34441 | 2.111× | +| 65 | 9.27130 | 4.48735 | 2.066× | +| 81 | 11.52226 | 5.66963 | 2.032× | +| 97 | 13.83826 | 6.86084 | 2.017× | +| 128 | 18.42069 | 9.09581 | 2.025× | + +## Float64 transpose solve, 8,192 RHS columns + +| N | Old ms | New ms | Speedup | +|---:|---:|---:|---:| +| 33 | 4.02212 | 2.26669 | 1.774× | +| 49 | 6.06880 | 3.45792 | 1.755× | +| 65 | 8.08314 | 4.63018 | 1.746× | +| 81 | 10.10325 | 5.89411 | 1.714× | +| 97 | 12.22342 | 7.19688 | 1.698× | +| 128 | 15.97574 | 9.35481 | 1.708× | + +## Controls and limitations + +Float32 N65 controls, RHS counts 1,7,32,8192: forward speedups respectively +1.275×, 2.176×, 2.279×, 2.325×; transpose 1.320×, 1.799×, 1.891×, 1.929×. +These sampled controls do not establish performance for every dtype/layout. + +Chebyshev-161 reference minimum/median: start 11.2374/12.0328 ms; end +10.7239/11.3017 ms. Reference minima span approximately 4.79%, so do not +overinterpret small differences against that reference. The approximately +2× old/new gain is from interleaved paired measurements on the same node, +not a comparison with earlier jobs or different hardware. + +No Cℓ accuracy, complete likelihood, or AD speedup is certified here. +No SIMD, reciprocal or multithreading optimization is part of this candidate. + +Raw outputs, relative to this checkout: +`../bspline_backend_validation/ace_candidate_results_6581056/` contains +`campaign.toml`, `production/`, `controls/` and the full `logs/`. Each trial +records raw times, medians, allocation counts/bytes and source provenance. +The deployed runner and batch script live under the corresponding external +validation directory; cluster campaign is +`/project/6033532/mbonici/blast_bspline_tilde_banks_20261019/ace_candidate_bench_20261020_2100`. + +Failed first setup **6578874** hit its ten-minute walltime; its dependent +measurement **6578876** was cancelled without producing timings. Resolution +finished late, and exact import delay was not isolated. The warm setup skipped +resolution, added flushed progress checkpoints and had a 20-minute limit; +measurement retained its separate ten-minute limit. Failure logs and original +batch script were preserved, not replaced by successful results. diff --git a/BENCHMARK_BSPLINE_STAGE1.md b/BENCHMARK_BSPLINE_STAGE1.md new file mode 100644 index 0000000..62b6466 --- /dev/null +++ b/BENCHMARK_BSPLINE_STAGE1.md @@ -0,0 +1,157 @@ +# B-spline Stage 0 + Stage 1: cached factorization in plan pullbacks + +2026-10-22, branch `96-b-spline`, base `3f27573` (equal to `origin/96-b-spline`). +Plan: `OPTIMIZATION_BSPLINE_NEXT_STEPS.md` §4, Stages 0 and 1 only. Uncommitted +working-tree candidate awaiting independent review; nothing committed or pushed. +Raw logs, TOMLs and scripts: `benchmark/reviewer_logs/stage1/`. + +## Change + +| File | Purpose | +|---|---| +| `src/chainrules.jl` | `_collocation_geometry_vjp(spline, c̄, fact)` takes a factorization; the 2-argument method rebuilds it for ordinary splines, as before. ChainRules coefficient and plan-evaluation rules pass `plan.factorization`. | +| `ext/MooncakeExt/MooncakeExt.jl` | Native `_bspline_coefficients` and `_apply_cubic_b_spline_plan` primitives pass `plan.factorization`. | +| `test/test_cubic_b_spline_plan_pullback.jl`, `test/runtests.jl` | 340 new focused tests, included unconditionally. | +| `benchmark/bench_bspline_coefficients.jl` | New `pullback` mode: Mooncake and Zygote, strict 30-sample gate. Existing modes unchanged. | + +`src/cubic_b_spline.jl` is unchanged (SHA256 `3cda5698…`). Solve arithmetic, +Λ = A⁻ᵀC̄ / Ā = −ΛCᵀ local contraction, not-a-knot mapping, projection, +zero-cotangent handling and all site/knot/query cotangents are unchanged. +The ordinary-spline construction rules still rebuild their factorization. +There is no new cache, mutable state, instrumentation or API change. + +## Stage 0 baseline run and source verification + +`JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 julia --project= -e 'using Pkg; Pkg.test()'` + +- 7,706 passed, **5 failed**, 0 errors (log `baseline_full_pkgtest.log`). +- All five failures are the Reactant Akima fallback assertions at + `test/test_ext_reactant.jl:659` (×3, nonfinite compiled gradients) and `:662` + (×2). They have the same locations and class as `benchmark/reviewer_logs/full_pkgtest.log`. + This is a pre-existing failure, **not a green suite**. +- An early candidate edit was on disk for 24 s while this run was still + precompiling dependencies. It was reverted before the test process loaded ACE. + The ACE test cache was rebuilt at 13:35:33 from pristine source (SHA `b8a3…`). + +## Candidate tests + +**Focused** (existing benchmark env, ACE path asserted to be this checkout, +`--check-bounds=yes -t 4`, BLAS 1). `ChainRulesCore` is made resolvable only +by stacking ACE's Project.toml, and the runner asserts it is ACE's module: + +``` +JULIA_LOAD_PATH="$ROOT/benchmark:$ROOT:@stdlib" OPENBLAS_NUM_THREADS=1 \ + julia --project=$ROOT/benchmark --check-bounds=yes -t 4 \ + benchmark/reviewer_logs/stage1/focused_runner.jl +``` + +- New file alone: 340/340 passed. Focused set (new file plus existing AD, + host solver, abstract inputs, plan and gaps): **6,341/6,341 passed**. +- **Mutation check:** the new file run against the frozen `3f27573` snapshot + fails exactly the 96 reuse assertions: 12 configurations × 2 losses × + {Zygote, Mooncake} × 2. The 2 errors are calls to the new method. Its + ForwardDiff/dense-forward checks and all other groups pass. Log: + `mutation_check_new_tests_on_baseline_3f27573.log`. + +**Full candidate `Pkg.test()`** (same command): **8,046 passed, 5 failed, +0 errors** (7,706 + 340 new). The failures are the same five Akima assertions +(`:659` ×3, `:662` ×2). Every pre-existing group has the same pass count. +No new failure. Log: `candidate_full_pkgtest.log`. + +## What the new tests establish + +- **Reuse occurs, through public paths.** A test plan keeps its sites, basis + and stencil but stores a factor of moved sites, A_m. Zygote and Mooncake + gradients of `bspline_coefficients(plan,u)` and `plan(u)` equal dense + A_mᵀ\G (≤1e-11) and ForwardDiff. Rebuilt-factor answers differ by >1e-4. + Covered: N=7/17, vector and M=1/3, `:clamp`/`:zero` with outside queries. +- **Default plans match the old path bitwise.** For ChainRules coefficient and + evaluation pullbacks, u, site and query cotangents are `==` to the rebuilding + implementation. Mooncake matches to rtol 1e-14. +- **Ordinary-spline fallback:** 2-argument == 3-argument with a rebuilt factor. + Zygote/Mooncake ordinate and site gradients agree with ForwardDiff. +- **Live geometry:** site and query gradients of coefficient and evaluation + losses agree with ForwardDiff for both backends. Coefficient query + gradients are exactly zero. A plan passed as an argument receives + site/query cotangents (Zygote `.sites`, Mooncake `.fields.sites`), so it is not frozen. +- Zero/No tangents return the existing types, and numeric zero cotangents give + zeros. Cotangents, inputs and every plan field (including LU bands) are unchanged. + Views flow back to parent arrays, and Float32 plans with Float64 ordinates work. +- Prepared A/B/A reuse (bitwise repeat) and interleaved preparations pass for both backends. +- N=81, M=256 versus dense transpose (≤1e-10) and ForwardDiff directional checks. +- Eight tasks, running under four Julia threads, each use an independent + prepared gradient on one shared plan. The + results are bitwise equal to serial and the plan is unmodified. Both backends. + +## Benchmark (Alcanter, i7-13700H) + +`bash benchmark/reviewer_logs/stage1/run_alternating_pullback.sh 2` +runs fresh processes in order baseline, candidate, baseline, candidate. All are +`taskset -c 4` (P core), with 1 Julia/BLAS/GC thread. The baseline is a +`git archive 3f27573` snapshot env in +`../bspline_backend_validation/stage1_baseline_3f27573/`. Its Manifest is +byte-identical except the ACE path. No method replacement is used. + +Each process loads packages, then compiles, prepares and passes correctness +gates (dense ≤1e-10 for input gradients; ForwardDiff directional ≤1e-7 for +live sites). It cools to 52 °C in-process and runs BenchmarkTools with +`evals=1`, interpolated arguments and exactly 30 samples (enforced). All cells +completed: 24 per baseline process and 26 per candidate process. Full table: `bench/comparison.md`. + +**Work/allocation evidence (deterministic, both rounds):** every plan-based +gradient cell drops **3 allocations and 4,632 bytes**. This holds for +Mooncake and Zygote, coefficients and evaluation, input-only and live sites, +and M=7 and M=8192. An in-process control, rebuild VJP 10 allocs/10,736 B +versus reuse 7/6,104 B, shows the same delta. The removed factor build costs +~3.2–4.1 µs (N=81). + +Prepared hot-gradient medians, N=81 (ratio = mean candidate / mean baseline): + +| Cell | Baseline r1/r2 ms | Candidate r1/r2 ms | Ratio | +|---|---|---|---| +| M7 coeff input, Mooncake | 0.0280/0.0274 | 0.0278/0.0244 | 0.94 | +| M7 coeff input, Zygote | 0.0250/0.0258 | 0.0225/0.0226 | 0.89 | +| M7 eval input, Mooncake / Zygote | 0.049/0.047, 0.046/0.048 | 0.044/0.043, 0.043/0.044 | 0.91 / 0.92 | +| M7 live sites, coeff/eval, Mooncake | 0.045, 0.066 | 0.043, 0.064 | 0.95 / 0.98 | +| M7 live sites, coeff/eval, Zygote | 0.035, 0.070 | 0.033, 0.067 | 0.92 / 0.96 | +| M8192 coeff input, Mooncake / Zygote | 13.96/14.31, 12.04/12.05 | 14.16/14.07, 12.06/12.00 | 1.00 / 1.00 | +| M8192 eval input, Mooncake / Zygote | 28.47/29.03, 26.28/26.33 | 29.17/28.47, 26.34/26.35 | 1.00 / 1.00 | +| M8192 live sites coeff, Mooncake / Zygote | 13.68/14.14, 12.09/12.07 | 14.17/13.95, 11.99/12.11 | 1.01 / 1.00 | +| M8192 live sites eval, Mooncake / Zygote | 27.76/28.42, 26.46/26.39 | 27.61/27.77, 26.40/26.45 | 0.99 / 1.00 | + +Interpretation: + +- **M=7:** a reduction in every cell, ~1.5–5 µs, of the size of the removed + factor build. Some cells drift more than 5% between same-revision + rounds: baseline ChainRules coefficient pullback 8%, candidate Mooncake + coefficient input 14%. So individual percentages are indicative, not precise. +- **M=8192:** no measurable change. All ratios are 0.986–1.011, within the + ≤3.4% same-revision drift. No control regression above 5%. This matches the + audit: factor construction is not the large-batch hotspot. This + housekeeping change does not deliver a large-batch speedup. +- **Setup is reported separately.** The first Mooncake `prepare_gradient` in a + fresh process took ~15.6 s, and the first Zygote gradient ~4.0 s. Both are + identical between revisions and measured after package load. They are + in-process first-call costs, not total cold-start time. Process wall time + was 1:34–1:40 including ~35 s cooling. Hot Mooncake re-preparation at + M=8192 took 13.6–34 ms (min of 3; noisy). Package load/precompile is excluded. +- **Thermal caveat:** cells ran at 65–91 °C (cooled to 52 °C first; heating is + fast on one turbo P core). Ranges were matched across revisions (M=8192 mean + start 78–81 °C). Do not compare these numbers with the audit's or Narval's. + +## Independent review and remaining gates + +Main-agent review is recorded in `REVIEW_BSPLINE_STAGE1.md`: its own focused run +passed 6,341/6,341 and its own full suite reproduced 8,046 passes and the exact +same five baseline Akima failures, with zero errors. Raw sample coverage, +source hashes and all 32 paired gradient allocation deltas were independently +checked. Stage 1 is accepted locally; the package suite remains non-green. + +- Other Julia/platform CI configurations have not been checked locally. +- Stage 2+ (reduction locality, retained intermediates, threading, SIMD, + reciprocals, frozen geometry, workspaces): not started, by design. +- Existing `forward`/`transpose`/`gradient` driver modes were not re-run, and + their `bench` still only warns on short coverage (review P2-2). The strict + gate covers only the new `pullback` mode. P2-1 (fixture-generator + provenance) is untouched. +- Only N=81 was benchmarked. Other production N and Float32 timing were not. diff --git a/BENCHMARK_BSPLINE_STAGE2A.md b/BENCHMARK_BSPLINE_STAGE2A.md new file mode 100644 index 0000000..30bbf5d --- /dev/null +++ b/BENCHMARK_BSPLINE_STAGE2A.md @@ -0,0 +1,262 @@ +# B-spline Stage 2a: column-streaming collocation geometry reduction + +2026-10-22, branch `96-b-spline`, base `3f27573` plus the accepted Stage 1 +working tree. Uncommitted candidate for independent review; nothing staged, +committed or pushed. Raw logs, TOMLs and scripts: `benchmark/reviewer_logs/stage2/`. + +## Change + +| File | Purpose | +|---|---| +| `src/chainrules.jl` | `_streamed_collocation_geometry!` (one helper, ~75 lines with its derivation) plus a 3-line call at the top of the 3-argument `_collocation_geometry_vjp`. `_cubic_basis_vjp` is split into `_cubic_basis_jets` (geometry only) and `_contract_cubic_basis_jets`, with the same operations in the same order. | +| `test/test_cubic_b_spline_streamed_geometry.jl`, `test/runtests.jl` | 316 new tests, included unconditionally. | +| `test/reference/bspline_adaptive_sites/` | Byte copies of the saved adaptive design k grids N81/N97/N129, with SHA256s. | +| `benchmark/bench_bspline_coefficients.jl` | New `stage2` mode. Earlier modes are unchanged. | + +Unchanged: the public API, Mooncake/ChainRules rule bodies, `src/cubic_b_spline.jl` +(SHA `3cda5698…`), band solves, cached-factor reuse, not-a-knot mapping, +projection, the Reactant extension and its Enzyme tests, and dependencies. There +are no threads, `@simd`, `@fastmath`, `muladd`, reciprocals, workspaces or global state. + +## What changes numerically + +The mathematics is unchanged: Λ = A⁻ᵀC̄ comes from the same factor (and is +returned bit-for-bit as before). Per site i there are four local entries +`values_bar[k] = -Σ_s Λ[i,s] C[j0(i)+k-1, s]`, contracted with the local basis +partials, with the same knot accumulation. Only the summation order of those +entries changes: + +- Previously: 4n strided BLAS `dot`s. +- Now: one pass over the columns s (contiguous Λ[:,s], C[:,s]) into 4×n + accumulators, using plain multiply-then-add. + +**Eligibility:** +- dense same-type `Float64` (`Matrix` coefficients, cotangent and Λ, plus + `Vector` sites and knots); +- M ≥ `_STREAMED_GEOMETRY_MIN_COLUMNS` = 512; +- contiguous in-range local rows. + +Everything else runs the previous loop unchanged: vectors, Float32, mixed types, +BigFloat, views and M < 512. The threshold is conservative: the pilot measured +M = 7 slower and M = 256 too noisy to judge. + +## Nonfinite and overflow contract (derivation) + +Notation: u = eps/2. A[k,i] = fl Σ_s fl(|fl(λc)|), accumulated in the same +pass. D[i,k,d] are the seven jet partials of local basis k at site i +(∂/∂x and ∂/∂ six knots). D depends only on geometry, and both orders compute +it with identical Float64 operations. The computed bound is + + G = Σ_i Σ_k A[k,i] · (1 + Σ_d |D[i,k,d]|). + +The streamed result is accepted only if G is finite and G ≤ floatmax/2. +Otherwise the outputs are re-zeroed and the **original reduction runs on the +already computed Λ** (no second transpose solve). That gives bit-for-bit the +previous output, including its NaN/Inf pattern. + +Why the accepted case is safe, for either summation order: + +1. **Reduction.** Every intermediate of any summation tree of the M rounded + products is at most (1+u)^M · S in magnitude, where S = Σ_s|λc| exact. This + includes BLAS multi-accumulator blocking and fused multiply-adds, since an + FMA's exact result is bounded by |ab| + |c|. A ≥ S(1−u)^M − (underflow) gives + S ≤ A(1−u)^{−M} + tiny. +2. **Contraction.** Each of the 7 outputs is ((vb₁D₁ + vb₂D₂) + vb₃D₃) + vb₄D₄. + Its intermediates are at most (1+u)^4 Σ_k |vb_k||D_k|, and the discarded + `.value` part is at most Σ_k |vb_k|. +3. **Knot accumulation** sums at most n local contributions per knot, giving a + factor (1+u)^n. +4. **The callers' not-a-knot mapping** adds at most five of these outputs + together; its pairwise `sum` is still a summation tree. + +Every such quantity is bounded by a sub-sum of the terms in G. Computing G +itself (32n nonnegative terms) loses at most a factor (1−u)^{32n+2}. The total +growth ((1+u)/(1−u))^K has K < 2M + 34n ≤ 2^42; `M ≤ 2^40` and `n ≤ 2^35` are +checked. That keeps the growth below exp(2^−10) < 1.001. Gradual-underflow +absolute errors total less than K·η·max(1,|D|) ≤ 2^−8, which is irrelevant +next to floatmax. + +Hence G ≤ floatmax/2 implies that no operation in either order reaches +floatmax. With finite operands and no overflow, none of these operations can +produce NaN: they contain no division, and 0·Inf and Inf−Inf need an Inf. So +both orders return all-finite results. + +Conversely, any NaN or ±Inf in a used entry of Λ or C, or in D, makes G +nonfinite (NaN propagates, Inf·0 = NaN, Inf·x = Inf). Such inputs always take +the original routine. + +**Contract.** For every input, `_collocation_geometry_vjp` and its not-a-knot +mapping return either: +- exactly the previous result (ineligible or unsafe inputs); or +- all-finite results that are also all-finite in the previous order, differing + only by reordered rounding within (M+16)·eps·Σ|λc| per local entry, propagated + through |D|. + +**Not covered** are external accumulations outside this function. Examples are +the evaluation-VJP site cotangent added in plan evaluation, and AD-framework +tangent accumulation with unrelated values near floatmax. There, any change in +rounding can move a sum across the overflow threshold. The previous BLAS order +is itself CPU-kernel dependent, so it was never a platform-stable reference +near floatmax. + +floatmax/2 is not a heuristic margin. Any constant below floatmax/1.001 would +do; 1/2 is chosen for clarity. The pilot's 2^−64 and 2^−8 margins are not used. + +## Validation + +**Focused** (benchmark env, ACE path and `ChainRulesCore` identity asserted, +`--check-bounds=yes -t 4`, BLAS 1): + +``` +JULIA_LOAD_PATH="$ROOT/benchmark:$ROOT:@stdlib" OPENBLAS_NUM_THREADS=1 \ + julia --project=$ROOT/benchmark --check-bounds=yes -t 4 \ + benchmark/reviewer_logs/stage2/focused_runner.jl +``` + +- New file alone: 316/316 (`focused_new_file_attempt1.log`). +- New file plus Stage 1, AD, host solver, abstract inputs, plan and gaps: + **6,657/6,657** (`focused_candidate.log`). + +**Mutation check** (disposable process; modified copies of the production +helper from the source text): both mutants are detected +(`mutation_check.log`). Removing the guard fails 15 assertions; skipping the +re-zeroing before fallback fails 5. The first attempt aborted after the first +mutant because of a harness try/catch omission; its log is kept. + +**Full candidate `Pkg.test()`** +(`JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 julia --project= -e 'using Pkg; Pkg.test()'`): +**8,362 passed, 5 failed, 0 errors**, which is 8,046 plus the 316 new tests. +The failures are the known Reactant Akima assertions +`test_ext_reactant.jl:659` (×3) and `:662` (×2). Every pre-existing group has +the same count. A concurrent Blast test job was running, so the 20:03 wall time +is not comparable. Log: `candidate_full_pkgtest.log`. + +**Cross-revision bitwise digests** (`bitwise_digest.jl` run in the frozen +Stage 1 env and in the candidate env; `compare_digests.py`): +- All **64 cases expected unchanged are bitwise identical**. They cover all + ordinate gradients (Λ), evaluation and query gradients through the refactored + local basis VJP, every M ∈ {1, 7, 256, 511} path, Float32, mixed types, view + cotangents, vectors, NaN and 1e306 cotangents, and ordinary splines. +- The 16 cases expected to change (site gradients and VJPs at M = 512 and + M = 8192) differ. Output: `digests/comparison.txt`. + +**What the new tests cover:** + +- **Fast branch actually taken.** The VJP is bitwise equal to an independent + sequential column-order oracle. The ChainRules rule and the Mooncake + plan-argument tangents equal the mapped oracle bitwise. The helper's return + value is checked directly; there is no instrumentation. Cases include N=4–7, + 17, adaptive log-k N81/N97, raw-k N81 (min Δk 7.6e−6) and M=512/1031, plus + ordinary splines and N129 at M=8192. +- **Exact fallbacks.** M ∈ {1, 7, 256, 511}, vector, view cotangent, view + coefficients, Float32, mixed and BigFloat are each `isequal` to a verbatim + copy of the previous routine, and inputs are unmodified. +- **Cancellation-aware BigFloat checks.** Every local entry is within + (M+16)·eps·Σ|λc| + 2Mη of the exact sum. Site and knot outputs, both new and + previous, are within that bound propagated through |D| of the exact reduction + pushed through the same assembly. Cases: N=4–7, 17, adaptive log-k N81 and + raw-k N81. For N81/97/129 (log-k and raw-k) at M up to 8192, new and previous + are compared by a pair bound, with BigFloat on 12 sampled sites. No full + BigFloat matrices are built at those sizes. +- **Extremes.** + - Strongly cancelling 1e298-scale products and 1e290 cotangents stay + streamed, finite and within bounds. + - 1e306 cotangents, overflowing products, NaN/±Inf in the cotangent or + coefficients, and Inf·0 all fall back with `isequal` results, with the NaN + pattern checked. + - A synthetic order-dependent overflow (sequential partial sums exceed + floatmax although the exact sum is 0) is rejected. + - Subnormal products, zero cotangents, and knot gaps of 1e−6 and 1e−9 are + covered. +- **Public gradients.** + - Zygote and Mooncake against full ForwardDiff for N=4–7 at M=512: plan and + ordinary-spline coefficients and evaluation, with ordinates, sites and + outside-domain queries. + - Adaptive log-k N81 (M=8192), N97 (M=1024) and N129 (M=8192): input-only + gradients against dense Aᵀ\G and Aᵀ\(SᵀW) (≤1e−10) and ForwardDiff + directional derivatives; live-site directional checks (rtol 1e−8) for + coefficients and evaluation in both backends. +- **Reuse and concurrency.** A/B/A preparations for both backends (input-only + and live sites, bitwise repeat), input and plan ownership, and eight + independent tasks with separate preparations on one shared plan. + +## Benchmark + +First matched run completed in four fresh processes (baseline, candidate, +baseline, candidate), 31 cells per process and 30 raw samples per cell. +All 124 cells and candidate source hashes were independently verified. +Both environments have identical dependency manifests except for the ACE path. +Each process compiled first, then cooled to 52 C; timings used CPU4 with one +Julia/BLAS/GC thread. Raw data: `benchmark/reviewer_logs/stage2/bench_main/`. + +Stable public prepared coefficient-gradient medians, N129 x 8192: + +| Backend / differentiated input | Stage 1, ms | Stage 2a, ms | Time reduction | +|---|---:|---:|---:| +| Mooncake / ordinates | 25.676 | 19.904 | 22.5% | +| Zygote / ordinates | 20.675 | 14.884 | 28.0% | +| Mooncake / live sites | 24.516 | 18.423 | 24.9% | +| Zygote / live sites | 20.711 | 14.834 | 28.4% | + +These are synthetic public coefficient-loss gradients, not Blast likelihood +or NUTS timings. Same-revision median drift in these cells is below 4%. +N81/N129 geometry VJP median ratios are 0.581/0.560 relative to Stage 1. + +Extra allocation per gradient is 8 small allocations, 6,128 bytes at N81 and +9,616 bytes at N129. Float32 median controls change by approximately +0.9% +(Mooncake) and +0.4% (Zygote), with unchanged allocation counts/bytes. + +**Unresolved timing cells:** several N81 coefficient medians and the N81 +Mooncake vector control are bimodal and drift by 14-34%; N129 Mooncake +evaluation-input medians drift by 5.4%. N81/M1024 Mooncake's average median +appears 6.5% slower despite repeatable, faster minima. Do not interpret these +medians as certified gains or regressions. Their minima are much more stable, +but the first run did not record per-sample GC times. A targeted normal-GC +and explicitly GC-isolated diagnostic is pending; all original samples remain +preserved. GC is a hypothesis to check, not an established root cause. + +## Main-agent independent review + +`REVIEW_BSPLINE_STAGE2A.md` records the independent checks. Main repeated the +focused suite (6,657/6,657) and full `Pkg.test()` (8,362 passes, the exact five +baseline Akima failures, zero errors). Source/dependency snapshot identity and +text-grid provenance were checked separately. The benchmark now reads the +checked-in grid fixtures rather than a private absolute filesystem path. + +The targeted diagnostic is retained under +`benchmark/reviewer_logs/stage2/gc_main/`; its qualified disposition follows. + +## Final disposition and GC diagnostic + +**Stage 2a is accepted locally**, with bounded performance claims. The complete +124-cell primary campaign, independent correctness tests and stable N129 public +coefficient-gradient gains support acceptance. N81 minimum timings also repeat +closely and improve, but its normal-GC medians are not certified. This is not a +claim that every shape, allocation pattern or downstream model is faster. + +The targeted diagnostic recorded both ordinary sampling and sampling with +`gcsample=true` (collection outside each timed call). Three processes completed; +the fourth hit the 900-second campaign limit after 11 of 16 cells. Thus **59/64 +diagnostic cells were recorded; the campaign is incomplete**. The final artifact +retains `complete=false`; none of the five missing cells is inferred. This +diagnostic does not replace the complete primary campaign. + +Important findings: + +- **GC does not explain the bimodality.** Vector, M512 and M1024 timed calls + exhibit it with zero timed GC. Large batches have occasional sub-millisecond + GC samples, insufficient to explain the observed multi-millisecond modes. + The underlying hardware/runtime cause remains unproven. +- GC-before-each-sample changes the measurement regime and can change cache or + CPU state. It is a hot-kernel diagnostic, not operational inference latency. +- Both recorded Mooncake M512 GC-isolated medians improve: Stage 1 + 0.922/0.907 ms versus candidate 0.842/0.844 ms. At M1024 they are + 1.697/1.690 ms versus 1.577/1.571 ms. The earlier apparent M1024 median + regression is not reproduced in these matched diagnostic cells. +- N81/M8192 in the primary run has stable minimum timings: Mooncake + 14.924 to 11.521 ms (22.8% reduction), Zygote 11.844 to 8.716 ms (26.4%). + Do not reinterpret these minimum-time results as stable normal-GC medians. + +No performance claim is made for missing diagnostic cells. Further work on +laptop timing stability is deferred; there is no exclusive CPU job left queued. +Cross-platform CI and downstream Blast likelihood timing remain separate gates. diff --git a/BENCHMARK_BSPLINE_STAGE3.md b/BENCHMARK_BSPLINE_STAGE3.md new file mode 100644 index 0000000..9df9bb8 --- /dev/null +++ b/BENCHMARK_BSPLINE_STAGE3.md @@ -0,0 +1,548 @@ +# Stage 3: unified `set_threads` and budget-aware host column solves + +2026-10-22, branch `96-b-spline`, base `3f27573` plus the accepted Stage 1 and +Stage 2a working tree. Unified API, correctness, scoped host-kernel timing and +real-bank theory-path scientific and supported Linux-version gates independently +accepted with the known failures/skips below. Downstream cooled-call measurements +are complete with the explicitly qualified thermal/control observations below; +no sustained-throughput or universal latency guarantee is made. +Nothing staged, committed or pushed. +Logs, raw TOMLs and scripts: +`benchmark/reviewer_logs/stage3/`. Approved design: `BSPLINE_THREADING_API_DESIGN.md`. + +## Change + +| File | Purpose | +|---|---| +| `src/threads.jl` (new) | Defines `set_threads(n)`, the deprecated `set_fft_threads` forwarder, the atomic host budget and `_host_thread_budget()`. | +| `src/AbstractCosmologicalEmulators.jl` | Exports `set_threads`; includes `threads.jl`; drops the old FFT-only setter body. | +| `src/cubic_b_spline.jl` | The host column driver splits independent columns into contiguous blocks run by `Threads.@spawn` tasks. It adds `_solve_host_column_block!` and `_host_column_tasks`. | +| `test/test_threads.jl` (new), `test/runtests.jl` | 266 tests (267 under `--depwarn=yes`), included unconditionally. | +| `test/test_chebyshev.jl` | The FFTW test now uses `set_threads`, checks FFTW's count, covers the deprecated forwarder, and restores both settings. | +| `README.md` | New "Threads" section. | +| `benchmark/bench_bspline_coefficients.jl` | New `stage3` mode. Other modes are unchanged. | +| `BSPLINE_THREADING_API_DESIGN.md` | Status line only. | + +Unchanged: +- `src/chainrules.jl` (`d6afc8d2…`) and `ext/MooncakeExt/MooncakeExt.jl` (`5f031466…`): no AD changes were needed. +- The Reactant extension, dependencies, Manifest and version, and BLAS settings. +- Plan layout, per-call signatures, within-column recurrences, factor + classification, Stage 2a geometry arithmetic, tolerances and physics inputs. + +## Semantics + +- `set_threads(n::Integer)` validates 1 ≤ n ≤ `typemax(Cint)`, FFTW's own limit, + before any side effect. Otherwise it throws `ArgumentError` with both settings + untouched. It then calls `FFTW.set_num_threads(n)`, and only after that + succeeds stores n in `_HOST_THREADS::Threads.Atomic{Int}`. It returns `nothing`. +- The B-spline budget is `min(n, Threads.nthreads(:default))`, excluding the + interactive pool. n above the pool is accepted: FFTW gets n, host solves are + capped, and no OS threads are created. +- **Default.** `_HOST_THREADS` starts at 0, meaning automatic: the whole + default pool, resolved at each solve. Importing ACE never touches FFTW's + process-global setting. + + This is checked in a fresh subprocess: FFTW set to 3 before `using` is still + 3 afterwards, and the automatic budget there is 2 under `--threads=2`. So the + budget is not frozen at precompile time. 0 is internal only; `set_threads(0)` + is rejected. +- **Per solve.** Once the factor has been classified, `_host_column_tasks(n, m)` + reads the budget once. It uses `clamp(div(n*m, 32768), 1, min(budget, m))` + contiguous blocks, so each task gets at least 32,768 band entries, about + 0.2 ms of serial work at N=81. Controlled measurements below support retaining + this conservative threshold, without claiming a universal optimum. + + One block means the unchanged serial loop. Otherwise there is one + `Threads.@spawn` per block under `@sync`. Tasks write only their own columns + of the call-owned working matrix, and read the factor and the original RHS + (used by the per-column nonfinite fallback). There is no thread-ID scratch, + `:static` scheduling or shared mutable workspace, and nested calls just spawn + more composable tasks. +- Every column is computed by the same kernel calls as before, so threaded + results are **bitwise identical** to serial ones. This includes the bordered + fast path, the full-band path, and nonfinite/overflow restoration from the + original RHS. +- **What it covers:** forward (`solve`, so `bspline_coefficients`, the + coefficient stage of `plan(u)` and ordinary splines) and transpose + (`solve_adjoint`, so the ChainRules and Mooncake pullbacks). + + Vector RHS (one column), small batches, Float32/Float64 mismatches, Duals, + BigFloat and other generic or device kernels keep their serial paths. Public + input adapters can densify views or convert integers before kernel dispatch; + those resulting dense Float32/64 matrices may be threaded. Reactant device + calls never reach the `Matrix` host driver. +- **AD.** Global configuration and task creation sit inside existing primal and + pullback primitives, which are never differentiated. No rule changes; + ForwardDiff Duals stay on the generic serial path. +- `set_fft_threads(n)` emits a deprecation warning and forwards to + `set_threads(n)`, so it now also sets the host budget. There is no + independent FFT-only state. +- **Caveats.** Configure before starting concurrent work. FFT plans keep the + thread count they were created with. One global budget cannot prevent + oversubscription across user-level parallel chains, so `set_threads(1)` is + documented for chain-parallel workloads. + +## Control provenance + +Before any edit, the accepted Stage 1 and Stage 2a tree was frozen at +`../bspline_backend_validation/stage3_baseline_stage2/` (HEAD archive plus live +`src`/`ext`/`test`/driver, verified with `diff -r`). Its hashes are recorded in +`SNAPSHOT_SHA256.txt` and match the stated production hashes: `chainrules` +`d6afc8d2…`, `MooncakeExt` `5f031466…`, `cubic_b_spline` `3cda5698…`. Its env +Manifest differs from `benchmark/Manifest.toml` only in the ACE path. The +controlled cross-revision serial ABBA measurements are reported below. Main's +8,362/5/0 full log is the valid serial baseline for the test suite. + +## Tests + +**Focused** (benchmark env, ACE path, `ChainRulesCore` identity and +`set_threads` asserted; `--check-bounds=yes`; BLAS 1): + +``` +JULIA_LOAD_PATH="$ROOT/benchmark:$ROOT:@stdlib" OPENBLAS_NUM_THREADS=1 \ + julia --project=$ROOT/benchmark --check-bounds=yes -t {4|1} \ + benchmark/reviewer_logs/stage3/focused_runner.jl [file] +``` + +| Run | Result | Log | +|---|---|---| +| `test_threads.jl`, `-t 4` (4 default + 1 interactive) | 266/266 | `focused_new_file_t4_attempt1.log` | +| `test_threads.jl`, `-t 1` | 265/265 (the "spread over ≥ 2 pool threads" check needs a pool ≥ 2) | `focused_new_file_t1.log` | +| All host spline files plus `test_threads.jl`, `-t 4` | 6,923 passed, 0 failed, 1 error | `focused_candidate_t4_chebyshev_env_error.log` | +| Same, `-t 1` | 6,922 passed, 0 failed, 1 error | `focused_candidate_t1_chebyshev_env_error.log` | + +The single error in the last two runs is environmental: `test_chebyshev.jl` +imports `FiniteDifferences`, which exists only in the package test extras, so +it could not load in the benchmark env. It was removed from the runner list; the +full suite covers it. Excluding it, 6,923 = 266 + the 6,657 Stage 2 focused set. + +**Mutation check** (`mutation_check.jl`/`.log`, `-t 4`, disposable process). +All three mutants are detected: never split (10 failures), dropping the final +column (158), and a budget that ignores `set_threads` (10). + +**What `test_threads.jl` covers:** + +- **Setter.** + - Valid values 1, 2 and pool+3: FFTW's getter equals n and the budget equals + `min(n, pool)`. + - Invalid values 0, −1, `typemax(Cint)+1`, `big(2)^70` and `UInt128(2)^100` + throw `ArgumentError` and change neither setting. + - Automatic mode, the deprecated forwarder, and an FFT plan created before a + change (still usable, bitwise same output, agrees with a new plan). + - The fresh-subprocess import and default check described above. + - Every test restores FFTW's count and ACE's setting exactly. +- **The parallel path is really taken.** + - Planned task counts under budgets 1, 2, 4 and automatic. + - Test-only recording kernels passed to the *production* driver: blocks are + contiguous, run on distinct tasks, number exactly the planned count and + cover every column once, for both the bordered and the full-band kernel. + - With a pool ≥ 2, columns are observed on at least two pool threads. + - The output matches the public serial solve bitwise. +- **Public bitwise equality**, serial versus budgets 2, 4 and automatic: + - forward and transpose solves, `bspline_coefficients` and `plan(U)`; + - Float32 and Float64; (N, M) = (5, 20001), (6, 13001), (7, 9999), + (81, 4099), (81, 8192) and (129, 8191), including odd tails; + - a full-band factor with a 1e−30 forbidden coupling; + - inputs and factor unmodified. + + Malformed storage still raises `BoundsError`; vectors, views and BigFloat + match their serial results. +- **Fallback patterns.** NaN, ±Inf and 1e308/−1e308 columns spread across + blocks give `isequal` threaded and serial results, and the results contain + both NaN and Inf. +- **AD.** + - With budget 4, N=7 and M=12000 (split into 2 tasks): Zygote and Mooncake + match full ForwardDiff for plan sites (coefficients and evaluation), + outside-domain queries and ordinary-spline sites. + - Input-only gradients match dense Aᵀ\G and Aᵀ\(SᵀW) (≤1e−10) and ForwardDiff + directional derivatives. + - Adaptive log-k N81/N129 at M=8192: one preparation per backend and loss + (ordinates and live sites, coefficients and evaluation) is created under + budget 1 and reused under 1 → 4 → 2 → 1. All four gradients are **bitwise + equal**. This proves numerical compatibility with configuration changes, + not by itself that a preparation uses a different task count. The runtime + atomic read inside the existing solve primitives and the separate driver + task evidence establish the execution-policy wiring. Live-site directional + checks pass under budget 4. +- **Concurrency.** Eight tasks with separate preparations share one read-only + plan under budget 4 (nested spawning). Results equal the serial ones bitwise + for both backends, and the factor is unmodified. + +**Full candidate `Pkg.test()`** (`JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 +julia --project= -e 'using Pkg; Pkg.test()'`): **8,633 passed, 5 failed, +0 errors** (`candidate_full_pkgtest.log`). + +- 8,633 = 8,362 + 267 (`Unified thread setting`) + 4 (Chebyshev FFTW test: + 1 → 5 assertions). +- The failures are exactly the known Reactant Akima assertions at + `test_ext_reactant.jl:659` (×3) and `:662` (×2). +- Every pre-existing group count is unchanged, including all Reactant and + Reactant/Enzyme groups. +- The run used the automatic budget with a 4-thread pool, so the other suites' + large solves were threaded too. +- Three unrelated Blast Julia processes ran concurrently; the 20:31 wall time is + not meaningful. + +## Independent main-agent review + +Source review found no new production correctness defect. Documentation was +corrected to distinguish public input densification from generic-kernel fallback +and to avoid treating equal gradients as proof of a changed execution policy. +An independent four-thread smoke probe also verified an empty `(5, 0)` RHS. + +Independent runs with `--depwarn=yes --check-bounds=yes`: + +- `--threads=1,0`: **266/266**, `main_focused_t1.log`. +- `--threads=4,1`: **6,924/6,924**, all focused host spline files, + `main_focused_t4.log`. The interactive pool is intentionally present and + excluded from the configured host worker budget. + +The independent full `Pkg.test()` rerun started only after both focused gates: +**8,633 passed, 5 failed, 0 errors**, `main_independent_pkgtest.log`. The five +failures are exactly the existing Reactant Akima assertions at lines 659 (three) +and 662 (two). No new failures. The production source hashes remained unchanged +through the run, including both accepted Stage 2 AD files. The API and numerical/ +AD behavior are accepted; this is not a green full suite and does not certify +the preliminary performance figures below. + +## Benchmark (preliminary; not acceptance evidence) + +An idle window appeared after the full suite: no other Julia processes, +recorded in each TOML. `run_stage3.sh` ran two fresh processes of the `stage3` +mode: +- `taskset -c 4,6,8,10` (four distinct physical P cores, one SMT sibling each; + turbo limits 5.0, 5.0, 4.8 and 4.8 GHz), `--threads=4,0`, GC and BLAS 1; +- cooled to 52 °C before measuring; cells ran at 62–91 °C; +- BenchmarkTools with `evals=1`, exactly 30 samples enforced, interpolated + arguments, `gctimes` kept; +- budget set outside the timed call; each gradient gated bitwise against + budget 1 before timing. + +The first attempt failed on a harness closure-capture bug (fixed; raw output in +`bench_attempt1_closure_capture_bug/`). Full table: `bench/summary.md`. + +**Repeatable** (both rounds within 2.4% at budgets 2 and 4; speedups vs budget 1): + +| Cell | Budget 2 | Budget 4 | +|---|---|---| +| N81 M8192 forward | 2.11× (min 1.75×) | 3.34× (min 2.85×) | +| N81 M8192 transpose | 1.92× (1.82×) | 3.00× (2.86×) | +| N129 M8192 forward / transpose | 1.89× / 1.91× | 3.08× / 3.13× | +| N129 Zygote coefficient gradient, input / live sites | 1.53× / 1.53× | 2.20× / 2.18× | +| N129 Mooncake coefficient gradient, live sites | 1.38× | 1.75× | + +Not established or problematic: + +- The **N129 budget-1 forward/transpose** controls drift 25% between rounds; + their speedups use the round means and the better minimum. +- **N129 Mooncake input-only, budget 2:** the median is *slower* than budget 1 + (20.7 vs 19.6 ms, repeated in both rounds), although the minimum is 1.35× + faster. At budget 4 the median drifts 26%. This is unexplained and is not a + claimed win. +- **N81 gradient cells** drift 25–70% between rounds, as in Stage 2. Not evidence. +- **Ordering artifact.** At N81 M256 every budget runs the *identical serial + path* (1 planned task), yet budgets 2 and 4 measured 1.28× faster than + budget 1 in both rounds. Cell-order and frequency effects of about 25% can + therefore appear in this protocol, so only effects well above that level, + such as the 2–3× solve speedups and the 2.2× N129 Zygote gradients, are + credible here. +- **Small controls.** M=7 is unchanged (serial, 0.99–1.00). M=1024 at N81 uses + 2 tasks: 2.1× by median, but subject to the artifact above. +- **Concurrency.** Four Mooncake chains on one plan: budget 4 versus 1 gives + 1.10× (min 1.04×). This is below the observed protocol noise and does not + establish either a gain or absence of a penalty when chains fill the cores. + GC dominates those samples (up to 255 ms of GC). +- **Allocations.** A threaded solve adds +20 allocations / +1,184 B with 2 tasks + and +33 / +2,112 B with 4. Gradients add about 40 and 66 allocations, + negligible against 25–34 MB. + +## Controlled follow-up campaign + +`benchmark/bench_bspline_threading_controlled.jl` reuses the original input, +prepared-AD and strict BenchmarkTools helpers. It warms each policy, records +raw samples/GC times/CPU clocks, and counterbalances budgets as 1/2/4/4/2/1 +within each workload. Hashes verify identical numerical results across budgets. +Artifacts are under `benchmark/reviewer_logs/stage3/controlled/`. + +- Protocol v1 smoke controls: 12/12 cells; identical serial kernels agree to + approximately 1%, unlike the old 25% ordering artifact. +- Protocol v1 first full round: **210/210 cells, 30 samples each**, maximum + endpoint temperature 88 C. These are a complete separate diagnostic round, + not pooled with later protocols. +- Protocol v1 repeat: **87 cells, incomplete**, rejected when the N81 Zygote + input-gradient budget-4 cell reached **98 C**. Preserve + `controlled_scaling_scaling_r2.toml` and `scaling_r2.log`; do not use its + partial timings to fill a matrix or certify a speedup. +- Protocol v2 prevents cumulative heat soak by cooling before each cell above + 65 C to 50 C, followed by a 0.10 s per-policy warmup. Two full rounds and + fresh-process baseline/candidate/candidate/baseline serial controls are + running sequentially. No other computation is allowed in the timing window. +- `driver_protocol_v1.jl` is preserved and SHA256-verified against the measured + v1 provenance; `driver_protocol_v2.jl` preserves the replacement protocol. + +Downstream wrapper: `../bspline_backend_validation/check_ace_threading_blast.jl` +reuses the real LSST workload and genuine N65 bank. It saves old-ACE spectra and +ForwardDiff references before comparing the candidate, keeping current Blast, +bank and scientific inputs fixed. It explicitly labels random amplitude points +as fixture-domain draws, not real model priors. The isolated baseline manifest +differs from the current Blast benchmark manifest only in the ACE source path. + +The production Turing example still pins ACE 0.11/upstream Blast and hardcodes +the Chebyshev non-Limber grid in its predictor. Marco explicitly chose to keep +that migration separate. Its real-prior LDF certification is therefore outside +this campaign, not replaced by a fixture-domain random draw. + +### Verified controlled results + +Both protocol-v2 scaling rounds completed: **420 cells, 30 samples each**. +Maximum endpoint temperatures were 92 C and 89 C; within-workload serial-anchor +minimum-time drift was at most 3.91% and 3.23%. These are laptop results on four +distinct P-cores (CPUs 4/6/8/10), Julia 1.12.6, one GC thread and one BLAS thread. +They are not extrapolations to Narval or end-to-end likelihood speedups. + +Four-worker speedups below are T(budget 1) / T(budget 4), computed from the +mean of the two counterbalanced trial minima in each fresh process; the ranges +span both processes and, where applicable, N81/N129 and input/live-site losses: + +| Public path, M8192 | Measured speedup range | +|---|---| +| Float64 coefficient recovery | 2.67–2.82× | +| Float64 transpose solve | 2.80–2.94× | +| Prepared Mooncake coefficient gradient | 1.62–1.75× | +| Prepared Zygote coefficient gradient | 2.16–2.24× | +| Float32 coefficient recovery | 3.16–3.27× | +| Float32 transpose solve | 3.23–3.26× | + +N129 Mooncake input gradients reproduce at 1.33–1.34× with two workers and +1.67× with four; the old two-worker slowdown does not reproduce. Correcting +the protocol resolves that apparent regression without production-code changes; +the individual frequency/cache/scheduling contributions are not isolated. +Some other two-worker cells retain variability, notably N129 forward recovery +(1.43–1.74×); do not claim universal linear scaling or stable medians. + +Retain **32,768 entries per task**: the near-threshold N129×512 case uses two +tasks and gains 1.75–1.77×; the N81×512 serial-path control remains within about +0.4% of budget 1. This validates a conservative cutoff, not an optimal threshold +for every dtype, shape or CPU. Four already-concurrent Mooncake chains gain +only about 1–3% in minima; prefer budget 1 when outer chains occupy the cores. + +Fresh-process serial baseline/candidate/candidate/baseline controls completed: +**176 trials ×30 samples**, all **22 numerical digests bitwise identical** +across all four processes. Largest averaged-minimum increase: **1.51%**. +Raw-case summary: `controlled/serial_abba_summary.tsv`. Microsecond controls +have unstable minima even between identical candidate processes (up to 31% in +one 5–8 μs control), so do not use their extrema alone to claim a code effect. +Median latency remains qualified: N81 live-site Mooncake is +5.05%, and N81 +Zygote input/sites are +8.02%/+6.71% in the combined serial comparison. Do not +attribute all of that to GC pauses: the second identical candidate process +has a slow plateau even among GC-free samples (input median about 11.6 ms, +versus about 8.9 ms in the first candidate). Minima stay near 8.7 ms. The +specific heap/cache/frequency contributions are not isolated. These data +support the stated **minimum-time** acceptance, not stable median latency or +a claim that all non-minimum timing regressions have been explained. + +The serial driver does add **one allocation / 32 B per solve**, hence generally +two allocations / 64 B per coefficient gradient. This is measured overhead, +not allocation parity. Its small time effect is included in the serial controls; +no production cleanup was mixed into these tests or timing runs. + +### Downstream and matrix environment failures preserved + +The first downstream import failed because its stale manifest omitted Blast's +declared SHA dependency and labelled the developed ACE source 0.11 despite its +0.12 Project. No scientific test ran. `Pkg.resolve()` repaired a separate +candidate validation environment, then its resolved graph was cloned for the +pre-threading Stage 2 ACE control, changing only the ACE source path. The shared +Blast benchmark environment and production inference pins are untouched. +Failure evidence: `../bspline_backend_validation/stage3_blast/attempt1_stale_manifest/`. + +Direct older-Julia tests failed before the suite because the root manifest +references Julia 1.12's bundled OpenSSL_jll. Evidence is preserved in +`version_matrix/attempt1_foreign_manifest/`. The repaired runner uses one local +developed-ACE environment per Julia version and still lets `Pkg.test` manage all +extras/targets unconditionally. No manual test dependencies or extension gates. +Disk guard: admit at 8 GiB free and terminate only its own job group at 6 GiB; +do not delete user data. These bootstrap failures were resolved; final results follow. + +The repaired pre-threading real-bank reference completed and was independently +checked: all 17 components, all three amplitude-fixture points, nine finite +spectral-reference files and finite ForwardDiff gradients. Prepared Mooncake +checks passed. All three baseline timing trials contain 30 samples below the +95 C admission/endpoint limit: preparation minimum 10.3 ms, objective 65.1 ms, +prepared gradient 302.9 ms. These single-process minima are reference data, not +yet matched downstream speedup claims. + +The candidate subsequently completed **all three scientific points**, including +the repeated **1 → 4 → 1 budget switches**, full public spectra and prepared +Mooncake comparisons against both freshly computed ForwardDiff and saved +pre-threading references. Independent post-run checks verified all nine saved +spectra and all three FD vectors, plus matching data/bank/Blast provenance and +unchanged current ACE/Blast source digests. This is theory-path scientific +acceptance, not production-prior or approximation-accuracy certification. + +Its timing phase rejected competing, unrelated DESIDR2MockChallenge Julia +tests **before collecting any timing samples**. The original candidate exit 1 +and log remain intact. It is not a numerical failure or a benchmark result. +Independent Julia-version suites proceeded automatically. + +Matched downstream recovery is queued behind both version suites and an idle +Julia machine (five-hour bounded wait). It uses four fresh processes in +baseline/candidate/candidate/baseline order, existing 30-sample and thermal +gates, and checks for competitors before **and after** each measured trial. +Scientific sources and the driver are SHA-pinned; any changes reject the run. +The complete original FD references are reused rather than recomputing the +expensive oracle; each new process still rechecks all three public spectra and +prepared gradients at every applicable budget. The initial full-FD driver is +preserved as `../bspline_backend_validation/check_ace_threading_blast_full_v1.jl`. +Recovery artifacts: `../bspline_backend_validation/stage3_blast/timing_recovery/`; +launcher: `benchmark/reviewer_logs/stage3/run_timing_recovery.sh`. + +The first recovery control rechecked all three scientific points successfully +but rejected its contiguous objective trial at **52 → 98 C**. No timing from +that process is accepted; its complete directory is preserved as +`timing_recovery_attempt1_hot/`, and its driver as +`check_ace_threading_blast_savedfd_v2_contiguous.jl`. + +Protocol v3 therefore uses **30 predetermined, single-evaluation bursts per +case**, each cooled below 50 C with the existing stability window. A compiled +BenchmarkTools benchmark is primed outside measurement and run explicitly with +`warmup=false`, `evals=1`, `gctrial=false`, `gcsample=false`; one GC occurs before +the burst sequence, not before every sample. No sample is retried or filtered. +Each burst journals its time, GC time, allocations, temperatures and hardware +core/package throttling counters before any rejection. Post-call temperatures +are sampled over 0.5 seconds, all endpoints must remain below 95 C, and throttle +counters on all four pinned cores must not increase. Competitor checks remain +before and after. These are **cooled-call latency** measurements, not thermally +stabilized sustained-throughput claims. The four-process matched comparison is +restarted in full; old contiguous results are not mixed with cooled bursts. + +The v3 control `baseline_a` completed and was independently checked: **90/90 +samples** across three cases, all journals complete, no core/package throttle +counter increase within measured bursts (see the later between-burst audit). +Maximum observed temperature was 69 C. Minimum preparation / +objective / prepared-gradient times: **9.993 / 63.637 / 314.611 ms**. These are +the first control's cooled-call measurements only; the candidate and second +controls are pending, so no downstream speedup is yet certified. The actual +measurement-loop smoke test passed **7/7**, including exactly 30 measured calls +after two priming calls and retaining a rejected first hot sample without retry. + +`candidate_a` also completed: **270/270 samples**, all nine journals verified, +maximum observed temperature 79 C, no hardware-counter increase within any +burst or across any case's full burst sequence. Its provisional within-process +T(budget 1, mean of before/after anchor minima) / T(budget 4) ratios are **1.514× +preparation, 1.065× whole objective, 1.030× prepared whole gradient**. This shows +why coefficient-only gains must not be presented as whole-likelihood gains. +The second candidate and final control are still pending; these ratios are +explicitly not the final matched comparison. + +The second candidate's scientific checks passed, but a new unrelated Julia +probe appeared during its third gradient burst. The exclusivity guard rejected +the phase; the three-sample rejected journal and two earlier complete case +journals remain intact. **The matched four-process comparison is incomplete**; +none of this partial second candidate is used to certify a speedup. No thermal +failure occurred. The completed first control/candidate remain valid scoped +observations. Further measurement is awaiting coordination of an exclusive +window with the other active conversation, not another blind retry. A continuation +can write its remaining full candidate/control into a fresh output directory +without overwriting any failed artifacts. + +The DESI conversation subsequently agreed not to start local Julia work until +07:45 UTC. It explicitly did **not** own the short interfering probe, so this +is coordination, not a claim of machine-wide exclusivity; guards remain active. +The remaining **whole** candidate and final control started at 06:59 UTC in +`timing_recovery_finish/`, with unchanged pinned scientific sources/protocol. +The interrupted candidate is not spliced into the comparison. Report the actual +order as A/B/(rejected B)/B/A rather than hiding the interruption. + +### Final downstream results and independent audit + +The remaining full candidate and control completed by **07:39:40 UTC**, before +the coordinated window expired; the peer was explicitly notified of release. +All **four complete processes / 24 cases / 720 samples** were independently +checked. Every measured burst has a complete journal, temperatures below 95 C +(maximum 79 C), unchanged core/package throttling counters, and the unchanged +pinned source/provenance. No rejected, hot, interrupted or contiguous-protocol +sample enters this comparison. Summary data: +`timing_recovery_finish/matched_summary.json`. + +The table uses means of complete trial minima: two old controls, four candidate +serial anchors, two four-worker trials. It is not a mean of noisy raw runtimes. + +| Public workload | Old serial ms | New budget 1 ms | New budget 4 ms | T1/T4 by candidate process | +|---|---:|---:|---:|---| +| Spectrum/source preparation | 10.018 | 10.029 | 6.573 | 1.514×, 1.538× | +| Whole objective | 63.776 | 63.937 | 60.227 | 1.065×, 1.058× | +| Prepared whole Mooncake gradient | 309.774 | 309.239 | 295.787 | 1.030×, 1.061× | + +Cross-revision serial minimum changes are **+0.114%, +0.252%, −0.173%**. +Old-control minimum drift is 0.51%, 0.43%, 3.17%, respectively. Combined T1/T4 +ratios are 1.526×, 1.062×, 1.045×; corresponding median ratios are 1.493×, +1.062×, 1.021×. The gradient benefit is modest and variable, not a robust precise +4.5% universal promise. Most whole-model cost is outside coefficient recovery. + +**Additional thermal audit qualification:** although all measured before/after +counter pairs are equal, the first control's objective has one counter jump +between bursts 20 and 21: +12 on core6's core counter and on each recorded +package counter. Adjacent observed temperatures are 46/45 C. Its cause was not +isolated; do not label it GC, and do not claim a throttle-free entire session. +The later measurement was independently cooled and every measured burst passed +the specified gate. Both complete candidate processes and the final control +have no such between-burst jump. Candidate-only budget comparisons therefore +have clean full-case counters; the strict cross-revision whole-session thermal +claim remains qualified. All 30 first-control samples remain in the raw report, +not selectively removed to improve a result. + +**Scientific precision audit:** all processes pass the original full-array +`isapprox` norm criterion (`rtol=1e-12, atol=1e-20`) and saved FD-gradient checks. +An additional, stricter elementwise `1e-12` relative check does not pass some +near-cancellation entries, including in the unchanged final old control. +Across all spectra/processes the maximum absolute difference is **1.8134e-16**, +maximum pointwise fractional difference **1.9652e-9**, and maximum relative +array norm **1.6504e-13**. This is reported, not hidden by substituting norms for +pointwise diagnostics. Full-model cross-process bitwise identity is not claimed; +the separate host-solve and controlled coefficient digests remain bitwise equal. + +### Supported Linux Julia-version results + +| Julia | Passed | Failed | Existing skips | New errors | Status | +|---|---:|---:|---:|---:|---| +| 1.10.12 | 8,601 | 5 | 0 | 0 | Only the exact known Akima failures; all 267 threading assertions pass | +| 1.11.9 | 8,605 | 5 | 2 | 0 | Same known failures and existing compiler-crash guards; all 267 threading assertions pass | +| 1.12.6 | 8,633 | 5 | 0 | 0 | Previously independently verified full suite | + +The 1.10 failures are exactly `test_ext_reactant.jl:659` ×3 and `:662` ×2, +with no `Error During Test`. Every other group count matches the independent +1.12 run except **Type Stability (8 versus 40)**: the existing +`test/test_type_stability.jl:36` explicitly runs its JET/inference section only +on Julia ≥1.11. That completely accounts for the 32-assertion difference; +no spline or Reactant extension group was disabled. Root Project/Manifest +checksums are identical before and after the 1.10 run. + +The 1.11 run likewise has exactly the same five Akima assertions and no test +errors. Its entire 28-pass difference from 1.12 lies in two **pre-existing** +`SKIP_REACTANT_REUSABLE_SPLINES` branches (`test_ext_reactant.jl:15,110,568`), +confirmed present in HEAD: reusable callable-spline forward compilation +(23 passes replaced by one skip) and its gradients (5 replaced by one skip). +The source records the existing Julia 1.11.9 `emit_bitcast`/LLVM compiler crash +and its CI provenance. No new gates or skips were added. Do not claim those +two compiled-structure paths certified on 1.11. Every other group count +matches 1.12, and shared Project/Manifest hashes are unchanged after the run. +Both older-version package commands therefore exit 1 for known failures; +the matrix is **not green**, despite no new regression. Logs and manifests: +`benchmark/reviewer_logs/stage3/version_matrix/`. + +## Acceptance scope and remaining limitations + +1. Correctness gate complete: independent source review, focused tests and full + reruns agree with the known-failure baseline. The package suite is not green + because those pre-existing failures remain; no new failure was introduced. +2. Controlled scaling and serial gates complete in the measured scope above; + retain the cutoff and the explicit timing/allocation limitations. +3. Actual Blast LSST/N65 scientific checks and cooled-call timing completed; + retain the median, between-burst-counter and cross-process precision + qualifications above. No sustained-throughput or production-prior + certification is claimed. Production Turing migration remains separate, + as explicitly requested. No additional benchmark retries are queued. +4. Isolated Linux Julia 1.10/1.11 suites complete with the exact known failures + and version guards above; Julia 1.12 full results independently verified. + macOS/Windows remain the existing remote CI's responsibility. diff --git a/BSPLINE_THREADING_API_DESIGN.md b/BSPLINE_THREADING_API_DESIGN.md new file mode 100644 index 0000000..ff13365 --- /dev/null +++ b/BSPLINE_THREADING_API_DESIGN.md @@ -0,0 +1,86 @@ +# Unified thread configuration for Stage 3 + +**Status: API approved by Marco on 2026-10-22. Implemented as an uncommitted +Stage 3 working-tree candidate (`src/threads.jl`, host column driver in +`src/cubic_b_spline.jl`); see `BENCHMARK_BSPLINE_STAGE3.md`. Independent API, +numerical, AD, scoped host-kernel timing and real-bank theory-path scientific +gates passed. Linux Julia 1.10/1.11/1.12 suites show no new failures, with the +known failures/version skips explicitly recorded. Downstream cooled-call +measurements completed with the explicit thermal/median/precision qualifications +in the report; no sustained-throughput guarantee. Nothing committed or pushed.** +The previous per-call keyword proposal is superseded. Stages 1 and 2a alone +do not enable threading. + +## Approved public surface + +```julia +set_threads(n) +C = bspline_coefficients(plan, U) +Y = plan(U) +``` + +One canonical setter configures FFTW's count for subsequently created plans +and ACE's CPU task budget. Julia's default pool cannot be enlarged at runtime: +the effective spline budget is `min(n, Threads.nthreads(:default))`. Launch +Julia with `--threads=N` or `JULIA_NUM_THREADS=N` to make those workers available. +`set_threads(1)` requests serial execution for both. Large dense matrix solves +use the budget automatically; small batches, vectors and generic inputs retain +the serial path when parallel execution would not be worthwhile or supported. + +There is no public `threaded` keyword or second independent spline setter. +The existing `set_fft_threads` may remain only as a deprecated compatibility +forwarder to the canonical setter, not an independent setting. Do not add +fields to reusable plans or change BLAS, process or GPU configuration. + +Before an explicit setter call, CPU work may use the available default pool +subject to its work threshold; leave FFTW's existing configuration alone rather +than changing a process-global third-party setting merely by importing ACE. +Resolve available Julia threads at runtime, not during precompilation. + +Validate the requested positive integer before changing state. Publish the CPU +budget only after FFTW accepts its setting. Use a small race-safe configuration +value and snapshot it once per solve, never a mutable global workspace. Configure +outside concurrent work. Existing FFT plans retain their original execution +configuration; create them after calling the setter. + +## What the setting controls + +- Independent RHS-column blocks in forward and transpose coefficient solves. +- Both coefficient-only calls and the coefficient stage of plan evaluation. +- The chosen transpose policy in Mooncake and ChainRules pullbacks, while + preserving all supported ordinate, site, knot and query derivatives. + +The dependent within-column recurrence, interpolation stencil, and Stage 2a +geometry reduction remain unchanged. Each task writes disjoint columns; original +RHS values remain available for per-column safety fallback. No plan-owned or +global mutable scratch, nested implicit parallelism, or thread-ID-owned buffers. + +## Device boundary + +This setter controls host work, not Reactant execution. Existing +`ReactantCubicBSplinePlan` device calls must retain their dense-operator path, +and the host-plan/device-input guard must remain intact. Inspect the callable +bridges in `ext/ExtReactant/reactant_splines.jl`; do not trace the global CPU +configuration or host task creation into device code. Enzyme remains Reactant-only. + +## Implementation and acceptance gates + +1. Prototype private column-block forward/transpose kernels without changing + public signatures. Compare serial and threaded results, including nonfinite + fallback and odd tail blocks, before benchmarking. +2. Measure one/two/four pinned physical cores, representative large batches, + and concurrent independent chains. Include copy, task and synchronization + costs. Obtain a controlled measurement window; do not reuse unstable laptop + medians as acceptance references. +3. Wire the single setting through forward and transpose solves without asking + Zygote or Mooncake to differentiate raw task mutation. Preserve all supported + public derivative paths and the ordinary two-argument call signatures. +4. Test both public APIs under one and multiple configured workers, serial fallback, + Float32/64, views/generic inputs, A/B/A prepared reuse, live geometry, + independent concurrent preparations and device regressions. Run focused tests + first, then `Pkg.test()` without gates or relaxed tolerances. + +Also test setter validation, FFTW integration, settings above the Julia pool +size, and one/multiple/one settings with a reused gradient preparation. + +This does not authorize commits, pushes or optional frozen-geometry/workspace APIs. diff --git a/OPTIMIZATION_BSPLINE.md b/OPTIMIZATION_BSPLINE.md new file mode 100644 index 0000000..81c1231 --- /dev/null +++ b/OPTIMIZATION_BSPLINE.md @@ -0,0 +1,545 @@ +# Cubic B-spline coefficient optimization plan + +**Continuation:** Stage A/B is implemented. For the current baseline and the +next reverse-mode/threading work, use +[OPTIMIZATION_BSPLINE_NEXT_STEPS.md](OPTIMIZATION_BSPLINE_NEXT_STEPS.md). +Host AD targets Mooncake and Zygote; Enzyme support is Reactant-only. +The historical baseline and prerequisites below describe the original campaign. + +**Status: design for discussion, not implementation approval.** +Written 2026-10-20. Scope: AbstractCosmologicalEmulators.jl (ACE), primarily +ordinary Julia CPU coefficient construction and its reverse-mode derivative. +Blast must continue consuming ACE; do not duplicate the solver in Blast. + +## 1. Baseline and repository prerequisite + +The inspected implementation is the ACE 0.12.0 source used by Blast's +`BSplines` campaign. Its `src/cubic_b_spline.jl`, `src/chainrules.jl`, and +`ext/MooncakeExt/MooncakeExt.jl` are byte-identical to fetched +`origin/96-b-spline` at **af7944975f422af0271ebdfb03a6ba2395a5e2c8**. + +This checkout was clean before adding this document, but its HEAD is +`56d54fd13303e5ed3a4322e74c67d44d1ca5a331`, five commits behind that upstream. +**Before implementation, reconcile/fast-forward this same branch after +checking for concurrent edits. Do not implement against its older AD rules.** +This document does not update the checkout, edit installed package/depot +sources, change a Manifest, or authorize commits, pushes, tags or releases. + +The older `IMPLEMENTATION.md` concerns a different, Reactant-focused campaign. +Its statement that host performance is already sufficient is not a conclusion +about the 8,192-RHS coefficient workload measured here. This proposal does not +replace that campaign's device algorithms or revive its obsolete experiments. + +### Measured forward baseline + +Narval job 6568629, node nc31126, AMD EPYC 7532, Julia 1.12.6. One Julia, +FFTW and BLAS thread. Actual `Blast.build_coeff(Blast.cϕTT, values, plan)`; +Float64 `(N,128,64)` input, reshaped to `N × 8192`. Plan construction and +source generation excluded; output allocation and coefficient wrapping included. +Every integer spline N=33:128 was measured, with 30 BenchmarkTools samples, +evals=1, five-second maximum sampling windows. All 103 cases completed. + +| Method | N | Minimum ms | Median ms | Allocated bytes | +|---|---:|---:|---:|---:| +| Chebyshev reference | 161 | 10.0183 | 10.0711 | 10552840 | +| B-spline | 33 | 4.57952 | 4.71777 | 2162888 | +| B-spline | 49 | 6.91324 | 7.20350 | 3211464 | +| B-spline | 65 | 9.23260 | 9.29297 | 4260040 | +| B-spline | 81 | 11.5376 | 11.6054 | 5308616 | +| B-spline | 97 | 13.8918 | 13.9714 | 6357192 | +| B-spline | 128 | 18.4174 | 18.5961 | 8388808 | + +The spline batch allocates six times, not once per column. Four Chebyshev-161 +reference minima agree within 0.228%; their medians vary by 9.37%. Same-N +Chebyshev minima are 1.46673 ms at N33 and 3.50030 ms at N65, but 60.1405 ms +at N128. DCT-I length is `2(N-1)`; N128 is not an FFT-friendly control. Do not +generalize either the favorable or unfavorable FFT case to every N. + +Evidence, relative to this checkout: + +* `../bspline_backend_validation/COEFFICIENT_PERFORMANCE.md` +* `../bspline_backend_validation/coefficient_bench_full_6568629/trials.toml` +* `../bspline_backend_validation/benchmark_coefficients_only.jl` +* `../bspline_backend_validation/CHEBYSHEV_CLS_COMPARISON.md` + +These are coefficient timings, not equal-accuracy or full-likelihood speedups. +The LSST comparison's persistent differences from Chebyshev have not been +isolated. Optimizing this solve must not change interpolation sites, knots, +boundary conditions, source normalization, quadrature, or the comparison budget. + +## 2. What the current code actually does + +Source locations below refer to af79449, not the older checked-out files. + +| Location | Operation | Consequence | +|---|---|---| +| `src/cubic_b_spline.jl:338–385` | Build and factor a seven-row band representation | Already paid during plan preparation; not the measured forward bottleneck | +| `src/cubic_b_spline.jl:399–410` | Allocate/copy RHS matrix; loop over column views | One scalar solve per independent source series | +| `src/cubic_b_spline.jl:413–429` | Full lower/upper bandwidth-three substitutions | Processes many exact structural zeros | +| `src/cubic_b_spline.jl:629–667` | Transposed band solve | Same opportunity in reverse mode | +| `src/cubic_b_spline.jl:764–765` | Public coefficient API to factor solve | Preserve this public entry point | +| `src/chainrules.jl:1140–1165` | Geometry VJP rebuilds a factorization, solves transpose, accumulates site/knot cotangents | Some work can reuse a plan's existing factorization | +| `ext/MooncakeExt/MooncakeExt.jl:280–315` | Coefficient primitive invokes full geometry VJP | Do not silently discard geometry derivatives | + +A local diagnostic profile of 120 warmed N65 × 8192 solves collected 685 +samples: 599 inside band solves, 58 in the matrix copy, 28 in allocation. +This is localization evidence, **not a Narval optimization benchmark**. +Generated LLVM for the concrete Float64 column-view kernel contains scalar +arithmetic/division and retained bounds-error branches. The Float64 dense-input +adapter returns the original matrix; it is not copying every source column. + +For nonuniform canonical plans at N=33,65,97,128, nonzero counts in the seven +factor rows were exactly: + +``` +[0, 1, N-2, N, N-2, 1, 0] +``` + +The outer nonzeros are `bands[2,4]` and `bands[6,N-3]`. At N65 the generic +kernel executes 378 off-diagonal updates per column, while only 128 have +nonzero factors. This motivates a structural fast path, not a claim of 3× speed. + +## 3. Decisions and invariants + +1. **Keep current public APIs and factor/plan layouts initially.** Retain the + seven-row factor storage, generic fallback, scalar promotion and AD contracts. + Do not add cached shape flags or reciprocal fields before proving they are + necessary; mutable factor arrays would make such metadata easy to stale. +2. First optimize the existing algorithm, not the basis or physical model. + No change to not-a-knot construction, support conventions, extrapolation, + pivot checks, input ownership, or output orientation. +3. Begin with narrow host dense Float32/Float64 paths. Mixed types, Duals, + BigFloat, other array representations and device arrays retain the current + general path until separately demonstrated safe and beneficial. +4. Every forward-kernel change must have a corresponding transpose-kernel + design and tests. Prepared Mooncake performance is a primary deliverable. +5. No `@fastmath`, tolerance-based deletion of small matrix entries, automatic + threading, global scratch buffers, or dense inverse as the default. +6. Source arrays and plans remain unmodified. Independent calls/AD preparations + must not share mutable scratch accidentally. +7. No approximation-error tolerance may be loosened to accept a performance patch. + +## 4. Stage A: tighten the existing full-band CPU kernel + +This is the first bounded implementation experiment, before structural pruning. + +* Add a private dense-host helper, retaining the full bandwidth-three algorithm. + Validate the factor/RHS dimensions before any unchecked access. Dense Matrix + storage is one-based; do not assume this for arbitrary AbstractArrays. +* Separate short boundary ranges from the fixed-width interior, or explicitly + unroll its three updates. Preserve the existing per-element operation order. + Inspect optimized IR rather than assuming an annotation removed the checks. +* Apply `@inbounds` only within the proven bounds of that helper. A malformed + manually constructed factor must still fail safely, never access invalid memory. +* Keep division initially. Cached reciprocal pivots are a separate optional + experiment because multiplication by a rounded reciprocal is not the same + numerical operation as division. +* Do not add `@simd` to the dependent spectral-index recurrence. + +Narrow dispatch must not become ambiguous with the device methods whose RHS +argument is `DeviceVec`/`DeviceMat`. Prefer an internal host selector or methods +restricted on **both** dense factor and dense RHS storage. Do not specialize the +factor argument while leaving the RHS as `AbstractMatrix` and assume it is safe. + +Measure the entire public coefficient call, including selection, allocation +and copying. Retain this change only if the target workload actually improves. + +## 5. Stage B: exact bordered-tridiagonal specialization + +### 5.1 Eligibility, not an assumption based on N + +Initial implementation retains the same factor representation and tests its +**actual exact structure once per solve**, outside the RHS-column loop. +An O(N) scan is cheap compared with O(N × 8192) solves; its cost nevertheless +belongs in every public benchmark. It also avoids stale structural metadata. + +Eligibility requires: + +* dense host factor and RHS with the same supported floating type; +* `size(bands) == (7,N)`, matching RHS height, and N >= 6 initially; +* band rows 1 and 7 are zero; +* row 2 is zero except possibly column 4; +* row 6 is zero except possibly column N-3. + +Use exact zero tests, never a magnitude cutoff. A tiny but nonzero forbidden +entry must select the general algorithm. Small N=4,5 uses the general path in +the first implementation; optimize those only if measurements justify it. +Do not inspect only primal parts of Dual factors to decide to drop derivatives. + +These tests allow all first upper/lower diagonals, including endpoint entries. +The fast algebra therefore does not depend on a further assumption that the +canonical endpoint entries happen to be zero or the endpoint pivots equal one. + +Select the minimum profitable RHS count from measured vector/small-matrix +controls. There is no pre-approved magic threshold. Keep vector dispatch and +small batches on the old path if classification costs outweigh the saving. + +### 5.2 Factor interpretation and primal algorithm + +With `B = fact.bands`, define + +``` +d[j] = B[4,j] # U[j,j] +l[j] = B[5,j] # L[j+1,j], j=1:N-1 +v[j] = B[3,j] # U[j-1,j], j=2:N +alpha = B[6,N-3] # L[N-1,N-3] +beta = B[2,4] # U[2,4] +``` + +For each RHS, start with a copy `x` of the input. The reference pseudocode is: + +``` +# L y = input +for j = 1:N + if j < N: x[j+1] -= l[j] * x[j] + if j == N-3: x[N-1] -= alpha * x[j] + +# U coefficients = y +for j = N:-1:1 + x[j] /= d[j] + if j == 4: x[2] -= beta * x[j] + if j > 1: x[j-1] -= v[j] * x[j] +``` + +This is a direct substitution, not an approximate tridiagonal replacement. +The boundary couplings must not be dropped. Split ranges to remove repeated +conditionals only after this straightforward form passes the reference tests. + +### 5.3 Transpose algorithm, derived independently + +For an output cotangent `g`, compute `A^-T g = L^-T U^-T g`: + +``` +x = copy(g) +# U^T z = g +for j = 1:N + s = x[j] + if j == 4: s -= beta * x[2] + if j > 1: s -= v[j] * x[j-1] + x[j] = s / d[j] + +# L^T input_bar = z +for j = N:-1:1 + s = x[j] + if j < N: s -= l[j] * x[j+1] + if j == N-3: s -= alpha * x[N-1] + x[j] = s +``` + +The special upper coupling is applied before the adjacent upper coupling in +the transpose forward substitution, matching the old increasing-index sum. +Do not derive the adjoint by simply reversing the primal loop and guessing. + +Design-time algebra check: these recurrences were evaluated against independent +dense `A \ S` and `transpose(A) \ S` solves for synthetic factors with N=6,7,17,33, +seven RHS columns, nonzero endpoint off-diagonals, and both extra couplings. +With seed 20261020, the largest observed absolute difference was 4.44e-16. +This checks the formulas, not an implemented optimized ACE path or its AD rules. + +### 5.4 IEEE edge behavior + +Skipping exact zeros can change NaN/Inf propagation (`0*Inf` is NaN). Finite +inputs can also overflow during a solve. Do not silently change the public +nonfinite behavior while calling this a pure performance refactor. + +Conservative initial policy: structural pruning is used for finite factor/RHS +values with nonzero pivots; otherwise use the unchanged general solver. If +the pruned result becomes nonfinite, recompute from the original, unmodified +RHS with the general solver. Include these checks and fallback costs in the +benchmarks. They may later be fused with copying/output handling if measured +worthwhile; they may not disappear merely to improve a timing table. + +Test signed zeros and subnormal finite values. Bitwise identity is not a new +requirement, but existing documented behavior and numerical tests remain binding. + +## 6. Stage C: batch SIMD without corrupting the memory layout + +The independent dimension is RHS columns, not the spectral recurrence. In +Julia's `N × M` layout each column is contiguous, but adjacent columns at the +same spectral index are N elements apart. A naive loop interchange is not a +vectorization strategy. + +Prototype a small panel layout `(tile_rhs,N)` with contiguous RHS lanes: + +1. Pack a tile from the existing source layout into call-owned scratch. +2. Walk j sequentially; apply each recurrence operation across RHS lanes. +3. Unpack solved coefficients to the existing `N × M` output. +4. Handle the final partial tile explicitly; never read or overwrite tail lanes. + +Start with a bounded comparison of tile widths 8,16,32, not a broad autotuning +framework. At N128 these panels are 8,16,32 KiB in Float64. Factor values can +be reused across the lanes. Keep division first; measure reciprocal reuse as +a distinct arithmetic change. No global transposition of the downstream ABI. + +The same panel layout must support the transpose kernel. Include pack, unpack, +scratch allocation and ownership costs in public-path timings. A kernel-only +win with a slower public call is rejected. A register-interleaved small-column +implementation may be compared if packing dominates, but do not ship multiple +unmeasured strategies or a configuration knob for every prototype. + +Default operation remains single-threaded. Threading is a later, explicit +experiment because inference already parallelizes chains/processes. It requires +per-task scratch and a measured grain size; do not add nested parallelism to +every coefficient call. + +## 7. Reverse mode: preserve general geometry, reuse what is already known + +### 7.1 Safe first improvement: reuse the existing factorization + +For `A(sites,knots) C = S`, the full VJP is + +``` +lambda = A^-T C_bar +S_bar = lambda +A_bar = -lambda * C^T +``` + +ACE contracts the relevant entries of `A_bar` into basis/site derivatives +without forming that dense matrix. Keep those derivatives. They are exercised +by the live-geometry tests added in the upstream commits missing locally. + +Extend the private geometry VJP so plan-based callers can pass their existing +factorization. Keep the reconstructing path for ordinary spline objects that +do not retain a factorization. Update both ChainRules and Mooncake callers. +Do not store a second stale copy of the factor or rebuild it per pullback. + +The generic public `bspline_coefficients(plan,u)` remains differentiable with +respect to the supported plan geometry. A plan captured in a closure is not +permission to redefine its derivative as zero. The existing low-level bare- +factor solve rule is a fixed-factor rule, not a replacement for geometry AD. + +Profile this pullback separately: row-wise, strided dot products over all RHS +may dominate once the transpose solve becomes faster. A geometry-VJP panel +optimization is a separate measured step, not an automatic part of Stage C. + +### 7.2 Optional later API: explicitly frozen geometry + +Blast's inference grid is fixed, so a deliberate coefficients-only, frozen- +geometry preparation could expose just the `A^-T` input pullback. This is +potentially valuable, but it is **not part of the initial no-API-change patch**. + +Before implementing it, obtain separate API approval specifying construction, +ownership, adaptation, supported AD backends, and what happens when a caller +tries to differentiate its geometry. It must be explicit opt-in, constructed +outside the differentiated model, with no silent loss of gradients. Do not +make Blast reach into ACE's private factor storage as a shortcut. + +## 8. Alternatives and deliberate non-goals + +* **Preallocation:** useful but secondary in the current forward profile. Do + not change the allocating API's alias/lifetime contract. If an in-place API + is later justified, design explicit output/workspace ownership and AD rules. +* **Dense precomputed coefficient operator:** may be a benchmark control for + these small N and large batches; BLAS can beat poorly optimized scalar code. + It changes O(NM) work into O(N²M), adds conditioning/roundoff questions, and + is not the default proposed solution. No production inverse without evidence. +* **LAPACK band solve:** not a drop-in interpretation of this custom seven-row + pivot-free LU storage. Any control must construct compatible factors/pivots + during preparation, not reinterpret the array or time hidden conversion. +* **Reactant/device rewrite:** out of scope. Preserve existing device solve + dispatch and prepared dense interpolation operator behavior, including its + memory cap. Host structural checks must not execute on traced arrays. +* **Changing sites, knot placement, quadrature or the source ratio:** these + change approximation/scientific behavior and belong in another investigation. + +## 9. Correctness and AD acceptance + +### References before edits + +Freeze the current source identity, focused outputs and benchmark harness. +Save small deterministic coefficient/evaluation/adjoint arrays as text fixtures +with sites, inputs, dtype and provenance. Do not commit large batches or binary +artifacts. Retain a test-only baseline algorithm or an explicitly callable +general fallback so both branches remain testable after optimized dispatch. + +Use three independent checks: existing solver parity, dense collocation solve +`A \ S`, and mathematical reproduction/adjoint identities. Do not validate +only against another function that now calls the same optimized helper. + +### Required matrix + +* N=4,5,6,7,8,17,33,49,65,81,97,128,129; vector and matrix RHS counts + 0,1,2,7,8,9,16,31,32,33,257,8192 where practical. Zero-column handling must + preserve existing behavior. Exercise every SIMD tail and non-square shape. +* Uniform, power-spaced, Chebyshev-like sorted sites; seeded random positive + spacings; moderately clustered sites. Keep interval endpoints. Use current + canonical banks' sites as downstream fixtures, not only synthetic uniform grids. +* Generic valid bases/collocation sites with nonzero outer bands; also inject + a tiny nonzero forbidden factor entry to prove exact fallback selection. +* Constants, low-degree polynomials, oscillatory sources, signed random RHS, + zero inputs, signed zeros, subnormals and large finite values; NaN/Inf and + overflow cases to test the compatibility fallback. +* Float64, Float32, mixed precision, integer/range/view inputs, ForwardDiff + Duals and a small BigFloat reference case. Optimized dispatch is narrow; + unsupported optimized types must remain correct through the general path. +* Invalid dimensions, malformed factor storage, repeated/unsorted/nonfinite + sites, and existing singularity/extrapolation tests remain safe and intact. + +For well-conditioned, O(1)-scaled Float64 fixtures, target coefficient parity +with scaled max error <=1e-12; Float32 <=2e-5. Existing tighter tests are not +relaxed. Also check the **maximum per-column** backward error + +``` +eta_j = norm(A*c_j - s_j, Inf) / + (norm(A, Inf)*norm(c_j, Inf) + norm(s_j, Inf)) +``` + +with a design target `max(eta_j) <= 100eps(T)` on those fixtures. For zero +denominator require exact zero residual. Check baseline feasibility before +implementation; do not quietly change these targets after seeing a failure. +Ill-conditioned cases require condition-aware diagnosis and a higher-precision +reference, not a blanket increase of every test's tolerance. + +### Public and derivative paths + +1. Test `bspline_coefficients(plan,u)`, `plan(u)`, one-shot `CubicBSpline`, and + the forced general path. A passing private helper is insufficient. +2. Test `A' * lambda ≈ g` and the dot identity + ` ≈ ` with signed nontrivial cotangents. +3. On small non-square cases, compare prepared Mooncake gradients to prepared + ForwardDiff, and preserve existing ChainRules/Zygote/Enzyme tests. Exercise + both input values and **live sites/knots/query coordinates** as applicable. +4. On full batches use a dense/independent adjoint and directional checks; + do not attempt a full high-dimensional ForwardDiff gradient of 8,192 columns. +5. Reuse a DifferentiationInterface preparation for input sequence A,B,A. + Check no stale buffers, cotangent accumulation errors or input mutation. +6. Interleave independent plans and independent prepared gradients; then test + concurrent calls sharing a read-only plan but not mutable workspaces. + +New/changed tests run unconditionally in `Pkg.test()`. Keep the existing +Reactant tests unconditional: changed runtime inputs through one compiled +thunk, input/plan immutability, dense-operator caps, direct concrete methods, +and relevant compiled AD contracts. No `@allowscalar` workarounds or env gates. +New internal host helpers must not intercept device methods or create ambiguities. + +## 10. Performance acceptance and reproducibility + +Extend the existing `benchmark/` environment with a focused coefficient driver, +for example `benchmark/bench_bspline_coefficients.jl`; do not build another +package/dependency environment. Existing `bench_plain_splines.jl` benchmarks +complete interpolation and different input/query dimensions, so it is a +regression control, not a substitute for this coefficient workload. + +### Measurement ladder + +1. Local correctness/profile/IR investigation only; no claim that laptop + speedups transfer to Narval. +2. Focused matched baseline/candidate measurements at N=33,65,97,128 and + RHS=1,7,32,8192, Float64 and Float32. Test allocation/copy and transpose paths. +3. Only after a candidate passes, run all integer N=33:128 at RHS8192, plus + boundary/vector/tail controls and the complete interpolation regression cases. +4. Prepared reverse-mode benchmarks with input-only and live-geometry losses + are separate rows, not conflated with the forward coefficient numbers. +5. Downstream Blast public coefficient/Cℓ/gradient regression using unchanged + inputs and banks. Require parity with pre-optimization outputs, not improved + agreement with Chebyshev or a revised physical accuracy budget. + +Use BenchmarkTools with interpolated arguments, evals=1, 30 samples and a +sufficient time cap (five seconds worked for the previous campaign). Assert +sample coverage, persist raw trials after every case, and mark final output +complete only after the entire matrix. Record minimum and median, allocation +count/bytes, sample count and reference repetitions. In-place experiments must +reset input buffers outside timing and use independent workspaces. + +Prepare AD once with DifferentiationInterface's `prepare_gradient` and reuse +that preparation for timed `gradient`/`gradient!`. Report compilation and +preparation separately from hot execution. Use the actual public path and +verify finite/correct outputs before interpreting timings. + +Prefer old/new forward-kernel controls **inside the same node/process**, using +a frozen test-only baseline helper and interleaving their order on unchanged +inputs. Verify the baseline helper reproduces the original public call and +its allocation/copy contract; do not monkey-patch shared methods between trials. + +For full public AD comparisons between package revisions, use sequential, +alternating A/B/A processes inside the **same allocation, node and CPU binding** +if both revisions cannot coexist safely in one process. Keep dependency +versions/preferences identical, warm each process separately, and repeat the +pairing to measure variability. Do not invent fragile duplicate-package loading +or alter AD rules merely to force a single-process comparison. + +Retain the allocating public-path comparison even if a workspace-only +microbenchmark looks better. Do not compare against historical measurements +from another node as a speedup estimate or combine their rows into one trial. + +Record node/CPU, Julia/ACE versions and source hashes, CPU affinity, thread +settings, shapes, dtypes, grid provenance and script hashes. Keep Julia/BLAS/ +FFTW single-threaded for the primary comparison. Pin within the allocated CPU +set; no whole-node allocation merely to make a small benchmark easier. + +Proposed decision rules (not measured results): + +* Require repeatable improvement on the large-batch public path; aim for at + least 20% at representative counts before accepting additional complexity. + Removing complexity may justify a smaller gain, but document that decision. +* Investigate >5% regressions on controls; do not accept unexplained >10% + regressions. Establish repeatability before applying percentage gates to + microsecond-scale cases. Adjust dispatch rather than penalizing small inputs. +* If reference minima drift >5%, inspect/repeat the affected measurement before + claiming a small gain. Always report median drift as well. +* Forward gains cannot hide a prepared-gradient regression or a loss of + geometry derivatives. Optional strategies fail independently; retain the + simpler accepted stage instead of forcing every experiment into production. + +Narval login nodes are for scheduler/filesystem inspection only. Provision and +warm imports in an allocation before the short measurement job; do not spend +the measurement allocation resolving packages. Use cluster-local manifests, +request roughly ten minutes for a bounded warm comparison, and split a larger +matrix into independent complete baseline/candidate groups if needed. + +The earlier campaign had a setup timeout and then an insufficient sampling +window at Chebyshev N128. Preserve both failures. Do not mask missing cells, +interpret an EXIT trap's zero as success over Slurm TIMEOUT, or merge partial +timings from different nodes to manufacture a complete same-node comparison. + +## 11. Files, staged delivery and review + +Expected implementation files: + +* `src/cubic_b_spline.jl`: narrow host dispatch, exact pattern guard, full-band + and structured primal/transpose helpers; possibly local tiled workspace. +* `src/chainrules.jl`: reuse the plan's factorization in its geometry VJP, + preserving the full geometry derivatives and ordinary-spline fallback. +* `ext/MooncakeExt/MooncakeExt.jl`: matching plan-pullback reuse and tests. +* Existing spline solver/AD/abstract-input tests, plus a focused optimization + test file if needed, included unconditionally by `test/runtests.jl`. +* `benchmark/bench_bspline_coefficients.jl` and concise results documentation. + +No unrelated emulator, cosmology, package-version, or artifact changes. No +Reactant implementation edits unless an actual compatibility regression from +these host changes is demonstrated and its scope separately reviewed. + +Delivery order: + +| Stage | Deliverable | Required exit evidence | +|---|---|---| +| 0 | Reconcile upstream, freeze baseline/fixtures and benchmark contract | Correct source loaded; baseline tests/results recorded | +| A | Bounds-safe tight full-band host kernels | Public parity, transpose/AD parity, focused matched timings | +| B | Exact guarded structured solve and transpose | Boundary/outer-band/nonfinite fallback tests; measured public gain | +| C | Optional RHS-panel SIMD | Tail/alias/concurrency checks; packing-inclusive gain over B | +| D | General plan-VJP factor reuse | Live-geometry derivatives preserved; prepared reverse measurements | +| E | Optional reciprocal/threading/frozen-geometry work | Separate evidence/API approval as applicable, not automatic scope | +| Final | Full package/device/downstream regression and report | Complete benchmark matrix, raw evidence, reviewed defaults | + +Run the package suite before the first implementation change. For each stage, +focused tests are the first feedback loop; they must enter normal CI. Run +`julia --project=/absolute/path/to/AbstractCosmologicalEmulators.jl -e 'using Pkg; Pkg.test()'` +before accepting that stage, not instead of focused public-path checks. Use +the supported Julia CI matrix; no manually assembled disposable test environment. + +Review the arithmetic, dispatch, safety, transpose and AD behavior after each +stage. Record rejected variants and why they lost. Do not promise a specific +speedup before measurements, or proceed to the next stage solely because the +implementation report says it passed. + +## 12. Recommendation for the first approved chunk + +Approve **baseline capture + Stage A + the straightforward guarded Stage B** +as the first bounded chunk, with independent forward/transpose/AD checks and +same-node benchmarks. Do not include SIMD, threading, reciprocal arithmetic, +new public APIs or device algorithm changes in that first patch. + +The desired outcome is a demonstrably faster, equally correct ACE coefficient +solve that Blast receives automatically through its existing public call. +If the small structural change is sufficient, stop there rather than building +an optimization framework around a problem already solved. diff --git a/OPTIMIZATION_BSPLINE_NEXT_STEPS.md b/OPTIMIZATION_BSPLINE_NEXT_STEPS.md new file mode 100644 index 0000000..d920af8 --- /dev/null +++ b/OPTIMIZATION_BSPLINE_NEXT_STEPS.md @@ -0,0 +1,314 @@ +# ACE B-spline decomposition: next-stage optimization plan + +**Status:** approved for staged implementation on 2026-10-22. Stages 1 and 2a +are independently accepted locally; see their review/benchmark documents for +known package failures and qualified timing claims. Stage 3's host threading +interface is approved as the unified `set_threads(n)` in +`BSPLINE_THREADING_API_DESIGN.md`; no per-call threading keyword is wanted. +Optional API changes retain the explicit decision gates below. +**Baseline:** `96-b-spline`, commit `3f27573`, checked against the remote on +2026-10-22. Work in the existing checkout; no commits, pushes or releases unless +requested separately. + +This continues the accepted host-kernel work in `OPTIMIZATION_BSPLINE.md`. +Its Stage A/B kernels are already implemented. Do not redo them or use their +original pre-optimization baseline to exaggerate the gains from this phase. + +## 1. Objective and boundaries + +Make repeated coefficient recovery and reverse differentiation faster while +preserving the mathematical interpolant, numerical safety and existing API. +The main workload is a small number of sites and thousands of independent +right-hand sides, as used by Blast. ACE owns the implementation; Blast should +not acquire its own solver or reach into ACE's private factor storage. + +**AD support contract:** + +- Ordinary Julia: native **Mooncake** rules and **Zygote through ChainRules**. +- **ForwardDiff** supplies independent derivative checks. +- **Enzyme only through Reactant.** No native Enzyme extension, host Enzyme + rules, or native Enzyme certification campaign belongs in this project. +- Preserve Reactant compilation, numerical results and its existing Enzyme + differentiation paths. Host optimizations must not intercept device arrays. + +Do not change knots, sampling grids, extrapolation policies, physical sources, +quadrature, cosmological priors or error budgets. In particular, choosing k81 +rather than k65 is a separate scientific-resolution decision, not an algorithmic +speedup. No new B-tilde generation is needed for this optimization project. + +## 2. Current implementation and evidence + +The plan caches a pivot-free band LU of the collocation matrix. For + +\[ +A(x,t)C=U, +\] + +the public coefficient call allocates/copies its output and solves each column. +The dense Float32/Float64 implementation has tight full-band kernels plus an +exactly guarded bordered-tridiagonal specialization, including nonfinite-result +fallback. It is O(NM), not a dense inverse or O(N²M) solve. + +| Area | Current behavior | Consequence | +|---|---|---| +| Forward and transpose column loops | Serial | More Julia/BLAS threads alone do not parallelize decomposition | +| Read-only plan | Reusable across independent calls | No shared mutable scratch should be introduced | +| Plan geometry VJP | Rebuilds an existing factorization | Avoidable work without changing derivative semantics | +| Geometry reductions | Four strided row dot products per site | A measured reverse-pass hotspot | +| Generic plan AD | Computes supported geometry cotangents | Must not silently become a fixed-geometry derivative | +| Plan evaluation AD | Recomputes coefficients after computing the output | Possible recomputation-versus-tape-memory tradeoff | + +Source locations at this baseline: + +- `src/cubic_b_spline.jl`: factorization, forward/transpose solves, host dispatch, + `CubicBSplinePlan`, `_bspline_coefficients`, `_apply_cubic_b_spline_plan`. +- `src/chainrules.jl`: `_collocation_geometry_vjp`, coefficient and plan rules. +- `ext/MooncakeExt/MooncakeExt.jl`: native coefficient and plan primitives. + +The accepted Narval results already demonstrate approximately 2× forward and +1.7× transpose improvement over the old generic kernels. Those are historical +same-node measurements, not remaining improvement forecasts. + +The latest Alcanter audit used synthetic nonuniform grids, Float64 N×8192, +one pinned CPU and prepared Mooncake gradients: + +| N | Forward median, ms | Prepared gradient median, ms | Fixed-geometry analytic-gradient diagnostic, ms | +|---|---|---|---| +| 81 | 4.65–4.68 | 14.35–15.87 | 8.07 | +| 97 | 5.69–5.70 | 15.85–17.20 | 9.89 | + +Approximately 16.5% of sampled N81 gradient time was in geometry row dot +products. Forward allocation was 5.31/6.36 MB, versus 21.24/25.44 MB for the +prepared gradients. The analytic diagnostic omits the general geometry-AD +contract and some framework work: it is **not an implemented speedup**. +Temperature and gradient timing drift preclude a precise percentage forecast. + +Audit and raw evidence: +`../bspline_backend_validation/ACE_DECOMPOSITION_AUDIT_20261022.md` and the +scripts/logs linked there. Existing review: `REVIEW_BSPLINE_STAGE_AB.md`. + +## 3. Mathematical contract for reverse mode + +For an upstream coefficient cotangent C̄: + +\[ +\Lambda=A^{-T}\bar C,\qquad \bar U=\Lambda, +\qquad \bar A=-\Lambda C^T. +\] + +Contract only the required local entries of Ā into site/knot derivatives; +do not form a dense N×N matrix merely to recover a few bands. Keep the existing +not-a-knot mapping, including repeated endpoint-knot contributions. + +Coefficient recovery does not depend on query coordinates. Plan evaluation +does, so its query cotangents must remain correct. Raw LU storage remains +structural, not a new differentiable public parameter. + +Capturing a plan in a closure is **not** permission to zero its derivatives. +Any frozen-geometry shortcut requires an explicit, separately approved contract. + +## 4. Delivery stages + +Each stage is independently reviewable and measured against the last accepted +stage. Run focused tests first, then the full package gate. Stop or reject a +variant that adds complexity without a demonstrated benefit. + +### Stage 0 — Freeze the current baseline and close test gaps + +1. Recheck branch freshness, local changes, dependency resolution and the actual + `pathof(AbstractCosmologicalEmulators)` in every benchmark environment. +2. Run baseline `Pkg.test()` using the existing project. Record all failures. + Earlier reviews recorded unrelated Reactant Akima failures; do not assume + those are still present, call a failing suite green, or hide new failures. +3. Capture current public forward, transpose, Mooncake and Zygote performance. +4. Extend focused host AD tests where needed so both reverse backends exercise + coefficient recovery, plan evaluation, live geometry and repeated calls. +5. Reuse existing SciPy text fixtures, dense collocation references and frozen + generic solver controls. Preserve small additional baseline outputs as text + if a new test requires them; do not commit binary benchmark artifacts. + +**Exit:** reproducible baseline and passing focused correctness/AD tests, with +an explicit disposition for any unrelated full-suite failures. + +### Stage 1 — Reuse the cached factorization in plan pullbacks + +Extend the private geometry-VJP implementation to accept an already available +factorization. Keep its existing reconstructing entry point for ordinary +splines that do not retain a factorization. + +- Pass `plan.factorization` from coefficient and plan-evaluation rules in both + ChainRules and Mooncake. +- Keep all site/knot/query cotangents and current transpose-solve dispatch. +- Do not introduce a second cached factor, mutable global cache, stale structure + flag, or altered arithmetic in the underlying solve. +- Retain correct abstract-input projection and zero-cotangent handling. + +**Exit:** independent gradients match; plan-based VJPs no longer reconstruct +the factorization; prepared-gradient allocations/work decrease without a +regression elsewhere. A large speedup is not required for this small cleanup: +the audit did not identify factor construction as the dominant large-batch cost. + +### Stage 2 — Improve reverse-pass locality and allocation + +Profile the Stage 1 result before choosing the next change. + +**First candidate:** replace strided geometry row reductions with a +column-streaming or small-panel accumulation of the required local Ā entries. +Keep only O(N) or bounded-panel temporary storage, not O(N²M) work or a dense +geometry Jacobian. Accumulate basis/site derivatives using the same mathematics. +Changed floating-point summation order must be explicitly validated. + +**Separate candidate:** avoid repeated coefficient recovery in plan evaluation +AD. Compute the coefficients and stencil output once and retain what the +pullback needs. Compare the saved computation with additional tape lifetime +and peak memory; do not trade an uncontrolled memory increase for a microbenchmark +win. This does not directly accelerate coefficient-only calls. + +**Allocation review:** eliminate demonstrably redundant copies/temporaries +only with clear ownership. Never overwrite user inputs or a cotangent that +another pullback may still need. Do not share scratch between preparations. + +**Exit:** public forward/gradient parity, reusable pullbacks/preparations and +measured improvement in the targeted workload. Report peak/live memory as well +as per-call allocations for any retained-intermediate design. + +### Stage 3 — Controlled threading experiment + +Parallelize **independent RHS columns**, not the dependent forward/backward +recurrence within a column. The same strategy must cover the transpose solve. + +- Prototype contiguous column blocks with an explicit internal serial/threaded + policy. Keep the serial implementation as the baseline and small-input path. +- Classify the factor once before launching tasks. Preserve each column's + nonfinite fallback and access to its original RHS. +- Each worker owns disjoint output columns. Scratch, if any, belongs to the + task/call; do not index shared buffers by `threadid()` and assume tasks cannot + migrate, or introduce mutable plan-owned workspace. +- Test ordinary single-call latency and concurrent-chain throughput separately. + A library call inside already parallel inference must not silently enable + nested parallelism. Keep BLAS single-threaded during the comparison. +- Compare 1/2/4 physical cores on Alcanter; keep P/E cores and SMT placement + controlled. Extend to 8 cores on a suitable Narval allocation if justified. +- Benchmark a size threshold from N×M and measured task overhead. Do not assume + `Threads.nthreads()>1` is sufficient reason to parallelize every call. + +**Approved API update:** use the single `set_threads(n)` configuration for FFTW +and ACE CPU work, as specified in `BSPLINE_THREADING_API_DESIGN.md`. Large +batches automatically use the available configured budget; do not add per-call +keywords or plan fields. Small/generic cases retain the serial path. Verify +both forward and transpose policies, Mooncake and ChainRules, without changing +device behavior or claiming runtime enlargement of Julia's thread pool. + +**Exit:** deterministic forward/transpose correctness, no races or input +mutation, correct gradients, a useful large-batch gain and no unexplained +small-input or concurrent-throughput regression. No fixed speedup is promised. + +### Stage 4 — Optional, separately approved experiments + +These are not prerequisites for accepting Stages 1–3: + +- **Frozen geometry:** explicit preparation outside the differentiated model, + with only the ordinate pullback A⁻ᵀ. Define ownership and behavior for attempts + to differentiate frozen geometry. Keep the existing general API unchanged. +- **RHS-panel SIMD:** vectorize across independent series with bounded packing + storage; include packing/unpacking and allocation in the timing. Do not put + `@simd` on the dependent spectral-index recurrence. +- **Reciprocal pivots:** test separately; rounded reciprocal multiplication is + not identical to division and needs overflow/subnormal and gradient checks. +- **Public in-place/workspace API:** only if allocation profiling justifies it; + specify aliasing, lifetime, task ownership and reverse rules before coding. + +Do not make a dense inverse the default or build a dispatch framework merely +to accommodate experiments that have not shown a benefit. + +### Stage 5 — Package and downstream acceptance + +1. Run the supported Julia CI matrix and full package tests. Keep Reactant tests, + including its Enzyme checks, unconditional; do not weaken them to pass a host + optimization. Native CPU Enzyme remains out of scope. +2. Verify actual Blast coefficient-building calls use the updated ACE checkout + with reusable plans, not a copied solver or stale package installation. +3. Compare unchanged scientific inputs and saved reference outputs. Check a + prepared end-to-end Mooncake gradient and a ForwardDiff reference/directional + check, including a valid random prior draw through the existing model path. + Record the draw and failures; do not change priors to conceal numerical issues. +4. Benchmark the complete affected downstream path as well as ACE kernels. + Report separately what improves in coefficient recovery and in the full model. +5. Document accepted/rejected variants, measured configurations and remaining + limitations. Do not turn one fiducial test into a full-domain certification. + +## 5. Correctness and AD matrix + +Use existing test files, especially `test_cubic_b_spline_host_solver.jl`, +`test_cubic_b_spline_ad.jl`, abstract-input tests and SciPy reference tests. +Add new focused tests to `test/runtests.jl` unconditionally. + +| Dimension | Required coverage | +|---|---| +| Shape | Vector; M=1, 2, 7, 32, 256, 6144, 8192; small N=4,5,6 and representative larger N | +| Production sizes | N=65,81,97,129; retain legacy N128/control coverage | +| Geometry | Uniform, nonuniform, actual saved adaptive log-k sites, and supported custom-basis/generic-factor controls | +| Types/containers | Float32/64, mixed-type inputs, views/abstract inputs, ForwardDiff duals and existing generic-type controls | +| Safety | Forbidden-band tiny nonzeros, nonfinite RHS, overflow fallback, malformed dimensions, and all existing boundary tests | +| Reverse mode | Mooncake and Zygote versus ForwardDiff; ordinate and live-site gradients, plan query gradients, coefficient query independence | +| Reuse | A/B/A inputs with one preparation, interleaved plans, repeated/zero cotangents, and unchanged user arrays | +| Concurrency | Shared read-only plan, separate outputs and separate AD preparations; serial/threaded equivalence and tail blocks | + +Keep existing tolerances. For controlled, well-conditioned new tests, initial +targets are approximately 1e-12 relative coefficient parity in Float64 and +1e-9 absolute/relative gradient agreement; use the existing appropriate Float32 +tolerances. Diagnose conditioning before changing a tolerance. Compare directly +with dense A\U and Aᵀ\G on small cases; use directional/adjoint identities on +large cases instead of constructing a huge ForwardDiff gradient. + +Factor reuse should preserve the algorithm's results. Reduction reordering +need not be bitwise identical, but must meet the independently justified +precision contract. Keep nonfinite behavior tests separate from finite-value +relative-error metrics. + +## 6. Benchmark and acceptance protocol + +- Use the existing benchmark project and extend + `benchmark/bench_bspline_coefficients.jl`; include Zygote prepared-gradient + measurements, which the current focused driver lacks. +- BenchmarkTools only, interpolated arguments, `evals=1`, at least 30 completed + samples per retained cell. Treat inadequate coverage as incomplete, not merely + a warning followed by a successful report. +- Prepare gradients with DifferentiationInterface once, then reuse preparations. + Separate process/compiler warmup, preparation cost and hot execution; a timer + inside an already compiled wrapper is not a complete cold-compilation measure. +- Record output allocation/copy costs, bytes, minimum/median, raw samples, + source hashes, dependency versions, affinity, thread counts and CPU temperatures. +- Warm first, cool in-process, then alternate baseline/candidate/reference + measurements on the same machine and affinity. Do not mix CPUs/nodes or + compare historical laptop timings with current cluster timings. +- Require stable reference repetitions before interpreting small gains. If + minima or medians drift by more than 5%, investigate/repeat the affected cells. + Do not use the audit's unstable minima as acceptance baselines. +- For cross-revision AD comparisons, use alternating isolated processes with + the same environment rather than unsafe method replacement in a shared session. +- For substantial locality/threading/SIMD complexity, target a repeatable ~20% + improvement on the intended large-batch public path. Investigate >5% control + regressions; reject unexplained >10% regressions. These are decision gates, + not claimed or guaranteed speedups. Tiny housekeeping changes can be accepted + for measured allocation/work reduction without meeting the 20% target. +- On Narval, run computation only inside allocations, use cluster-local + manifests and bounded jobs, and monitor both success and failure. Do not + initiate a cluster campaign just to write this plan. + +Full-suite entry point, using an absolute checkout path: + +```bash +julia --project=/absolute/path/to/AbstractCosmologicalEmulators.jl \ + -e 'using Pkg; Pkg.test()' +``` + +## 7. Recommended first implementation chunk + +Approve **Stage 0 plus Stage 1** first: establish current Mooncake/Zygote baselines +and reuse the cached factorization without changing the public API. Review that +small patch independently, then choose the Stage 2 change from its new profile. + +Threading remains a measured follow-up, not an untested default switch. Frozen +geometry, public workspaces and other API changes require their own explicit +decision. Preserve all existing supported derivatives throughout. diff --git a/Project.toml b/Project.toml index 2f09547..fba7797 100644 --- a/Project.toml +++ b/Project.toml @@ -1,6 +1,6 @@ name = "AbstractCosmologicalEmulators" uuid = "c83c1981-e5c4-4837-9eb8-c9b1572acfc6" -version = "0.11.0" +version = "0.12.0" authors = ["Marco Bonici ", "Sofia Chiarenza "] [deps] @@ -35,6 +35,7 @@ Aqua = "0.8" Artifacts = "1.10" ChainRulesCore = "1.26" DataInterpolations = "6, 8, 9" +DelimitedFiles = "1.9" DifferentiationInterface = "0.7.16" Enzyme = "0.13" FFTW = "1" @@ -47,7 +48,7 @@ JET = "0.9, 0.11" JSON = "1" LinearAlgebra = "1.10" Lux = "1" -Mooncake = "0.4, 0.5" +Mooncake = "0.5" NPZ = "0.4" OrdinaryDiffEqTsit5 = "1, 2" Random = "1.10" @@ -62,6 +63,7 @@ julia = "1.10" ADTypes = "47edcb42-4c32-4615-8424-f2b9edc5f35b" Aqua = "4c88cf16-eb10-579e-8560-4a9242c79595" DataInterpolations = "82cc6244-b520-54b8-b5a6-8a565e85f1d0" +DelimitedFiles = "8bb1440f-4735-579b-a4ab-409b98df4dab" DifferentiationInterface = "a0c0ee7d-e4b9-4e03-894e-1c5f64a51d63" Enzyme = "7da242da-08ed-463a-9acd-ee780be4f1d9" FastChebInterp = "cf66c380-9a80-432c-aff8-4f9c79c0bdde" @@ -78,4 +80,4 @@ Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40" Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f" [targets] -test = ["ADTypes", "Aqua", "DataInterpolations", "DifferentiationInterface", "Enzyme", "FastChebInterp", "FastGaussQuadrature", "FiniteDifferences", "Integrals", "JET", "Mooncake", "OrdinaryDiffEqTsit5", "Random", "Reactant", "SciMLSensitivity", "Test", "Zygote"] +test = ["ADTypes", "Aqua", "DataInterpolations", "DelimitedFiles", "DifferentiationInterface", "Enzyme", "FastChebInterp", "FastGaussQuadrature", "FiniteDifferences", "Integrals", "JET", "Mooncake", "OrdinaryDiffEqTsit5", "Random", "Reactant", "SciMLSensitivity", "Test", "Zygote"] diff --git a/README.md b/README.md index 8813edf..517da98 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,53 @@ At the moment, the neural-network emulator backends supported here are based on - Extension support for optional packages, including `Reactant.jl` and `Mooncake.jl`. +## Cubic B-Spline Interpolation + +The package provides differentiable not-a-knot cubic B-spline interpolation. +The knot vector is determined uniquely from the interpolation sites: endpoint +knots have multiplicity four and the internal knots are `t[3:end-2]`. +Custom knots and custom basis objects are deliberately not accepted by the +high-level `CubicBSpline` or `CubicBSplinePlan` constructors. + +Use `cubic_b_spline_interpolation(u, t, t_new)` for one-shot interpolation, +`CubicBSpline(u, t)` when values are fixed and query points change, and +`CubicBSplinePlan(t, t_new)` when grids are fixed and values change. + +Matrix ordinates are supported, with each column treated as an independent +function over the same interpolation sites. Outside queries are clamped to +the nearest endpoint by default. The explicit extrapolation policies +`:clamp`, `:throw`, and `:zero` select endpoint continuation, strict domain +checking, or zero outside the domain. Callers should perform transformations +such as `log.(k)` before constructing the spline. + +ForwardDiff, Zygote, and Mooncake support derivatives through B-spline +ordinates, interpolation sites, and query coordinates on plain Julia arrays. +Reactant plans use a prepared dense interpolation operator and support Enzyme +differentiation through compiled execution. The one-shot Reactant path supports +fixed host sites with dynamic device ordinates and queries; fully dynamic device +sites are not currently supported. + +In compiled Reactant evaluation, dynamic `extrapolation=:throw` is unsupported +because XLA cannot lower data-dependent Julia exceptions. Use `:clamp` or +`:zero` for dynamic device queries. A fixed `CubicBSplinePlan` may use `:throw` +because its fixed query points are validated during host plan construction. + +## Threads + +`set_threads(n)` is the single thread setting. It sets FFTW's thread count for +FFT plans created afterwards (for example by `prepare_chebyshev_plan`), and the +task budget for large dense `Float32`/`Float64` B-spline coefficient solves in +`bspline_coefficients`, `plan(u)` and their Zygote/Mooncake pullbacks. +Independent columns are split across tasks; each column is computed exactly as +in the serial solve. Small batches, vectors and other element types stay serial. + +Julia's default thread pool is fixed at startup, so the B-spline budget is +`min(n, Threads.nthreads(:default))`: start Julia with `--threads=N` or +`JULIA_NUM_THREADS=N`. Without a call, large solves may use the whole default +pool and FFTW keeps its own setting. If you already parallelize over chains or +tasks, call `set_threads(1)`. `set_fft_threads` is deprecated and forwards to +`set_threads`. + ## Automatic differentiation compatibility The package is designed to be usable in differentiable cosmology pipelines. The interpolation and emulator utilities are tested with multiple AD systems, including: diff --git a/REVIEW_BSPLINE_STAGE1.md b/REVIEW_BSPLINE_STAGE1.md new file mode 100644 index 0000000..5559f2a --- /dev/null +++ b/REVIEW_BSPLINE_STAGE1.md @@ -0,0 +1,57 @@ +# Independent main-agent review: Stage 1 factorization reuse + +Base: `3f27573`, branch `96-b-spline`. Reviewed 2026-10-22. +No changes committed, staged or pushed. + +## Source review + +No production-code defect found in the bounded patch: + +- The existing two-argument geometry VJP retains factor reconstruction for + ordinary splines. Its new three-argument implementation receives the cached + factor from all four affected ChainRules/Mooncake plan-rule call sites. +- Transpose-solve arithmetic, local site/knot derivatives, not-a-knot mapping, + projection and zero-cotangent handling are unchanged. Geometry is not frozen. +- No new shared mutable state, public API, device dispatch, native Enzyme + support or dependency change. The host solver source hash remains unchanged. +- New tests exercise both public coefficient and evaluation paths, including + distinguishable marked-factor controls and independently checked live geometry. + +The marked-factor plans intentionally have inconsistent geometry/factor metadata +as test instruments. Only ordinate derivatives are certified for those plans; +live-geometry correctness is checked separately on normally constructed plans. + +## Independently checked evidence + +- Main-agent focused run: **6,341/6,341 passed**, bounds checks enabled, + Julia 1.12.6, four Julia threads and one BLAS thread. Correct checkout/module + identity asserted. Log: `benchmark/reviewer_logs/stage1/main_independent_focused.log`. +- Parsed raw TOMLs from both baseline/candidate rounds: all 100 cells are marked + complete with 30 raw samples each; candidate source hashes match this patch. +- All 32 paired public prepared-gradient measurements independently confirm + **three fewer allocations and 4,632 fewer bytes**. No large-batch speedup is + established. Small-batch percentages remain qualified by thermal/timing drift. +- Claude's baseline/candidate full logs contain 7,706/8,046 passing tests and + the same five Reactant Akima failures at lines 659/662, with no errors. + The baseline run had a transient edit before ACE reportedly loaded; that + provenance caveat remains in `BENCHMARK_BSPLINE_STAGE1.md`. The timed baseline + instead uses an immutable archived source snapshot in isolated processes. + +## Full-suite gate and disposition + +The main-agent full `Pkg.test()` rerun completed: **8,046 passed, five failed, +zero errors** in 19m23.5s. All five failures are the same pre-existing Reactant +Akima assertions at `test_ext_reactant.jl:659` (three) and `:662` (two). +Log: `benchmark/reviewer_logs/stage1/main_independent_pkgtest.log`. + +**Stage 1 is independently accepted as a bounded no-observed-regression patch.** +The package suite is still not green. Other Julia/platform CI versions have not +been run in this local review. No commit or push is authorized by this review. + +## Follow-up boundary + +An isolated Stage 2a prototype exists outside ACE under +`../bspline_backend_validation/stage2a_streaming_experiment/`. It is not integrated +or accepted. Its reordered reductions, guard costs and near-overflow guarantees +need independent validation; heuristic safety margins are not a general proof. +No further production edit should occur during the Stage 1 package test run. diff --git a/REVIEW_BSPLINE_STAGE2A.md b/REVIEW_BSPLINE_STAGE2A.md new file mode 100644 index 0000000..0494449 --- /dev/null +++ b/REVIEW_BSPLINE_STAGE2A.md @@ -0,0 +1,85 @@ +# Independent review: streamed collocation geometry VJP + +2026-10-22. Control: the accepted Stage 1 working tree, not bare `3f27573`. +**Disposition: accepted locally with the performance qualifications below.** + +## Code and numerical contract + +No production defect identified in source review so far: + +- Dense Float64 matrix batches with at least 512 columns use a column-streamed + contraction. Small batches, other types and abstract storage retain the old + dot-based loop. Forward and transpose solve arithmetic is untouched. +- The same computed Lambda is returned on either path. Unsafe-input fallback + clears provisional site/knot outputs before executing the old reduction; + it does not perform a second solve or mutate user arrays. +- The guard includes absolute product sums and absolute local basis partials, + covering local contractions, knot accumulation and not-a-knot mapping. The + checked dimension limits bound rounding growth below 1.001; floatmax/2 gives + a conservative finite-result bound. This replaces the pilot's heuristic + margins. Nonfinite bounds trigger exact fallback. +- Geometry-jet extraction is factored out without changing its arithmetic. + Shared geometry and user inputs remain read-only; scratch is call-local. +- Geometry cotangents may differ by reordered rounding. The overflow argument + is VJP-local, not a whole-program guarantee for subsequent unrelated tangent + additions near floatmax. No bitwise geometry-gradient claim is made. +- No public API, threading, native CPU Enzyme support, device extension or + dependency change is introduced. Mooncake and Zygote retain live geometry. + +## Independent checks completed + +- Main-agent bounds-checked focused run: **6,657/6,657 passed**, including the + new streamed-path cases, cached-factor tests and existing host spline tests. + Log: `benchmark/reviewer_logs/stage2/main_independent_focused.log`. +- Main-agent full suite: **8,362 passed, five failed, zero errors**, in + 17m14.4s. All failures match the baseline Akima assertions at lines 659 + (three) and 662 (two). Log: + `benchmark/reviewer_logs/stage2/main_independent_pkgtest.log`. +- Frozen Stage 1 source hashes match the accepted implementation. Parsed + baseline/candidate manifests are identical after normalizing only the ACE + checkout path. +- All three adaptive-site text fixtures are byte-identical to the saved design + grids; their recorded SHA256 values were verified independently. +- Worker full-suite log inspected: **8,362 passed, five failed, zero errors**. + Failure locations and class match the five existing Reactant Akima failures. + This is not yet the main-agent full-suite rerun result and not a green suite. +- Cross-revision digest artifacts report 64 unchanged cases identical and + changes confined to the intended streamed geometry reductions. Numerical + acceptance relies additionally on ForwardDiff and cancellation-aware + BigFloat tests, not just bitwise comparisons between implementations. + +## Review correction + +The new public-gradient benchmark initially depended on a private absolute +path outside the repository. Main review changed it to the checked-in text +fixtures under `test/reference/bspline_adaptive_sites`, resolved from the driver +location. Both revisions therefore read the same portable inputs. Production +source was not changed during the main-agent tests. + +## Performance acceptance + +The complete primary run has 124/124 cells with 30 raw samples each; source +hashes match the candidate. N129/M8192 prepared coefficient gradients improve +22.5-28.4% for both backends and both ordinate/live-site objectives, with +same-revision median drift below 4%. Float32 controls remain within about 1% +and have identical allocation counts. Additional scratch is 8 allocations and +6,128/9,616 bytes per gradient at N81/N129. + +N81 large-batch minimum timings repeat closely and improve 22.8% (Mooncake) +and 26.4% (Zygote); several medians are unstable and remain unqualified. +A targeted GC diagnostic recorded 59/64 cells before its deadline, explicitly +remaining incomplete. It rejects GC as the explanation for bimodality and +reproduces improvements rather than regressions in the two measured Mooncake +threshold cases. No missing result is treated as measured. Full details and +the changed measurement semantics are in `BENCHMARK_BSPLINE_STAGE2A.md`. + +Acceptance is for this bounded host optimization, not a green package suite, +universal median-latency guarantee, cross-platform CI result or downstream Blast +speedup. The threshold is conservative, not proven optimal. No additional +exclusive measurement is queued. + +The worker session timed out after writing the candidate and running its tests, +before recording public benchmarks. Main owns the remaining gates directly. +Main completed the primary benchmark and disposition separately; the worker's +partial handoff alone was not accepted as evidence. Nothing is staged, +committed or pushed. diff --git a/REVIEW_BSPLINE_STAGE_AB.md b/REVIEW_BSPLINE_STAGE_AB.md new file mode 100644 index 0000000..07fdac1 --- /dev/null +++ b/REVIEW_BSPLINE_STAGE_AB.md @@ -0,0 +1,157 @@ +# Independent review: bounded B-spline host solver optimization + +2026-10-20. Base `af7944975f422af0271ebdfb03a6ba2395a5e2c8`, branch +`96-b-spline`. Fetch confirmed HEAD and upstream have zero divergent commits. +Candidate kernel source SHA256: +`3cda5698898ca8eefa7437d937f266a8a325dd081450ff515d4788cc824b7af0`. +No implementation subagent was used for this review. + +## Current disposition + +No P1 runtime defect found in the bounded primal/transpose implementation. +**Independent numerical/AD and full-suite regression checks are complete.** +Full suite: 7,706 passed, five failed, zero errors, 15m22.5s. All five failures +match the baseline Reactant Akima test locations and failure class. This is +evidence of no observed solver regression, **not a green package suite**. +Delivery still has the two P2 harness/provenance findings below. +Two P2 reproducibility/harness issues are identified below. Do not describe +the package benchmark driver as a strict sample-coverage gate without fixing +the second issue; the actual Narval campaign separately enforced its gate. + +The main reviewer read the entire new host driver, both complete structured +recurrences, both complete full-band recurrences, all 588 focused-test lines, +the frozen-reference generator, benchmark driver and unchanged relevant AD rules. + +## Independent evidence + +- Fresh local focused run: **5,718/5,718 passed**, four Julia threads, + `--check-bounds=yes`, 48.8 seconds. Loaded package path asserted equal to this + checkout. Log: `benchmark/reviewer_logs/focused_host_solver.log`. +- Prepared Mooncake versus ForwardDiff includes input-only and live-site + gradients, A/B/A cache reuse, separate preparations, a larger-batch dense + transpose reference, and read-only shared-plan concurrency. +- Actual public coefficient paths are covered: plan, one-shot spline and + interpolation APIs, vector and matrix inputs. Frozen text, independent dense + solves and baseline band kernels provide separate reference mechanisms. +- Independent full `Pkg.test()` completed after focused success with four + threads and single-threaded BLAS: 7,706 passes, five Akima failures, no errors. + All B-spline host, AD and Reactant B-spline groups passed. Log is + `benchmark/reviewer_logs/full_pkgtest.log`. +- The implementer's 7,706-pass/5-fail full run and 1,988-pass/5-fail baseline + reported the same Reactant Akima fallback failures at + `test/test_ext_reactant.jl:659,662`. The fresh run independently reproduced + the same five assertions: nonfinite compiled Akima gradients and failures + against finite reference gradients. Reactant tests remain unconditional. +- Narval job 6581056 passed separate dense gates and complete paired coverage. + Forward speedup 2.02–2.17×; transpose solve 1.70–1.77×. See + `BENCHMARK_BSPLINE_CANDIDATE.md` for full provenance and limitations. +- `git diff --check` passed. No package API, dependency, factorization, + ChainRules, Mooncake-rule, Reactant implementation or version change. + +## Source-level checks + +### Bounds and eligibility + +`src/cubic_b_spline.jl:439–477` restricts selection to exact dense host +Float32/Float64 storage, equal factor/RHS types and the actual factor pattern. +The unchecked driver verifies seven band rows and matching order. Structured +selection additionally requires N≥6 and at least two RHS columns. The exact +guard rejects tiny nonzero forbidden couplings, nonfinite used entries and zero +pivots. It deliberately ignores the two never-read padding entries. + +Both full-width kernels split the three short boundary cases from the interior +while preserving the original update order. Inspection of N=0:5 confirms the +empty/short loop ranges avoid invalid unrolled indices; focused tests cover +those hand-built factors bitwise. Malformed storage goes to checked generic +code rather than entering unchecked kernels. + +### Structured recurrences + +In the seven-row storage, the only second off-diagonal couplings retained are +`alpha=B[6,N-3]=L[N-1,N-3]` and `beta=B[2,4]=U[2,4]`. + +The primal forward substitution updates rows N−2 and N−1 from the same finished +row N−3 before finishing the lower bidiagonal tail. Its upper substitution +applies beta to row 2 from finished row 4 before completing rows 3,2,1. +The transpose first solves Uᵀ with beta contributing from row 2 into row 4, +then Lᵀ with alpha contributing from row N−1 into row N−3. This remains valid +at N=6 and N=7, including the nearby boundary couplings. + +### Nonfinite semantics and ownership + +Pruning zero multiplications would change NaN/Inf propagation. The driver +checks each structured result column for finiteness. Any nonfinite result is +restored from the original, unmodified RHS and recomputed with the original +full-band arithmetic order. Finite factors with nonzero pivots cannot turn an +input NaN/Inf into an entirely finite result, so this also detects nonfinite +inputs. The focused tests cover each bad input position, overflow, factor NaNs, +zero pivots, signed zeros and subnormals against the frozen algorithm. + +No factor metadata or shared scratch is mutated. Each public solve owns its +output copy; the source array is retained only for restoration. Matrix/vector +views, mixed types, integers, Duals and BigFloat retain generic paths where +applicable. Unchanged AD primitives use the optimized transpose result without +introducing a new fixed-geometry assumption or factorization-reuse scheme. + +## P2 findings + +### P2-1: reference regeneration can falsely claim the old revision + +File: `test/reference/bspline_coefficient_solver/generate_fixtures.jl`, usage +comment, package import and metadata-writing block. + +The script loads whichever ACE the active environment resolves, writes fixtures +in place, and unconditionally stamps `source_commit=af79449...`. Running its +documented command against this dirty candidate therefore regenerates from the +new solver while still labelling the outputs as the old revision. The current +fixtures independently agree with dense and frozen references; this is a +future regeneration/provenance defect, not evidence they are numerically wrong. + +Required repair: verify the loaded baseline kernel source hash before **any** +output write, refuse a candidate/different source with actionable instructions, +and record the verified hash. Do not change the existing numerical fixtures. +Checking only Git HEAD is insufficient: HEAD is still af79449 in this dirty +checkout. A source hash must detect dirty implementation contents too. + +Acceptance: on this candidate, regeneration must fail before creating or +modifying files; all existing fixture checksums remain unchanged. Against the +verified original source, generation remains possible and metadata records the +actual verified provenance. + +### P2-2: the standalone benchmark marks incomplete sampling as complete + +File: `benchmark/bench_bspline_coefficients.jl`, `bench` and final `save` calls. + +The driver requests 30 samples but merely warns when the time cap returns fewer; +the caller can still mark the matrix complete. In particular, there is no hard +minimum of five samples. A slower machine or later larger case can therefore +produce a nominally complete but insufficiently sampled result. + +Required repair: enforce an explicit minimum valid sample count before accepting +a trial; keep raw actual counts and distinguish requested 30 from the valid +minimum. Do not weaken the current campaign's stricter 30-sample acceptance. +Use an independently testable coverage validator or equivalent deterministic +test rather than making CI sleep until a benchmark times out. + +Acceptance: synthetic counts below the minimum must raise; valid counts must +pass; a failed trial cannot produce a newly complete result. The existing +Narval campaign is unaffected because its wrapper independently checked all +80 trials had 30 samples and returned exit zero only after all checks. + +## Focused repair order and handoff + +1. Keep numerical solver and saved numeric fixtures unchanged. +2. Fix the fixture generator's provenance guard and prove candidate refusal + without touching fixture bytes. +3. Fix and directly test benchmark sample validation, preserving raw samples. +4. Re-run focused tests before any further full run. The independent full run + has reproduced the five baseline Akima failures; report them separately, + never claim a green full suite. +5. Re-review only changed harness code. No SIMD/threading/API/geometry-VJP/device + work, no new package dependencies, no commits/pushes/tags. + +Bounded implementer prompt: “Read this review and OPTIMIZATION_BSPLINE.md. +Repair only P2-1/P2-2 with deterministic focused checks. Preserve numeric +fixtures and kernel source hash exactly. State commands, results and remaining +full-suite failures. Do not reinterpret the measured coefficient gain as an +AD or full-likelihood gain. Do not commit or push.” diff --git a/benchmark/bench_bspline_coefficients.jl b/benchmark/bench_bspline_coefficients.jl new file mode 100644 index 0000000..73b9033 --- /dev/null +++ b/benchmark/bench_bspline_coefficients.jl @@ -0,0 +1,618 @@ +# Focused B-spline coefficient benchmark (forward, transpose, prepared gradient). +# +# julia --project=/abs/path/to/AbstractCosmologicalEmulators.jl/benchmark \ +# /abs/path/to/benchmark/bench_bspline_coefficients.jl OUTDIR [forward|transpose|gradient|all] +# julia ... bench_bspline_coefficients.jl OUTDIR pullback TAG +# julia ... bench_bspline_coefficients.jl OUTDIR stage2 TAG +# julia --threads=4 ... bench_bspline_coefficients.jl OUTDIR stage3 TAG +# +# The benchmark project must have THIS checkout developed into it. Timings are +# diagnostic for the machine they ran on; they are not cluster results. +# +# Controls: +# * "baseline": a private, verbatim copy of the original (af79449) allocating +# solve and generic kernels defined in this file. It does NOT call any +# helper from src/, so it cannot be routed through the optimized code. +# * "public": the actual public `bspline_coefficients(plan, u)` call, +# including classification, allocation/copy and non-finite guards. +# Per-case raw samples are persisted after every case; the file is marked +# `complete = true` only after the whole matrix finished. + +using AbstractCosmologicalEmulators +using BenchmarkTools +using DifferentiationInterface +using ForwardDiff +using LinearAlgebra +using Mooncake +using Random +using SHA +using TOML +using Zygote +import ADTypes: AutoMooncake, AutoZygote + +const ACE = AbstractCosmologicalEmulators +const ChainRulesCore = ACE.ChainRulesCore + +# ---- frozen baseline (verbatim original algorithm) --------------------------- +function baseline_band_solve!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + for j in 1:n + for i in (j+1):min(n, j+3) + x[i] -= B[4 + i - j, j] * x[j] + end + end + for j in n:-1:1 + x[j] /= B[4, j] + for i in max(1, j-3):(j-1) + x[i] -= B[4 + i - j, j] * x[j] + end + end + return x +end + +function baseline_band_solve_adjoint!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + for j in 1:n + s = x[j] + for i in max(1, j-3):(j-1) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s / B[4, j] + end + for j in n:-1:1 + s = x[j] + for i in (j+1):min(n, j+3) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s + end + return x +end + +function baseline_solve(bands::AbstractMatrix, B_mat::AbstractMatrix) + X = similar(B_mat, promote_type(eltype(bands), eltype(B_mat))) + copyto!(X, B_mat) + for c in 1:size(X, 2) + baseline_band_solve!(bands, view(X, :, c)) + end + return X +end + +function baseline_solve_adjoint(bands::AbstractMatrix, B_mat::AbstractMatrix) + X = similar(B_mat, promote_type(eltype(bands), eltype(B_mat))) + copyto!(X, B_mat) + for c in 1:size(X, 2) + baseline_band_solve_adjoint!(bands, view(X, :, c)) + end + return X +end + +# ---- inputs ------------------------------------------------------------------- +# LSST-like source grid: Chebyshev-like nonuniform sites and a non-polynomial source. +function make_grid(n) + k = 0:(n - 1) + return sort(2.0 .+ 0.5 .* (cos.(pi .* k ./ (n - 1)) .+ 1) .* (9000 - 2)) +end + +function make_values(::Type{T}, sites, m, rng) where {T} + base = @. exp(-sites / 3000) * (1 + 0.1 * sin(sites / 40)) + U = base .* (1 .+ 0.01 .* randn(rng, 1, m)) .+ 0.001 .* randn(rng, length(sites), m) + return T.(U) +end + +function summarize(trial) + t = BenchmarkTools.minimum(trial) + md = BenchmarkTools.median(trial) + return Dict( + "min_ns" => t.time, "median_ns" => md.time, "allocs" => md.allocs, + "bytes" => md.memory, "samples" => length(trial.times), + "times_ns" => collect(trial.times), + "gctimes_ns" => collect(trial.gctimes), + ) +end + +const SAMPLES = 30 +const SECONDS = 5 + +function bench(f, args...) + # warm, then measure with interpolated args and evals=1 + f(args...) + trial = @benchmark $f($(args)...) samples=SAMPLES evals=1 seconds=SECONDS + length(trial.times) == SAMPLES || + @warn "short sample coverage" got = length(trial.times) want = SAMPLES + return summarize(trial) +end + +function provenance(root) + git(args) = try readchomp(`git -C $root $args`) catch; "unavailable" end + return Dict( + "julia" => string(VERSION), + "pathof_ACE" => pathof(ACE), + "git_head" => git(`rev-parse HEAD`), + "src_sha256" => bytes2hex(sha256(read(joinpath(root, "src", "cubic_b_spline.jl")))), + "script_sha256" => bytes2hex(sha256(read(@__FILE__))), + "julia_threads" => Threads.nthreads(), + "blas_threads" => BLAS.get_num_threads(), + "cpu" => Sys.cpu_info()[1].model, + "hostname" => gethostname(), + "samples" => SAMPLES, "seconds_cap" => SECONDS, + ) +end + +function save(path, data, complete) + data["complete"] = complete + open(path, "w") do io + TOML.print(io, data) + end +end + +function run_forward(out, ns, ms, types, mode) + root = dirname(dirname(pathof(ACE))) + data = Dict{String,Any}("provenance" => provenance(root), "cases" => Dict{String,Any}()) + path = joinpath(out, "bspline_coefficients_$(mode).toml") + rng = MersenneTwister(20261020) + for T in types, n in ns, m in ms + sites = T.(make_grid(n)) + plan = CubicBSplinePlan(sites, sites[2:end-1]) + bands = plan.factorization.bands + U = make_values(T, sites, m, rng) + # correctness gate before timing + if mode == "transpose" + ref = baseline_solve_adjoint(bands, U) + got = ACE.solve_adjoint(plan.factorization, U) + pub_f = (p, u) -> ACE.solve_adjoint(p.factorization, u) + base_f = (p, u) -> baseline_solve_adjoint(p.factorization.bands, u) + else + ref = baseline_solve(bands, U) + got = bspline_coefficients(plan, U) + pub_f = bspline_coefficients + base_f = (p, u) -> baseline_solve(p.factorization.bands, u) + end + tol = T == Float64 ? 1e-12 : 2e-5 + @assert all(isfinite, got) + @assert maximum(abs, got .- ref) / max(1, maximum(abs, ref)) <= tol + key = "$(T)_N$(n)_M$(m)" + # interleave baseline / public order across two rounds + rows = Dict{String,Any}() + rows["baseline_1"] = bench(base_f, plan, U) + rows["public_1"] = bench(pub_f, plan, U) + rows["public_2"] = bench(pub_f, plan, U) + rows["baseline_2"] = bench(base_f, plan, U) + data["cases"][key] = rows + save(path, data, false) + println(key, " baseline min ms = ", + round(min(rows["baseline_1"]["min_ns"], rows["baseline_2"]["min_ns"]) / 1e6; digits=4), + " public min ms = ", + round(min(rows["public_1"]["min_ns"], rows["public_2"]["min_ns"]) / 1e6; digits=4), + " allocs(public) = ", rows["public_1"]["allocs"]) + end + save(path, data, true) + return path +end + +function run_gradient(out, ns, ms) + root = dirname(dirname(pathof(ACE))) + data = Dict{String,Any}("provenance" => provenance(root), "cases" => Dict{String,Any}()) + path = joinpath(out, "bspline_coefficients_gradient.toml") + rng = MersenneTwister(20261020) + mc = AutoMooncake(; config=Mooncake.Config()) + for n in ns, m in ms + sites = make_grid(n) + q = sites[2:end-1] + plan = CubicBSplinePlan(sites, q) + U = make_values(Float64, sites, m, rng) + W = randn(rng, n, m) + loss_u(u) = sum(abs2, bspline_coefficients(plan, u)) + loss_g(t) = dot(W, bspline_coefficients(CubicBSplinePlan(t, q), U)) + rows = Dict{String,Any}() + for (name, loss, x0) in (("input_only", loss_u, U), ("live_geometry", loss_g, sites)) + prep = DifferentiationInterface.prepare_gradient(loss, mc, x0) + g = DifferentiationInterface.gradient(loss, prep, mc, x0) + @assert all(isfinite, g) + rows[name] = bench( + (l, p, x) -> DifferentiationInterface.gradient(l, p, mc, x), loss, prep, x0) + end + key = "Float64_N$(n)_M$(m)" + data["cases"][key] = rows + save(path, data, false) + println(key, " input_only min ms = ", round(rows["input_only"]["min_ns"] / 1e6; digits=4), + " live_geometry min ms = ", round(rows["live_geometry"]["min_ns"] / 1e6; digits=4)) + end + save(path, data, true) + return path +end + +# ---- plan pullbacks: prepared Mooncake and Zygote gradients ------------------- +# Public plan coefficient/evaluation gradients, input-only and with live sites. +# Compare revisions by running this mode in alternating fresh processes, one +# per revision, with identical dependencies; nothing here replaces package +# methods. Unlike `bench`, a cell with fewer than SAMPLES samples is an error. + +const PULLBACK_SECONDS = 120 + +function bench_strict(f, args...) + f(args...) + trial = @benchmark $f($(args)...) samples=SAMPLES evals=1 seconds=PULLBACK_SECONDS + got = length(trial.times) + got == SAMPLES || error("incomplete sample coverage: got $got, require $SAMPLES") + return summarize(trial) +end + +function pkg_temp_c() + for zone in readdir("/sys/class/thermal"; join=true) + type_file = joinpath(zone, "type") + isfile(type_file) && strip(read(type_file, String)) == "x86_pkg_temp" || continue + return parse(Int, strip(read(joinpath(zone, "temp"), String))) / 1000 + end + return NaN +end + +function cool_down(target_c, max_wait_s) + start = time() + while pkg_temp_c() > target_c && time() - start < max_wait_s + sleep(1) + end + return Dict("temp_c" => pkg_temp_c(), "waited_s" => time() - start) +end + +# Dense stencil operator S, so plan(u) == S * coefficients. +stencil_matrix(plan) = ACE._evaluate_stencil( + plan.stencil, + Matrix{Float64}(I, length(plan.sites), length(plan.sites)), +) + +function run_pullback(out, tag; n=81, ms=(7, 8192), cool_target_c=52.0, cool_max_s=240.0) + root = dirname(dirname(pathof(ACE))) + prov = provenance(root) + for file in ("src/chainrules.jl", "ext/MooncakeExt/MooncakeExt.jl") + prov["sha256_" * basename(file)] = bytes2hex(sha256(read(joinpath(root, file)))) + end + prov["tag"] = tag + prov["affinity"] = try strip(read(`taskset -pc $(getpid())`, String)) catch; "unavailable" end + prov["gc_threads"] = Threads.ngcthreads() + prov["versions"] = Dict(string(m) => string(pkgversion(m)) + for m in (Mooncake, Zygote, DifferentiationInterface, BenchmarkTools, ForwardDiff)) + prov["seconds_cap"] = PULLBACK_SECONDS + data = Dict{String,Any}("provenance" => prov, "setup" => Dict{String,Any}(), + "cases" => Dict{String,Any}(), "temperature" => Dict{String,Any}()) + path = joinpath(out, "bspline_pullback_$(tag).toml") + backends = (("mooncake", AutoMooncake(; config=Mooncake.Config())), ("zygote", AutoZygote())) + rng = MersenneTwister(20261022) + sites = make_grid(n) + q = sites[2:end-1] + cells = Any[] + + # Compile and prepare everything first; correctness gates precede timing. + for m in ms + plan = CubicBSplinePlan(sites, q) + U = make_values(Float64, sites, m, rng) + G = randn(rng, n, m) + W = randn(rng, length(q), m) + A = basis_matrix(plan.basis, sites) + S = stencil_matrix(plan) + d = randn(rng, n) .* (1 .< (1:n) .< n) .* 1e-3 .* minimum(diff(sites)) + losses = ( + ("coeff_input", u -> dot(G, bspline_coefficients(plan, u)), U, transpose(A) \ G), + ("eval_input", u -> dot(W, plan(u)), U, transpose(A) \ (transpose(S) * W)), + ("coeff_live_sites", t -> dot(G, bspline_coefficients(CubicBSplinePlan(t, q), U)), sites, nothing), + ("eval_live_sites", t -> dot(W, CubicBSplinePlan(t, q)(U)), sites, nothing), + ) + for (bname, backend) in backends, (lname, loss, x0, dense) in losses + key = "N$(n)_M$(m)_$(lname)_$(bname)" + prep_cold_s = @elapsed prep = DifferentiationInterface.prepare_gradient(loss, backend, x0) + grad_cold_s = @elapsed g = DifferentiationInterface.gradient(loss, prep, backend, x0) + if dense === nothing + directional = ForwardDiff.derivative(h -> loss(x0 .+ h .* d), 0.0) + rel = abs(dot(g, d) - directional) / max(abs(directional), eps()) + rel <= 1e-7 || error("$key directional gate failed: $rel") + else + err = maximum(abs, g .- dense) / max(1, maximum(abs, dense)) + err <= 1e-10 || error("$key dense gate failed: $err") + end + prep_hot_s = [@elapsed(DifferentiationInterface.prepare_gradient(loss, backend, x0)) for _ in 1:3] + data["setup"][key] = Dict("prepare_first_s" => prep_cold_s, + "gradient_first_s" => grad_cold_s, "prepare_again_s" => prep_hot_s) + grad = (l, p, b, x) -> DifferentiationInterface.gradient(l, p, b, x) + push!(cells, (key, grad, (loss, prep, backend, x0))) + end + + # Rule-level pullbacks exist in every revision: direct allocation evidence. + _, coeff_pb = ChainRulesCore.rrule(bspline_coefficients, plan, U) + _, eval_pb = ChainRulesCore.rrule(ACE._apply_cubic_b_spline_plan, plan, U) + push!(cells, ("N$(n)_M$(m)_chainrules_coeff_pullback", coeff_pb, (G,))) + push!(cells, ("N$(n)_M$(m)_chainrules_eval_pullback", eval_pb, (W,))) + push!(cells, ("N$(n)_M$(m)_factorization_build", + ACE.CubicBSplineFactorization, (plan.basis, plan.sites))) + + # In-process control: the rebuilding geometry VJP (both revisions) + # versus the cached-factor method, where the revision provides it. + spline = CubicBSpline(plan.sites, plan.basis, bspline_coefficients(plan, U), + plan.extrapolation) + push!(cells, ("N$(n)_M$(m)_collocation_vjp_rebuild", + (s, g) -> ACE._collocation_geometry_vjp(s, g), (spline, G))) + if hasmethod(ACE._collocation_geometry_vjp, Tuple{Any,Any,ACE.CubicBSplineFactorization}) + push!(cells, ("N$(n)_M$(m)_collocation_vjp_reuse", + (s, g, f) -> ACE._collocation_geometry_vjp(s, g, f), + (spline, G, plan.factorization))) + end + end + save(path, data, false) + + data["temperature"]["after_setup_c"] = pkg_temp_c() + data["temperature"]["cool_down"] = cool_down(cool_target_c, cool_max_s) + for (key, f, args) in cells + before = pkg_temp_c() + row = bench_strict(f, args...) + row["temp_before_c"] = before + row["temp_after_c"] = pkg_temp_c() + data["cases"][key] = row + save(path, data, false) + println(rpad(key, 48), " median ms = ", round(row["median_ns"] / 1e6; digits=4), + " min ms = ", round(row["min_ns"] / 1e6; digits=4), + " allocs = ", row["allocs"], " bytes = ", row["bytes"], + " T = ", before, "→", row["temp_after_c"]) + end + save(path, data, true) + return path +end + +# ---- streamed collocation geometry: prepared public gradients ------------------ +# Saved adaptive log-k production sites (read from the frozen design grids, so +# every revision measures identical inputs). Same protocol as `run_pullback`. + +const ADAPTIVE_GRIDS = normpath(joinpath( + @__DIR__, "..", "test", "reference", "bspline_adaptive_sites", +)) + +adaptive_logk(n) = log.(parse.(Float64, readlines(joinpath(ADAPTIVE_GRIDS, "adaptive_design_N$(n).txt")))) + +function stage2_cases(T, n, m, rng) + sites = T.(adaptive_logk(n)) + q = collect(range(sites[1], sites[end]; length=2n)) + plan = CubicBSplinePlan(sites, q) + U = m == 0 ? randn(rng, T, n) : randn(rng, T, n, m) + G = randn(rng, T, size(U)...) + W = randn(rng, T, length(q), size(U)[2:end]...) + A = basis_matrix(CubicBSplinePlan(Float64.(sites), Float64.(q)).basis, Float64.(sites)) + S = stencil_matrix(CubicBSplinePlan(Float64.(sites), Float64.(q))) + return (; sites, q, plan, U, G, W, A, S) +end + +function run_stage2(out, tag; cool_target_c=52.0, cool_max_s=240.0) + root = dirname(dirname(pathof(ACE))) + prov = provenance(root) + for file in ("src/chainrules.jl", "ext/MooncakeExt/MooncakeExt.jl") + prov["sha256_" * basename(file)] = bytes2hex(sha256(read(joinpath(root, file)))) + end + prov["tag"] = tag + prov["streamed_branch_defined"] = isdefined(ACE, :_streamed_collocation_geometry!) + prov["affinity"] = try strip(read(`taskset -pc $(getpid())`, String)) catch; "unavailable" end + prov["other_julia_processes"] = try + strip(read(pipeline(`pgrep -a julia`; stderr=devnull), String)) + catch + "" + end + prov["gc_threads"] = Threads.ngcthreads() + prov["versions"] = Dict(string(m) => string(pkgversion(m)) + for m in (Mooncake, Zygote, DifferentiationInterface, BenchmarkTools, ForwardDiff)) + prov["seconds_cap"] = PULLBACK_SECONDS + data = Dict{String,Any}("provenance" => prov, "setup" => Dict{String,Any}(), + "cases" => Dict{String,Any}(), "temperature" => Dict{String,Any}()) + path = joinpath(out, "bspline_stage2_$(tag).toml") + backends = (("mooncake", AutoMooncake(; config=Mooncake.Config())), ("zygote", AutoZygote())) + rng = MersenneTwister(20261023) + cells = Any[] + + function add_gradient_cells!(label, c, losses) + for (bname, backend) in backends, (lname, loss, x0, dense) in losses + key = "$(label)_$(lname)_$(bname)" + prep_cold_s = @elapsed prep = DifferentiationInterface.prepare_gradient(loss, backend, x0) + grad_cold_s = @elapsed g = DifferentiationInterface.gradient(loss, prep, backend, x0) + if dense === nothing + d = randn(rng, length(x0)) .* (1 .< (1:length(x0)) .< length(x0)) .* + (1e-3 * minimum(diff(x0))) + directional = ForwardDiff.derivative(h -> loss(x0 .+ h .* d), 0.0) + rel = abs(dot(g, d) - directional) / max(abs(directional), eps()) + rel <= 1e-7 || error("$key directional gate failed: $rel") + else + tol = eltype(x0) == Float32 ? 1e-3 : 1e-10 + err = maximum(abs, g .- dense) / max(1, maximum(abs, dense)) + err <= tol || error("$key dense gate failed: $err") + end + prep_hot_s = [@elapsed(DifferentiationInterface.prepare_gradient(loss, backend, x0)) for _ in 1:3] + data["setup"][key] = Dict("prepare_first_s" => prep_cold_s, + "gradient_first_s" => grad_cold_s, "prepare_again_s" => prep_hot_s) + grad = (l, p, b, x) -> DifferentiationInterface.gradient(l, p, b, x) + push!(cells, (key, grad, (loss, prep, backend, x0))) + end + end + + # Production shapes: coefficients and evaluation, input-only and live sites. + for n in (81, 129) + c = stage2_cases(Float64, n, 8192, rng) + add_gradient_cells!("N$(n)_M8192", c, ( + ("coeff_input", u -> dot(c.G, bspline_coefficients(c.plan, u)), c.U, transpose(c.A) \ c.G), + ("eval_input", u -> dot(c.W, c.plan(u)), c.U, transpose(c.A) \ (transpose(c.S) * c.W)), + ("coeff_live_sites", t -> dot(c.G, bspline_coefficients(CubicBSplinePlan(t, c.q), c.U)), c.sites, nothing), + ("eval_live_sites", t -> dot(c.W, CubicBSplinePlan(t, c.q)(c.U)), c.sites, nothing), + )) + spline = CubicBSpline(c.plan.sites, c.plan.basis, bspline_coefficients(c.plan, c.U), c.plan.extrapolation) + push!(cells, ("N$(n)_M8192_collocation_vjp", + (s, g, f) -> ACE._collocation_geometry_vjp(s, g, f), (spline, c.G, c.plan.factorization))) + end + + # Threshold neighbourhood and controls (coefficient input-only). + for (label, T, m) in (("N81_M7", Float64, 7), ("N81_M256", Float64, 256), + ("N81_M512", Float64, 512), ("N81_M1024", Float64, 1024), + ("N81_M8192_float32", Float32, 8192), ("N81_vector", Float64, 0)) + c = stage2_cases(T, 81, m, rng) + dense = T == Float32 ? transpose(c.A) \ Float64.(c.G) : transpose(c.A) \ c.G + add_gradient_cells!(label, c, ( + ("coeff_input", u -> dot(c.G, bspline_coefficients(c.plan, u)), c.U, dense),)) + if label == "N81_M512" + spline = CubicBSpline(c.plan.sites, c.plan.basis, bspline_coefficients(c.plan, c.U), c.plan.extrapolation) + push!(cells, ("N81_M512_collocation_vjp", + (s, g, f) -> ACE._collocation_geometry_vjp(s, g, f), (spline, c.G, c.plan.factorization))) + end + end + save(path, data, false) + + data["temperature"]["after_setup_c"] = pkg_temp_c() + data["temperature"]["cool_down"] = cool_down(cool_target_c, cool_max_s) + for (key, f, args) in cells + before = pkg_temp_c() + row = bench_strict(f, args...) + row["temp_before_c"] = before + row["temp_after_c"] = pkg_temp_c() + data["cases"][key] = row + save(path, data, false) + println(rpad(key, 48), " median ms = ", round(row["median_ns"] / 1e6; digits=4), + " min ms = ", round(row["min_ns"] / 1e6; digits=4), + " allocs = ", row["allocs"], " bytes = ", row["bytes"], + " T = ", before, "→", row["temp_after_c"]) + end + save(path, data, true) + return path +end + +# ---- set_threads: host column-task budgets ------------------------------------- +# One process; `set_threads(k)` is applied before each cell, outside the timed +# call, for k in `budgets` not exceeding the default pool. Pin the process to +# distinct physical cores (one SMT sibling each), e.g. `taskset -c 4,6,8,10` +# with `--threads=4`. The serial budget-1 cells are the in-process control; +# cross-revision serial parity uses the `stage2` mode against the Stage 2 snapshot. + +function run_stage3(out, tag; budgets=(1, 2, 4), cool_target_c=52.0, cool_max_s=240.0) + isdefined(ACE, :set_threads) || error("stage3 mode needs set_threads") + root = dirname(dirname(pathof(ACE))) + prov = provenance(root) + for file in ("src/chainrules.jl", "src/threads.jl", "ext/MooncakeExt/MooncakeExt.jl") + prov["sha256_" * basename(file)] = bytes2hex(sha256(read(joinpath(root, file)))) + end + prov["tag"] = tag + prov["default_pool"] = Threads.nthreads(:default) + prov["interactive_pool"] = Threads.nthreads(:interactive) + prov["affinity"] = try strip(read(`taskset -pc $(getpid())`, String)) catch; "unavailable" end + prov["other_julia_processes"] = try + strip(read(pipeline(`pgrep -a julia`; stderr=devnull), String)) + catch + "" + end + prov["gc_threads"] = Threads.ngcthreads() + prov["versions"] = Dict(string(m) => string(pkgversion(m)) + for m in (Mooncake, Zygote, DifferentiationInterface, BenchmarkTools, ForwardDiff)) + budgets = filter(<=(Threads.nthreads(:default)), collect(budgets)) + prov["budgets"] = budgets + data = Dict{String,Any}("provenance" => prov, "setup" => Dict{String,Any}(), + "cases" => Dict{String,Any}(), "temperature" => Dict{String,Any}()) + path = joinpath(out, "bspline_stage3_$(tag).toml") + backends = (("mooncake", AutoMooncake(; config=Mooncake.Config())), ("zygote", AutoZygote())) + rng = MersenneTwister(20261024) + cells = Any[] # (key, budget, (n, m), f, args) + + for n in (81, 129) + c = stage2_cases(Float64, n, 8192, rng) + for k in budgets + push!(cells, ("N$(n)_M8192_forward_b$(k)", k, (n, 8192), bspline_coefficients, (c.plan, c.U))) + push!(cells, ("N$(n)_M8192_transpose_b$(k)", k, (n, 8192), ACE.solve_adjoint, (c.plan.factorization, c.G))) + end + losses = ( + ("coeff_input", u -> dot(c.G, bspline_coefficients(c.plan, u)), c.U), + ("coeff_live_sites", t -> dot(c.G, bspline_coefficients(CubicBSplinePlan(t, c.q), c.U)), c.sites), + ) + for (bname, backend) in backends, (lname, loss, x0) in losses + prep_s = @elapsed prep = DifferentiationInterface.prepare_gradient(loss, backend, x0) + set_threads(1) + g1 = DifferentiationInterface.gradient(loss, prep, backend, x0) + data["setup"]["N$(n)_M8192_$(lname)_$(bname)"] = Dict("prepare_first_s" => prep_s) + for k in budgets + set_threads(k) + DifferentiationInterface.gradient(loss, prep, backend, x0) == g1 || + error("gradient changed with budget $k") + grad = (l, p, b, x) -> DifferentiationInterface.gradient(l, p, b, x) + push!(cells, ("N$(n)_M8192_$(lname)_$(bname)_b$(k)", k, (n, 8192), grad, (loss, prep, backend, x0))) + end + end + end + for m in (7, 256, 1024) + c = stage2_cases(Float64, 81, m, rng) + for k in budgets + push!(cells, ("N81_M$(m)_forward_b$(k)", k, (81, m), bspline_coefficients, (c.plan, c.U))) + end + end + + # Four independent chains, each with its own preparation, sharing one plan. + # (its own variable: closures in the loops above must not capture it) + chain_case = stage2_cases(Float64, 81, 8192, rng) + chain_plan, chain_U = chain_case.plan, chain_case.U + chains = 4 + Gs = [randn(rng, size(chain_U)...) for _ in 1:chains] + chain_losses = [u -> dot(Gs[i], bspline_coefficients(chain_plan, u)) for i in 1:chains] + mc = backends[1][2] + chain_preps = [DifferentiationInterface.prepare_gradient(chain_losses[i], mc, chain_U) for i in 1:chains] + run_chains = (ls, ps, b, x) -> @sync for i in eachindex(ls) + Threads.@spawn DifferentiationInterface.gradient(ls[i], ps[i], b, x) + end + for k in unique([1, maximum(budgets)]) + push!(cells, ("N81_M8192_4chains_mooncake_b$(k)", k, (81, 8192), run_chains, (chain_losses, chain_preps, mc, chain_U))) + end + save(path, data, false) + + data["temperature"]["after_setup_c"] = pkg_temp_c() + data["temperature"]["cool_down"] = cool_down(cool_target_c, cool_max_s) + try + for (key, k, (n, m), f, args) in cells + set_threads(k) + before = pkg_temp_c() + row = bench_strict(f, args...) + row["budget"] = k + row["planned_tasks_per_solve"] = ACE._host_column_tasks(n, m) + row["temp_before_c"] = before + row["temp_after_c"] = pkg_temp_c() + data["cases"][key] = row + save(path, data, false) + println(rpad(key, 48), " median ms = ", round(row["median_ns"] / 1e6; digits=4), + " min ms = ", round(row["min_ns"] / 1e6; digits=4), + " allocs = ", row["allocs"], " T = ", before, "→", row["temp_after_c"]) + end + finally + set_threads(1) + end + save(path, data, true) + return path +end + +function main(args) + out = length(args) >= 1 ? args[1] : mktempdir() + which = length(args) >= 2 ? args[2] : "all" + mkpath(out) + if which == "stage3" + length(args) >= 3 || error("stage3 mode requires a tag argument") + run_stage3(out, args[3]) + println("results in ", out) + return + end + if which == "stage2" + length(args) >= 3 || error("stage2 mode requires a revision tag argument") + run_stage2(out, args[3]) + println("results in ", out) + return + end + if which == "pullback" + length(args) >= 3 || error("pullback mode requires a revision tag argument") + run_pullback(out, args[3]) + println("results in ", out) + return + end + ns = (33, 65, 97, 128) + ms = (1, 7, 32, 8192) + types = (Float64, Float32) + which in ("forward", "all") && run_forward(out, ns, ms, types, "forward") + which in ("transpose", "all") && run_forward(out, ns, ms, types, "transpose") + which in ("gradient", "all") && run_gradient(out, ns, (7, 256)) + println("results in ", out) +end + +if abspath(PROGRAM_FILE) == abspath(@__FILE__) + main(ARGS) +end diff --git a/benchmark/bench_bspline_threading_controlled.jl b/benchmark/bench_bspline_threading_controlled.jl new file mode 100644 index 0000000..c00f906 --- /dev/null +++ b/benchmark/bench_bspline_threading_controlled.jl @@ -0,0 +1,152 @@ +# Reuse the established input factories, prepared AD and strict BenchmarkTools +# measurement helpers. No package methods are replaced by this driver. +include("bench_bspline_coefficients.jl") + +function configure_budget(k) + if isdefined(ACE, :set_threads) + ACE.set_threads(k) + else + k == 1 || error("pre-threading control only supports one worker") + ACE.FFTW.set_num_threads(1) + end +end + +digest(x::AbstractArray) = bytes2hex(sha256(reinterpret(UInt8, vec(x)))) +digest(xs::Vector{<:AbstractArray}) = join(digest.(xs), ":") + +function gradient_group(c, backend, kind) + loss, x = if kind == "input" + u -> dot(c.G, bspline_coefficients(c.plan, u)), c.U + else + t -> dot(c.G, bspline_coefficients(CubicBSplinePlan(t, c.q), c.U)), c.sites + end + prep = DifferentiationInterface.prepare_gradient(loss, backend, x) + run = (f, p, b, u) -> DifferentiationInterface.gradient(f, p, b, u) + return run, (loss, prep, backend, x) +end + +function chain_group(c, backend) + rng = MersenneTwister(410) + gs = [randn(rng, size(c.U)) for _ in 1:4] + losses = [u -> dot(gs[i], bspline_coefficients(c.plan, u)) for i in 1:4] + preps = [DifferentiationInterface.prepare_gradient(f, backend, c.U) for f in losses] + function run(fs, ps, b, u) + results = Vector{Matrix{Float64}}(undef, length(fs)) + @sync for i in eachindex(fs) + Threads.@spawn results[i] = DifferentiationInterface.gradient(fs[i], ps[i], b, u) + end + return results + end + return run, (losses, preps, backend, c.U) +end + +function clocks() + return [try parse(Int, strip(read("/sys/devices/system/cpu/cpu$c/cpufreq/scaling_cur_freq", String))) + catch; -1 end for c in (4, 6, 8, 10)] +end + +function check_idle() + others = try parse.(Int, split(read(`pgrep -x julia`, String))) catch; Int[] end + filter!(!=(getpid()), others) + isempty(others) || error("other Julia processes started: $others; do not certify partial timings") +end + +function controlled_main(out, mode, tag) + mode in ("scaling", "serial", "smoke") || error("unknown mode $mode") + root = dirname(dirname(pathof(ACE))) + configure_budget(1) + groups = Any[] + rng = MersenneTwister(20261024) + backends = (("mc", AutoMooncake(; config=Mooncake.Config())), ("zy", AutoZygote())) + sizes = mode == "smoke" ? ((81, 512),) : + mode == "serial" ? Tuple((n, m) for n in (81, 129) for m in (7, 256, 8192)) : + Tuple((n, m) for n in (81, 129) for m in (7, 256, 512, 1024, 2048, 8192)) + for (n, m) in sizes + c = stage2_cases(Float64, n, m, rng) + push!(groups, ("N$(n)_M$(m)_forward", bspline_coefficients, (c.plan, c.U))) + push!(groups, ("N$(n)_M$(m)_transpose", ACE.solve_adjoint, (c.plan.factorization, c.G))) + if m == 8192 + for (name, backend) in backends, kind in ("input", "sites") + f, args = gradient_group(c, backend, kind) + push!(groups, ("N$(n)_M$(m)_$(name)_$(kind)", f, args)) + end + if mode == "scaling" && n == 81 + f, args = chain_group(c, backends[1][2]) + push!(groups, ("N81_M8192_4chains", f, args)) + end + end + end + if mode != "smoke" + c = stage2_cases(Float32, 129, 8192, rng) + push!(groups, ("F32_N129_M8192_forward", bspline_coefficients, (c.plan, c.U))) + push!(groups, ("F32_N129_M8192_transpose", ACE.solve_adjoint, (c.plan.factorization, c.G))) + end + order = mode == "serial" ? (1, 1) : (1, 2, 4, 4, 2, 1) + all(k -> k <= Threads.nthreads(:default), order) || error("insufficient Julia pool") + metadata = provenance(root) + metadata["controlled_driver_sha256"] = bytes2hex(sha256(read(@__FILE__))) + for relative in ("src/chainrules.jl", "src/threads.jl", "ext/MooncakeExt/MooncakeExt.jl") + file = joinpath(root, relative) + isfile(file) && (metadata["sha256_" * basename(file)] = bytes2hex(sha256(read(file)))) + end + metadata["mode"] = mode + metadata["protocol"] = "counterbalanced-v2-cool-each-cell" + metadata["order"] = collect(order) + metadata["affinity"] = readchomp(`taskset -pc $(getpid())`) + metadata["gc_threads"] = Threads.ngcthreads() + metadata["default_threads"] = Threads.nthreads(:default) + metadata["interactive_threads"] = Threads.nthreads(:interactive) + data = Dict{String,Any}("provenance" => metadata, "cases" => Dict{String,Any}(), + "digests" => Dict{String,Any}()) + mkpath(out) + path = joinpath(out, "controlled_$(mode)_$(tag).toml") + ispath(path) && error("refusing to overwrite $path") + # Compile every policy before the in-process cool-in, not in timed trials. + for (_, f, args) in groups, k in unique(order) + configure_budget(k) + f(args...) + end + save(path, data, false) + data["cool_in"] = cool_down(52.0, 300.0) + for (name, f, args) in groups + configure_budget(1) + reference = digest(f(args...)) + data["digests"][name] = reference + for (position, k) in enumerate(order) + check_idle() + configure_budget(k) + digest(f(args...)) == reference || error("numerical result changed: $name budget $k") + # A previous complete run stayed below 88 C, but a repeat starting + # a trial at 79 C reached 98 C and was rejected. Prevent heat soak + # across cells rather than retrying or cherry-picking hot samples. + pkg_temp_c() > 65 && cool_down(50.0, 300.0) + # Sustained per-policy warmup is setup only, not reported as timing. + @benchmark $f($(args)...) samples=100000 seconds=0.10 evals=1 gctrial=false + before = pkg_temp_c() + frequency = clocks() + row = bench_strict(f, args...) + after = pkg_temp_c() + row["budget"] = k + row["position"] = position + row["temp_before_c"] = before + row["temp_after_c"] = after + row["freq_before_khz"] = frequency + row["freq_after_khz"] = clocks() + row["thermal_ok"] = max(before, after) < 95 + key = "$(name)_p$(position)_b$(k)" + data["cases"][key] = row + save(path, data, false) + println(key, " min_ms=", row["min_ns"] / 1e6, " median_ms=", row["median_ns"] / 1e6, + " temperature=", before, "/", after) + flush(stdout) + row["thermal_ok"] || error("thermal gate failed; retain partial results") + end + end + save(path, data, true) + println("CONTROLLED_COMPLETE ", path) +end + +if abspath(PROGRAM_FILE) == abspath(@__FILE__) + length(ARGS) == 3 || error("usage: OUTDIR scaling|serial|smoke TAG") + controlled_main(ARGS...) +end diff --git a/benchmark/bench_dense_operator.jl b/benchmark/bench_dense_operator.jl new file mode 100644 index 0000000..c0842c1 --- /dev/null +++ b/benchmark/bench_dense_operator.jl @@ -0,0 +1,97 @@ +using AbstractCosmologicalEmulators +using BenchmarkTools +using Enzyme +using ForwardDiff +using LinearAlgebra +using Reactant + +Reactant.set_default_backend("cpu") + +function compile_with_time(f, args...) + start = time_ns() + compiled = Reactant.@compile sync=true f(args...) + return compiled, (time_ns() - start) / 1e6 +end + +function timed_call(f, args...) + result = f(args...) + Reactant.synchronize(result) + return result +end + +function summarize(label, trial) + println( + label, + "\tmin_ns=", BenchmarkTools.minimum(trial).time, + "\tmedian_ns=", BenchmarkTools.median(trial).time, + "\tallocs=", BenchmarkTools.median(trial).allocs, + "\tbytes=", BenchmarkTools.median(trial).memory, + ) +end + +function main() + n = 128 + nquery = 1028 + nrhs = 128 + + k = 0:(n - 1) + sites = sort(2 .+ 0.5 .* (cos.(pi .* k ./ (n - 1)) .+ 1) .* (9000 - 2)) + query = collect(range(first(sites), last(sites); length=nquery)) + values = @. exp(-sites / 3000) * (1 + 0.1 * sin(sites / 40)) + values_matrix = hcat((values .* (1 + 0.001 * j) for j in 1:nrhs)...) + + plan = CubicBSplinePlan(sites, query; extrapolation=:clamp) + identity_rhs = Matrix{Float64}(I, n, n) + operator = plan(identity_rhs) + + @assert operator * values ≈ plan(values) atol=1e-10 rtol=1e-10 + @assert operator * values_matrix ≈ plan(values_matrix) atol=1e-10 rtol=1e-10 + + plan_R = Reactant.to_rarray(plan) + operator_R = Reactant.to_rarray(operator) + values_R = Reactant.to_rarray(values) + values_matrix_R = Reactant.to_rarray(values_matrix) + + plan_apply(p, x) = p(x) + operator_apply(P, x) = P * x + + plan_vec, plan_vec_compile = compile_with_time(plan_apply, plan_R, values_R) + dense_vec, dense_vec_compile = compile_with_time(operator_apply, operator_R, values_R) + plan_mat, plan_mat_compile = compile_with_time(plan_apply, plan_R, values_matrix_R) + dense_mat, dense_mat_compile = compile_with_time(operator_apply, operator_R, values_matrix_R) + + changed_values_R = Reactant.to_rarray(values .+ 0.07) + changed_matrix_R = Reactant.to_rarray(values_matrix .+ 0.07) + @assert Array(dense_vec(operator_R, changed_values_R)) ≈ operator * (values .+ 0.07) + @assert Array(dense_mat(operator_R, changed_matrix_R)) ≈ operator * (values_matrix .+ 0.07) + @assert !isapprox(Array(dense_vec(operator_R, values_R)), Array(dense_vec(operator_R, changed_values_R))) + @assert !isapprox(Array(dense_mat(operator_R, values_matrix_R)), Array(dense_mat(operator_R, changed_matrix_R))) + + println("operator_shape=", size(operator), "\toperator_bytes=", Base.summarysize(operator)) + println("plan_vec_compile_ms=", plan_vec_compile) + println("dense_vec_compile_ms=", dense_vec_compile) + println("plan_mat_compile_ms=", plan_mat_compile) + println("dense_mat_compile_ms=", dense_mat_compile) + + plan_vec_trial = @benchmark timed_call($plan_vec, $plan_R, $values_R) seconds=2 samples=1000 evals=1 + dense_vec_trial = @benchmark timed_call($dense_vec, $operator_R, $values_R) seconds=2 samples=1000 evals=1 + plan_mat_trial = @benchmark timed_call($plan_mat, $plan_R, $values_matrix_R) seconds=2 samples=1000 evals=1 + dense_mat_trial = @benchmark timed_call($dense_mat, $operator_R, $values_matrix_R) seconds=2 samples=1000 evals=1 + summarize("plan_vector", plan_vec_trial) + summarize("dense_vector", dense_vec_trial) + summarize("plan_matrix", plan_mat_trial) + summarize("dense_matrix", dense_mat_trial) + + dense_loss(x) = sum(abs2, operator * x) + dense_grad(x) = Enzyme.gradient(Reverse, dense_loss, x)[1] + dense_grad_ref = ForwardDiff.gradient(dense_loss, values_matrix) + dense_grad_R, dense_grad_compile = compile_with_time(dense_grad, values_matrix_R) + dense_grad_result = dense_grad_R(values_matrix_R) + Reactant.synchronize(dense_grad_result) + @assert Array(dense_grad_result) ≈ dense_grad_ref atol=1e-8 rtol=1e-8 + println("dense_matrix_gradient_compile_ms=", dense_grad_compile) + dense_grad_trial = @benchmark timed_call($dense_grad_R, $values_matrix_R) seconds=2 samples=1000 evals=1 + summarize("dense_matrix_gradient", dense_grad_trial) +end + +main() diff --git a/benchmark/bench_plain_splines.jl b/benchmark/bench_plain_splines.jl new file mode 100644 index 0000000..5cf66a4 --- /dev/null +++ b/benchmark/bench_plain_splines.jl @@ -0,0 +1,158 @@ +using AbstractCosmologicalEmulators +using BenchmarkTools +using DifferentiationInterface +using Mooncake +import ADTypes: AutoMooncake + +struct BenchmarkResult + interpolation::String + case::String + path::String + operation::String + prep_ms::Float64 + min_ns::Float64 + median_ns::Float64 + allocs::Int + bytes::Int +end + +function trial_result(interpolation, case, path, operation, prep_ms, trial) + return BenchmarkResult( + interpolation, + case, + path, + operation, + prep_ms, + Float64(BenchmarkTools.minimum(trial).time), + Float64(BenchmarkTools.median(trial).time), + BenchmarkTools.median(trial).allocs, + BenchmarkTools.median(trial).memory, + ) +end + +function benchmark_forward(interpolation, case, path, f, input) + output = f(input) + @assert all(isfinite, output) + trial = @benchmark $f($input) seconds=2 samples=1000 evals=1 + return trial_result(interpolation, case, path, "forward", NaN, trial) +end + +function benchmark_gradient(interpolation, case, path, f, input) + loss(values) = sum(abs2, f(values)) + backend = AutoMooncake(; config=Mooncake.Config()) + + start = time_ns() + prep = DifferentiationInterface.prepare_gradient(loss, backend, input) + prep_ms = (time_ns() - start) / 1e6 + + grad = similar(input) + DifferentiationInterface.gradient!(loss, grad, prep, backend, input) + @assert all(isfinite, grad) + + trial = @benchmark DifferentiationInterface.gradient!( + $loss, + $grad, + $prep, + $backend, + $input, + ) seconds=2 samples=1000 evals=1 + return trial_result(interpolation, case, path, "gradient", prep_ms, trial), copy(grad) +end + +function spline_functions(name, sites, query) + if name == "Akima" + plan = AkimaSplinePlan(sites, query) + on_the_fly = values -> akima_interpolation(values, sites, query) + elseif name == "Cubic" + plan = CubicSplinePlan(sites, query) + on_the_fly = values -> cubic_spline_interpolation(values, sites, query) + elseif name == "CubicBSpline" + plan = CubicBSplinePlan(sites, query; extrapolation=:clamp) + on_the_fly = values -> CubicBSpline( + values, + sites; + extrapolation=:clamp, + )(query) + else + error("Unknown interpolation: $name") + end + + planned(values) = plan(values) + return on_the_fly, planned +end + +function print_results(results) + println( + "interpolation\tcase\tpath\toperation\tprep_ms\tmin_ns\tmedian_ns\tallocs\tbytes", + ) + for row in results + println( + row.interpolation, + '\t', row.case, + '\t', row.path, + '\t', row.operation, + '\t', row.prep_ms, + '\t', row.min_ns, + '\t', row.median_ns, + '\t', row.allocs, + '\t', row.bytes, + ) + end +end + +function main() + nsites = 40 + nseries = 161 + k = 0:(nsites - 1) + sites = sort(2 .+ 0.5 .* (cos.(pi .* k ./ (nsites - 1)) .+ 1) .* (9000 - 2)) + query_short = collect(range(first(sites), last(sites); length=40)) + query_long = collect(range(first(sites), last(sites); length=8192)) + values = @. exp(-sites / 3000) * (1 + 0.1 * sin(sites / 40)) + values_matrix = hcat((values .* (1 + 0.001 * j) for j in 1:nseries)...) + + cases = ( + ("vec_40_40", query_short, values), + ("vec_40_8192", query_long, values), + ("mat_40x161_8192", query_long, values_matrix), + ) + interpolations = split( + get(ENV, "SPLINE_BENCHMARKS", "Akima,Cubic,CubicBSpline"), + ',', + ) + results = BenchmarkResult[] + + for interpolation in interpolations + for (case, query, input) in cases + on_the_fly, planned = spline_functions(interpolation, sites, query) + + forward_on_the_fly = on_the_fly(input) + forward_plan = planned(input) + @assert isapprox(forward_plan, forward_on_the_fly; atol=1e-9, rtol=1e-11) + + push!(results, benchmark_forward(interpolation, case, "on_the_fly", on_the_fly, input)) + push!(results, benchmark_forward(interpolation, case, "plan", planned, input)) + + gradient_on_the_fly, grad_on_the_fly = benchmark_gradient( + interpolation, + case, + "on_the_fly", + on_the_fly, + input, + ) + gradient_plan, grad_plan = benchmark_gradient( + interpolation, + case, + "plan", + planned, + input, + ) + @assert isapprox(grad_plan, grad_on_the_fly; atol=1e-8, rtol=1e-10) + push!(results, gradient_on_the_fly) + push!(results, gradient_plan) + end + end + + print_results(results) +end + +main() diff --git a/benchmark/bench_reactant_splines.jl b/benchmark/bench_reactant_splines.jl new file mode 100644 index 0000000..b0d22fa --- /dev/null +++ b/benchmark/bench_reactant_splines.jl @@ -0,0 +1,330 @@ +using AbstractCosmologicalEmulators +using BenchmarkTools +using Enzyme +using Reactant + +Reactant.set_default_backend("cpu") + +struct ReactantForwardResult + interpolation::String + case::String + path::String + compile_ms::Float64 + min_ns::Float64 + median_ns::Float64 + allocs::Int + bytes::Int +end + +struct ReactantGradientResult + interpolation::String + case::String + path::String + compile_ms::Float64 + min_ns::Float64 + median_ns::Float64 + allocs::Int + bytes::Int +end + +function compile_timed(f, args...) + start = time_ns() + compiled = Reactant.@compile sync=true f(args...) + return compiled, (time_ns() - start) / 1e6 +end + +function synchronized_call(f, args...) + result = f(args...) + Reactant.synchronize(result) + return result +end + +function synchronized_call_tuple(f, args) + return synchronized_call(f, args...) +end + +function benchmark_compiled(interpolation, case, path, compiled, args...) + args_tuple = args + trial = @benchmark synchronized_call_tuple($compiled, $args_tuple) seconds=2 samples=1000 evals=1 + return trial +end + +function make_result(interpolation, case, path, compile_ms, trial) + return ReactantForwardResult( + interpolation, + case, + path, + compile_ms, + Float64(BenchmarkTools.minimum(trial).time), + Float64(BenchmarkTools.median(trial).time), + BenchmarkTools.median(trial).allocs, + BenchmarkTools.median(trial).memory, + ) +end + +function make_gradient_result(interpolation, case, path, compile_ms, trial) + return ReactantGradientResult( + interpolation, + case, + path, + compile_ms, + Float64(BenchmarkTools.minimum(trial).time), + Float64(BenchmarkTools.median(trial).time), + BenchmarkTools.median(trial).allocs, + BenchmarkTools.median(trial).memory, + ) +end + +function on_the_fly_function(name, sites, query) + if name == "Akima" + f = (values, knots, target) -> akima_interpolation(values, knots, target) + return f, (Reactant.to_rarray(sites), Reactant.to_rarray(query)) + elseif name == "Cubic" + f = (values, knots, target) -> cubic_spline_interpolation(values, knots, target) + return f, (Reactant.to_rarray(sites), Reactant.to_rarray(query)) + elseif name == "CubicBSpline" + # B-spline basis/factorization construction is structural and uses the + # fixed host grid. Ordinates remain the only dynamic runtime input. + f = values -> CubicBSpline( + values, + sites; + extrapolation=:clamp, + )(query) + return f, () + end + error("Unknown interpolation: $name") +end + +function host_on_the_fly(name, values, sites, query) + name == "Akima" && return akima_interpolation(values, sites, query) + name == "Cubic" && return cubic_spline_interpolation(values, sites, query) + name == "CubicBSpline" && return CubicBSpline( + values, + sites; + extrapolation=:clamp, + )(query) + error("Unknown interpolation: $name") +end + +function construct_plan(name, sites, query) + name == "Akima" && return AkimaSplinePlan(sites, query) + name == "Cubic" && return CubicSplinePlan(sites, query) + name == "CubicBSpline" && return CubicBSplinePlan( + sites, + query; + extrapolation=:clamp, + ) + error("Unknown interpolation: $name") +end + +function print_results(results) + println("interpolation\tcase\tpath\tcompile_ms\tmin_ns\tmedian_ns\tallocs\tbytes") + for row in results + println( + row.interpolation, + '\t', row.case, + '\t', row.path, + '\t', row.compile_ms, + '\t', row.min_ns, + '\t', row.median_ns, + '\t', row.allocs, + '\t', row.bytes, + ) + end +end + +function print_gradient_results(results) + println("gradient_interpolation\tcase\tpath\tcompile_ms\tmin_ns\tmedian_ns\tallocs\tbytes") + for row in results + println( + row.interpolation, + '\t', row.case, + '\t', row.path, + '\t', row.compile_ms, + '\t', row.min_ns, + '\t', row.median_ns, + '\t', row.allocs, + '\t', row.bytes, + ) + end +end + +function main() + nsites = 40 + nseries = 161 + k = 0:(nsites - 1) + sites = sort(2 .+ 0.5 .* (cos.(pi .* k ./ (nsites - 1)) .+ 1) .* (9000 - 2)) + query_short = collect(range(first(sites), last(sites); length=40)) + query_long = collect(range(first(sites), last(sites); length=8192)) + values = @. exp(-sites / 3000) * (1 + 0.1 * sin(sites / 40)) + values_matrix = hcat((values .* (1 + 0.001 * j) for j in 1:nseries)...) + + cases = ( + ("vec_40_40", query_short, values), + ("vec_40_8192", query_long, values), + ("mat_40x161_8192", query_long, values_matrix), + ) + results = ReactantForwardResult[] + gradient_results = ReactantGradientResult[] + benchmark_gradients = get(ENV, "BENCH_GRADIENTS", "0") == "1" + + interpolations = split( + get(ENV, "SPLINE_BENCHMARKS", "Akima,Cubic,CubicBSpline"), + ',', + ) + for interpolation in interpolations + for (case, query, input) in cases + input_R = Reactant.to_rarray(input) + changed = input .+ 0.07 + changed_R = Reactant.to_rarray(changed) + + on_the_fly, static_args = on_the_fly_function(interpolation, sites, query) + on_the_fly_args = (input_R, static_args...) + compiled_on_the_fly, compile_on_the_fly = compile_timed( + on_the_fly, + on_the_fly_args..., + ) + output_on_the_fly = synchronized_call(compiled_on_the_fly, on_the_fly_args...) + host_reference = host_on_the_fly(interpolation, input, sites, query) + @assert isapprox(Array(output_on_the_fly), host_reference; atol=1e-8, rtol=1e-10) + + changed_args = (changed_R, static_args...) + changed_output = synchronized_call(compiled_on_the_fly, changed_args...) + changed_reference = host_on_the_fly(interpolation, changed, sites, query) + @assert isapprox(Array(changed_output), changed_reference; atol=1e-8, rtol=1e-10) + @assert !isapprox(Array(changed_output), Array(output_on_the_fly)) + + on_the_fly_trial = benchmark_compiled( + interpolation, + case, + "on_the_fly", + compiled_on_the_fly, + on_the_fly_args..., + ) + push!(results, make_result( + interpolation, + case, + "on_the_fly", + compile_on_the_fly, + on_the_fly_trial, + )) + + plan = construct_plan(interpolation, sites, query) + plan_R = Reactant.to_rarray(plan) + apply_plan(p, values) = p(values) + compiled_plan, compile_plan = compile_timed(apply_plan, plan_R, input_R) + output_plan = synchronized_call(compiled_plan, plan_R, input_R) + @assert isapprox(Array(output_plan), plan(input); atol=1e-8, rtol=1e-10) + changed_plan_output = synchronized_call(compiled_plan, plan_R, changed_R) + @assert isapprox(Array(changed_plan_output), plan(changed); atol=1e-8, rtol=1e-10) + @assert !isapprox(Array(changed_plan_output), Array(output_plan)) + + plan_trial = benchmark_compiled( + interpolation, + case, + "plan", + compiled_plan, + plan_R, + input_R, + ) + push!(results, make_result( + interpolation, + case, + "plan", + compile_plan, + plan_trial, + )) + + if benchmark_gradients + gradient_on_the_fly = (values, args...) -> Enzyme.gradient( + Reverse, + v -> sum(abs2, on_the_fly(v, args...)), + values, + )[1] + compiled_gradient_on_the_fly, gradient_on_the_fly_compile = compile_timed( + gradient_on_the_fly, + on_the_fly_args..., + ) + gradient_on_the_fly_result = synchronized_call( + compiled_gradient_on_the_fly, + on_the_fly_args..., + ) + changed_gradient_on_the_fly = synchronized_call( + compiled_gradient_on_the_fly, + changed_args..., + ) + @assert !isapprox( + Array(changed_gradient_on_the_fly), + Array(gradient_on_the_fly_result), + ) + gradient_on_the_fly_trial = benchmark_compiled( + interpolation, + case, + "on_the_fly", + compiled_gradient_on_the_fly, + on_the_fly_args..., + ) + push!(gradient_results, make_gradient_result( + interpolation, + case, + "on_the_fly", + gradient_on_the_fly_compile, + gradient_on_the_fly_trial, + )) + + gradient_plan = (p, values) -> Enzyme.gradient( + Reverse, + v -> sum(abs2, p(v)), + values, + )[1] + compiled_gradient_plan, gradient_plan_compile = compile_timed( + gradient_plan, + plan_R, + input_R, + ) + gradient_plan_result = synchronized_call( + compiled_gradient_plan, + plan_R, + input_R, + ) + changed_gradient_plan = synchronized_call( + compiled_gradient_plan, + plan_R, + changed_R, + ) + @assert isapprox( + Array(gradient_plan_result), + Array(gradient_on_the_fly_result); + atol=1e-8, + rtol=1e-10, + ) + @assert isapprox( + Array(changed_gradient_plan), + Array(changed_gradient_on_the_fly); + atol=1e-8, + rtol=1e-10, + ) + gradient_plan_trial = benchmark_compiled( + interpolation, + case, + "plan", + compiled_gradient_plan, + plan_R, + input_R, + ) + push!(gradient_results, make_gradient_result( + interpolation, + case, + "plan", + gradient_plan_compile, + gradient_plan_trial, + )) + end + end + end + + print_results(results) + benchmark_gradients && print_gradient_results(gradient_results) +end + +main() diff --git a/benchmark/benchmarks.jl b/benchmark/benchmarks.jl index ce8b03c..a8ab08b 100644 --- a/benchmark/benchmarks.jl +++ b/benchmark/benchmarks.jl @@ -106,8 +106,146 @@ SUITE["cubic_spline"]["plan_512_to_8999"] = @benchmarkable plan(u) setup = ( plan = CubicSplinePlan(t, t_new) ) +SUITE["cubic_b_spline"] = BenchmarkGroup(["b_spline"]) + +SUITE["cubic_b_spline"]["basis_row_search"] = @benchmarkable AbstractCosmologicalEmulators.basis_row(basis, xq) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + xq = 4500.0 +) + +SUITE["cubic_b_spline"]["basis_row_preselected"] = @benchmarkable AbstractCosmologicalEmulators._cubic_basis_values(basis.knot_vector, span, xq) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + xq = 4500.0; + span = AbstractCosmologicalEmulators._find_cubic_span(basis.knot_vector, xq) +) + +SUITE["cubic_b_spline"]["basis_stencil_512_to_8999"] = @benchmarkable AbstractCosmologicalEmulators.basis_stencil(basis, t_new) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + t_new = collect(2.0:9000.0) +) + +SUITE["cubic_b_spline"]["factorization_512"] = @benchmarkable AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, t) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]) +) + +SUITE["cubic_b_spline"]["solve_vector_512"] = @benchmarkable AbstractCosmologicalEmulators.solve(fact, u) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, t); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)) +) + +SUITE["cubic_b_spline"]["solve_matrix_512x10"] = @benchmarkable AbstractCosmologicalEmulators.solve(fact, U) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, t); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + U = repeat(u, 1, 10) +) + +SUITE["cubic_b_spline"]["construct_512"] = @benchmarkable AbstractCosmologicalEmulators.CubicBSpline(u, t) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)) +) + +SUITE["cubic_b_spline"]["eval_scalar"] = @benchmarkable spline_obj(xq) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + spline_obj = AbstractCosmologicalEmulators.CubicBSpline(u, t); + xq = 4500.0 +) + +SUITE["cubic_b_spline"]["eval_vector_8999"] = @benchmarkable spline_obj(t_new) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + spline_obj = AbstractCosmologicalEmulators.CubicBSpline(u, t); + t_new = collect(2.0:9000.0) +) + +SUITE["cubic_b_spline"]["plan_construct_512_to_8999"] = @benchmarkable AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + t_new = collect(2.0:9000.0) +) + +SUITE["cubic_b_spline"]["plan_512_to_8999"] = @benchmarkable plan(u) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + t_new = collect(2.0:9000.0); + plan = AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) +) + +SUITE["cubic_b_spline"]["plan_construct_128"] = @benchmarkable AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) setup = ( + k = 0:127; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 127) .+ 1) .* (9000 - 2)); + t_new = collect(2.0:9000.0) +) + +SUITE["cubic_b_spline"]["plan_apply_128"] = @benchmarkable plan(u) setup = ( + k = 0:127; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 127) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + t_new = collect(2.0:9000.0); + plan = AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) +) + +SUITE["cubic_b_spline"]["plan_construct_3000"] = @benchmarkable AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) setup = ( + k = 0:2999; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 2999) .+ 1) .* (9000 - 2)); + t_new = collect(2.0:9000.0) +) + +SUITE["cubic_b_spline"]["plan_apply_3000"] = @benchmarkable plan(u) setup = ( + k = 0:2999; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 2999) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + t_new = collect(2.0:9000.0); + plan = AbstractCosmologicalEmulators.CubicBSplinePlan(t, t_new) +) + +# Compile Reactant in setup to measure pure steady-state execution time +using Reactant +function synchronized_reactant_call(f, args...) + result = f(args...) + Reactant.synchronize(result) + return result +end + +SUITE["cubic_b_spline"]["reactant_stencil"] = @benchmarkable synchronized_reactant_call(compiled_f, c_R) setup = ( + k = 0:511; + t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); + u = @. exp(-t / 3000) * (1 + 0.1 * sin(t / 40)); + t_new = collect(2.0:9000.0); + basis = AbstractCosmologicalEmulators.CubicBSplineBasis(domain=(first(t), last(t)), internal_knots=t[3:end-2]); + stencil = AbstractCosmologicalEmulators.basis_stencil(basis, t_new); + f(c) = AbstractCosmologicalEmulators._evaluate_stencil(stencil, c); + c_R = Reactant.to_rarray(u); + compiled_f = Reactant.@compile sync=true f(c_R) +) + SUITE["akima_spline"] = BenchmarkGroup(["interpolation"]) +# AirspeedVelocity also runs this script against the pre-feature baseline. +# Keep all sixteen B-spline cases on the head; absent baseline results are +# reported as missing, not fabricated timings or a comparison against zero. +if !isdefined(AbstractCosmologicalEmulators, :CubicBSplineBasis) + delete!(SUITE, "cubic_b_spline") +end + SUITE["akima_spline"]["pure_512_to_8999"] = @benchmarkable akima_interpolation(u, t, t_new) setup = ( k = 0:511; t = sort(2 .+ 0.5 .* (cos.(pi .* k ./ 511) .+ 1) .* (9000 - 2)); diff --git a/ext/ExtReactant/reactant_splines.jl b/ext/ExtReactant/reactant_splines.jl index b02c12e..cdbb7df 100644 --- a/ext/ExtReactant/reactant_splines.jl +++ b/ext/ExtReactant/reactant_splines.jl @@ -6,6 +6,60 @@ const DeviceVec = Union{TracedVec,ConcreteVec} const DeviceMat = Union{TracedMat,ConcreteMat} const HostOrDeviceVec = Union{AbstractVector,DeviceVec} +# Device inputs already have the representation needed by traced kernels. +AbstractCosmologicalEmulators._bspline_dense_input(x::Union{DeviceVec,DeviceMat}) = x + +struct ReactantCubicBSplinePlan{O} + operator::O +end + +const _MAX_REACTANT_BSPLINE_OPERATOR_BYTES = 64 * 1024^2 + +function Reactant.to_rarray( + plan::AbstractCosmologicalEmulators.CubicBSplinePlan; + kwargs..., +) + nsites = length(plan.sites) + nquery = length(plan.stencil.i1) + operator_type = promote_type( + eltype(plan.factorization.bands), + eltype(plan.stencil.w1), + ) + operator_bytes = try + Base.checked_mul( + Base.checked_mul(nsites, nquery), + sizeof(operator_type), + ) + catch error + error isa OverflowError || rethrow() + throw(ArgumentError( + "Reactant CubicBSplinePlan dense operator size overflows Int.", + )) + end + if operator_bytes > _MAX_REACTANT_BSPLINE_OPERATOR_BYTES + throw(ArgumentError( + "Reactant CubicBSplinePlan requires a dense operator of " * + "$(Base.format_bytes(operator_bytes)), exceeding the 64 MiB limit.", + )) + end + + operator = AbstractCosmologicalEmulators._build_cubic_bspline_dense_operator( + plan.factorization, + plan.stencil, + nsites, + ) + return ReactantCubicBSplinePlan(Reactant.to_rarray(operator; kwargs...)) +end + +function (plan::ReactantCubicBSplinePlan)(u::DeviceVec) + return plan.operator * u +end + + +function (plan::ReactantCubicBSplinePlan)(u::DeviceMat) + return plan.operator * u +end + # Vectorized interval indices for query array. # Returns indices clamped to [1, n-1]. function _interval_indices(t::HostOrDeviceVec, tq::HostOrDeviceVec) @@ -158,6 +212,26 @@ function _pcr_right_neighbor(M::AbstractMatrix, stride::Int) return vcat(M[(stride + 1):n, :], _pcr_zeros_like(M, stride, nrhs)) end +@inline function _pcr_left_neighbor!(out::AbstractVector, v::AbstractVector, stride::Int) + out .= _pcr_left_neighbor(v, stride) + return out +end + +@inline function _pcr_left_neighbor!(out::AbstractMatrix, M::AbstractMatrix, stride::Int) + out .= _pcr_left_neighbor(M, stride) + return out +end + +@inline function _pcr_left_mask!(out::AbstractVector, stride::Int) + out .= _pcr_left_mask(length(out), stride, eltype(out)) + return out +end + +@inline function _pcr_left_mask(n::Int, stride::Int, ::Type{T}) where {T} + has_left = vcat(fill(false, stride), fill(true, max(n - stride, 0))) + return ifelse.(has_left, one(T), zero(T)) +end + function _pcr_masks(T, n::Int, stride::Int) has_left = vcat(fill(false, stride), fill(true, n - stride)) has_right = vcat(fill(true, n - stride), fill(false, stride)) @@ -417,3 +491,574 @@ function cubic_spline_interpolation(u::DeviceMat, t::HostOrDeviceVec, t_new::Hos h, z = _cubic_spline_coefficients(u, t) return _cubic_spline_eval(u, t, h, z, t_new) end + +# ----------------------------------------------------------------------------- +# Cubic B-Spline coefficient evaluation (traced dispatch) +# Split stencil columns on the host before conversion to avoid traced 2D +# slicing (idx[:, k]), which triggers StackOverflowError in the MLIR tracer. +# ----------------------------------------------------------------------------- + +@inline function _load_tail_zeros!(dst::AbstractVector, src::AbstractVector, tail_zeros::Int) + # Equivalent to vcat(src, fill(zero, tail_zeros)) + src_vec = vec(src) + n = length(dst) + m = length(src_vec) + T = eltype(dst) + n_keep = min(m, n - tail_zeros) + if n_keep > 0 + dst .= vcat(src_vec[1:n_keep], fill(zero(T), n - n_keep)) + else + dst .= fill(zero(T), n) + end + return dst +end + +@inline function _load_head_zeros!(dst::AbstractVector, src::AbstractVector, head_zeros::Int) + # Equivalent to vcat(fill(zero, head_zeros), src) + src_vec = vec(src) + n = length(dst) + m = length(src_vec) + T = eltype(dst) + n_keep = min(m, n - head_zeros) + if n_keep > 0 + tail_zeros = n - head_zeros - n_keep + dst .= vcat( + fill(zero(T), head_zeros), + src_vec[1:n_keep], + fill(zero(T), tail_zeros), + ) + else + dst .= fill(zero(T), n) + end + return dst +end + +@inline function _reverse_first_dim(x::AbstractVector) + return x[end:-1:1] +end + +@inline function _reverse_first_dim(X::AbstractMatrix) + return X[end:-1:1, :] +end + +function _extract_cubic_factorization_bands(B::AbstractMatrix) + n = size(B, 2) + B1 = similar(B[4, :]) + B2 = similar(B[4, :]) + B3 = similar(B[4, :]) + B4 = copy(B[4, :]) + B5 = similar(B[4, :]) + B6 = similar(B[4, :]) + B7 = similar(B[4, :]) + + _load_tail_zeros!(B1, B[1, 4:n], 3) + _load_tail_zeros!(B2, B[2, 3:n], 2) + _load_tail_zeros!(B3, B[3, 2:n], 1) + _load_head_zeros!(B5, B[5, 1:n-1], 1) + _load_head_zeros!(B6, B[6, 1:n-2], 2) + _load_head_zeros!(B7, B[7, 1:n-3], 3) + + return B1, B2, B3, B4, B5, B6, B7 +end + +function _solve_affine_recurrence_scan(rhs::AbstractVector, c1::AbstractVector, c2::AbstractVector, c3::AbstractVector) + return vec(_solve_affine_recurrence_scan(reshape(rhs, length(rhs), 1), c1, c2, c3)) +end + +function _solve_affine_recurrence_scan( + rhs::AbstractMatrix, + c1::AbstractVector, + c2::AbstractVector, + c3::AbstractVector +) + n, nrhs = size(rhs) + @assert n == length(c1) == length(c2) == length(c3) + n <= 1 && return copy(rhs) + + if eltype(rhs) <: Reactant.TracedRNumber + return _solve_affine_recurrence_scan_traced(rhs, c1, c2, c3) + end + + T = promote_type(eltype(rhs), eltype(c1), eltype(c2), eltype(c3)) + x1 = similar(rhs, T, n, nrhs) + x1 .= rhs + x2 = similar(x1) + x3 = similar(x1) + x2 .= zero(T) + x3 .= zero(T) + + m11 = similar(c1, T, n) + m12 = similar(c1, T, n) + m13 = similar(c1, T, n) + m21 = similar(c1, T, n) + m22 = similar(c1, T, n) + m23 = similar(c1, T, n) + m31 = similar(c1, T, n) + m32 = similar(c1, T, n) + m33 = similar(c1, T, n) + m11 .= -c1 + m12 .= -c2 + m13 .= -c3 + m21 .= one(T) + m22 .= zero(T) + m23 .= zero(T) + m31 .= zero(T) + m32 .= one(T) + m33 .= zero(T) + + l11 = similar(m11) + l12 = similar(m11) + l13 = similar(m11) + l21 = similar(m11) + l22 = similar(m11) + l23 = similar(m11) + l31 = similar(m11) + l32 = similar(m11) + l33 = similar(m11) + + lx1 = similar(x1) + lx2 = similar(x1) + lx3 = similar(x1) + + nm11 = similar(m11) + nm12 = similar(m11) + nm13 = similar(m11) + nm21 = similar(m11) + nm22 = similar(m11) + nm23 = similar(m11) + nm31 = similar(m11) + nm32 = similar(m11) + nm33 = similar(m11) + nx1 = similar(x1) + nx2 = similar(x1) + nx3 = similar(x1) + + left = similar(m11) + + stride = 1 + while stride < n + _pcr_left_neighbor!(l11, m11, stride) + _pcr_left_neighbor!(l12, m12, stride) + _pcr_left_neighbor!(l13, m13, stride) + _pcr_left_neighbor!(l21, m21, stride) + _pcr_left_neighbor!(l22, m22, stride) + _pcr_left_neighbor!(l23, m23, stride) + _pcr_left_neighbor!(l31, m31, stride) + _pcr_left_neighbor!(l32, m32, stride) + _pcr_left_neighbor!(l33, m33, stride) + + _pcr_left_neighbor!(lx1, x1, stride) + _pcr_left_neighbor!(lx2, x2, stride) + _pcr_left_neighbor!(lx3, x3, stride) + + _pcr_left_mask!(left, stride) + left_complement = one(T) .- left + + @. nm11 = left * (m11 * l11 + m12 * l21 + m13 * l31) + left_complement * m11 + @. nm12 = left * (m11 * l12 + m12 * l22 + m13 * l32) + left_complement * m12 + @. nm13 = left * (m11 * l13 + m12 * l23 + m13 * l33) + left_complement * m13 + # After the first doubling the matrices are no longer companion + # matrices: all three rows require the full composition product. + @. nm21 = left * (m21 * l11 + m22 * l21 + m23 * l31) + left_complement * m21 + @. nm22 = left * (m21 * l12 + m22 * l22 + m23 * l32) + left_complement * m22 + @. nm23 = left * (m21 * l13 + m22 * l23 + m23 * l33) + left_complement * m23 + @. nm31 = left * (m31 * l11 + m32 * l21 + m33 * l31) + left_complement * m31 + @. nm32 = left * (m31 * l12 + m32 * l22 + m33 * l32) + left_complement * m32 + @. nm33 = left * (m31 * l13 + m32 * l23 + m33 * l33) + left_complement * m33 + + @. nx1 = left * (m11 * lx1 + m12 * lx2 + m13 * lx3 + x1) + left_complement * x1 + @. nx2 = left * (m21 * lx1 + m22 * lx2 + m23 * lx3 + x2) + left_complement * x2 + @. nx3 = left * (m31 * lx1 + m32 * lx2 + m33 * lx3 + x3) + left_complement * x3 + + m11, nm11 = nm11, m11 + m12, nm12 = nm12, m12 + m13, nm13 = nm13, m13 + m21, nm21 = nm21, m21 + m22, nm22 = nm22, m22 + m23, nm23 = nm23, m23 + m31, nm31 = nm31, m31 + m32, nm32 = nm32, m32 + m33, nm33 = nm33, m33 + x1, nx1 = nx1, x1 + x2, nx2 = nx2, x2 + x3, nx3 = nx3, x3 + + stride *= 2 + end + + return x1 +end + +function _solve_affine_recurrence_scan_traced( + rhs::AbstractMatrix, + c1::AbstractVector, + c2::AbstractVector, + c3::AbstractVector +) + n, nrhs = size(rhs) + @assert n == length(c1) == length(c2) == length(c3) + n <= 1 && return copy(rhs) + + T = promote_type(eltype(rhs), eltype(c1), eltype(c2), eltype(c3)) + x1 = similar(rhs, T, n, nrhs) + x2 = similar(x1) + x3 = similar(x1) + x1 .= rhs + x2 .= zero(T) + x3 .= zero(T) + + m11 = similar(c1, T, n) + m12 = similar(c1, T, n) + m13 = similar(c1, T, n) + m21 = similar(c1, T, n) + m22 = similar(c1, T, n) + m23 = similar(c1, T, n) + m31 = similar(c1, T, n) + m32 = similar(c1, T, n) + m33 = similar(c1, T, n) + m11 .= -c1 + m12 .= -c2 + m13 .= -c3 + m21 .= one(T) + m22 .= zero(T) + m23 .= zero(T) + m31 .= zero(T) + m32 .= one(T) + m33 .= zero(T) + + l11 = similar(m11) + l12 = similar(m11) + l13 = similar(m11) + l21 = similar(m11) + l22 = similar(m11) + l23 = similar(m11) + l31 = similar(m11) + l32 = similar(m11) + l33 = similar(m11) + + lx1 = similar(x1) + lx2 = similar(x1) + lx3 = similar(x1) + + nm11 = similar(m11) + nm12 = similar(m11) + nm13 = similar(m11) + nm21 = similar(m11) + nm22 = similar(m11) + nm23 = similar(m11) + nm31 = similar(m11) + nm32 = similar(m11) + nm33 = similar(m11) + nx1 = similar(x1) + nx2 = similar(x1) + nx3 = similar(x1) + + left = similar(m11) + + stride = 1 + while stride < n + _pcr_left_neighbor!(l11, m11, stride) + _pcr_left_neighbor!(l12, m12, stride) + _pcr_left_neighbor!(l13, m13, stride) + _pcr_left_neighbor!(l21, m21, stride) + _pcr_left_neighbor!(l22, m22, stride) + _pcr_left_neighbor!(l23, m23, stride) + _pcr_left_neighbor!(l31, m31, stride) + _pcr_left_neighbor!(l32, m32, stride) + _pcr_left_neighbor!(l33, m33, stride) + + _pcr_left_neighbor!(lx1, x1, stride) + _pcr_left_neighbor!(lx2, x2, stride) + _pcr_left_neighbor!(lx3, x3, stride) + + _pcr_left_mask!(left, stride) + @. nm11 = left * (m11 * l11 + m12 * l21 + m13 * l31) + (one(T) - left) * m11 + @. nm12 = left * (m11 * l12 + m12 * l22 + m13 * l32) + (one(T) - left) * m12 + @. nm13 = left * (m11 * l13 + m12 * l23 + m13 * l33) + (one(T) - left) * m13 + @. nm21 = left * (m21 * l11 + m22 * l21 + m23 * l31) + (one(T) - left) * m21 + @. nm22 = left * (m21 * l12 + m22 * l22 + m23 * l32) + (one(T) - left) * m22 + @. nm23 = left * (m21 * l13 + m22 * l23 + m23 * l33) + (one(T) - left) * m23 + @. nm31 = left * (m31 * l11 + m32 * l21 + m33 * l31) + (one(T) - left) * m31 + @. nm32 = left * (m31 * l12 + m32 * l22 + m33 * l32) + (one(T) - left) * m32 + @. nm33 = left * (m31 * l13 + m32 * l23 + m33 * l33) + (one(T) - left) * m33 + + @. nx1 = left * (m11 * lx1 + m12 * lx2 + m13 * lx3 + x1) + (one(T) - left) * x1 + @. nx2 = left * (m21 * lx1 + m22 * lx2 + m23 * lx3 + x2) + (one(T) - left) * x2 + @. nx3 = left * (m31 * lx1 + m32 * lx2 + m33 * lx3 + x3) + (one(T) - left) * x3 + + m11, nm11 = nm11, m11 + m12, nm12 = nm12, m12 + m13, nm13 = nm13, m13 + m21, nm21 = nm21, m21 + m22, nm22 = nm22, m22 + m23, nm23 = nm23, m23 + m31, nm31 = nm31, m31 + m32, nm32 = nm32, m32 + m33, nm33 = nm33, m33 + x1, nx1 = nx1, x1 + x2, nx2 = nx2, x2 + x3, nx3 = nx3, x3 + + stride *= 2 + end + + return x1 +end + +@inline function _solve_affine_recurrence_scan_backward(rhs, c1, c2, c3) + rhs_r = _reverse_first_dim(rhs) + c1_r = _reverse_first_dim(c1) + c2_r = _reverse_first_dim(c2) + c3_r = _reverse_first_dim(c3) + return _reverse_first_dim(_solve_affine_recurrence_scan(rhs_r, c1_r, c2_r, c3_r)) +end + +function AbstractCosmologicalEmulators.solve( + fact::AbstractCosmologicalEmulators.CubicBSplineFactorization, + b::DeviceVec +) + B = fact.bands + + B1, B2, B3, B4, B5, B6, B7 = _extract_cubic_factorization_bands(B) + + # Forward solve with affine scan + x = _solve_affine_recurrence_scan(b, B5, B6, B7) + + # Backward solve on reversed affine recurrence + B4_inv = one(eltype(B4)) ./ B4 + x_scaled = x .* B4_inv + return _solve_affine_recurrence_scan_backward(x_scaled, B3 .* B4_inv, B2 .* B4_inv, B1 .* B4_inv) +end + +function AbstractCosmologicalEmulators.solve( + fact::AbstractCosmologicalEmulators.CubicBSplineFactorization, + B_mat::DeviceMat +) + B = fact.bands + + # Pre-extract bands + B1, B2, B3, B4, B5, B6, B7 = _extract_cubic_factorization_bands(B) + + # Forward solve with affine scan + X = _solve_affine_recurrence_scan(B_mat, B5, B6, B7) + + # Backward solve on reversed affine recurrence + B4_inv = one(eltype(B4)) ./ B4 + X_scaled = X .* B4_inv + return _solve_affine_recurrence_scan_backward(X_scaled, B3 .* B4_inv, B2 .* B4_inv, B1 .* B4_inv) +end + +function (plan::AbstractCosmologicalEmulators.CubicBSplinePlan)(u::DeviceVec) + throw(ArgumentError( + "Reactant CubicBSplinePlan requires preparation with Reactant.to_rarray.", + )) +end + +function (plan::AbstractCosmologicalEmulators.CubicBSplinePlan)(u::DeviceMat) + throw(ArgumentError( + "Reactant CubicBSplinePlan requires preparation with Reactant.to_rarray.", + )) +end + + +function AbstractCosmologicalEmulators._evaluate_stencil( + stencil::AbstractCosmologicalEmulators.CubicBSplineStencil, + c::DeviceVec +) + return c[stencil.i1] .* stencil.w1 .+ + c[stencil.i2] .* stencil.w2 .+ + c[stencil.i3] .* stencil.w3 .+ + c[stencil.i4] .* stencil.w4 +end + +function _gather_rows(c::DeviceMat, rows) + n_query = length(rows) + n_basis, n_series = size(c) + + offsets = n_basis .* reshape(0:(n_series - 1), 1, :) + linear = vec(reshape(rows, :, 1) .+ offsets) + + return reshape(vec(c)[linear], n_query, n_series) +end + +function AbstractCosmologicalEmulators._evaluate_stencil( + stencil::AbstractCosmologicalEmulators.CubicBSplineStencil, + c::DeviceMat +) + n_query = length(stencil.i1) + n_series = size(c, 2) + + w1 = reshape(stencil.w1, n_query, 1) + w2 = reshape(stencil.w2, n_query, 1) + w3 = reshape(stencil.w3, n_query, 1) + w4 = reshape(stencil.w4, n_query, 1) + + return _gather_rows(c, stencil.i1) .* w1 .+ + _gather_rows(c, stencil.i2) .* w2 .+ + _gather_rows(c, stencil.i3) .* w3 .+ + _gather_rows(c, stencil.i4) .* w4 +end + +function _cubic_b_spline_eval(c::DeviceVec, T::HostOrDeviceVec, xq::HostOrDeviceVec) + n_basis = length(T) - 4 + cmp = reshape(T, :, 1) .<= reshape(xq, 1, :) + idx = vec(sum(cmp; dims=1)) + span = clamp.(idx, 4, n_basis) + + T_span = T[span] + T_span_p1 = T[span .+ 1] + T_span_m1 = T[span .- 1] + T_span_p2 = T[span .+ 2] + T_span_m2 = T[span .- 2] + T_span_p3 = T[span .+ 3] + + left1 = xq .- T_span + right1 = T_span_p1 .- xq + + temp1 = one(eltype(right1)) ./ (right1 .+ left1) + N1_0 = right1 .* temp1 + N1_1 = left1 .* temp1 + + left2 = xq .- T_span_m1 + right2 = T_span_p2 .- xq + + temp2_0 = N1_0 ./ (right1 .+ left2) + N2_0 = right1 .* temp2_0 + saved = left2 .* temp2_0 + + temp2_1 = N1_1 ./ (right2 .+ left1) + N2_1 = saved .+ right2 .* temp2_1 + N2_2 = left1 .* temp2_1 + + left3 = xq .- T_span_m2 + right3 = T_span_p3 .- xq + + temp3_0 = N2_0 ./ (right1 .+ left3) + N3_0 = right1 .* temp3_0 + saved = left3 .* temp3_0 + + temp3_1 = N2_1 ./ (right2 .+ left2) + N3_1 = saved .+ right2 .* temp3_1 + saved = left2 .* temp3_1 + + temp3_2 = N2_2 ./ (right3 .+ left1) + N3_2 = saved .+ right3 .* temp3_2 + N3_3 = left1 .* temp3_2 + + c_0 = c[span .- 3] + c_1 = c[span .- 2] + c_2 = c[span .- 1] + c_3 = c[span] + + return c_0 .* N3_0 .+ c_1 .* N3_1 .+ c_2 .* N3_2 .+ c_3 .* N3_3 +end + +function _cubic_b_spline_eval(c::DeviceMat, T::HostOrDeviceVec, xq::HostOrDeviceVec) + n_basis = length(T) - 4 + cmp = reshape(T, :, 1) .<= reshape(xq, 1, :) + idx = vec(sum(cmp; dims=1)) + span = clamp.(idx, 4, n_basis) + + T_span = T[span] + T_span_p1 = T[span .+ 1] + T_span_m1 = T[span .- 1] + T_span_p2 = T[span .+ 2] + T_span_m2 = T[span .- 2] + T_span_p3 = T[span .+ 3] + + left1 = xq .- T_span + right1 = T_span_p1 .- xq + + temp1 = one(eltype(right1)) ./ (right1 .+ left1) + N1_0 = right1 .* temp1 + N1_1 = left1 .* temp1 + + left2 = xq .- T_span_m1 + right2 = T_span_p2 .- xq + + temp2_0 = N1_0 ./ (right1 .+ left2) + N2_0 = right1 .* temp2_0 + saved = left2 .* temp2_0 + + temp2_1 = N1_1 ./ (right2 .+ left1) + N2_1 = saved .+ right2 .* temp2_1 + N2_2 = left1 .* temp2_1 + + left3 = xq .- T_span_m2 + right3 = T_span_p3 .- xq + + temp3_0 = N2_0 ./ (right1 .+ left3) + N3_0 = right1 .* temp3_0 + saved = left3 .* temp3_0 + + temp3_1 = N2_1 ./ (right2 .+ left2) + N3_1 = saved .+ right2 .* temp3_1 + saved = left2 .* temp3_1 + + temp3_2 = N2_2 ./ (right3 .+ left1) + N3_2 = saved .+ right3 .* temp3_2 + N3_3 = left1 .* temp3_2 + + c_0 = _gather_rows(c, span .- 3) + c_1 = _gather_rows(c, span .- 2) + c_2 = _gather_rows(c, span .- 1) + c_3 = _gather_rows(c, span) + + w0 = reshape(N3_0, :, 1) + w1 = reshape(N3_1, :, 1) + w2 = reshape(N3_2, :, 1) + w3 = reshape(N3_3, :, 1) + + return c_0 .* w0 .+ c_1 .* w1 .+ c_2 .* w2 .+ c_3 .* w3 +end + +function _apply_reactant_extrapolation(xq::DeviceVec, T, E) + xmin = T[[4]] + xmax = T[[length(T) - 3]] + if E === AbstractCosmologicalEmulators.ClampExtrap + return clamp.(xq, xmin, xmax) + elseif E === AbstractCosmologicalEmulators.ThrowExtrap + error("Dynamic bounds checking (`extrapolation=:throw`) is not currently supported in Reactant compiled contexts because the XLA compiler cannot lower dynamic exceptions. Please use `extrapolation=:clamp` or `:zero`.") + else + return xq + end +end + +function _apply_reactant_zero_mask(out, xq::DeviceVec, T, E) + if E === AbstractCosmologicalEmulators.ZeroExtrap + xmin = T[[4]] + xmax = T[[length(T) - 3]] + mask = (xq .>= xmin) .& (xq .<= xmax) + if out isa DeviceMat + return out .* reshape(mask, :, 1) + else + return out .* mask + end + end + return out +end + +function (spline::AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E})(xq::DeviceVec) where {X, B, C<:AbstractVector, E} + T = AbstractCosmologicalEmulators.knot_vector(spline.basis) + xq_eval = _apply_reactant_extrapolation(xq, T, E) + out = _cubic_b_spline_eval(spline.coefficients, T, xq_eval) + return _apply_reactant_zero_mask(out, xq, T, E) +end + +function (spline::AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E})(xq::DeviceVec) where {X, B, C<:AbstractMatrix, E} + T = AbstractCosmologicalEmulators.knot_vector(spline.basis) + xq_eval = _apply_reactant_extrapolation(xq, T, E) + out = _cubic_b_spline_eval(spline.coefficients, T, xq_eval) + return _apply_reactant_zero_mask(out, xq, T, E) +end + +# A traced scalar is not a Real. Reuse the vector kernel without materializing +# its value on the host, then recover the public scalar/series-vector shape. +function (spline::AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E})(xq::Reactant.TracedRNumber) where {X, B, C<:AbstractVector, E} + # Reduce the singleton on-device; `only` would perform scalar indexing. + return sum(spline(Reactant.broadcast_to_size(xq, (1,)))) +end + +function (spline::AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E})(xq::Reactant.TracedRNumber) where {X, B, C<:AbstractMatrix, E} + return vec(spline(Reactant.broadcast_to_size(xq, (1,)))) +end diff --git a/ext/MooncakeExt/MooncakeExt.jl b/ext/MooncakeExt/MooncakeExt.jl index 5f572f2..0374fe2 100644 --- a/ext/MooncakeExt/MooncakeExt.jl +++ b/ext/MooncakeExt/MooncakeExt.jl @@ -25,6 +25,8 @@ using Mooncake: @from_chainrules, MinimalCtx, NoFData, NoRData @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._akima_coefficients), Any, AbstractMatrix} @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._akima_eval), AbstractMatrix, Any, AbstractMatrix, AbstractMatrix, AbstractMatrix, Any} @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._akima_eval), AbstractMatrix, Any, AbstractMatrix, AbstractMatrix, AbstractMatrix, AbstractArray} +@from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._akima_plan_eval), AbstractVector, AbstractVector, AbstractVector, AbstractVector, Any, Any} +@from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._akima_plan_eval), AbstractMatrix, AbstractMatrix, AbstractMatrix, AbstractMatrix, Any, Any} # High-level Akima interpolation interface @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators.akima_interpolation), AbstractVector, AbstractVector, AbstractArray} @@ -37,6 +39,330 @@ using Mooncake: @from_chainrules, MinimalCtx, NoFData, NoRData @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._cubic_spline_coefficients), AbstractMatrix, AbstractVector} @from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators._cubic_spline_eval), AbstractMatrix, Any, Any, AbstractMatrix, AbstractArray} +# Dense native pullback: unlike the former NoTangent(plan) bridge, preserve +# cotangents for all weights and the second-derivative operator. Abstract +# ordinate containers retain the generic AD path instead of assuming their +# forward data is a mutable dense array. +const DenseCubicSplinePlan = AbstractCosmologicalEmulators.CubicSplinePlan{ + T,TQ,Matrix{F},I,Vector{F},Vector{F},Vector{F},Vector{F}, +} where {T,TQ,I,F<:Base.IEEEFloat} + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._cubic_spline_plan_eval), + DenseCubicSplinePlan, + Union{Vector{<:Base.IEEEFloat},Matrix{<:Base.IEEEFloat}}, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._cubic_spline_plan_eval)}, + plan_dual::Mooncake.CoDual{<:DenseCubicSplinePlan}, + u_dual::Mooncake.CoDual{<:Union{Vector{<:Base.IEEEFloat},Matrix{<:Base.IEEEFloat}}}, +) + plan, u = Mooncake.primal(plan_dual), Mooncake.primal(u_dual) + output_dual = Mooncake.zero_fcodual(AbstractCosmologicalEmulators._cubic_spline_plan_eval(plan, u)) + output_bar = Mooncake.tangent(output_dual) + plan_bar = Mooncake.tangent(plan_dual).data + u_bar = Mooncake.tangent(u_dual) + z = plan.second_derivative_operator * u + z_bar = zero(z) + + function cubic_plan_pullback(::Mooncake.NoRData) + fill!(z_bar, zero(eltype(z_bar))) + # Series-major traversal keeps matrix ordinates and output cotangents + # contiguous. A vector is also indexable as an n-by-1 array in Julia. + @inbounds for s in axes(u, 2), i in eachindex(plan.interval_indices) + j = plan.interval_indices[i] + delta = output_bar[i, s] + u_bar[j, s] += delta * plan.left_value_weights[i] + u_bar[j + 1, s] += delta * plan.right_value_weights[i] + z_bar[j, s] += delta * plan.left_curve_weights[i] + z_bar[j + 1, s] += delta * plan.right_curve_weights[i] + plan_bar.left_value_weights[i] += delta * u[j, s] + plan_bar.right_value_weights[i] += delta * u[j + 1, s] + plan_bar.left_curve_weights[i] += delta * z[j, s] + plan_bar.right_curve_weights[i] += delta * z[j + 1, s] + end + u_bar .+= transpose(plan.second_derivative_operator) * z_bar + plan_bar.second_derivative_operator .+= z_bar * transpose(u) + # t/t_new are not read directly by evaluation; their derivatives flow + # through construction of the weights/operator, not a fabricated zero + # tangent for the entire plan. + return Mooncake.NoRData(), Mooncake.zero_rdata(plan), Mooncake.NoRData() + end + return output_dual, cubic_plan_pullback +end + +# Cubic B-spline coefficient solve and fixed-stencil evaluation +@from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators.solve), AbstractCosmologicalEmulators.CubicBSplineFactorization, AbstractVector} +@from_chainrules MinimalCtx Tuple{typeof(AbstractCosmologicalEmulators.solve), AbstractCosmologicalEmulators.CubicBSplineFactorization, AbstractMatrix} + +# High-level B-spline rules need to move cotangents through immutable structs +# containing mutable array fields. Do this directly instead of asking +# @from_chainrules to translate a structured ChainRules tangent into Mooncake +# forward data. +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._construct_cubic_b_spline), + Union{Vector,Matrix}, + Vector, + Any, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._construct_cubic_b_spline)}, + u_dual::Mooncake.CoDual{<:Union{Vector,Matrix}}, + sites_dual::Mooncake.CoDual{<:Vector}, + extrap_dual::Mooncake.CoDual, +) + spline = AbstractCosmologicalEmulators._construct_cubic_b_spline( + Mooncake.primal(u_dual), + Mooncake.primal(sites_dual), + Mooncake.primal(extrap_dual), + ) + spline_dual = Mooncake.zero_fcodual(spline) + spline_data = Mooncake.tangent(spline_dual).data + + function construct_pullback(::Mooncake.NoRData) + c_bar = spline_data.coefficients + u_bar, sites_bar, knot_bar = + AbstractCosmologicalEmulators._collocation_geometry_vjp(spline, c_bar) + sites_bar .+= spline_data.sites + knot_bar .+= spline_data.basis.data.knot_vector + AbstractCosmologicalEmulators._map_not_a_knot_bar!(sites_bar, knot_bar) + Mooncake.tangent(u_dual) .+= u_bar + Mooncake.tangent(sites_dual) .+= sites_bar + return Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData() + end + return spline_dual, construct_pullback +end + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._evaluate_cubic_b_spline), + AbstractCosmologicalEmulators.CubicBSpline, + Vector, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._evaluate_cubic_b_spline)}, + spline_dual::Mooncake.CoDual{<:AbstractCosmologicalEmulators.CubicBSpline}, + query_dual::Mooncake.CoDual{<:Vector}, +) + spline = Mooncake.primal(spline_dual) + query = Mooncake.primal(query_dual) + output_dual = Mooncake.zero_fcodual( + AbstractCosmologicalEmulators._evaluate_cubic_b_spline(spline, query), + ) + output_bar = Mooncake.tangent(output_dual) + spline_data = Mooncake.tangent(spline_dual).data + + function evaluate_pullback(::Mooncake.NoRData) + c_bar, sites_bar, knot_bar, query_bar = + AbstractCosmologicalEmulators._evaluation_geometry_vjp( + spline, + query, + output_bar, + ) + spline_data.coefficients .+= c_bar + spline_data.sites .+= sites_bar + spline_data.basis.data.knot_vector .+= knot_bar + Mooncake.tangent(query_dual) .+= query_bar + return Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData() + end + return output_dual, evaluate_pullback +end + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._evaluate_cubic_b_spline), + AbstractCosmologicalEmulators.CubicBSpline, + Real, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._evaluate_cubic_b_spline)}, + spline_dual::Mooncake.CoDual{<:AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E}}, + query_dual::Mooncake.CoDual{<:Real}, +) where {X,B,C<:AbstractVector,E} + spline = Mooncake.primal(spline_dual) + query = Mooncake.primal(query_dual) + output = AbstractCosmologicalEmulators._evaluate_cubic_b_spline(spline, query) + + function evaluate_pullback(output_bar) + c_bar, sites_bar, knot_bar, query_bar = + AbstractCosmologicalEmulators._evaluation_geometry_vjp( + spline, + [query], + [output_bar], + ) + spline_data = Mooncake.tangent(spline_dual).data + spline_data.coefficients .+= c_bar + spline_data.sites .+= sites_bar + spline_data.basis.data.knot_vector .+= knot_bar + query_rdata = Mooncake.zero_rdata(query) + # Mooncake treats integers as inactive, unlike ChainRules' continuous + # integer projection. Preserve the backend's activity and scalar type. + if !(query_rdata isa Mooncake.NoRData) + query_rdata = convert(typeof(query_rdata), only(query_bar)) + end + return Mooncake.NoRData(), Mooncake.NoRData(), query_rdata + end + return Mooncake.zero_fcodual(output), evaluate_pullback +end + +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._evaluate_cubic_b_spline)}, + spline_dual::Mooncake.CoDual{<:AbstractCosmologicalEmulators.CubicBSpline{X,B,C,E}}, + query_dual::Mooncake.CoDual{<:Real}, +) where {X,B,C<:AbstractMatrix,E} + spline = Mooncake.primal(spline_dual) + query = Mooncake.primal(query_dual) + output_dual = Mooncake.zero_fcodual( + AbstractCosmologicalEmulators._evaluate_cubic_b_spline(spline, query), + ) + output_bar = Mooncake.tangent(output_dual) + + function evaluate_pullback(::Mooncake.NoRData) + c_bar, sites_bar, knot_bar, query_bar = + AbstractCosmologicalEmulators._evaluation_geometry_vjp( + spline, + [query], + reshape(output_bar, 1, :), + ) + spline_data = Mooncake.tangent(spline_dual).data + spline_data.coefficients .+= c_bar + spline_data.sites .+= sites_bar + spline_data.basis.data.knot_vector .+= knot_bar + query_rdata = Mooncake.zero_rdata(query) + if !(query_rdata isa Mooncake.NoRData) + query_rdata = convert(typeof(query_rdata), only(query_bar)) + end + return Mooncake.NoRData(), Mooncake.NoRData(), query_rdata + end + return output_dual, evaluate_pullback +end + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._construct_cubic_b_spline_plan), + Vector, + Vector, + Any, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._construct_cubic_b_spline_plan)}, + sites_dual::Mooncake.CoDual{<:Vector}, + query_dual::Mooncake.CoDual{<:Vector}, + extrap_dual::Mooncake.CoDual, +) + plan = AbstractCosmologicalEmulators._construct_cubic_b_spline_plan( + Mooncake.primal(sites_dual), + Mooncake.primal(query_dual), + Mooncake.primal(extrap_dual), + ) + plan_dual = Mooncake.zero_fcodual(plan) + plan_data = Mooncake.tangent(plan_dual).data + function construct_plan_pullback(::Mooncake.NoRData) + sites_bar = copy(plan_data.sites) + knot_bar = copy(plan_data.basis.data.knot_vector) + stencil_knot_bar, stencil_query_bar = + AbstractCosmologicalEmulators._stencil_geometry_vjp( + plan.basis, + plan.stencil.query, + plan.extrapolation, + plan_data.stencil.data.w1, + plan_data.stencil.data.w2, + plan_data.stencil.data.w3, + plan_data.stencil.data.w4, + ) + knot_bar .+= stencil_knot_bar + AbstractCosmologicalEmulators._map_not_a_knot_bar!(sites_bar, knot_bar) + Mooncake.tangent(sites_dual) .+= sites_bar + Mooncake.tangent(query_dual) .+= + plan_data.stencil.data.query .+ stencil_query_bar + return Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData() + end + return plan_dual, construct_plan_pullback +end + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._bspline_coefficients), + AbstractCosmologicalEmulators.CubicBSplinePlan, + Union{Vector,Matrix}, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._bspline_coefficients)}, + plan_dual::Mooncake.CoDual{<:AbstractCosmologicalEmulators.CubicBSplinePlan}, + u_dual::Mooncake.CoDual{<:Union{Vector,Matrix}}, +) + plan = Mooncake.primal(plan_dual) + u = Mooncake.primal(u_dual) + coefficients = AbstractCosmologicalEmulators._bspline_coefficients(plan, u) + coefficients_dual = Mooncake.zero_fcodual(coefficients) + coefficients_bar = Mooncake.tangent(coefficients_dual) + plan_data = Mooncake.tangent(plan_dual).data + + function coefficients_pullback(::Mooncake.NoRData) + spline = AbstractCosmologicalEmulators.CubicBSpline( + plan.sites, + plan.basis, + coefficients, + plan.extrapolation, + ) + u_bar, sites_bar, knot_bar = + AbstractCosmologicalEmulators._collocation_geometry_vjp( + spline, + coefficients_bar, + plan.factorization, + ) + AbstractCosmologicalEmulators._map_not_a_knot_bar!(sites_bar, knot_bar) + plan_data.sites .+= sites_bar + Mooncake.tangent(u_dual) .+= u_bar + return Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData() + end + return coefficients_dual, coefficients_pullback +end + +Mooncake.@is_primitive MinimalCtx Tuple{ + typeof(AbstractCosmologicalEmulators._apply_cubic_b_spline_plan), + AbstractCosmologicalEmulators.CubicBSplinePlan, + Union{Vector,Matrix}, +} +function Mooncake.rrule!!( + ::Mooncake.CoDual{typeof(AbstractCosmologicalEmulators._apply_cubic_b_spline_plan)}, + plan_dual::Mooncake.CoDual{<:AbstractCosmologicalEmulators.CubicBSplinePlan}, + u_dual::Mooncake.CoDual{<:Union{Vector,Matrix}}, +) + plan = Mooncake.primal(plan_dual) + u = Mooncake.primal(u_dual) + output_dual = Mooncake.zero_fcodual( + AbstractCosmologicalEmulators._apply_cubic_b_spline_plan(plan, u), + ) + output_bar = Mooncake.tangent(output_dual) + plan_data = Mooncake.tangent(plan_dual).data + function apply_plan_pullback(::Mooncake.NoRData) + c = AbstractCosmologicalEmulators.bspline_coefficients(plan, u) + spline = AbstractCosmologicalEmulators.CubicBSpline( + plan.sites, + plan.basis, + c, + plan.extrapolation, + ) + c_bar, sites_bar, knot_bar, query_bar = + AbstractCosmologicalEmulators._evaluation_geometry_vjp( + spline, + plan.stencil.query, + output_bar, + ) + u_bar, collocation_sites_bar, collocation_knot_bar = + AbstractCosmologicalEmulators._collocation_geometry_vjp( + spline, + c_bar, + plan.factorization, + ) + sites_bar .+= collocation_sites_bar + knot_bar .+= collocation_knot_bar + AbstractCosmologicalEmulators._map_not_a_knot_bar!(sites_bar, knot_bar) + plan_data.sites .+= sites_bar + plan_data.stencil.data.query .+= query_bar + Mooncake.tangent(u_dual) .+= u_bar + return Mooncake.NoRData(), Mooncake.NoRData(), Mooncake.NoRData() + end + return output_dual, apply_plan_pullback +end + # Chebyshev optimization Mooncake.tangent_type(::Type{P}) where {P<:FFTW.FFTWPlan} = Mooncake.NoTangent Mooncake.fdata_type(::Type{P}) where {P<:FFTW.FFTWPlan} = NoFData diff --git a/src/AbstractCosmologicalEmulators.jl b/src/AbstractCosmologicalEmulators.jl index 19da5b6..3710dce 100644 --- a/src/AbstractCosmologicalEmulators.jl +++ b/src/AbstractCosmologicalEmulators.jl @@ -17,16 +17,21 @@ export AbstractTrainedEmulators, LuxEmulator, SimpleChainsEmulator, GenericEmula export maximin, inv_maximin, run_emulator, get_emulator_description, init_emulator export to_reactant export validate_nn_dict_structure, validate_parameter_ranges, validate_layer_structure, safe_dict_access -export akima_interpolation, cubic_spline_interpolation +export akima_interpolation, cubic_spline_interpolation, cubic_b_spline_interpolation export AkimaSpline, CubicSpline, AkimaSplinePlan, CubicSplinePlan +export CubicBSplineBasis, CubicBSpline, CubicBSplinePlan +export knot_vector, internal_knots, nbasis, bspline_domain, basis_support +export basis_row, basis_stencil, basis_matrix, bspline_basis, bspline_coefficients export ChebyshevPlan, chebpoints export prepare_chebyshev_plan, chebyshev_polynomials, chebyshev_decomposition -export set_fft_threads +export set_threads, set_fft_threads include("core.jl") include("initialization.jl") include("utils.jl") +include("threads.jl") include("chebyshev.jl") +include("cubic_b_spline.jl") include("chainrules.jl") const trained_emulators = Dict{String,GenericEmulator}() @@ -63,14 +68,4 @@ activate them. """ function to_reactant end -""" - set_fft_threads(n::Integer) - -Set the number of threads used by FFTW.jl for operations in `AbstractCosmologicalEmulators`. -Call this before calling `prepare_chebyshev_plan` to improve performance on large grids or batched evaluations. -""" -function set_fft_threads(n::Integer) - FFTW.set_num_threads(n) -end - end # module AbstractCosmologicalEmulators diff --git a/src/chainrules.jl b/src/chainrules.jl index 8e08d47..96e5ac6 100644 --- a/src/chainrules.jl +++ b/src/chainrules.jl @@ -489,6 +489,101 @@ function ChainRulesCore.rrule(::typeof(_akima_eval), u::AbstractMatrix, t, b::Ab return results, _akima_eval_matrix_pullback end +function ChainRulesCore.rrule( + ::typeof(_akima_plan_eval), + u::AbstractVector, + b::AbstractVector, + c::AbstractVector, + d::AbstractVector, + interval_indices, + offsets, +) + out = _akima_plan_eval(u, b, c, d, interval_indices, offsets) + project_u = ChainRulesCore.ProjectTo(u) + project_b = ChainRulesCore.ProjectTo(b) + project_c = ChainRulesCore.ProjectTo(c) + project_d = ChainRulesCore.ProjectTo(d) + + function _akima_plan_eval_pullback(Δ) + Δ = ChainRulesCore.unthunk(Δ) + if Δ isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent(), ZeroTangent(), + ZeroTangent(), NoTangent(), ZeroTangent() + end + + ∂u = zero(u) + ∂b = zero(b) + ∂c = zero(c) + ∂d = zero(d) + ∂offsets = zero(offsets) + @inbounds for i in eachindex(interval_indices) + idx = interval_indices[i] + w = offsets[i] + Δi = Δ[i] + ∂u[idx] += Δi + ∂b[idx] += Δi * w + ∂c[idx] += Δi * w^2 + ∂d[idx] += Δi * w^3 + ∂offsets[i] += Δi * (b[idx] + 2 * c[idx] * w + 3 * d[idx] * w^2) + end + return NoTangent(), project_u(∂u), project_b(∂b), project_c(∂c), + project_d(∂d), NoTangent(), ChainRulesCore.ProjectTo(offsets)(∂offsets) + end + + return out, _akima_plan_eval_pullback +end + +function ChainRulesCore.rrule( + ::typeof(_akima_plan_eval), + u::AbstractMatrix, + b::AbstractMatrix, + c::AbstractMatrix, + d::AbstractMatrix, + interval_indices, + offsets, +) + out = _akima_plan_eval(u, b, c, d, interval_indices, offsets) + project_u = ChainRulesCore.ProjectTo(u) + project_b = ChainRulesCore.ProjectTo(b) + project_c = ChainRulesCore.ProjectTo(c) + project_d = ChainRulesCore.ProjectTo(d) + + function _akima_plan_eval_matrix_pullback(Δ) + Δ = ChainRulesCore.unthunk(Δ) + if Δ isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent(), ZeroTangent(), + ZeroTangent(), NoTangent(), ZeroTangent() + end + + ∂u = zero(u) + ∂b = zero(b) + ∂c = zero(c) + ∂d = zero(d) + ∂offsets = zero(offsets) + nseries = size(u, 2) + @inbounds for i in eachindex(interval_indices) + idx = interval_indices[i] + w = offsets[i] + w2 = w * w + w3 = w2 * w + ∂w = zero(eltype(∂offsets)) + @simd for s in 1:nseries + Δis = Δ[i, s] + ∂u[idx, s] += Δis + ∂b[idx, s] += Δis * w + ∂c[idx, s] += Δis * w2 + ∂d[idx, s] += Δis * w3 + ∂w += Δis * (b[idx, s] + 2 * c[idx, s] * w + 3 * d[idx, s] * w2) + end + ∂offsets[i] = ∂w + end + return NoTangent(), project_u(∂u), project_b(∂b), project_c(∂c), + project_d(∂d), NoTangent(), ChainRulesCore.ProjectTo(offsets)(∂offsets) + end + + return out, _akima_plan_eval_matrix_pullback +end + function ChainRulesCore.rrule(::typeof(akima_interpolation), u::AbstractVector, t::AbstractVector, t_new::AbstractArray) n = length(u) dt = diff(t) @@ -873,6 +968,620 @@ function ChainRulesCore.rrule(::typeof(_cubic_spline_coefficients), u::AbstractM return (h, z), _cubic_spline_coefficients_matrix_pullback end +# ============================================================================= +# Cubic B-Spline Chainrules +# ============================================================================= + +struct _CubicBasisJet{T} + value::T + partials::NTuple{7,T} +end + +Base.zero(::Type{_CubicBasisJet{T}}) where {T} = + _CubicBasisJet(zero(T), ntuple(_ -> zero(T), 7)) +Base.one(::Type{_CubicBasisJet{T}}) where {T} = + _CubicBasisJet(one(T), ntuple(_ -> zero(T), 7)) +Base.:+(a::_CubicBasisJet, b::_CubicBasisJet) = + _CubicBasisJet(a.value + b.value, ntuple(i -> a.partials[i] + b.partials[i], 7)) +Base.:-(a::_CubicBasisJet, b::_CubicBasisJet) = + _CubicBasisJet(a.value - b.value, ntuple(i -> a.partials[i] - b.partials[i], 7)) +Base.:*(a::_CubicBasisJet, b::_CubicBasisJet) = _CubicBasisJet( + a.value * b.value, + ntuple(i -> a.partials[i] * b.value + a.value * b.partials[i], 7), +) +Base.:/(a::_CubicBasisJet, b::_CubicBasisJet) = _CubicBasisJet( + a.value / b.value, + ntuple( + i -> (a.partials[i] * b.value - a.value * b.partials[i]) / b.value^2, + 7, + ), +) +Base.:*(a::Number, b::_CubicBasisJet) = + _CubicBasisJet(a * b.value, ntuple(i -> a * b.partials[i], 7)) +Base.:*(a::_CubicBasisJet, b::Number) = b * a + +function _cubic_basis_local_values(x, tm2, tm1, t0, tp1, tp2, tp3) + left1 = x - t0 + right1 = tp1 - x + + temp = one(typeof(right1)) / (right1 + left1) + N1_0 = right1 * temp + N1_1 = left1 * temp + + left2 = x - tm1 + right2 = tp2 - x + + temp = N1_0 / (right1 + left2) + N2_0 = right1 * temp + saved = left2 * temp + + temp = N1_1 / (right2 + left1) + N2_1 = saved + right2 * temp + N2_2 = left1 * temp + + left3 = x - tm2 + right3 = tp3 - x + + temp = N2_0 / (right1 + left3) + N3_0 = right1 * temp + saved = left3 * temp + + temp = N2_1 / (right2 + left2) + N3_1 = saved + right2 * temp + saved = left2 * temp + + temp = N2_2 / (right3 + left1) + N3_2 = saved + right3 * temp + N3_3 = left1 * temp + + return (N3_0, N3_1, N3_2, N3_3) +end + +@inline function _cubic_basis_jet(value, ::Val{active}, ::Type{V}) where {active,V} + return _CubicBasisJet( + convert(V, value), + ntuple(i -> i == active ? one(V) : zero(V), Val(7)), + ) +end + +# The four local basis values at x as jets in (x, T[span-2:span+3]). They +# depend on geometry only, not on the cotangent they are contracted with. +@inline function _cubic_basis_jets(T, span, x, ::Type{V}) where {V} + return _cubic_basis_local_values( + _cubic_basis_jet(x, Val(1), V), + _cubic_basis_jet(T[span-2], Val(2), V), + _cubic_basis_jet(T[span-1], Val(3), V), + _cubic_basis_jet(T[span], Val(4), V), + _cubic_basis_jet(T[span+1], Val(5), V), + _cubic_basis_jet(T[span+2], Val(6), V), + _cubic_basis_jet(T[span+3], Val(7), V), + ) +end + +@inline function _contract_cubic_basis_jets(values, values_bar) + weighted = values_bar[1] * values[1] + values_bar[2] * values[2] + + values_bar[3] * values[3] + values_bar[4] * values[4] + return weighted.partials[1], ntuple(i -> weighted.partials[i+1], 6) +end + +@inline function _cubic_basis_vjp(T, span, x, values_bar) + V = promote_type( + eltype(T), + typeof(x), + typeof(values_bar[1]), + typeof(values_bar[2]), + typeof(values_bar[3]), + typeof(values_bar[4]), + ) + return _contract_cubic_basis_jets(_cubic_basis_jets(T, span, x, V), values_bar) +end + +function _accumulate_local_knot_bar!(T_bar, span, local_bar) + for k in 1:6 + T_bar[span-3+k] += local_bar[k] + end + return T_bar +end + +function _map_not_a_knot_bar!(sites_bar, knot_bar) + n = length(sites_bar) + sites_bar[1] += sum(@view knot_bar[1:4]) + if n > 4 + @views sites_bar[3:n-2] .+= knot_bar[5:n] + end + sites_bar[end] += sum(@view knot_bar[n+1:n+4]) + return sites_bar +end + +function _evaluation_geometry_vjp(spline, query::AbstractVector, output_bar) + c = spline.coefficients + T = knot_vector(spline.basis) + V = promote_type(eltype(c), eltype(T), eltype(query), eltype(output_bar)) + c_bar = zeros(V, size(c)) + knot_bar = zeros(V, length(T)) + sites_bar = zeros(V, length(spline.sites)) + query_bar = zeros(V, length(query)) + xmin, xmax = bspline_domain(spline.basis) + + for j in eachindex(query) + q = query[j] + outside_left = q < xmin + outside_right = q > xmax + if spline.extrapolation isa ZeroExtrap && (outside_left || outside_right) + continue + end + + x = _apply_extrapolation(spline.extrapolation, q, xmin, xmax) + row = basis_row(spline.basis, x) + if c isa AbstractVector + delta = output_bar[j] + values_bar = ntuple(k -> delta * c[row.indices[k]], 4) + for k in 1:4 + c_bar[row.indices[k]] += delta * row.values[k] + end + else + values_bar = ntuple( + k -> dot(@view(output_bar[j, :]), @view(c[row.indices[k], :])), + 4, + ) + for k in 1:4 + idx = row.indices[k] + @views c_bar[idx, :] .+= output_bar[j, :] .* row.values[k] + end + end + + span = row.indices[4] + x_bar, local_knot_bar = _cubic_basis_vjp(T, span, x, values_bar) + _accumulate_local_knot_bar!(knot_bar, span, local_knot_bar) + + if spline.extrapolation isa ClampExtrap && outside_left + sites_bar[1] += x_bar + elseif spline.extrapolation isa ClampExtrap && outside_right + sites_bar[end] += x_bar + else + query_bar[j] += x_bar + end + end + return c_bar, sites_bar, knot_bar, query_bar +end + +# Below this many right-hand sides the per-site strided `dot` reduction is kept: +# an isolated pilot measured the streamed reduction slower at M = 7 and only +# noisily faster at M = 256. +const _STREAMED_GEOMETRY_MIN_COLUMNS = 512 + +# Dense Float64 batches form the local entries Σ_s Λ[i,s] C[j,s], j = j0(i):j0(i)+3, +# in one pass over the columns s instead of 4n strided dot products. Only the +# summation order changes. Returns false, with zero outputs, when the inputs are +# not eligible or the bound below fails; the caller then runs the original +# reduction on the same Λ, so such inputs keep exactly their previous results. +# +# Overflow bound: A[k,i] accumulates fl(|fl(λc)|) and D[i,k,:] are the local +# basis jet partials, which do not depend on Λ. In either summation order (any +# tree, BLAS blocking or fused multiply-add), every intermediate of the +# reduction, of the jet contraction, of the knot accumulation and of the callers' +# not-a-knot mapping is at most G = Σ_i Σ_k A[k,i] (1 + Σ_d |D[i,k,d]|) in +# magnitude, times the rounding growth ((1+u)/(1-u))^K with K < 2M + 34n ≤ 2^42, +# which is below 1.001, plus underflow terms below 1. If the computed G is finite +# and ≤ floatmax/2, no step in either order overflows and, without Inf operands, +# none produces NaN, so both give finite results. Any NaN or Inf in the used +# entries of Λ, C or D makes G nonfinite, since Inf * 0 is NaN. +function _streamed_collocation_geometry!(sites_bar, knot_bar, spline, c_bar, Λ) + c = spline.coefficients + sites = spline.sites + T = knot_vector(spline.basis) + (c isa Matrix{Float64} && c_bar isa Matrix{Float64} && Λ isa Matrix{Float64} && + sites isa Vector{Float64} && T isa Vector{Float64} && + sites_bar isa Vector{Float64} && knot_bar isa Vector{Float64}) || return false + n, M = size(c) + (size(Λ) == (n, M) && length(sites) == n && + _STREAMED_GEOMETRY_MIN_COLUMNS <= M <= 2^40 && n <= 2^35) || return false + + first = Vector{Int}(undef, n) + for i in 1:n + j = basis_row(spline.basis, sites[i]).indices[1] + 1 <= j <= n - 3 || return false + first[i] = j + end + + P = zeros(4, n) + A = zeros(4, n) + @inbounds for s in 1:M, i in 1:n + λ = Λ[i, s] + j = first[i] + p1 = λ * c[j, s] + p2 = λ * c[j+1, s] + p3 = λ * c[j+2, s] + p4 = λ * c[j+3, s] + P[1, i] += p1 + P[2, i] += p2 + P[3, i] += p3 + P[4, i] += p4 + A[1, i] += abs(p1) + A[2, i] += abs(p2) + A[3, i] += abs(p3) + A[4, i] += abs(p4) + end + + G = 0.0 + for i in 1:n + span = first[i] + 3 + values = _cubic_basis_jets(T, span, sites[i], Float64) + for k in 1:4 + G += A[k, i] * (1 + sum(abs, values[k].partials)) + end + x_bar, local_knot_bar = _contract_cubic_basis_jets( + values, + (-P[1, i], -P[2, i], -P[3, i], -P[4, i]), + ) + sites_bar[i] += x_bar + _accumulate_local_knot_bar!(knot_bar, span, local_knot_bar) + end + isfinite(G) && G <= floatmax(Float64) / 2 && return true + fill!(sites_bar, 0.0) + fill!(knot_bar, 0.0) + return false +end + +# Ordinary splines do not retain their collocation factorization, so rebuild it. +_collocation_geometry_vjp(spline, c_bar) = _collocation_geometry_vjp( + spline, + c_bar, + CubicBSplineFactorization(spline.basis, spline.sites), +) + +# Plans pass their cached factorization of the same collocation matrix. It is +# only read by the transpose solve; site and knot cotangents are still formed +# from the live sites, basis and coefficients below. +function _collocation_geometry_vjp(spline, c_bar, fact::CubicBSplineFactorization) + c = spline.coefficients + sites = spline.sites + ordinates_bar = solve_adjoint(fact, c_bar) + T = knot_vector(spline.basis) + V = promote_type(eltype(c), eltype(c_bar), eltype(T), eltype(sites)) + sites_bar = zeros(V, length(sites)) + knot_bar = zeros(V, length(T)) + if _streamed_collocation_geometry!(sites_bar, knot_bar, spline, c_bar, ordinates_bar) + return ordinates_bar, sites_bar, knot_bar + end + + for i in eachindex(sites) + row = basis_row(spline.basis, sites[i]) + if c isa AbstractVector + values_bar = ntuple(k -> -ordinates_bar[i] * c[row.indices[k]], 4) + else + values_bar = ntuple( + k -> -dot(@view(ordinates_bar[i, :]), @view(c[row.indices[k], :])), + 4, + ) + end + span = row.indices[4] + x_bar, local_knot_bar = _cubic_basis_vjp(T, span, sites[i], values_bar) + sites_bar[i] += x_bar + _accumulate_local_knot_bar!(knot_bar, span, local_knot_bar) + end + return ordinates_bar, sites_bar, knot_bar +end + +function _cotangent_field(delta, field, primal) + delta = ChainRulesCore.unthunk(delta) + delta isa ChainRulesCore.AbstractZero && return zero(primal) + value = ChainRulesCore.unthunk(getproperty(delta, field)) + value isa ChainRulesCore.AbstractZero && return zero(primal) + return ChainRulesCore.ProjectTo(primal)(value) +end + +function _basis_knot_cotangent(delta, basis) + delta = ChainRulesCore.unthunk(delta) + delta isa ChainRulesCore.AbstractZero && return zero(knot_vector(basis)) + basis_delta = ChainRulesCore.unthunk(getproperty(delta, :basis)) + basis_delta isa ChainRulesCore.AbstractZero && return zero(knot_vector(basis)) + knot_delta = ChainRulesCore.unthunk(getproperty(basis_delta, :knot_vector)) + knot_delta isa ChainRulesCore.AbstractZero && return zero(knot_vector(basis)) + return ChainRulesCore.ProjectTo(knot_vector(basis))(knot_delta) +end + +function _stencil_geometry_vjp(basis, xq, policy, w1_bar, w2_bar, w3_bar, w4_bar) + T = knot_vector(basis) + V = promote_type(eltype(T), eltype(xq), eltype(w1_bar)) + knot_bar = zeros(V, length(T)) + query_bar = zeros(V, length(xq)) + xmin, xmax = bspline_domain(basis) + for i in eachindex(xq) + q = xq[i] + outside_left = q < xmin + outside_right = q > xmax + if policy isa ZeroExtrap && (outside_left || outside_right) + continue + end + x = _apply_extrapolation(policy, q, xmin, xmax) + row = basis_row(basis, x) + x_bar, local_knot_bar = _cubic_basis_vjp( + T, + row.indices[4], + x, + (w1_bar[i], w2_bar[i], w3_bar[i], w4_bar[i]), + ) + _accumulate_local_knot_bar!(knot_bar, row.indices[4], local_knot_bar) + if policy isa ClampExtrap && outside_left + knot_bar[4] += x_bar + elseif policy isa ClampExtrap && outside_right + knot_bar[end-3] += x_bar + else + query_bar[i] += x_bar + end + end + return knot_bar, query_bar +end + +function ChainRulesCore.rrule(::typeof(_evaluate_cubic_b_spline), spline, query::AbstractVector) + output = _evaluate_cubic_b_spline(spline, query) + project_query = ChainRulesCore.ProjectTo(query) + function evaluate_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent() + end + c_bar, sites_bar, knot_bar, query_bar = + _evaluation_geometry_vjp(spline, query, delta) + spline_bar = Tangent{typeof(spline)}( + sites=sites_bar, + basis=Tangent{typeof(spline.basis)}(knot_vector=knot_bar), + coefficients=c_bar, + extrapolation=NoTangent(), + ) + return NoTangent(), spline_bar, project_query(query_bar) + end + return output, evaluate_pullback +end + +function ChainRulesCore.rrule(::typeof(_evaluate_cubic_b_spline), spline, query::Real) + output = _evaluate_cubic_b_spline(spline, query) + project_query = ChainRulesCore.ProjectTo(query) + function evaluate_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent() + end + output_bar = spline.coefficients isa AbstractVector ? [delta] : reshape(delta, 1, :) + c_bar, sites_bar, knot_bar, query_bar = + _evaluation_geometry_vjp(spline, [query], output_bar) + spline_bar = Tangent{typeof(spline)}( + sites=sites_bar, + basis=Tangent{typeof(spline.basis)}(knot_vector=knot_bar), + coefficients=c_bar, + extrapolation=NoTangent(), + ) + return NoTangent(), spline_bar, project_query(only(query_bar)) + end + return output, evaluate_pullback +end + +function ChainRulesCore.rrule(::typeof(_construct_cubic_b_spline), u, sites, extrap) + spline = _construct_cubic_b_spline(u, sites, extrap) + project_u = ChainRulesCore.ProjectTo(u) + project_sites = ChainRulesCore.ProjectTo(sites) + function construct_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent(), NoTangent() + end + c_bar = _cotangent_field(delta, :coefficients, spline.coefficients) + direct_sites_bar = _cotangent_field(delta, :sites, spline.sites) + direct_knot_bar = _basis_knot_cotangent(delta, spline.basis) + u_bar, sites_bar, knot_bar = _collocation_geometry_vjp(spline, c_bar) + sites_bar .+= direct_sites_bar + knot_bar .+= direct_knot_bar + _map_not_a_knot_bar!(sites_bar, knot_bar) + return NoTangent(), project_u(u_bar), project_sites(sites_bar), NoTangent() + end + return spline, construct_pullback +end + +function ChainRulesCore.rrule( + ::typeof(bspline_coefficients), + plan::CubicBSplinePlan, + u::AbstractVecOrMat, +) + coefficients = bspline_coefficients(plan, u) + spline = CubicBSpline(plan.sites, plan.basis, coefficients, plan.extrapolation) + project_u = ChainRulesCore.ProjectTo(u) + function coefficients_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent() + end + u_bar, sites_bar, knot_bar = + _collocation_geometry_vjp(spline, delta, plan.factorization) + _map_not_a_knot_bar!(sites_bar, knot_bar) + plan_bar = Tangent{typeof(plan)}( + sites=sites_bar, + basis=NoTangent(), + factorization=NoTangent(), + stencil=NoTangent(), + extrapolation=NoTangent(), + ) + return NoTangent(), plan_bar, project_u(u_bar) + end + return coefficients, coefficients_pullback +end + +function ChainRulesCore.rrule(::typeof(_apply_cubic_b_spline_plan), plan, u) + output = _apply_cubic_b_spline_plan(plan, u) + c = bspline_coefficients(plan, u) + spline = CubicBSpline(plan.sites, plan.basis, c, plan.extrapolation) + project_u = ChainRulesCore.ProjectTo(u) + function plan_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent() + end + c_bar, sites_bar, knot_bar, query_bar = + _evaluation_geometry_vjp(spline, plan.stencil.query, delta) + u_bar, collocation_sites_bar, collocation_knot_bar = + _collocation_geometry_vjp(spline, c_bar, plan.factorization) + sites_bar .+= collocation_sites_bar + knot_bar .+= collocation_knot_bar + _map_not_a_knot_bar!(sites_bar, knot_bar) + stencil_bar = Tangent{typeof(plan.stencil)}( + i1=NoTangent(), i2=NoTangent(), i3=NoTangent(), i4=NoTangent(), + w1=NoTangent(), w2=NoTangent(), w3=NoTangent(), w4=NoTangent(), + query=query_bar, + ) + plan_bar = Tangent{typeof(plan)}( + sites=sites_bar, + basis=NoTangent(), + factorization=NoTangent(), + stencil=stencil_bar, + extrapolation=NoTangent(), + ) + return NoTangent(), plan_bar, project_u(u_bar) + end + return output, plan_pullback +end + +function ChainRulesCore.rrule( + ::typeof(_construct_cubic_b_spline_plan), + sites, + query, + extrap, +) + plan = _construct_cubic_b_spline_plan(sites, query, extrap) + project_sites = ChainRulesCore.ProjectTo(sites) + project_query = ChainRulesCore.ProjectTo(query) + function construct_plan_pullback(delta) + delta = ChainRulesCore.unthunk(delta) + if delta isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent(), NoTangent() + end + sites_bar = _cotangent_field(delta, :sites, plan.sites) + knot_bar = _basis_knot_cotangent(delta, plan.basis) + # The pivot-free LU bands are storage, not an independent geometric + # input. Exported coefficient differentiation is handled by the + # bspline_coefficients rule above, which applies the implicit adjoint + # before returning a site cotangent to this constructor. + stencil_delta = ChainRulesCore.unthunk(getproperty(delta, :stencil)) + if stencil_delta isa ChainRulesCore.AbstractZero + query_bar = zero(query) + else + query_bar = _cotangent_field(stencil_delta, :query, plan.stencil.query) + stencil_knot_bar, stencil_query_bar = _stencil_geometry_vjp( + plan.basis, + plan.stencil.query, + plan.extrapolation, + _cotangent_field(stencil_delta, :w1, plan.stencil.w1), + _cotangent_field(stencil_delta, :w2, plan.stencil.w2), + _cotangent_field(stencil_delta, :w3, plan.stencil.w3), + _cotangent_field(stencil_delta, :w4, plan.stencil.w4), + ) + knot_bar .+= stencil_knot_bar + query_bar .+= stencil_query_bar + end + _map_not_a_knot_bar!(sites_bar, knot_bar) + return NoTangent(), project_sites(sites_bar), project_query(query_bar), NoTangent() + end + return plan, construct_plan_pullback +end + +function ChainRulesCore.rrule(::typeof(solve), fact::CubicBSplineFactorization, b::AbstractVecOrMat) + c = solve(fact, b) + + project_b = ChainRulesCore.ProjectTo(b) + + function solve_pullback(Δ) + Δ_unthunked = ChainRulesCore.unthunk(Δ) + + # A bare factorization does not retain the unfactorized collocation + # geometry. Public spline and plan rules handle site derivatives with + # the implicit collocation adjoint before reaching this low-level rule. + if Δ_unthunked isa ChainRulesCore.AbstractZero + return NoTangent(), NoTangent(), ChainRulesCore.ZeroTangent() + end + + # Adjoint solve A^T b_bar = c_bar + ∂b = solve_adjoint(fact, Δ_unthunked) + return NoTangent(), NoTangent(), project_b(∂b) + end + + return c, solve_pullback +end + +function ChainRulesCore.rrule(::typeof(_evaluate_stencil), stencil::CubicBSplineStencil, c::AbstractVector) + out = _evaluate_stencil(stencil, c) + + project_c = ChainRulesCore.ProjectTo(c) + + function _evaluate_stencil_pullback(Δ) + Δ_unthunked = ChainRulesCore.unthunk(Δ) + + if Δ_unthunked isa ChainRulesCore.AbstractZero + return NoTangent(), NoTangent(), ChainRulesCore.ZeroTangent() + end + + ∂c = zero(c) + ∂w1 = zero(stencil.w1); ∂w2 = zero(stencil.w2) + ∂w3 = zero(stencil.w3); ∂w4 = zero(stencil.w4) + for i in 1:length(stencil.i1) + ∂c[stencil.i1[i]] += Δ_unthunked[i] * stencil.w1[i] + ∂c[stencil.i2[i]] += Δ_unthunked[i] * stencil.w2[i] + ∂c[stencil.i3[i]] += Δ_unthunked[i] * stencil.w3[i] + ∂c[stencil.i4[i]] += Δ_unthunked[i] * stencil.w4[i] + ∂w1[i] = Δ_unthunked[i] * c[stencil.i1[i]] + ∂w2[i] = Δ_unthunked[i] * c[stencil.i2[i]] + ∂w3[i] = Δ_unthunked[i] * c[stencil.i3[i]] + ∂w4[i] = Δ_unthunked[i] * c[stencil.i4[i]] + end + stencil_bar = Tangent{typeof(stencil)}( + i1=NoTangent(), i2=NoTangent(), i3=NoTangent(), i4=NoTangent(), + w1=∂w1, w2=∂w2, w3=∂w3, w4=∂w4, query=NoTangent(), + ) + return NoTangent(), stencil_bar, project_c(∂c) + end + + return out, _evaluate_stencil_pullback +end + +function ChainRulesCore.rrule(::typeof(_evaluate_stencil), stencil::CubicBSplineStencil, c::AbstractMatrix) + out = _evaluate_stencil(stencil, c) + + project_c = ChainRulesCore.ProjectTo(c) + + function _evaluate_stencil_pullback(Δ) + Δ_unthunked = ChainRulesCore.unthunk(Δ) + + if Δ_unthunked isa ChainRulesCore.AbstractZero + return NoTangent(), NoTangent(), ChainRulesCore.ZeroTangent() + end + + ∂c = zero(c) + ∂w1 = zero(stencil.w1); ∂w2 = zero(stencil.w2) + ∂w3 = zero(stencil.w3); ∂w4 = zero(stencil.w4) + n_series = size(c, 2) + for i in 1:length(stencil.i1) + idx1, idx2, idx3, idx4 = stencil.i1[i], stencil.i2[i], stencil.i3[i], stencil.i4[i] + w1, w2, w3, w4 = stencil.w1[i], stencil.w2[i], stencil.w3[i], stencil.w4[i] + for s in 1:n_series + Δ_val = Δ_unthunked[i, s] + ∂c[idx1, s] += Δ_val * w1 + ∂c[idx2, s] += Δ_val * w2 + ∂c[idx3, s] += Δ_val * w3 + ∂c[idx4, s] += Δ_val * w4 + ∂w1[i] += Δ_val * c[idx1, s] + ∂w2[i] += Δ_val * c[idx2, s] + ∂w3[i] += Δ_val * c[idx3, s] + ∂w4[i] += Δ_val * c[idx4, s] + end + end + stencil_bar = Tangent{typeof(stencil)}( + i1=NoTangent(), i2=NoTangent(), i3=NoTangent(), i4=NoTangent(), + w1=∂w1, w2=∂w2, w3=∂w3, w4=∂w4, query=NoTangent(), + ) + return NoTangent(), stencil_bar, project_c(∂c) + end + + return out, _evaluate_stencil_pullback +end + function ChainRulesCore.rrule(::typeof(_cubic_spline_eval), u, t, h, z, tq::AbstractArray) n_query = length(tq) results = similar(tq, promote_type(eltype(u), eltype(z), eltype(tq))) @@ -1039,3 +1748,110 @@ function ChainRulesCore.rrule(::typeof(_cubic_spline_eval), u::AbstractMatrix, t return results, _cubic_spline_eval_matrix_pullback end + +function ChainRulesCore.rrule(::Type{<:CubicBSplineFactorization}, basis, xq) + fact = CubicBSplineFactorization(basis, xq) + function CubicBSplineFactorization_pullback(Δ) + return NoTangent(), NoTangent(), NoTangent() + end + return fact, CubicBSplineFactorization_pullback +end + +function ChainRulesCore.rrule(::typeof(_basis_stencil), basis, xq, policy) + stencil = _basis_stencil(basis, xq, policy) + function _basis_stencil_pullback(Δ) + Δ = ChainRulesCore.unthunk(Δ) + if Δ isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent(), NoTangent() + end + ∂w1 = _cotangent_field(Δ, :w1, stencil.w1) + ∂w2 = _cotangent_field(Δ, :w2, stencil.w2) + ∂w3 = _cotangent_field(Δ, :w3, stencil.w3) + ∂w4 = _cotangent_field(Δ, :w4, stencil.w4) + ∂T, ∂xq = _stencil_geometry_vjp( + basis, + xq, + policy, + ∂w1, + ∂w2, + ∂w3, + ∂w4, + ) + basis_bar = Tangent{typeof(basis)}(knot_vector=∂T) + return NoTangent(), basis_bar, ChainRulesCore.ProjectTo(xq)(∂xq), NoTangent() + end + return stencil, _basis_stencil_pullback +end + +function ChainRulesCore.rrule(::typeof(basis_row), basis, x) + row = basis_row(basis, x) + function basis_row_pullback(Δ) + Δ = ChainRulesCore.unthunk(Δ) + if Δ isa ChainRulesCore.AbstractZero + return NoTangent(), ZeroTangent(), ZeroTangent() + end + values_bar = _cotangent_field(Δ, :values, row.values) + T = knot_vector(basis) + xmin, xmax = bspline_domain(basis) + if x < xmin || x > xmax + return NoTangent(), Tangent{typeof(basis)}( + knot_vector=zeros(eltype(T), length(T)), + ), zero(x) + end + x_bar, local_knot_bar = _cubic_basis_vjp( + T, + row.indices[4], + x, + values_bar, + ) + knot_bar = zeros(promote_type(eltype(T), typeof(x_bar)), length(T)) + _accumulate_local_knot_bar!(knot_bar, row.indices[4], local_knot_bar) + return NoTangent(), Tangent{typeof(basis)}(knot_vector=knot_bar), x_bar + end + return row, basis_row_pullback +end + +function ChainRulesCore.rrule(::typeof(_evaluate_spline), c::AbstractVector, row::CubicBSplineRow) + out = _evaluate_spline(c, row) + project_c = ChainRulesCore.ProjectTo(c) + function _evaluate_spline_pullback(Δ) + Δ_unthunked = ChainRulesCore.unthunk(Δ) + if Δ_unthunked isa ChainRulesCore.AbstractZero + return NoTangent(), ChainRulesCore.ZeroTangent(), NoTangent() + end + ∂c = zero(c) + values_bar = ntuple(k -> Δ_unthunked * c[row.indices[k]], 4) + for k in 1:4 + ∂c[row.indices[k]] += Δ_unthunked * row.values[k] + end + row_bar = Tangent{typeof(row)}(indices=NoTangent(), values=values_bar) + return NoTangent(), project_c(∂c), row_bar + end + return out, _evaluate_spline_pullback +end + +function ChainRulesCore.rrule(::typeof(_evaluate_spline), c::AbstractMatrix, row::CubicBSplineRow) + out = _evaluate_spline(c, row) + project_c = ChainRulesCore.ProjectTo(c) + function _evaluate_spline_pullback(Δ) + Δ_unthunked = ChainRulesCore.unthunk(Δ) + if Δ_unthunked isa ChainRulesCore.AbstractZero + return NoTangent(), ChainRulesCore.ZeroTangent(), NoTangent() + end + ∂c = zero(c) + values_bar = ntuple( + k -> dot(Δ_unthunked, @view(c[row.indices[k], :])), + 4, + ) + for k in 1:4 + idx = row.indices[k] + w = row.values[k] + for s in 1:size(c, 2) + ∂c[idx, s] += Δ_unthunked[s] * w + end + end + row_bar = Tangent{typeof(row)}(indices=NoTangent(), values=values_bar) + return NoTangent(), project_c(∂c), row_bar + end + return out, _evaluate_spline_pullback +end diff --git a/src/cubic_b_spline.jl b/src/cubic_b_spline.jl new file mode 100644 index 0000000..b2bc732 --- /dev/null +++ b/src/cubic_b_spline.jl @@ -0,0 +1,1161 @@ +# ============================================================================= +# Cubic B-Spline Basis +# ============================================================================= + +""" + CubicBSplineBasis{K} + +A fixed degree-3 (order-4) B-spline basis defined by a nondecreasing knot vector. +""" +struct CubicBSplineBasis{K<:AbstractVector} + knot_vector::K + + function CubicBSplineBasis(knot_vector::K) where {K<:AbstractVector} + _validate_knot_vector(knot_vector) + new{K}(knot_vector) + end +end + +Adapt.@adapt_structure CubicBSplineBasis + +function _validate_knot_vector(T::AbstractVector) + M = length(T) + if M < 8 + throw(ArgumentError("Knot vector must have at least length 8 for a valid cubic basis.")) + end + + if !all(isfinite, T) + throw(ArgumentError("Knot vector contains non-finite values.")) + end + + if !issorted(T) + throw(ArgumentError("Knot vector must be nondecreasing.")) + end + + if T[1] != T[4] || (M > 4 && T[4] == T[5]) + throw(ArgumentError("Left endpoint must have exactly multiplicity 4.")) + end + + if T[end-3] != T[end] || (M > 4 && T[end-4] == T[end-3]) + throw(ArgumentError("Right endpoint must have exactly multiplicity 4.")) + end + + for a in 1:(M-4) + if T[a] == T[a+4] + throw(ArgumentError("Knot sequence is degenerate: T[$a] == T[$(a+4)].")) + end + end + + for i in 5:(M-7) + if T[i] == T[i+3] + throw(ArgumentError("Internal knot $(T[i]) has multiplicity > 3.")) + end + end +end + +""" + CubicBSplineBasis(; domain, internal_knots=nothing, knot_vector=nothing) + +Construct a `CubicBSplineBasis` from either a full `knot_vector`, or a `domain` `(xmin, xmax)` and optional `internal_knots`. +If `internal_knots` is omitted, the result is an endpoint-clamped cubic +polynomial basis with four basis functions. +""" +function CubicBSplineBasis(; domain=nothing, internal_knots=nothing, knot_vector=nothing) + if !isnothing(knot_vector) + if !isnothing(domain) || !isnothing(internal_knots) + throw(ArgumentError("Cannot provide both knot_vector and (domain, internal_knots)")) + end + return CubicBSplineBasis(knot_vector) + end + + if isnothing(domain) + throw(ArgumentError("Must provide either knot_vector or domain and internal_knots")) + end + + xmin, xmax = domain + if xmin >= xmax || !isfinite(xmin) || !isfinite(xmax) + throw(ArgumentError("Domain must have finite xmin < xmax")) + end + + if !isnothing(internal_knots) && !all(isfinite, internal_knots) + throw(ArgumentError("Internal knots must be finite")) + end + + if isnothing(internal_knots) + T = [xmin, xmin, xmin, xmin, xmax, xmax, xmax, xmax] + else + T = vcat(fill(xmin, 4), internal_knots, fill(xmax, 4)) + end + + return CubicBSplineBasis(T) +end + +""" + knot_vector(basis::CubicBSplineBasis) + +Return the full knot vector of the B-spline basis. +""" +knot_vector(basis::CubicBSplineBasis) = basis.knot_vector + +""" + nbasis(basis::CubicBSplineBasis) + +Return the total number of basis functions in the basis space (number of knots - 4). +""" +nbasis(basis::CubicBSplineBasis) = length(basis.knot_vector) - 4 + +""" + bspline_domain(basis::CubicBSplineBasis) + +Return the fundamental domain `(T[4], T[end-3])` of the B-spline basis. +""" +bspline_domain(basis::CubicBSplineBasis) = (basis.knot_vector[4], basis.knot_vector[end-3]) + +""" + internal_knots(basis::CubicBSplineBasis) + +Return the internal knots of the B-spline basis (all knots strictly inside the fundamental domain). +""" +internal_knots(basis::CubicBSplineBasis) = basis.knot_vector[5:end-4] + +""" + basis_support(basis::CubicBSplineBasis, a::Integer) + +Return the support interval `(T[a], T[a+4])` of the `a`-th basis function. +""" +function basis_support(basis::CubicBSplineBasis, a::Integer) + 1 <= a <= nbasis(basis) || throw(BoundsError(Base.OneTo(nbasis(basis)), a)) + return (basis.knot_vector[a], basis.knot_vector[a+4]) +end + +""" + _find_cubic_span(T, x) +""" +function _find_cubic_span(T, x) + n_basis = length(T) - 4 + if x >= T[n_basis + 1] + return n_basis + end + if x < T[4] + return 4 + end + + low = 4 + high = n_basis + 1 + + while low < high + mid = (low + high) >> 1 + if x < T[mid] + high = mid + else + low = mid + 1 + end + end + + return low - 1 +end + +""" + _cubic_basis_values(T, span, x) +""" +function _cubic_basis_values(T, span, x) + left1 = x - T[span] + right1 = T[span+1] - x + + temp = one(typeof(right1)) / (right1 + left1) + N1_0 = right1 * temp + N1_1 = left1 * temp + + left2 = x - T[span-1] + right2 = T[span+2] - x + + temp = N1_0 / (right1 + left2) + N2_0 = right1 * temp + saved = left2 * temp + + temp = N1_1 / (right2 + left1) + N2_1 = saved + right2 * temp + N2_2 = left1 * temp + + left3 = x - T[span-2] + right3 = T[span+3] - x + + temp = N2_0 / (right1 + left3) + N3_0 = right1 * temp + saved = left3 * temp + + temp = N2_1 / (right2 + left2) + N3_1 = saved + right2 * temp + saved = left2 * temp + + temp = N2_2 / (right3 + left1) + N3_2 = saved + right3 * temp + N3_3 = left1 * temp + + return (N3_0, N3_1, N3_2, N3_3) +end + +struct CubicBSplineRow{I,V} + indices::NTuple{4,I} + values::NTuple{4,V} +end + +Adapt.@adapt_structure CubicBSplineRow + +""" + basis_row(basis::CubicBSplineBasis, x) + +Evaluate the non-zero basis function values at a single point `x`. +Returns a `CubicBSplineRow` containing the 4 active basis function indices and their corresponding weights. +""" +function basis_row(basis::CubicBSplineBasis, x) + _validate_bspline_query(x) + T = knot_vector(basis) + xmin, xmax = bspline_domain(basis) + + V = typeof(one(eltype(T)) * one(typeof(x)) / one(typeof(x))) + + if x < xmin || x > xmax + return CubicBSplineRow{Int, V}((1, 2, 3, 4), (zero(V), zero(V), zero(V), zero(V))) + end + + span = _find_cubic_span(T, x) + vals = _cubic_basis_values(T, span, x) + indices = (span - 3, span - 2, span - 1, span) + return CubicBSplineRow{Int, V}(indices, V.(vals)) +end + +struct CubicBSplineStencil{I,W,Q} + i1::I; i2::I; i3::I; i4::I + w1::W; w2::W; w3::W; w4::W + query::Q +end + +Adapt.@adapt_structure CubicBSplineStencil + +""" + basis_stencil(basis::CubicBSplineBasis, xq; extrapolation=:throw) + +Evaluate the non-zero basis function values at a vector of query points `xq`. +Returns a `CubicBSplineStencil` struct encapsulating the indices and weights. +Supported `extrapolation` policies are `:throw`, `:clamp`, and `:zero`. +""" +function basis_stencil(basis::CubicBSplineBasis, xq; extrapolation=:throw) + policy = _get_extrapolation_policy(extrapolation) + return _basis_stencil(basis, xq, policy) +end + +function _basis_stencil(basis::CubicBSplineBasis, xq, policy) + n_query = length(xq) + + i1 = zeros(Int, n_query); i2 = zeros(Int, n_query); i3 = zeros(Int, n_query); i4 = zeros(Int, n_query) + + T_type = promote_type(eltype(knot_vector(basis)), eltype(xq)) + V = typeof(one(T_type) / one(T_type)) + w1 = zeros(V, n_query); w2 = zeros(V, n_query); w3 = zeros(V, n_query); w4 = zeros(V, n_query) + + xmin, xmax = bspline_domain(basis) + + for i in 1:n_query + x = _apply_extrapolation(policy, xq[i], xmin, xmax) + row = basis_row(basis, x) + + i1[i] = row.indices[1] + i2[i] = row.indices[2] + i3[i] = row.indices[3] + i4[i] = row.indices[4] + w1[i] = row.values[1] + w2[i] = row.values[2] + w3[i] = row.values[3] + w4[i] = row.values[4] + end + + return CubicBSplineStencil(i1, i2, i3, i4, w1, w2, w3, w4, xq) +end + +""" + basis_matrix(basis::CubicBSplineBasis, xq) + +Construct the dense evaluation matrix mapping B-spline coefficients to values at query points `xq`. +The output matrix has size `(length(xq), nbasis(basis))`. +""" +function basis_matrix(basis::CubicBSplineBasis, xq; storage=:dense) + if storage != :dense + throw(ArgumentError("Only :dense storage is currently implemented for basis_matrix")) + end + + n_q = length(xq) + n_b = nbasis(basis) + T_type = promote_type(eltype(knot_vector(basis)), eltype(xq)) + V = typeof(one(T_type) / one(T_type)) + B = zeros(V, n_q, n_b) + + for i in 1:n_q + row = basis_row(basis, xq[i]) + for j in 1:4 + idx = row.indices[j] + if 1 <= idx <= n_b + B[i, idx] += row.values[j] + end + end + end + return B +end + +# ============================================================================= +# Cubic B-Spline Collocation Solver +# ============================================================================= + +""" + CubicBSplineFactorization{F<:AbstractMatrix} + +A precomputed matrix factorization used to solve for cubic B-spline coefficients given a set of ordinate values. +Construct via `CubicBSplineFactorization(basis, x)`. +""" +struct CubicBSplineFactorization{F<:AbstractMatrix} + bands::F +end + +Adapt.@adapt_structure CubicBSplineFactorization + +function _validate_bspline_sites(x::AbstractVector) + if length(x) < 4 + throw(ArgumentError("At least 4 interpolation sites are required.")) + end + if !all(isfinite, x) + throw(ArgumentError("Interpolation sites must be finite.")) + end + for i in 1:(length(x)-1) + if x[i] >= x[i+1] + throw(ArgumentError("Interpolation sites must be strictly increasing.")) + end + end +end + +""" + CubicBSplineFactorization(basis::CubicBSplineBasis, xq::AbstractVector) + +Compute the LU factorization of the B-spline collocation matrix for the given `basis` evaluated at the sites `xq`. +The number of interpolation sites must equal `nbasis(basis)`. +""" +function CubicBSplineFactorization(basis::CubicBSplineBasis, xq::AbstractVector) + _validate_bspline_sites(xq) + n = length(xq) + if n != nbasis(basis) + throw(ArgumentError("Number of interpolation sites ($n) must equal number of basis functions ($(nbasis(basis))) for exact interpolation.")) + end + + T_vec = knot_vector(basis) + T_type = promote_type(eltype(T_vec), eltype(xq)) + V = typeof(one(T_type) / one(T_type)) + B = zeros(V, 7, n) + + for i in 1:n + x = xq[i] + + if x < T_vec[i] || x > T_vec[i+4] + throw(ArgumentError("Schoenberg-Whitney condition violated at site $i (x = $x, support = [$(T_vec[i]), $(T_vec[i+4])]).")) + end + + row = basis_row(basis, x) + for k in 1:4 + j = row.indices[k] + if 1 <= j <= n + B[4 + i - j, j] = row.values[k] + end + end + end + + # Pivot-free LU Factorization (in-place Doolittle for band matrices) + for k in 1:n + pivot = B[4, k] + if abs(pivot) < eps(V) * 10 + throw(LinearAlgebra.SingularException(k)) + end + + for i in (k+1):min(n, k+3) + B[4 + i - k, k] /= pivot + + for j in (k+1):min(n, k+3) + B[4 + i - j, j] -= B[4 + i - k, k] * B[4 + k - j, j] + end + end + end + + return CubicBSplineFactorization(B) +end + +function solve(fact::CubicBSplineFactorization, b::AbstractVector) + n = size(fact.bands, 2) + if length(b) != n + throw(DimensionMismatch("RHS vector length ($(length(b))) does not match factorization order ($n).")) + end + x = similar(b, promote_type(eltype(fact.bands), eltype(b))) + copyto!(x, b) + _solve_band_vector!(fact.bands, x, b) + return x +end + +function solve(fact::CubicBSplineFactorization, B_mat::AbstractMatrix) + n = size(fact.bands, 2) + if size(B_mat, 1) != n + throw(DimensionMismatch("RHS matrix rows ($(size(B_mat, 1))) does not match factorization order ($n).")) + end + X = similar(B_mat, promote_type(eltype(fact.bands), eltype(B_mat))) + copyto!(X, B_mat) + _solve_band_columns!(fact.bands, X, B_mat) + return X +end + +function _band_solve!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + # Forward substitution: L y = b + for j in 1:n + for i in (j+1):min(n, j+3) + x[i] -= B[4 + i - j, j] * x[j] + end + end + + # Backward substitution: U x = y + for j in n:-1:1 + x[j] /= B[4, j] + for i in max(1, j-3):(j-1) + x[i] -= B[4 + i - j, j] * x[j] + end + end + return x +end + +# ----------------------------------------------------------------------------- +# Dense-host fast paths (Float32/Float64 factor and RHS of the same type). +# +# Everything below is an internal optimization of `_band_solve!` and +# `_band_solve_adjoint!`; the generic kernels above and below remain the +# reference and the fallback. Dispatch is restricted on dense `Matrix`/`Vector` +# storage of BOTH the factor and the right-hand side, so device and +# non-dense methods are never intercepted. +# ----------------------------------------------------------------------------- + +const _HostFloat = Union{Float32,Float64} + +# Minimum number of right-hand sides for which the O(7n) structure scan is +# repaid by the cheaper bordered kernels. Measured locally (one core, N=33 and +# N=128, Float64): a single column is slower with classification, two or more +# are faster. Single columns use the full-band kernel. +const _BORDERED_MIN_RHS = 2 + +# True when `B` is a 7×n factor to which the unchecked kernels may be applied +# for an n-row right-hand side. Anything else is handled by the generic code, +# which raises ordinary bounds errors for malformed factors. +@inline _band_shape_ok(B::Matrix, n::Integer) = size(B, 1) == 7 && size(B, 2) == n + +# Exact structural test of the bordered-tridiagonal pattern, on actual factor +# contents (never on N or the spline kind). Requires n >= 6; rows 1 and 7 zero; +# row 2 zero except column 4; row 6 zero except column n-3; every used entry +# finite and every pivot finite and nonzero. Zero tests are exact (`iszero`): +# a tiny nonzero forbidden entry selects the general kernels. Entries that the +# solvers never read (U[0,1] and L[n+1,n]) are not inspected. +function _is_bordered_tridiagonal_factor(B::AbstractMatrix) + n = size(B, 2) + (size(B, 1) == 7 && n >= 6) || return false + @inbounds for j in 1:n + iszero(B[1, j]) && iszero(B[7, j]) || return false + if j == 4 + isfinite(B[2, j]) || return false + else + iszero(B[2, j]) || return false + end + if j == n - 3 + isfinite(B[6, j]) || return false + else + iszero(B[6, j]) || return false + end + d = B[4, j] + (isfinite(d) && !iszero(d)) || return false + (j == 1 || isfinite(B[3, j])) || return false + (j == n || isfinite(B[5, j])) || return false + end + return true +end + +# Full-band substitutions on column `c` of `X`, in exactly the operation order +# of `_band_solve!` / `_band_solve_adjoint!` (so results are bitwise equal), +# with the fixed-width interior separated from the short boundary ranges. +# Callers guarantee size(B) == (7, n) and size(X, 1) == n, 1 <= c <= size(X, 2). +@inline function _full_band_solve_column!(B::Matrix, X::Matrix, c::Int, n::Int) + @inbounds begin + for j in 1:(n-3) + xj = X[j, c] + X[j+1, c] -= B[5, j] * xj + X[j+2, c] -= B[6, j] * xj + X[j+3, c] -= B[7, j] * xj + end + for j in max(1, n - 2):n + xj = X[j, c] + for i in (j+1):min(n, j+3) + X[i, c] -= B[4 + i - j, j] * xj + end + end + for j in n:-1:4 + X[j, c] /= B[4, j] + xj = X[j, c] + X[j-3, c] -= B[1, j] * xj + X[j-2, c] -= B[2, j] * xj + X[j-1, c] -= B[3, j] * xj + end + for j in min(n, 3):-1:1 + X[j, c] /= B[4, j] + xj = X[j, c] + for i in max(1, j-3):(j-1) + X[i, c] -= B[4 + i - j, j] * xj + end + end + end + return nothing +end + +@inline function _full_band_solve_adjoint_column!(B::Matrix, X::Matrix, c::Int, n::Int) + @inbounds begin + for j in 1:min(n, 3) + s = X[j, c] + for i in max(1, j-3):(j-1) + s -= B[4 + i - j, j] * X[i, c] + end + X[j, c] = s / B[4, j] + end + for j in 4:n + s = X[j, c] + s -= B[1, j] * X[j-3, c] + s -= B[2, j] * X[j-2, c] + s -= B[3, j] * X[j-1, c] + X[j, c] = s / B[4, j] + end + for j in n:-1:max(1, n - 2) + s = X[j, c] + for i in (j+1):min(n, j+3) + s -= B[4 + i - j, j] * X[i, c] + end + X[j, c] = s + end + for j in (n-3):-1:1 + s = X[j, c] + s -= B[5, j] * X[j+1, c] + s -= B[6, j] * X[j+2, c] + s -= B[7, j] * X[j+3, c] + X[j, c] = s + end + end + return nothing +end + +# Bordered-tridiagonal column solves: only the main diagonal, the first +# sub/superdiagonals, B[6, n-3] = L[n-1, n-3] and B[2, 4] = U[2, 4] are used. +# Requires `_is_bordered_tridiagonal_factor(B)` and size(X, 1) == n >= 6. +@inline function _bordered_solve_column!(B::Matrix, X::Matrix, c::Int, n::Int) + @inbounds begin + alpha = B[6, n-3] + beta = B[2, 4] + # L y = b + for j in 1:(n-4) + X[j+1, c] -= B[5, j] * X[j, c] + end + xj = X[n-3, c] + X[n-2, c] -= B[5, n-3] * xj + X[n-1, c] -= alpha * xj + X[n-1, c] -= B[5, n-2] * X[n-2, c] + X[n, c] -= B[5, n-1] * X[n-1, c] + # U x = y + for j in n:-1:5 + X[j, c] /= B[4, j] + X[j-1, c] -= B[3, j] * X[j, c] + end + x4 = X[4, c] / B[4, 4] + X[4, c] = x4 + X[2, c] -= beta * x4 + X[3, c] -= B[3, 4] * x4 + x3 = X[3, c] / B[4, 3] + X[3, c] = x3 + X[2, c] -= B[3, 3] * x3 + x2 = X[2, c] / B[4, 2] + X[2, c] = x2 + X[1, c] -= B[3, 2] * x2 + X[1, c] /= B[4, 1] + end + return nothing +end + +@inline function _bordered_solve_adjoint_column!(B::Matrix, X::Matrix, c::Int, n::Int) + @inbounds begin + alpha = B[6, n-3] + beta = B[2, 4] + # U^T z = g + X[1, c] /= B[4, 1] + X[2, c] = (X[2, c] - B[3, 2] * X[1, c]) / B[4, 2] + X[3, c] = (X[3, c] - B[3, 3] * X[2, c]) / B[4, 3] + s = X[4, c] + s -= beta * X[2, c] + s -= B[3, 4] * X[3, c] + X[4, c] = s / B[4, 4] + for j in 5:n + X[j, c] = (X[j, c] - B[3, j] * X[j-1, c]) / B[4, j] + end + # L^T b = z + X[n-1, c] -= B[5, n-1] * X[n, c] + X[n-2, c] -= B[5, n-2] * X[n-1, c] + s = X[n-3, c] + s -= B[5, n-3] * X[n-2, c] + s -= alpha * X[n-1, c] + X[n-3, c] = s + for j in (n-4):-1:1 + X[j, c] -= B[5, j] * X[j+1, c] + end + end + return nothing +end + +# Generic column loops: the reference algorithm and the fallback. +function _solve_band_columns_general!(B::AbstractMatrix, X::AbstractMatrix) + for c in 1:size(X, 2) + _band_solve!(B, view(X, :, c)) + end + return X +end + +function _solve_band_adjoint_columns_general!(B::AbstractMatrix, X::AbstractMatrix) + for c in 1:size(X, 2) + _band_solve_adjoint!(B, view(X, :, c)) + end + return X +end + +# Entry points. `X` is the call-owned working copy of `source`. The fast +# methods require factor, working copy AND the caller's original RHS to be +# dense matrices of one Float32/Float64 type; every other combination (mixed +# types, Duals, BigFloat, views, ranges, device arrays) takes the general loop. +_solve_band_columns!(B::AbstractMatrix, X::AbstractMatrix, source::AbstractMatrix) = + _solve_band_columns_general!(B, X) + +_solve_band_adjoint_columns!(B::AbstractMatrix, X::AbstractMatrix, source::AbstractMatrix) = + _solve_band_adjoint_columns_general!(B, X) + +function _solve_band_columns!( + B::Matrix{T}, + X::Matrix{T}, + source::Matrix{T}, +) where {T<:_HostFloat} + return _solve_band_columns_host!( + _full_band_solve_column!, + _bordered_solve_column!, + _solve_band_columns_general!, + B, X, source, + ) +end + +function _solve_band_adjoint_columns!( + B::Matrix{T}, + X::Matrix{T}, + source::Matrix{T}, +) where {T<:_HostFloat} + return _solve_band_columns_host!( + _full_band_solve_adjoint_column!, + _bordered_solve_adjoint_column!, + _solve_band_adjoint_columns_general!, + B, X, source, + ) +end + +# Vector right-hand sides: dense Float32/Float64 vectors reuse the column +# kernels through a zero-copy n×1 reshape; everything else is unchanged. +_solve_band_vector!(B::AbstractMatrix, x::AbstractVector, b::AbstractVector) = + _band_solve!(B, x) + +_solve_band_adjoint_vector!(B::AbstractMatrix, x::AbstractVector, b::AbstractVector) = + _band_solve_adjoint!(B, x) + +function _solve_band_vector!( + B::Matrix{T}, + x::Vector{T}, + b::Vector{T}, +) where {T<:_HostFloat} + _solve_band_columns!(B, reshape(x, :, 1), reshape(b, :, 1)) + return x +end + +function _solve_band_adjoint_vector!( + B::Matrix{T}, + x::Vector{T}, + b::Vector{T}, +) where {T<:_HostFloat} + _solve_band_adjoint_columns!(B, reshape(x, :, 1), reshape(b, :, 1)) + return x +end + +# Shared driver. Structure is classified once per call, outside the column +# loop. Bordered path policy (see OPTIMIZATION_BSPLINE.md 5.4): skipping exact +# zero couplings is only used for finite factors with nonzero pivots; a column +# whose bordered result is not finite (non-finite input, or overflow) is +# restored from the ORIGINAL right-hand side and recomputed by the general +# algorithm. A non-finite input always yields a non-finite output entry (each +# solution entry is only modified by finite-coefficient updates after being +# divided by a finite nonzero pivot), so checking the result is sufficient. +# +# Columns are independent, so a large batch is split into contiguous column +# blocks solved by separate tasks (see `_host_column_tasks`). Each task writes +# only its own columns of X and reads B and source; every column is computed +# exactly as in the serial loop. +function _solve_band_columns_host!( + full_column!, + bordered_column!, + general!, + B::Matrix{T}, + X::Matrix{T}, + source::Matrix{T}, +) where {T} + n = size(X, 1) + if !_band_shape_ok(B, n) || size(source) != size(X) + return general!(B, X) + end + m = size(X, 2) + # single column, N < 6, or an outer-band entry is not exactly zero: + # full-band kernel + bordered = m >= _BORDERED_MIN_RHS && _is_bordered_tridiagonal_factor(B) + ntasks = _host_column_tasks(n, m) + if ntasks == 1 + _solve_host_column_block!(full_column!, bordered_column!, B, X, source, 1:m, bordered) + else + @sync for t in 1:ntasks + columns = (div((t - 1) * m, ntasks) + 1):div(t * m, ntasks) + Threads.@spawn _solve_host_column_block!( + full_column!, bordered_column!, B, X, source, columns, bordered) + end + end + return X +end + +function _solve_host_column_block!( + full_column!, + bordered_column!, + B::Matrix{T}, + X::Matrix{T}, + source::Matrix{T}, + columns::UnitRange{Int}, + bordered::Bool, +) where {T} + n = size(X, 1) + if bordered + for c in columns + bordered_column!(B, X, c, n) + if !_all_finite_column(X, c, n) + @inbounds for i in 1:n + X[i, c] = source[i, c] + end + full_column!(B, X, c, n) + end + end + else + for c in columns + full_column!(B, X, c, n) + end + end + return nothing +end + +# Minimum band-solve entries (rows × columns) per task before a solve is split: +# about 0.2 ms of serial work at N = 81, far above task start-up cost. +# Conservative until benchmarked; smaller solves stay serial. +const _HOST_SOLVE_MIN_TASK_ENTRIES = 32_768 + +# Number of column blocks for an n × m solve under the current budget, read once. +function _host_column_tasks(n::Int, m::Int) + budget = _host_thread_budget() + budget <= 1 && return 1 + return clamp(div(n * m, _HOST_SOLVE_MIN_TASK_ENTRIES), 1, min(budget, m)) +end + +@inline function _all_finite_column(X::Matrix, c::Int, n::Int) + ok = true + @inbounds for i in 1:n + ok &= isfinite(X[i, c]) + end + return ok +end + +# ============================================================================= +# High-Level Spline Objects +# ============================================================================= + +struct ThrowExtrap end +struct ClampExtrap end +struct ZeroExtrap end + +function _get_extrapolation_policy(e::Symbol) + e === :throw && return ThrowExtrap() + e === :clamp && return ClampExtrap() + e === :zero && return ZeroExtrap() + throw(ArgumentError("Unknown extrapolation policy: $e")) +end + +@inline function _validate_bspline_query(x) + isfinite(x) || throw(ArgumentError("B-spline query coordinates must be finite; got $x.")) + return x +end + +@inline function _apply_extrapolation(policy::ThrowExtrap, x, xmin, xmax) + _validate_bspline_query(x) + if x < xmin || x > xmax + throw(ArgumentError("Query point $x is outside domain [$xmin, $xmax]")) + end + return x +end + +@inline function _apply_extrapolation(policy::ClampExtrap, x, xmin, xmax) + _validate_bspline_query(x) + return clamp(x, xmin, xmax) +end + +@inline function _apply_extrapolation(policy::ZeroExtrap, x, xmin, xmax) + _validate_bspline_query(x) + return x +end + +""" + CubicBSpline{X, B, C, E} + +A callable cubic B-spline interpolator representing the function values through pre-solved coefficients. +""" +struct CubicBSpline{X,B,C,E} + sites::X + basis::B + coefficients::C + extrapolation::E +end + +Adapt.@adapt_structure CubicBSpline + +# Materialize before the dense-array AD primitives so ordinary AD propagates +# back through views and range endpoints. Floating dense arrays are unchanged; +# integer inputs become floating storage rather than inactive tangent buffers. +_bspline_dense_input(x::Array) = float(x) +_bspline_dense_input(x::AbstractVecOrMat) = float(collect(x)) + +""" + CubicBSpline(u, x; extrapolation=:clamp) + +Construct a not-a-knot cubic B-spline through ordinates `u` at interpolation +sites `x`. The sites must be a finite, strictly increasing vector with at least +four entries. For matrix `u`, `size(u, 1) == length(x)` and each column is an +independent series. + +Calling the result with a scalar query returns a scalar for vector ordinates or +a series vector for matrix ordinates. A vector query returns a vector or an +`nquery × nseries` matrix. Extrapolation policies are `:clamp`, `:throw`, and +`:zero`. + +ForwardDiff, Zygote, and Mooncake support derivatives through ordinates, sites, +and query coordinates on plain Julia arrays. + +In compiled Reactant evaluation, dynamic `extrapolation=:throw` is unsupported +because XLA cannot lower data-dependent exceptions. Use `:clamp` or `:zero` for +dynamic device queries. +""" +function CubicBSpline( + u::AbstractVecOrMat, + x::AbstractVector; + extrapolation=:clamp, +) + return _construct_cubic_b_spline( + _bspline_dense_input(u), + _bspline_dense_input(x), + _get_extrapolation_policy(extrapolation), + ) +end + +function _construct_cubic_b_spline(u::AbstractVecOrMat, x::AbstractVector, extrap) + _validate_bspline_sites(x) + if size(u, 1) != length(x) + throw(DimensionMismatch("Number of ordinates ($(size(u, 1))) does not match number of sites ($(length(x))).")) + end + + b = CubicBSplineBasis(domain=(first(x), last(x)), internal_knots=x[3:end-2]) + + fact = CubicBSplineFactorization(b, x) + c = solve(fact, u) + + return CubicBSpline(x, b, c, extrap) +end + +""" + cubic_b_spline_interpolation(u, t, t_new; extrapolation=:clamp) + +Interpolate vector or matrix ordinates `u` from sites `t` onto `t_new` using +the not-a-knot cubic B-spline derived from `t`. + +Sites must be finite, strictly increasing, and contain at least four entries. +For matrix ordinates, each column is an independent series. A scalar query +returns a scalar or series vector; a vector query returns a vector or an +`nquery × nseries` matrix. Extrapolation policies are `:clamp`, `:throw`, and +`:zero`. + +Plain Julia supports differentiation with respect to ordinates, sites, and +queries. Under Reactant, fixed host sites with dynamic device ordinates and +queries are supported; fully dynamic device sites are not currently supported. +""" +function cubic_b_spline_interpolation( + u::AbstractVecOrMat, + t::AbstractVector, + t_new; + extrapolation=:clamp, +) + return CubicBSpline(u, t; extrapolation=extrapolation)(t_new) +end + +""" + bspline_coefficients(spline::CubicBSpline) + bspline_coefficients(plan::CubicBSplinePlan, u) + +Return the computed B-spline coefficients for the spline, or solve for them using the precomputed `plan` and input data `u`. + +For a `CubicBSplinePlan`, reverse-mode AD propagates through both ordinates and +source sites using the implicit adjoint of the collocation solve. The stored LU +factorization is an implementation detail; differentiate this helper rather +than accessing `plan.factorization` directly. +""" +bspline_coefficients(spline::CubicBSpline) = spline.coefficients + +""" + bspline_basis(spline::CubicBSpline) + +Return the underlying `CubicBSplineBasis` of the given spline. +""" +bspline_basis(spline::CubicBSpline) = spline.basis + +function _evaluate_cubic_b_spline(spline::CubicBSpline, xq::Real) + xmin, xmax = bspline_domain(spline.basis) + x = _apply_extrapolation(spline.extrapolation, xq, xmin, xmax) + row = basis_row(spline.basis, x) + return _evaluate_spline(spline.coefficients, row) +end + +(spline::CubicBSpline)(xq::Real) = _evaluate_cubic_b_spline(spline, xq) + +function _evaluate_spline(c::AbstractVector, row) + val = zero(eltype(c)) * zero(eltype(row.values)) + for k in 1:4 + @inbounds val += c[row.indices[k]] * row.values[k] + end + return val +end + +function _evaluate_spline(c::AbstractMatrix, row) + n_series = size(c, 2) + val = zeros(typeof(zero(eltype(c)) * zero(eltype(row.values))), n_series) + for k in 1:4 + idx = row.indices[k] + w = row.values[k] + for s in 1:n_series + @inbounds val[s] += c[idx, s] * w + end + end + return val +end + +function _evaluate_cubic_b_spline( + spline::CubicBSpline{X,B,C,E}, + xq::AbstractVector, +) where {X,B,C<:AbstractVector,E} + stencil = _basis_stencil(spline.basis, xq, spline.extrapolation) + return _evaluate_stencil(stencil, spline.coefficients) +end + +function _evaluate_cubic_b_spline( + spline::CubicBSpline{X,B,C,E}, + xq::AbstractVector, +) where {X,B,C<:AbstractMatrix,E} + stencil = _basis_stencil(spline.basis, xq, spline.extrapolation) + return _evaluate_stencil(stencil, spline.coefficients) +end + +(spline::CubicBSpline)(xq::AbstractVector) = _evaluate_cubic_b_spline(spline, _bspline_dense_input(xq)) + +function solve_adjoint(fact::CubicBSplineFactorization, c_bar::AbstractVector) + b_bar = similar(c_bar, promote_type(eltype(fact.bands), eltype(c_bar))) + copyto!(b_bar, c_bar) + _solve_band_adjoint_vector!(fact.bands, b_bar, c_bar) + return b_bar +end + +function solve_adjoint(fact::CubicBSplineFactorization, c_bar_mat::AbstractMatrix) + b_bar_mat = similar(c_bar_mat, promote_type(eltype(fact.bands), eltype(c_bar_mat))) + copyto!(b_bar_mat, c_bar_mat) + _solve_band_adjoint_columns!(fact.bands, b_bar_mat, c_bar_mat) + return b_bar_mat +end + +function _band_solve_adjoint!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + # Forward substitution: U^T z = x + for j in 1:n + s = x[j] + for i in max(1, j-3):(j-1) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s / B[4, j] + end + + # Backward substitution: L^T b_bar = z + for j in n:-1:1 + s = x[j] + for i in (j+1):min(n, j+3) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s + end + return x +end + +""" + CubicBSplinePlan{F, S, E} + +A prepared plan for repeated evaluation of a cubic B-spline with different sample ordinates but fixed source interpolation sites and fixed query points. + +""" +struct CubicBSplinePlan{X,B,F,S,E} + sites::X + basis::B + factorization::F + stencil::S + extrapolation::E +end + +Adapt.@adapt_structure CubicBSplinePlan + +""" + CubicBSplinePlan(x, xq; extrapolation=:clamp) + +Prepare a not-a-knot cubic B-spline plan for fixed source sites `x` and fixed +query points `xq`, with changing vector or matrix ordinates. Each matrix column +is treated as an independent series. + +Sites must be finite, strictly increasing, and contain at least four entries. +Applying the plan to a vector returns a query vector. Applying it to an +`nsites × nseries` matrix returns an `nquery × nseries` matrix. Reverse-mode AD +supports ordinates, sites, and fixed query coordinates. + +The exported `plan(u)`, `bspline_coefficients(plan, u)`, and +`bspline_basis(plan)` operations compose through plan construction. Raw LU +factorization storage is structural and is not a differentiable public input. + +Plain Julia stores a band factorization and four-entry query stencil. Preparing +the plan with `Reactant.to_rarray` constructs a dense fixed interpolation +operator, limited to 64 MiB, so compiled execution and its Enzyme pullback are +matrix multiplication and transpose multiplication. + +Dynamic compiled Reactant evaluation cannot use `extrapolation=:throw`; use +`:clamp` or `:zero`. A fixed plan may use `:throw` because `xq` is validated on +the host during plan construction. +""" +function CubicBSplinePlan( + x::AbstractVector, + xq::AbstractVector; + extrapolation=:clamp, +) + return _construct_cubic_b_spline_plan( + _bspline_dense_input(x), + _bspline_dense_input(xq), + _get_extrapolation_policy(extrapolation), + ) +end + +function _construct_cubic_b_spline_plan( + x::AbstractVector, + xq::AbstractVector, + extrap, +) + _validate_bspline_sites(x) + + b = CubicBSplineBasis(domain=(first(x), last(x)), internal_knots=x[3:end-2]) + + fact = CubicBSplineFactorization(b, x) + stencil = _basis_stencil(b, xq, extrap) + + return CubicBSplinePlan(x, b, fact, stencil, extrap) +end + +function _build_cubic_bspline_dense_operator(fact, stencil, nsites::Int) + nquery = length(stencil.i1) + T = promote_type(eltype(fact.bands), eltype(stencil.w1)) + + if nquery >= nsites + # Solving nsites inverse columns is cheaper than solving nquery adjoint + # right-hand sides. In this branch, the nsites² temporary is no larger + # than the final nquery × nsites operator. + identity_rhs = Matrix{T}(I, nsites, nsites) + coefficients = solve(fact, identity_rhs) + return _evaluate_stencil(stencil, coefficients) + end + + # For skewed nsites ≫ nquery plans, construct Sᵀ directly and solve + # A⁻ᵀSᵀ. This avoids an otherwise hidden nsites² temporary. + stencil_transpose = zeros(T, nsites, nquery) + + @inbounds for i in 1:nquery + stencil_transpose[stencil.i1[i], i] += stencil.w1[i] + stencil_transpose[stencil.i2[i], i] += stencil.w2[i] + stencil_transpose[stencil.i3[i], i] += stencil.w3[i] + stencil_transpose[stencil.i4[i], i] += stencil.w4[i] + end + + return copy(transpose(solve_adjoint(fact, stencil_transpose))) +end + +bspline_basis(plan::CubicBSplinePlan) = plan.basis +bspline_coefficients(plan::CubicBSplinePlan, u::AbstractVecOrMat) = _bspline_coefficients(plan, _bspline_dense_input(u)) +_bspline_coefficients(plan::CubicBSplinePlan, u::AbstractVecOrMat) = solve(plan.factorization, u) + +function (plan::CubicBSplinePlan)(u::AbstractVector) + return _apply_cubic_b_spline_plan(plan, _bspline_dense_input(u)) +end + +function (plan::CubicBSplinePlan)(u::AbstractMatrix) + return _apply_cubic_b_spline_plan(plan, _bspline_dense_input(u)) +end + +function _apply_cubic_b_spline_plan(plan::CubicBSplinePlan, u::AbstractVecOrMat) + c = bspline_coefficients(plan, u) + return _evaluate_stencil(plan.stencil, c) +end + +function _evaluate_stencil(stencil::CubicBSplineStencil, c::AbstractVector) + n_q = length(stencil.i1) + V = typeof(zero(eltype(c)) * zero(eltype(stencil.w1))) + out = similar(c, V, n_q) + + for i in 1:n_q + @inbounds out[i] = c[stencil.i1[i]] * stencil.w1[i] + + c[stencil.i2[i]] * stencil.w2[i] + + c[stencil.i3[i]] * stencil.w3[i] + + c[stencil.i4[i]] * stencil.w4[i] + end + return out +end + +function _evaluate_stencil(stencil::CubicBSplineStencil, c::AbstractMatrix) + n_q = length(stencil.i1) + n_series = size(c, 2) + V = typeof(zero(eltype(c)) * zero(eltype(stencil.w1))) + out = similar(c, V, n_q, n_series) + fill!(out, zero(V)) + + # Series-major loop order: each output column is contiguous in + # column-major Julia arrays, so iterating over queries in the + # inner loop gives better cache locality. + for s in 1:n_series + for i in 1:n_q + @inbounds out[i, s] = c[stencil.i1[i], s] * stencil.w1[i] + + c[stencil.i2[i], s] * stencil.w2[i] + + c[stencil.i3[i], s] * stencil.w3[i] + + c[stencil.i4[i], s] * stencil.w4[i] + end + end + return out +end diff --git a/src/threads.jl b/src/threads.jl new file mode 100644 index 0000000..02e9bfc --- /dev/null +++ b/src/threads.jl @@ -0,0 +1,63 @@ +# ============================================================================= +# Thread configuration +# ============================================================================= + +# Requested host task budget for B-spline coefficient solves. Zero means +# automatic: the whole default Julia pool, resolved when a solve runs so that +# precompilation does not freeze a thread count. Only `set_threads` writes it. +const _HOST_THREADS = Threads.Atomic{Int}(0) + +""" + set_threads(n::Integer) + +Use up to `n` threads in AbstractCosmologicalEmulators. This single setting +controls both: + +- FFTW: the thread count of FFT plans created afterwards, for example by + `prepare_chebyshev_plan`. Existing plans keep the setting they were created with. +- B-spline host solves: the task budget for large dense `Float32`/`Float64` + coefficient solves in `bspline_coefficients`, plan evaluation and their + Zygote/Mooncake pullbacks. + +Julia's default thread pool is fixed at startup, so the B-spline budget is +`min(n, Threads.nthreads(:default))`. Start Julia with `--threads=N` or +`JULIA_NUM_THREADS=N` to make workers available. FFTW receives `n` as given. +`set_threads(1)` requests serial host solves and serial newly created FFT plans. +Small batches and vectors stay serial. Other kernels retain their serial paths; +public input adapters may first convert containers to dense floating-point arrays. + +If `set_threads` has not been called, large coefficient solves may use the whole +default pool and FFTW keeps its existing setting. When you already parallelize +over independent chains or tasks, call `set_threads(1)` to avoid oversubscription. +Configure before starting concurrent work. +""" +function set_threads(n::Integer) + 1 <= n <= typemax(Cint) || + throw(ArgumentError("set_threads requires 1 ≤ n ≤ $(typemax(Cint)); got $n.")) + requested = Int(n) + FFTW.set_num_threads(requested) + _HOST_THREADS[] = requested + return nothing +end + +""" + set_fft_threads(n::Integer) + +Deprecated; use [`set_threads`](@ref), which configures FFTW and the B-spline +host task budget together. +""" +function set_fft_threads(n::Integer) + Base.depwarn( + "`set_fft_threads` is deprecated; use `set_threads`, which also sets " * + "the B-spline host thread budget.", + :set_fft_threads, + ) + return set_threads(n) +end + +# Tasks a host solve may use right now: snapshot once per solve. +function _host_thread_budget() + requested = _HOST_THREADS[] + available = Threads.nthreads(:default) + return requested == 0 ? available : min(requested, available) +end diff --git a/src/utils.jl b/src/utils.jl index a77adf6..40a133c 100644 --- a/src/utils.jl +++ b/src/utils.jl @@ -944,7 +944,9 @@ function CubicSplinePlan(t, t_new::AbstractVector) ) end -function (plan::CubicSplinePlan)(u::AbstractVector) +# AD must propagate through both ordinates and the plan's weights/operator: +# source and query geometry enter through those differentiable fields. +function _cubic_spline_plan_eval(plan::CubicSplinePlan, u::AbstractVector) z = plan.second_derivative_operator * u idx = plan.interval_indices return plan.left_value_weights .* u[idx] .+ @@ -953,7 +955,7 @@ function (plan::CubicSplinePlan)(u::AbstractVector) plan.right_curve_weights .* z[idx .+ 1] end -function (plan::CubicSplinePlan)(u::AbstractMatrix) +function _cubic_spline_plan_eval(plan::CubicSplinePlan, u::AbstractMatrix) z = plan.second_derivative_operator * u idx = plan.interval_indices left_value_weights = reshape(plan.left_value_weights, :, 1) @@ -966,6 +968,9 @@ function (plan::CubicSplinePlan)(u::AbstractMatrix) right_curve_weights .* z[idx .+ 1, :] end +(plan::CubicSplinePlan)(u::AbstractVector) = _cubic_spline_plan_eval(plan, u) +(plan::CubicSplinePlan)(u::AbstractMatrix) = _cubic_spline_plan_eval(plan, u) + """ cubic_spline_interpolation(u, t, t_new) diff --git a/test/reference/bspline_adaptive_sites/README.md b/test/reference/bspline_adaptive_sites/README.md new file mode 100644 index 0000000..919704e --- /dev/null +++ b/test/reference/bspline_adaptive_sites/README.md @@ -0,0 +1,13 @@ +# Saved adaptive k grids + +Byte-for-byte copies of the frozen adaptive linear-Pmm design grids +(physical k in Mpc^-1, domain [5e-5, 16]) from +`bspline_backend_validation/pk_grid_design_20261021/frozen_grids/`. +Tests use them as representative production interpolation sites, both as +log(k) and as raw k (strongly nonuniform, tiny low-k spacings). + +SHA256: + + 4ef22e5b505713dbe6467135325019c129e3c0cd89951dc05c2c8c37ab93eb1f adaptive_design_N129.txt + 84f0d9dc536320eb80daf49fff6db323a0bb7e1e0f5748917cfa93e10211dd74 adaptive_design_N81.txt + 6952b63f1e9f1496d53fa1b1619b21efc7b3b7fae14c4c52389f308804403e2f adaptive_design_N97.txt diff --git a/test/reference/bspline_adaptive_sites/adaptive_design_N129.txt b/test/reference/bspline_adaptive_sites/adaptive_design_N129.txt new file mode 100644 index 0000000..e8cc7dd --- /dev/null +++ b/test/reference/bspline_adaptive_sites/adaptive_design_N129.txt @@ -0,0 +1,129 @@ +5.0e-5 +5.764948329629404e-5 +7.616548067124573e-5 +9.342523891413652e-5 +0.00011746878941342912 +0.00016307588845747308 +0.00024384494202286838 +0.0003364286325052201 +0.0004938019084804189 +0.0007247906428271114 +0.000911319900068234 +0.0011892071150027212 +0.0016205430572046162 +0.0023348350478610185 +0.0028286949212954545 +0.003496650435592009 +0.00449629416262246 +0.005812774658203125 +0.007420074462890626 +0.009694163758759918 +0.011803619384765627 +0.014540467862709877 +0.017412782382430058 +0.020500563317509594 +0.02426019287109375 +0.02832807143244218 +0.03233322143554688 +0.036511319709521275 +0.03950938915293851 +0.04248983435046351 +0.04530787317406137 +0.04836968994140625 +0.05107287597656251 +0.05352035522460938 +0.058926727294921884 +0.06320068359375 +0.06813217163085938 +0.07285886429227517 +0.07733761596679688 +0.08138258806261306 +0.08548370361328125 +0.08851565551757813 +0.0913971492979014 +0.0966329424262223 +0.10177587890625 +0.10661005816941374 +0.11131008911132813 +0.11397674560546876 +0.11543792724609375 +0.11938311767578126 +0.12318218994140626 +0.12698126220703126 +0.13063421630859376 +0.13428717041015625 +0.13797665405273438 +0.14367526245117188 +0.14919122314453126 +0.15478024291992187 +0.16015416031332788 +0.16378813876878 +0.1678938135528268 +0.17154730224609377 +0.17520025634765626 +0.18168014930174387 +0.18820477294921875 +0.1935798319992957 +0.19923669433593752 +0.20446041870117188 +0.2101590270996094 +0.2173553466796875 +0.2243324890136719 +0.2303890524935642 +0.236712999049015 +0.24646939086914063 +0.25509036254882816 +0.265225476347966 +0.2741953125 +0.2796747436523438 +0.2856748290944216 +0.29220437622070317 +0.2985239868164063 +0.3103960876464844 +0.315985107421875 +0.3228526611328125 +0.3325695190429688 +0.3428343200683594 +0.35207629394531254 +0.36113562011718753 +0.3779757385253906 +0.3928067321777344 +0.40745507812500004 +0.4192541198730469 +0.43715359497070316 +0.4519480590820313 +0.47262377929687505 +0.49739080810546876 +0.5230710754394532 +0.5922945556640625 +0.6727691345214845 +0.7602208557128907 +0.8408050231933594 +1.0070509643554686 +1.2027469453741064 +1.386754798740262 +1.569498509666675 +1.7436445366866835 +1.9251604788512406 +2.0864680426671525 +2.405676091479822 +2.722691166274103 +3.0061272920847424 +3.2782360942415405 +3.641977625647644 +3.9716423646645835 +4.607693801537358 +5.182708462694294 +5.722235980933662 +6.357155132250456 +6.975634745869574 +7.60705565075932 +8.19357307927439 +9.388812907003967 +10.430562520730048 +11.445338807205138 +12.404334039197243 +13.527150257208415 +14.660578705035329 +15.50042718861155 +16.0 diff --git a/test/reference/bspline_adaptive_sites/adaptive_design_N81.txt b/test/reference/bspline_adaptive_sites/adaptive_design_N81.txt new file mode 100644 index 0000000..fc89a06 --- /dev/null +++ b/test/reference/bspline_adaptive_sites/adaptive_design_N81.txt @@ -0,0 +1,81 @@ +5.0e-5 +5.764948329629404e-5 +7.616548067124573e-5 +0.00011746878941342912 +0.00016307588845747308 +0.00024384494202286838 +0.0003364286325052201 +0.0004938019084804189 +0.0007247906428271114 +0.0011892071150027212 +0.0023348350478610185 +0.003496650435592009 +0.005812774658203125 +0.009694163758759918 +0.014540467862709877 +0.020500563317509594 +0.02426019287109375 +0.02832807143244218 +0.03233322143554688 +0.036511319709521275 +0.04248983435046351 +0.04836968994140625 +0.05352035522460938 +0.058926727294921884 +0.06320068359375 +0.06813217163085938 +0.07285886429227517 +0.07733761596679688 +0.08138258806261306 +0.08548370361328125 +0.0913971492979014 +0.0966329424262223 +0.10177587890625 +0.10661005816941374 +0.11543792724609375 +0.12318218994140626 +0.13063421630859376 +0.13797665405273438 +0.14367526245117188 +0.14919122314453126 +0.16015416031332788 +0.1678938135528268 +0.17520025634765626 +0.18168014930174387 +0.18820477294921875 +0.19923669433593752 +0.2101590270996094 +0.2243324890136719 +0.236712999049015 +0.24646939086914063 +0.25509036254882816 +0.2741953125 +0.2856748290944216 +0.2985239868164063 +0.3103960876464844 +0.3228526611328125 +0.3428343200683594 +0.36113562011718753 +0.3779757385253906 +0.3928067321777344 +0.4192541198730469 +0.4519480590820313 +0.5230710754394532 +0.6727691345214845 +0.8408050231933594 +1.0070509643554686 +1.2027469453741064 +1.386754798740262 +1.7436445366866835 +2.0864680426671525 +2.722691166274103 +3.2782360942415405 +3.9716423646645835 +4.607693801537358 +5.722235980933662 +6.975634745869574 +8.19357307927439 +10.430562520730048 +12.404334039197243 +14.660578705035329 +16.0 diff --git a/test/reference/bspline_adaptive_sites/adaptive_design_N97.txt b/test/reference/bspline_adaptive_sites/adaptive_design_N97.txt new file mode 100644 index 0000000..a81eff3 --- /dev/null +++ b/test/reference/bspline_adaptive_sites/adaptive_design_N97.txt @@ -0,0 +1,97 @@ +5.0e-5 +5.764948329629404e-5 +7.616548067124573e-5 +0.00011746878941342912 +0.00016307588845747308 +0.00024384494202286838 +0.0003364286325052201 +0.0004938019084804189 +0.0007247906428271114 +0.0011892071150027212 +0.0016205430572046162 +0.0023348350478610185 +0.003496650435592009 +0.00449629416262246 +0.005812774658203125 +0.009694163758759918 +0.011803619384765627 +0.014540467862709877 +0.017412782382430058 +0.020500563317509594 +0.02426019287109375 +0.02832807143244218 +0.03233322143554688 +0.036511319709521275 +0.04248983435046351 +0.04836968994140625 +0.05352035522460938 +0.058926727294921884 +0.06320068359375 +0.06813217163085938 +0.07285886429227517 +0.07733761596679688 +0.08138258806261306 +0.08548370361328125 +0.0913971492979014 +0.0966329424262223 +0.10177587890625 +0.10661005816941374 +0.11131008911132813 +0.11543792724609375 +0.11938311767578126 +0.12318218994140626 +0.12698126220703126 +0.13063421630859376 +0.13797665405273438 +0.14367526245117188 +0.14919122314453126 +0.15478024291992187 +0.16015416031332788 +0.1678938135528268 +0.17520025634765626 +0.18168014930174387 +0.18820477294921875 +0.19923669433593752 +0.20446041870117188 +0.2101590270996094 +0.2173553466796875 +0.2243324890136719 +0.2303890524935642 +0.236712999049015 +0.24646939086914063 +0.25509036254882816 +0.265225476347966 +0.2741953125 +0.2856748290944216 +0.2985239868164063 +0.3103960876464844 +0.3228526611328125 +0.3325695190429688 +0.3428343200683594 +0.36113562011718753 +0.3779757385253906 +0.3928067321777344 +0.4192541198730469 +0.4519480590820313 +0.5230710754394532 +0.5922945556640625 +0.6727691345214845 +0.8408050231933594 +1.0070509643554686 +1.2027469453741064 +1.386754798740262 +1.7436445366866835 +2.0864680426671525 +2.405676091479822 +2.722691166274103 +3.2782360942415405 +3.9716423646645835 +4.607693801537358 +5.722235980933662 +6.975634745869574 +8.19357307927439 +9.388812907003967 +10.430562520730048 +12.404334039197243 +14.660578705035329 +16.0 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_adjoint.txt b/test/reference/bspline_coefficient_solver/cheb_n9_adjoint.txt new file mode 100644 index 0000000..abb1796 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_adjoint.txt @@ -0,0 +1,9 @@ +2.9031661112495817 -1.12091116784846 -0.39930956360963266 -0.19349403767098566 -3.0606069084400556 +-5.9920348147390232 1.2718104902594334 -0.015517465936062402 -0.62677603571147533 4.808794125044197 +3.8385077860180474 1.3860616893944999 -2.7105295975095762 3.2110253102729871 -4.4672447422050388 +-0.90412345683079531 0.39001351699536785 0.87938198409443846 -2.9956666148458155 4.2865220694624968 +2.7339908104603281 -0.010782852103245921 -0.29188812394570735 1.7348944130261914 -4.3273222331463668 +0.27167767170978829 -1.5146739653863004 2.4939754799226392 0.42575893041687318 4.8816334621475646 +0.90505979120224778 0.94991997738837797 -1.1642276766942856 0.34947010163452336 -5.7134692119343198 +3.9272491224621477 0.063786772992718926 -0.77868648918819994 1.8528907005353541 6.7880136724413749 +-1.7198985106426752 -0.92341658070639865 0.76464945948109453 -1.0885940940065502 -4.7518757889254069 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_coefficients.txt b/test/reference/bspline_coefficient_solver/cheb_n9_coefficients.txt new file mode 100644 index 0000000..48323bb --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_coefficients.txt @@ -0,0 +1,9 @@ +0.29999999999999999 1 0.07910227194074318 -0.73493774802280054 0 +0.32735921971403775 -0.85832198666645065 -1.4987009926903416 0.86408559631620774 0 +1.0718429627553625 0.44132763218368398 1.1194424741956208 -1.6032008107170141 0 +0.61885058106801327 -0.14793864241010105 -2.3139637813781229 0.76211203895245916 0 +-0.68829597464148462 0.042716174750204207 1.5029189640920024 -0.63188320226449013 0 +-1.7449723920324203 -0.0096373465204585684 -4.2322900433066613 0.69509642813127404 0 +-0.033511478226393263 0.0024672854136213122 4.8144192784085558 -0.65769570069978911 0 +0.11201611065261316 -0.0003390678971760229 -5.1982359399354259 -0.76915787493486254 0 +0.93140930606014849 5.5325112087858585e-06 -0.41447520591117032 -0.30403098976907783 0 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_cotangent.txt b/test/reference/bspline_coefficient_solver/cheb_n9_cotangent.txt new file mode 100644 index 0000000..f505608 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_cotangent.txt @@ -0,0 +1,9 @@ +0.47398191558075969 -0.60531637603839439 -0.40560037869568516 -0.447590431842318 -1.1111111111111112 +-2.0001986709988526 1.0323780763866195 -0.7565471945461042 0.56673583008845596 1.2222222222222223 +1.5697981394944605 0.99495487239831393 -1.4043719124791858 1.2064903942489793 -1.3333333333333333 +0.40544698777474875 0.44979556542159438 0.14918757000614269 -1.21678341338028 1.4444444444444444 +1.6875596351991089 -0.16060579309563985 0.27135226855675987 0.77467509023384418 -1.5555555555555556 +0.79368319385903507 -0.86382655009231091 1.4218847185419197 0.63712162033261122 1.6666666666666665 +0.90534409805895677 0.24704843405776036 -0.22777254676150019 0.4434266183622792 -1.7777777777777777 +2.2557622232894565 0.29493693349525701 -0.7192527487575554 1.0428610625523222 1.8888888888888888 +-0.12778301136802708 -0.89755728154720704 0.44896823074991593 -0.33742809694479109 -2 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_dense_adjoint.txt b/test/reference/bspline_coefficient_solver/cheb_n9_dense_adjoint.txt new file mode 100644 index 0000000..a1fe6c2 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_dense_adjoint.txt @@ -0,0 +1,9 @@ +2.9031661112495821 -1.1209111678484598 -0.39930956360963266 -0.19349403767098555 -3.0606069084400556 +-5.9920348147390241 1.2718104902594329 -0.015517465936062413 -0.62677603571147567 4.808794125044197 +3.838507786018047 1.3860616893944999 -2.7105295975095762 3.2110253102729875 -4.4672447422050388 +-0.9041234568307952 0.3900135169953679 0.87938198409443857 -2.9956666148458155 4.2865220694624968 +2.7339908104603281 -0.010782852103245888 -0.29188812394570729 1.7348944130261914 -4.3273222331463659 +0.27167767170978857 -1.5146739653863004 2.4939754799226392 0.42575893041687318 4.8816334621475654 +0.90505979120224778 0.94991997738837786 -1.1642276766942858 0.34947010163452341 -5.7134692119343207 +3.9272491224621477 0.063786772992718926 -0.77868648918819983 1.8528907005353541 6.7880136724413749 +-1.719898510642675 -0.92341658070639865 0.76464945948109442 -1.0885940940065502 -4.7518757889254069 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_dense_coefficients.txt b/test/reference/bspline_coefficient_solver/cheb_n9_dense_coefficients.txt new file mode 100644 index 0000000..14c6328 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_dense_coefficients.txt @@ -0,0 +1,9 @@ +0.29999999999999999 1 0.07910227194074318 -0.73493774802280054 0 +0.32735921971403775 -0.85832198666645076 -1.4987009926903416 0.86408559631620785 0 +1.0718429627553625 0.44132763218368409 1.1194424741956208 -1.6032008107170146 0 +0.61885058106801327 -0.14793864241010107 -2.3139637813781229 0.76211203895245938 0 +-0.68829597464148462 0.042716174750204228 1.5029189640920024 -0.63188320226449013 0 +-1.7449723920324203 -0.0096373465204585736 -4.2322900433066621 0.69509642813127415 0 +-0.03351147822639327 0.0024672854136213135 4.8144192784085558 -0.65769570069978922 0 +0.11201611065261316 -0.00033906789717602306 -5.1982359399354259 -0.76915787493486254 0 +0.93140930606014849 5.5325112087858585e-06 -0.41447520591117032 -0.30403098976907783 0 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_rhs.txt b/test/reference/bspline_coefficient_solver/cheb_n9_rhs.txt new file mode 100644 index 0000000..0607b24 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_rhs.txt @@ -0,0 +1,9 @@ +0.29999999999999999 1 0.07910227194074318 -0.73493774802280054 0 +0.37759528329346903 0.0025973365104230719 -0.64787341927600306 0.014700734634968793 0 +0.80327296292148875 0.00048870003859101353 -0.080792308790989892 -0.5930606775055085 0 +0.5341345199706119 0.00014258503984537367 -1.0815611843730599 0.081843808465884349 0 +-0.64431926653528504 4.9584480032984403e-05 -0.17420531762687125 -0.15414354636576588 0 +-1.2461933114068218 2.0200111262644056e-05 -1.5753237702542751 0.23368129087140566 0 +-0.23115422877340963 1.005741089637171e-05 0.79183033487482213 -0.50048742725304018 0 +0.42782097162152244 6.4470429399737519e-06 -2.441293727314338 -0.5679471269903329 0 +0.93140930606014849 5.5325112087858585e-06 -0.41447520591117032 -0.30403098976907783 0 diff --git a/test/reference/bspline_coefficient_solver/cheb_n9_sites.txt b/test/reference/bspline_coefficient_solver/cheb_n9_sites.txt new file mode 100644 index 0000000..3689a6c --- /dev/null +++ b/test/reference/bspline_coefficient_solver/cheb_n9_sites.txt @@ -0,0 +1,9 @@ +2 +344.46598323172094 +1319.726591441723 +2779.3072377894614 +4501 +6222.6927622105395 +7682.273408558277 +8657.5340167682789 +9000 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_adjoint.txt b/test/reference/bspline_coefficient_solver/clustered_n7_adjoint.txt new file mode 100644 index 0000000..bac72a3 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_adjoint.txt @@ -0,0 +1,7 @@ +-0.63378998204043457 -0.058208514410760304 0.67679507970496755 1.1522690543057412 -1.4906152858294657 +-5.188241906441279 3.3258267858755799 -2.8703570903643341 1.0774304929946341 4.1732026259218085 +2.852117056143471 -3.9229919513234464 4.3533370815000039 2.0820056796147526 -9.1305164734828814 +-3.7237164043756139 2.6200674173647593 2.5755616889868476 2.6230583204374578 12.679071999696035 +4.4266580537685387 1.6384313310661314 -7.0663267040181266 -4.1722317647301628 -11.076069667189765 +-0.22083839383045778 -3.7436236405151493 4.7123730153153858 0.3529694742648759 5.7528940119372614 +0.68123917002783019 0.37534619548349529 -0.65969825459326559 -0.032180872104446409 -2.4793957824815638 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_coefficients.txt b/test/reference/bspline_coefficient_solver/clustered_n7_coefficients.txt new file mode 100644 index 0000000..0fd7118 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_coefficients.txt @@ -0,0 +1,7 @@ +0.29999999999999999 1 1.7162917340290094 0.97413693612210084 0 +0.90030326394617088 0.29753360972301268 -2.2264443562722298 -2.7455235211938356 0 +2.3706399135107121 0.16129912106349448 -1.7778207118236939 3.4126177287591601 0 +-1.0543512638359314 0.070101354230891935 -0.53515647620795637 -1.3595591325041132 0 +-0.19691279064459322 0.023556086395773859 0.93867070897355065 -0.31569955436568542 0 +-0.94777706509344462 0.015604594003994601 0.90044712831507001 2.3180514695142769 0 +0.9314093060601486 0.0099574136735727913 -0.50834329094927244 0.35723119435381784 0 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_cotangent.txt b/test/reference/bspline_coefficient_solver/clustered_n7_cotangent.txt new file mode 100644 index 0000000..f9b7607 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_cotangent.txt @@ -0,0 +1,7 @@ +-1.0661326052977145 0.21893675040806126 0.43760466867333137 1.24205267159243 -1.1428571428571428 +-2.0752262104387373 1.2127766845838175 -0.99240725828757959 0.58098111374271966 1.2857142857142856 +-1.0916144600137527 -0.26878268743819095 1.1527889193744976 1.6688294646759234 -1.4285714285714286 +-0.038315824515686471 1.0074581692313975 0.95984522381772841 1.2568607243368446 1.5714285714285714 +1.64869504567502 -0.47799267206013685 -1.2029363287882284 -1.5806491586993519 -1.7142857142857144 +0.15318521466243576 -1.520934022546252 1.633799967098126 -0.081986942174241212 1.8571428571428572 +0.66283643318048935 0.063385401361913743 -0.26701037535639688 -0.0027674886914718219 -2 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_dense_adjoint.txt b/test/reference/bspline_coefficient_solver/clustered_n7_dense_adjoint.txt new file mode 100644 index 0000000..bdecb15 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_dense_adjoint.txt @@ -0,0 +1,7 @@ +-0.63378998204043446 -0.058208514410760304 0.67679507970496755 1.1522690543057412 -1.4906152858294659 +-5.1882419064412799 3.3258267858755799 -2.8703570903643345 1.0774304929946341 4.1732026259218094 +2.8521170561434723 -3.9229919513234477 4.3533370815000056 2.0820056796147535 -9.130516473482885 +-3.7237164043756144 2.6200674173647602 2.5755616889868458 2.6230583204374573 12.679071999696037 +4.4266580537685396 1.6384313310661311 -7.0663267040181275 -4.1722317647301628 -11.076069667189769 +-0.22083839383045784 -3.7436236405151493 4.7123730153153858 0.35296947426487596 5.7528940119372614 +0.6812391700278303 0.37534619548349529 -0.65969825459326559 -0.032180872104446409 -2.4793957824815638 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_dense_coefficients.txt b/test/reference/bspline_coefficient_solver/clustered_n7_dense_coefficients.txt new file mode 100644 index 0000000..eb1544c --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_dense_coefficients.txt @@ -0,0 +1,7 @@ +0.29999999999999999 1 1.7162917340290094 0.97413693612210084 0 +0.90030326394617066 0.29753360972301274 -2.2264443562722294 -2.7455235211938369 0 +2.3706399135107126 0.16129912106349448 -1.7778207118236942 3.412617728759161 0 +-1.0543512638359314 0.070101354230891935 -0.53515647620795637 -1.3595591325041134 0 +-0.19691279064459322 0.023556086395773859 0.93867070897355065 -0.31569955436568498 0 +-0.9477770650934445 0.015604594003994599 0.9004471283150699 2.318051469514276 0 +0.93140930606014871 0.0099574136735727913 -0.50834329094927244 0.35723119435381784 0 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_rhs.txt b/test/reference/bspline_coefficient_solver/clustered_n7_rhs.txt new file mode 100644 index 0000000..0d609ab --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_rhs.txt @@ -0,0 +1,7 @@ +0.29999999999999999 1 1.7162917340290094 0.97413693612210084 0 +1.2765084852217052 0.28221041452796208 -1.5753922858200642 0.15487870625621714 0 +0.6754286971596859 0.12599929063462367 -1.2178536069367927 0.82007848128832905 0 +-0.64431926653528504 0.074376720049476611 -0.51302319822160236 -0.80268809614706949 0 +-0.64277760949410756 0.045026822086643034 0.24254445726715568 -0.65947346940545626 0 +-0.49851079986814639 0.022912769795564752 0.67763711856425113 0.78724899262722836 0 +0.93140930606014849 0.0099574136735727896 -0.50834329094927233 0.35723119435381778 0 diff --git a/test/reference/bspline_coefficient_solver/clustered_n7_sites.txt b/test/reference/bspline_coefficient_solver/clustered_n7_sites.txt new file mode 100644 index 0000000..26bc1bf --- /dev/null +++ b/test/reference/bspline_coefficient_solver/clustered_n7_sites.txt @@ -0,0 +1,7 @@ +0.5 +1.3596317800642939 +2.0262984467309604 +2.5 +2.9737015532690392 +3.6403682199357061 +4.5 diff --git a/test/reference/bspline_coefficient_solver/generate_fixtures.jl b/test/reference/bspline_coefficient_solver/generate_fixtures.jl new file mode 100644 index 0000000..efe47af --- /dev/null +++ b/test/reference/bspline_coefficient_solver/generate_fixtures.jl @@ -0,0 +1,88 @@ +# Regenerates the small text fixtures in this directory. +# +# Usage (from an environment containing AbstractCosmologicalEmulators): +# julia --project=/path/to/AbstractCosmologicalEmulators.jl generate_fixtures.jl +# +# The fixtures were frozen from the af79449 sources BEFORE any solver change. +# "coefficients" and "adjoint" come from that revision's `solve` / +# `solve_adjoint`; `dense_*` come from an independent dense solve with +# `basis_matrix` (LU via `\`). Both are stored so tests compare the current +# solver against the frozen one and against a dense reference. +# All values are written with 17 significant digits (exact Float64 round trip). + +using AbstractCosmologicalEmulators +using LinearAlgebra +using Random +using Printf + +const ACE = AbstractCosmologicalEmulators +const OUT = @__DIR__ + +function write_matrix(name, M) + open(joinpath(OUT, name), "w") do io + for i in 1:size(M, 1) + println(io, join((@sprintf("%.17g", M[i, j]) for j in 1:size(M, 2)), " ")) + end + end +end + +function make_sites(kind, n, rng) + if kind == :power + t = range(0, 1; length=n) .^ 2.3 + return 2.0 .+ 9000.0 .* collect(t) + elseif kind == :cheb + k = 0:(n - 1) + return sort(2.0 .+ 0.5 .* (cos.(pi .* k ./ (n - 1)) .+ 1) .* (9000 - 2)) + elseif kind == :random + h = 0.2 .+ rand(rng, n - 1) + return cumsum(vcat(-3.0, h)) + elseif kind == :clustered + t = collect(range(0, 1; length=n)) + return 0.5 .+ 4.0 .* (t .+ 0.35 .* sin.(2pi .* t) ./ (2pi)) + end + error("unknown site kind") +end + +function make_rhs(n, x, rng) + nonpoly = hcat( + @.(sin(7 * (x - x[1]) / (x[end] - x[1])) + 0.3 * cos(31 * (x - x[1]) / (x[end] - x[1]))), + @.(exp(-3 * (x - x[1]) / (x[end] - x[1])) / (1 + abs(x - x[1]))), + randn(rng, n), + 2 .* rand(rng, n) .- 1, + zeros(n), + ) + return nonpoly +end + +cases = [ + ("power_n17", :power, 17, 20261020), + ("random_n33", :random, 33, 20261021), + ("cheb_n9", :cheb, 9, 20261022), + ("clustered_n7", :clustered, 7, 20261023), + ("random_n6", :random, 6, 20261024), +] + +open(joinpath(OUT, "metadata.txt"), "w") do io + println(io, "source_commit = af7944975f422af0271ebdfb03a6ba2395a5e2c8") + println(io, "dtype = Float64") + println(io, "rhs_columns = 5 # sin+cos, damped exp, randn, uniform(-1,1), zeros") + println(io, "cases = ", join(first.(cases), ", ")) + println(io, "files = _{sites,rhs,coefficients,dense_coefficients,cotangent,adjoint,dense_adjoint}.txt") +end + +for (name, kind, n, seed) in cases + rng = Xoshiro(seed) + x = make_sites(kind, n, rng) + S = make_rhs(n, x, rng) + G = hcat(randn(rng, n, 4), [(-1.0)^j * (1 + j / n) for j in 1:n]) + basis = CubicBSplineBasis(domain=(first(x), last(x)), internal_knots=x[3:end-2]) + fact = ACE.CubicBSplineFactorization(basis, x) + A = basis_matrix(basis, x) + write_matrix("$(name)_sites.txt", reshape(x, :, 1)) + write_matrix("$(name)_rhs.txt", S) + write_matrix("$(name)_coefficients.txt", ACE.solve(fact, S)) + write_matrix("$(name)_dense_coefficients.txt", A \ S) + write_matrix("$(name)_cotangent.txt", G) + write_matrix("$(name)_adjoint.txt", ACE.solve_adjoint(fact, G)) + write_matrix("$(name)_dense_adjoint.txt", transpose(A) \ G) +end diff --git a/test/reference/bspline_coefficient_solver/metadata.txt b/test/reference/bspline_coefficient_solver/metadata.txt new file mode 100644 index 0000000..4099959 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/metadata.txt @@ -0,0 +1,5 @@ +source_commit = af7944975f422af0271ebdfb03a6ba2395a5e2c8 +dtype = Float64 +rhs_columns = 5 # sin+cos, damped exp, randn, uniform(-1,1), zeros +cases = power_n17, random_n33, cheb_n9, clustered_n7, random_n6 +files = _{sites,rhs,coefficients,dense_coefficients,cotangent,adjoint,dense_adjoint}.txt diff --git a/test/reference/bspline_coefficient_solver/power_n17_adjoint.txt b/test/reference/bspline_coefficient_solver/power_n17_adjoint.txt new file mode 100644 index 0000000..cebcb9b --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_adjoint.txt @@ -0,0 +1,17 @@ +1.9014092106655316 -0.65228686763224597 1.5194384367172369 -2.13586518133864 -4.3925710091847856 +-2.8128598474714552 0.27252983314578549 -2.7775171329913908 3.054717390808539 6.5865939444836696 +2.4063812713173767 0.79431169965399873 1.9513420286344925 -4.7638432413575176 -5.0158539075045772 +-1.6495003895035367 -1.5223279389903035 -2.5698213931726333 0.13568063531088928 4.4487822563773571 +2.1060989114693243 1.6308497109992248 2.4278305551868593 0.49775189622573951 -4.2829789017066133 +-1.9315761446325996 -0.91979411174989634 2.677663116941158 -1.5642000836620635 4.3274779335998694 +2.0992052372863874 2.9626676349623389 0.89784354059129601 2.7586009898956299 -4.4354072879917048 +-0.36139887203117915 -0.2451621491490259 -2.5605993516926757 -2.3970649973105238 4.5714979180032032 +-0.82241621569309209 -2.5832514154775605 3.8431193803450103 1.7896190064641651 -4.7255506777557486 +-0.47652315044696275 -0.71389261746732191 -1.5226281899966978 0.076284668513545484 4.9000544103295232 +2.7629689243591766 -0.32212190920633449 2.2209309651435443 1.0479238426799355 -5.1180139498563975 +-2.3582807867102629 2.112643664628481 -1.7210696230070175 -0.57946194825824759 5.4605908809204191 +-0.12000258800087915 -3.6851156472080215 1.8738884202401001 0.18446287049278309 -6.1938763178032588 +-1.2062036133915659 6.2470941836569835 -3.0395941092722851 -4.5433225023855783 8.1868683045567074 +1.53409620811666 -3.0458266821852225 2.5868615332648597 5.8975172467580865 -8.8623271604222271 +-2.2522550270519504 -0.047789530265327167 -1.9323637146155404 -2.2444844905157595 5.6316868181102944 +0.61391360954671159 0.49037036704117143 0.40751687421190208 1.9752640748383852 -2.6163850188616111 diff --git a/test/reference/bspline_coefficient_solver/power_n17_coefficients.txt b/test/reference/bspline_coefficient_solver/power_n17_coefficients.txt new file mode 100644 index 0000000..7a44303 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_coefficients.txt @@ -0,0 +1,17 @@ +0.29999999999999999 1 -1.6274137158591773 0.24461357145404428 0 +0.31954010819527767 -1.0652173273482566 3.6511249706704176 -2.2513026522359496 0 +0.360583373091096 0.78871464465814878 -1.831060800996775 1.6650347675720361 0 +0.39863948567660296 -0.38857354308761799 -4.0650956299891803 -1.8610310381479382 0 +0.37486542685396451 0.17726295035352388 2.7878082205618915 1.4595686299244852 0 +0.27491117136605681 -0.069253254912117618 -1.6523564494442746 -1.5362359790243623 0 +0.31093354396581302 0.027083038371406281 1.585607798866671 -0.39093540857669218 0 +0.88462674443120126 -0.0089730854904844781 -1.7247897076272416 0.88478864131495061 0 +1.5346388350588611 0.0035125090535089751 -0.2628577837650089 -0.21587715141331651 0 +0.70106913662775816 -0.0009062601686202253 -0.40712304513202591 -0.29888983479142489 0 +0.46017966415423317 0.00046451367157460848 1.4708889789133743 -0.84286102720996781 0 +0.80297047411579114 -4.391118901570743e-05 -1.4117372035125435 1.0043458746655971 0 +-1.295494302170364 7.8816749237037184e-05 -2.0290534043879651 -1.4701869476517015 0 +-0.27546251167729197 1.4978665075765075e-05 3.6939598620105634 -0.26722140922799181 0 +-2.0432105493641117 2.0264880156514695e-05 -2.8045887522311395 1.4142455588030687 0 +0.75406741576435743 2.5783485967056374e-06 0.71227576055275565 -1.3186727331102537 0 +0.93140930606014849 5.5312818984406114e-06 -0.81473422890805736 -0.67210852272081478 0 diff --git a/test/reference/bspline_coefficient_solver/power_n17_cotangent.txt b/test/reference/bspline_coefficient_solver/power_n17_cotangent.txt new file mode 100644 index 0000000..05cc8d8 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_cotangent.txt @@ -0,0 +1,17 @@ +0.47770456050771931 -0.51434825291414277 0.1136221953970348 -0.58974643030257723 -1.0588235294117647 +-0.38008595839396159 0.41471702580234765 -0.5315499018064479 -0.3781907966950277 1.1176470588235294 +0.72200731879644908 0.0030264230147882031 0.20169065342097209 -2.4585171630336871 -1.1764705882352942 +-0.27706926831529233 -0.45083533481850285 -0.80074436889547018 -0.16209683931295196 1.2352941176470589 +0.72909524134154469 0.68385464723906386 1.9749977665939857 -0.052571949728947992 -1.2941176470588236 +-0.55712246256458975 0.24608576919527408 2.1779872308885562 -0.33030910244835021 1.3529411764705883 +1.0752038973698961 1.7764429477923738 0.32378526107168559 1.1010826014798427 -1.4117647058823528 +-0.16066479277852427 -0.35387063581987599 -0.75992320979581296 -0.86504286867076008 1.4705882352941178 +-0.68509298127070362 -1.8790600722760729 1.8963069182206289 0.89400452072591519 -1.5294117647058822 +0.13624709603486906 -0.87198899540225683 -0.057714898875193384 0.49440441857541229 1.5882352941176472 +1.2959944332129518 0.11073179899641557 0.9240949264506928 0.58838437388996856 -1.6470588235294117 +-1.2079110313762544 0.6344947745518329 -0.46990150921959117 -0.20451467698770204 1.7058823529411766 +-0.64093420513485433 -0.94213881971583036 0.41553449005254162 -0.8363309077237806 -1.7647058823529411 +-0.40454667158947094 2.7180919096356684 -0.99632450898614033 -1.0515024445784329 1.8235294117647058 +-0.095590783942719526 -0.9833386896715185 0.38286422505880563 1.8665667449890997 -1.8823529411764706 +-0.96158319202619524 -0.30410610014122763 -0.70790466353785098 -0.55564578720902458 1.9411764705882353 +0.36740553795682118 0.48513982928838756 0.19602073048982308 1.7296064841903722 -2 diff --git a/test/reference/bspline_coefficient_solver/power_n17_dense_adjoint.txt b/test/reference/bspline_coefficient_solver/power_n17_dense_adjoint.txt new file mode 100644 index 0000000..8019fa1 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_dense_adjoint.txt @@ -0,0 +1,17 @@ +1.9014092106655314 -0.65228686763224597 1.5194384367172364 -2.1358651813386391 -4.3925710091847856 +-2.8128598474714548 0.27252983314578566 -2.7775171329913899 3.0547173908085368 6.5865939444836687 +2.4063812713173762 0.79431169965399862 1.9513420286344916 -4.7638432413575158 -5.0158539075045772 +-1.6495003895035367 -1.5223279389903035 -2.5698213931726328 0.135680635310889 4.448782256377358 +2.1060989114693243 1.6308497109992248 2.4278305551868593 0.49775189622573973 -4.2829789017066142 +-1.9315761446325999 -0.91979411174989623 2.6776631169411584 -1.5642000836620638 4.3274779335998703 +2.0992052372863879 2.9626676349623389 0.89784354059129623 2.7586009898956303 -4.4354072879917057 +-0.36139887203117921 -0.24516214914902593 -2.5605993516926757 -2.3970649973105238 4.571497918003204 +-0.82241621569309209 -2.5832514154775605 3.8431193803450094 1.7896190064641648 -4.7255506777557486 +-0.47652315044696236 -0.7138926174673218 -1.5226281899966976 0.076284668513545706 4.9000544103295223 +2.7629689243591757 -0.3221219092063346 2.2209309651435438 1.0479238426799353 -5.1180139498563975 +-2.3582807867102629 2.1126436646284814 -1.7210696230070177 -0.57946194825824782 5.4605908809204191 +-0.12000258800087905 -3.6851156472080215 1.8738884202401001 0.18446287049278362 -6.1938763178032579 +-1.2062036133915661 6.2470941836569827 -3.0395941092722851 -4.5433225023855792 8.1868683045567074 +1.5340962081166605 -3.045826682185222 2.5868615332648597 5.8975172467580865 -8.8623271604222271 +-2.2522550270519504 -0.047789530265327305 -1.9323637146155406 -2.2444844905157599 5.6316868181102944 +0.61391360954671159 0.49037036704117143 0.40751687421190208 1.9752640748383854 -2.6163850188616111 diff --git a/test/reference/bspline_coefficient_solver/power_n17_dense_coefficients.txt b/test/reference/bspline_coefficient_solver/power_n17_dense_coefficients.txt new file mode 100644 index 0000000..3852f66 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_dense_coefficients.txt @@ -0,0 +1,17 @@ +0.29999999999999999 1 -1.6274137158591773 0.24461357145404428 0 +0.31954010819527773 -1.0652173273482566 3.6511249706704172 -2.2513026522359496 0 +0.36058337309109589 0.78871464465814844 -1.8310608009967739 1.6650347675720354 0 +0.39863948567660296 -0.38857354308761782 -4.0650956299891812 -1.8610310381479378 0 +0.37486542685396451 0.17726295035352382 2.787808220561891 1.459568629924485 0 +0.27491117136605675 -0.069253254912117604 -1.6523564494442746 -1.5362359790243623 0 +0.31093354396581308 0.027083038371406284 1.585607798866671 -0.39093540857669218 0 +0.88462674443120126 -0.0089730854904844781 -1.7247897076272416 0.88478864131495061 0 +1.5346388350588611 0.0035125090535089751 -0.2628577837650089 -0.21587715141331648 0 +0.70106913662775816 -0.0009062601686202253 -0.40712304513202591 -0.29888983479142489 0 +0.46017966415423317 0.00046451367157460832 1.4708889789133741 -0.84286102720996769 0 +0.80297047411579126 -4.3911189015707383e-05 -1.4117372035125435 1.0043458746655971 0 +-1.295494302170364 7.8816749237037157e-05 -2.0290534043879651 -1.4701869476517015 0 +-0.27546251167729191 1.4978665075765088e-05 3.6939598620105638 -0.26722140922799181 0 +-2.0432105493641122 2.0264880156514685e-05 -2.8045887522311395 1.4142455588030687 0 +0.75406741576435754 2.5783485967056437e-06 0.71227576055275543 -1.3186727331102539 0 +0.93140930606014849 5.5312818984406114e-06 -0.81473422890805736 -0.67210852272081478 0 diff --git a/test/reference/bspline_coefficient_solver/power_n17_rhs.txt b/test/reference/bspline_coefficient_solver/power_n17_rhs.txt new file mode 100644 index 0000000..d6566ec --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_rhs.txt @@ -0,0 +1,17 @@ +0.29999999999999999 1 -1.6274137158591773 0.24461357145404428 0 +0.31148513631489522 0.061027643447392685 0.73623089596039115 -0.81770223421885646 0 +0.34852917659358618 0.012771150348198829 0.0067154550172444155 -0.057145206425003758 0 +0.38546212919022971 0.0048738427571977886 -2.8346326670574435 -0.54650242841367014 0 +0.37116170692499739 0.0023746679170747039 0.52398843216205815 0.27803810179151323 0 +0.30318385913296497 0.0013096255323105548 -0.21412788333602409 -0.68154676464291519 0 +0.37113678449553 0.00077359060200683566 0.45099936433154586 -0.50041090649738518 0 +0.84061142678664647 0.00047487523065497969 -0.81781530081443099 0.46796407839506871 0 +1.2888465320373399 0.00029738657566447834 -0.59083825835351989 0.0061579503756554743 0 +0.84068425578500394 0.000187675676899344 -0.12641797784718983 -0.3544744333718941 0 +0.55565478002203206 0.00011832697675453029 0.6978248058353268 -0.48059450020558891 0 +0.44284600754062409 7.4058326430194224e-05 -0.92567278201727388 0.29335429503542443 0 +-0.74085283821740311 4.5787700500724986e-05 -1.0994418595627524 -0.81612884405259467 0 +-0.65352636234286621 2.7856227221292758e-05 1.9228183037061362 -0.32757500958217189 0 +-1.1128030777491162 1.6623539561492436e-05 -0.007840891876553303 0.52259856696877316 0 +-0.2522860212135678 9.7053919957397225e-06 -0.51352577955614365 -0.24328046234296052 0 +0.93140930606014849 5.5312818984406114e-06 -0.81473422890805736 -0.67210852272081478 0 diff --git a/test/reference/bspline_coefficient_solver/power_n17_sites.txt b/test/reference/bspline_coefficient_solver/power_n17_sites.txt new file mode 100644 index 0000000..080cf77 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/power_n17_sites.txt @@ -0,0 +1,17 @@ +2 +17.302646620439688 +77.359071584583148 +193.48970724407621 +373.11159990487664 +622.00837980684457 +945.00593314639184 +1346.2871317953761 +1829.5678918015301 +2398.2069366121473 +3055.2794121049187 +3803.6289412151573 +4645.9059453771588 +5584.5967657392557 +6622.0463689653543 +7760.4764310969467 +9002 diff --git a/test/reference/bspline_coefficient_solver/random_n33_adjoint.txt b/test/reference/bspline_coefficient_solver/random_n33_adjoint.txt new file mode 100644 index 0000000..e389984 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_adjoint.txt @@ -0,0 +1,33 @@ +-1.6410305714899631 0.047060970731612028 -1.7847597220681752 -0.85145622638367957 -1.6392907617383619 +0.59647738460754551 1.5745846847624896 0.53032997049071884 -1.454939494439516 2.586067073687933 +-0.47459906735663449 -7.8825877212737945 -3.6910936022930434 3.9402854081402729 -5.9719358575915331 +-2.443261320966061 5.6319529352030795 1.2794165973772058 -4.1330185743497339 5.6423695444276847 +1.837134109844623 -3.1142992721954155 1.1784817077051299 1.7177394101266685 -3.7504251413418155 +-4.2129647303409037 4.6259893004546369 -1.0771833451057333 -1.6669856509651488 5.6750497906322837 +5.8425908365727004 -3.5945312131517264 -0.68848858238042099 0.84688912789904114 -4.1969649629283241 +-4.2846403615418467 4.5995344834913592 -0.33898784836295182 1.7865281644090878 3.6530386126842926 +3.4825168435747762 -4.8857047656032693 3.6627100563949022 -3.3746950912569371 -4.8904607582883663 +1.0702395488977194 2.775464675626889 -2.2445119084287795 3.5638014361751713 3.7148711140762143 +-1.9221751137583598 2.5672254908147831 1.8271387085475956 0.63108494320177111 -4.8500909950264841 +-1.3853479779916618 -3.3240051247708005 -2.4355317960855918 0.63877537736995316 5.1474106263936843 +3.9344837177684409 0.62469117060075852 -1.0964123338965512 -1.6083611613577067 -3.5338868292266188 +-1.4996223368891906 0.56229590136857355 1.064513602108665 -1.2278902915841907 4.4606981346763295 +1.4306013133260629 -1.3717390624358066 -2.1468343488195329 -1.4381657287493876 -4.8015375048633571 +-0.56660107375715763 -2.425363685917818 -0.066647211524571565 2.398604232209562 4.0428767836162161 +-2.9112366892386845 1.3003594438754851 -1.6214684480247876 -2.4288997783874273 -4.9263959745897195 +1.8960981717357013 -1.8925033798569095 1.8651375643148635 1.9786219824067763 7.9143275920984948 +0.89850542411978607 0.49449357499265129 -1.655270014336528 -0.1951221750440047 -8.1907059170176773 +-1.7292785596119908 -1.164030275332379 -1.5178486208515951 -0.38511789181144856 5.1591470698659636 +-0.50081246296434079 -1.3569443649217108 3.0299352265910633 1.352164745445755 -3.8307918912622867 +1.7346500129365392 -1.5324158149998315 -3.2174001465869679 -3.422852543371441 6.3501601698187651 +-2.7065530096328243 2.1197080361572258 4.3680755083059797 3.6326090204625419 -6.1956764799040256 +2.3632256339785074 -0.92571768998921078 -2.6781320398721498 -2.5465169810707322 4.775355521085082 +0.5599620571141275 1.9193411207570914 3.1952927006780123 1.3989464521680854 -6.7154823381052573 +-0.88676244339062071 2.1068075517008902 -4.3576354152154222 0.098501314970332932 6.9600654293004398 +0.64046362807896184 3.13613843298962 0.49328402229287199 -0.33101203235206628 -5.4603057524680345 +0.97042129688351775 -0.723177841290916 1.4236592661494081 -0.11325307806640855 5.2491367115451855 +0.90984704180630904 -0.87532912300885379 0.81263969797437252 -1.3245669493527374 -5.4187516121960169 +-5.2306767077771497 1.6827774796898383 -2.8809853547072835 1.5307647320414912 14.343715714303157 +3.7687952582975135 2.7446088233670092 1.9600661191646638 -0.17899603345121054 -17.190690184079934 +2.3072166950957738 -4.0386494383537608 -4.358802705864913 -0.17032733646359785 6.7841956442104241 +0.097344980413006585 -1.6243192824248227 1.367888390045328 -0.080427465663856751 -2.4102440869458586 diff --git a/test/reference/bspline_coefficient_solver/random_n33_coefficients.txt b/test/reference/bspline_coefficient_solver/random_n33_coefficients.txt new file mode 100644 index 0000000..9d4081a --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_coefficients.txt @@ -0,0 +1,33 @@ +0.29999999999999999 1 0.56279158383407879 -0.4480900760157589 0 +0.4935572649957698 0.45424139454982665 -0.79049372397364137 -0.62689558697368131 0 +0.27388649981775914 0.34806382341093189 2.156639209536853 1.6089481739576108 0 +0.30662187379264333 0.20824153250941657 -3.1537126330146048 0.11365939938970439 0 +0.59412443011143212 0.16426091847899976 1.3160157193915389 0.26346448995469113 0 +0.97559332127202048 0.13081323816949758 -0.21459118343573341 -0.22228917859207567 0 +1.3050022672833848 0.10320777234479069 -2.2060047343785665 1.411206503185388 0 +1.3232455575501176 0.082972398212601384 0.41326977891354877 -2.3183926080830979 0 +0.96053823055886312 0.066560609896204465 -0.36523387555226405 1.8108963293110438 0 +0.56814411160019407 0.053428686526932646 0.32224290622741436 -1.100510795671616 0 +0.48185052277542784 0.044176983318325085 0.20162622190810195 1.3979812992495333 0 +0.64862080623260765 0.035515525861402893 -0.16361656703091509 -0.17887925521210779 0 +0.74414855874998709 0.029263887674965291 0.60825308162455816 0.21070648436121941 0 +0.29709988706098378 0.024170577227861884 -2.5173599556592592 -1.9532787373458342 0 +-0.25618174496760365 0.020612642590842709 -1.8652261439093634 2.0834060725276085 0 +-0.6707049033073762 0.017819912453504977 -0.26843060581403255 -2.5650934569887327 0 +-0.78649886832175253 0.015765344522163924 -2.5158827279023419 1.3126764958830111 0 +-0.74576156490841761 0.014381013035117138 1.7594406635041531 -0.36145824288721407 0 +-0.68439507135142219 0.013343184721875139 -1.0336271834238788 0.86951547505193716 0 +-0.5508347932698564 0.011694823760944125 3.0511176463142431 -0.3184652913311965 0 +-0.59831163414419852 0.0097910390558329646 -0.96450999148102601 -2.4052774833414992 0 +-1.0654267536845612 0.0083031852757882007 2.1105461890173909 2.2840391037898997 0 +-1.3063150194232402 0.0071727663672470016 -4.6982607918124151 -1.7867691167000428 0 +-1.2587518325660842 0.0063793041309609024 0.92785055048799314 0.27694763961519842 0 +-0.95891369060247666 0.0057103327265934263 0.87697660350932338 0.40540830724245402 0 +-0.65812363568855003 0.0052006178038753806 0.16218364654383946 -0.2995280664090586 0 +-0.31916215013988974 0.0046408848409228197 -0.46927660302681468 1.7111567858847501 0 +-0.1538681468678518 0.0040461049998298118 -0.34900957333030158 -1.5657094938129552 0 +-0.28948415046404025 0.0034560110108846735 0.62567824787696291 -0.69851701483083817 0 +-0.30341081712737195 0.0030588642036255783 -2.865863804329039 2.3188703183779729 0 +0.057839697986934384 0.0025469757651704057 6.9289727855869536 -4.1195784789526932 0 +0.69154001148689825 0.0022610381244552937 -13.542180968600395 4.151690399304 0 +0.93140930606014927 0.0020537128754347547 0.83912016823515567 0.56390889780467168 0 diff --git a/test/reference/bspline_coefficient_solver/random_n33_cotangent.txt b/test/reference/bspline_coefficient_solver/random_n33_cotangent.txt new file mode 100644 index 0000000..f16282d --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_cotangent.txt @@ -0,0 +1,33 @@ +-1.5005673124351198 0.41785674972850217 -1.6598733844602582 -1.1940770002643921 -1.0303030303030303 +0.27579498609659042 0.49918615113369441 0.13235968916912977 -0.57666783981437497 1.0606060606060606 +-0.71909402903256781 -2.3586898005138544 -1.4991758807697733 0.67910631306238622 -1.0909090909090908 +-1.7628522378762896 0.30040360680906125 -0.62593319239038525 -1.0706589983472641 1.1212121212121211 +0.43910340734735437 -0.91470877188523703 0.59317469239126464 0.53783041339855209 -1.1515151515151516 +-0.094021681548290034 0.86721497663286906 -0.67033674624074258 -0.26773624711815408 1.1818181818181819 +2.1941478394992187 -0.93460568126047006 -0.51962269067167832 0.40810425426961983 -1.2121212121212122 +-1.7252754709230036 1.8251215665173357 0.27788976503713902 0.61452285743418045 1.2424242424242424 +1.5250503933327495 -1.2550702329147503 1.9073010341047401 -0.80370806260233052 -1.2727272727272727 +0.91409182456543614 1.2167927152886899 -0.7735775007807022 1.7343956381355479 1.303030303030303 +-1.4818926482542734 1.0148931149073817 0.2863016062207831 0.92286277813770412 -1.3333333333333333 +-0.82626215614958998 -1.3414665927824778 -1.2706147247013526 0.33941093634964203 1.3636363636363638 +2.1646831588140789 0.22916071296657978 -0.71531989183348199 -1.0619221927446543 -1.393939393939394 +0.085507350562330803 0.2932076114786335 0.13231001874993523 -1.3705903842121925 1.4242424242424243 +0.5155100038627769 -1.2883292867316931 -1.2446931545169342 -0.83695878751334485 -1.4545454545454546 +-0.34340775731089607 -1.6480571724512503 -0.47890525869622574 1.1283297023034058 1.4848484848484849 +-1.6071575468104686 0.17747240367454975 -0.79440059546976527 -0.81295666270307287 -1.5151515151515151 +0.56907901920970894 -0.75095553261650705 0.27561055546248636 0.48716586811738688 1.5454545454545454 +0.22923377670099504 -0.56720337258381659 -1.3843367596285201 0.10630107423075105 -1.5757575757575757 +-0.92989854643086756 -0.80874886316571359 -0.31640140420447699 0.031300177066635577 1.606060606060606 +-0.29352284116826394 -0.93546088084195789 1.5240379455172948 0.59159398842811384 -1.6363636363636362 +0.33792996736185904 -0.79764472697508215 -0.28142339787235748 -0.99790490877530547 1.6666666666666665 +-1.0216143174125267 0.85663648172863882 1.6566529430682095 1.1151910852692046 -1.696969696969697 +1.2335673838555237 -0.2041817699348305 -0.9470284058003493 -1.0905503396456162 1.7272727272727273 +0.87442835640684324 1.5305613339385447 0.48907285387077015 0.26009315960503659 -1.7575757575757576 +-0.30744467643776469 2.779471203263904 -2.1841087201291991 0.27350292299412865 1.7878787878787878 +0.481856183110142 1.9781486583276371 0.16510631865957223 -0.21341346357975208 -1.8181818181818183 +0.87359068110858584 -0.33248292589092193 1.1367592678276452 -0.36244105773675178 1.8484848484848486 +0.51352511150879621 -0.60211482687189499 0.63202984548522656 -0.78552329211386229 -1.8787878787878789 +-1.5770166877748399 1.9582123734498069 -1.4787076241159227 0.77341220573582092 1.9090909090909092 +1.7466826744470925 -0.18355340722344982 -1.7618747914234851 0.18104040108629946 -1.9393939393939394 +0.92439366186918071 -1.3708111321175147 -1.5060058822896718 -0.065615421037606744 1.9696969696969697 +0.23686365824971672 -1.8685386620274389 1.1043091641468676 -0.090727254510462318 -2 diff --git a/test/reference/bspline_coefficient_solver/random_n33_dense_adjoint.txt b/test/reference/bspline_coefficient_solver/random_n33_dense_adjoint.txt new file mode 100644 index 0000000..474f84a --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_dense_adjoint.txt @@ -0,0 +1,33 @@ +-1.6410305714899631 0.04706097073161214 -1.7847597220681752 -0.85145622638367968 -1.6392907617383619 +0.59647738460754551 1.5745846847624891 0.53032997049071884 -1.4549394944395158 2.586067073687933 +-0.47459906735663465 -7.8825877212737936 -3.6910936022930434 3.9402854081402716 -5.9719358575915331 +-2.4432613209660605 5.6319529352030786 1.279416597377206 -4.133018574349733 5.6423695444276838 +1.837134109844623 -3.114299272195415 1.1784817077051297 1.7177394101266688 -3.7504251413418155 +-4.2129647303409046 4.6259893004546377 -1.0771833451057331 -1.6669856509651491 5.6750497906322845 +5.8425908365727013 -3.5945312131517269 -0.68848858238042099 0.84688912789904147 -4.196964962928325 +-4.2846403615418467 4.5995344834913592 -0.33898784836295193 1.7865281644090873 3.6530386126842922 +3.4825168435747762 -4.8857047656032702 3.6627100563949027 -3.3746950912569371 -4.8904607582883663 +1.0702395488977194 2.7754646756268895 -2.2445119084287795 3.5638014361751709 3.7148711140762143 +-1.9221751137583603 2.5672254908147831 1.8271387085475956 0.63108494320177111 -4.8500909950264841 +-1.3853479779916615 -3.3240051247708005 -2.4355317960855918 0.63877537736995327 5.1474106263936843 +3.9344837177684409 0.62469117060075874 -1.0964123338965512 -1.6083611613577067 -3.5338868292266183 +-1.4996223368891906 0.56229590136857344 1.064513602108665 -1.2278902915841905 4.4606981346763295 +1.4306013133260627 -1.3717390624358066 -2.1468343488195329 -1.4381657287493876 -4.8015375048633562 +-0.56660107375715751 -2.4253636859178176 -0.06664721152457162 2.3986042322095615 4.0428767836162152 +-2.9112366892386841 1.3003594438754851 -1.6214684480247876 -2.4288997783874269 -4.9263959745897186 +1.8960981717357006 -1.8925033798569098 1.8651375643148635 1.9786219824067761 7.9143275920984948 +0.89850542411978618 0.49449357499265145 -1.655270014336528 -0.19512217504400442 -8.1907059170176773 +-1.7292785596119908 -1.1640302753323792 -1.5178486208515951 -0.38511789181144868 5.1591470698659636 +-0.50081246296434079 -1.3569443649217108 3.0299352265910633 1.352164745445755 -3.8307918912622867 +1.7346500129365392 -1.5324158149998315 -3.2174001465869679 -3.4228525433714401 6.3501601698187642 +-2.7065530096328243 2.1197080361572258 4.3680755083059797 3.6326090204625414 -6.1956764799040247 +2.3632256339785074 -0.92571768998921089 -2.6781320398721493 -2.5465169810707318 4.775355521085082 +0.5599620571141275 1.9193411207570914 3.1952927006780123 1.398946452168085 -6.7154823381052573 +-0.88676244339062082 2.1068075517008902 -4.3576354152154222 0.098501314970333015 6.9600654293004407 +0.64046362807896184 3.13613843298962 0.49328402229287199 -0.33101203235206628 -5.4603057524680354 +0.97042129688351786 -0.72317784129091611 1.4236592661494081 -0.11325307806640862 5.2491367115451846 +0.90984704180630893 -0.87532912300885357 0.8126396979743723 -1.3245669493527372 -5.418751612196016 +-5.2306767077771497 1.6827774796898376 -2.880985354707283 1.5307647320414912 14.343715714303155 +3.7687952582975139 2.7446088233670092 1.9600661191646638 -0.17899603345121057 -17.190690184079934 +2.3072166950957738 -4.0386494383537608 -4.358802705864913 -0.17032733646359785 6.7841956442104241 +0.097344980413006571 -1.6243192824248229 1.367888390045328 -0.080427465663856751 -2.4102440869458586 diff --git a/test/reference/bspline_coefficient_solver/random_n33_dense_coefficients.txt b/test/reference/bspline_coefficient_solver/random_n33_dense_coefficients.txt new file mode 100644 index 0000000..7d0b28c --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_dense_coefficients.txt @@ -0,0 +1,33 @@ +0.29999999999999999 1 0.56279158383407879 -0.4480900760157589 0 +0.4935572649957698 0.45424139454982659 -0.79049372397364204 -0.6268955869736812 0 +0.27388649981775909 0.34806382341093189 2.1566392095368543 1.6089481739576108 0 +0.30662187379264338 0.2082415325094166 -3.1537126330146057 0.11365939938970429 0 +0.59412443011143201 0.16426091847899976 1.3160157193915392 0.26346448995469113 0 +0.97559332127202048 0.13081323816949758 -0.21459118343573341 -0.22228917859207567 0 +1.3050022672833848 0.10320777234479071 -2.2060047343785665 1.411206503185388 0 +1.3232455575501176 0.08297239821260137 0.41326977891354882 -2.3183926080830979 0 +0.96053823055886312 0.066560609896204465 -0.36523387555226405 1.8108963293110438 0 +0.56814411160019396 0.053428686526932646 0.32224290622741431 -1.100510795671616 0 +0.48185052277542789 0.044176983318325085 0.20162622190810195 1.3979812992495333 0 +0.64862080623260765 0.035515525861402886 -0.16361656703091504 -0.17887925521210779 0 +0.74414855874998709 0.029263887674965298 0.60825308162455793 0.21070648436121941 0 +0.29709988706098378 0.024170577227861881 -2.5173599556592587 -1.9532787373458342 0 +-0.25618174496760365 0.020612642590842709 -1.8652261439093631 2.0834060725276085 0 +-0.6707049033073762 0.017819912453504977 -0.26843060581403255 -2.5650934569887327 0 +-0.78649886832175253 0.015765344522163924 -2.5158827279023419 1.3126764958830111 0 +-0.74576156490841761 0.014381013035117138 1.7594406635041528 -0.36145824288721401 0 +-0.68439507135142219 0.013343184721875141 -1.0336271834238788 0.86951547505193727 0 +-0.5508347932698564 0.011694823760944125 3.0511176463142435 -0.3184652913311965 0 +-0.59831163414419852 0.0097910390558329646 -0.96450999148102601 -2.4052774833414992 0 +-1.0654267536845612 0.0083031852757882007 2.1105461890173909 2.2840391037898997 0 +-1.30631501942324 0.0071727663672470016 -4.6982607918124151 -1.7867691167000428 0 +-1.258751832566084 0.0063793041309609042 0.92785055048799303 0.2769476396151983 0 +-0.95891369060247678 0.0057103327265934254 0.87697660350932338 0.40540830724245402 0 +-0.65812363568855015 0.0052006178038753815 0.16218364654383952 -0.29952806640905866 0 +-0.31916215013988974 0.0046408848409228197 -0.46927660302681479 1.7111567858847501 0 +-0.15386814686785177 0.0040461049998298118 -0.34900957333030147 -1.5657094938129552 0 +-0.2894841504640403 0.003456011010884674 0.6256782478769628 -0.69851701483083817 0 +-0.30341081712737195 0.0030588642036255788 -2.8658638043290385 2.3188703183779724 0 +0.05783969798693453 0.0025469757651704053 6.9289727855869536 -4.1195784789526924 0 +0.69154001148689803 0.0022610381244552941 -13.542180968600393 4.151690399304 -0 +0.93140930606014938 0.0020537128754347547 0.83912016823515578 0.56390889780467168 0 diff --git a/test/reference/bspline_coefficient_solver/random_n33_rhs.txt b/test/reference/bspline_coefficient_solver/random_n33_rhs.txt new file mode 100644 index 0000000..dea83dc --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_rhs.txt @@ -0,0 +1,33 @@ +0.29999999999999999 1 0.56279158383407879 -0.4480900760157589 0 +0.38843756722507505 0.55018744899666572 0.20819537608721286 -0.0071259440710274013 0 +0.29573641468078982 0.29079117815213873 -0.25947465414293747 0.88008397116804615 0 +0.31355860585578321 0.24122590573916017 -1.5762923115544736 0.49919530757100872 0 +0.72489518507275108 0.15408727422171836 0.40413154276508567 0.06142268024745734 0 +0.97670624027518571 0.13086648317861432 -0.29812143479042863 0.018668627894812717 0 +1.1661266815239184 0.11391866646462423 -1.231137350202318 0.53317658063858153 0 +1.2028645635889423 0.079404137972839087 -0.075272659826687377 -0.6337264119492434 0 +0.96517225774931337 0.067310464352784719 -0.17655517468981119 0.89600478193252586 0 +0.68315392110800133 0.056648157094563174 0.093859956091620136 0.063281854834295048 0 +0.53789336986880665 0.042125285669723372 0.098251664639858668 0.76284337627993604 0 +0.61008930768686176 0.037436296751345466 -0.018080699449147742 0.26602534323360727 0 +0.63104614204862042 0.029256813381736475 -0.20067365200616405 -0.32406239200428733 0 +0.20469097662916991 0.023795117514767334 -2.0482359848873246 -0.74401179370686887 0 +-0.23425152225695378 0.020734463369824999 -1.7236277182060067 0.76407010959313038 0 +-0.61015008381082747 0.018006056041904028 -0.97052287236406054 -0.98504840111869507 0 +-0.7635477846649632 0.015400819173879093 -0.79415183974229198 0.43057503715496881 0 +-0.73610151732068019 0.014266983515852195 0.8848520799498879 0.0090864339036167419 0 +-0.69647432438311585 0.013573907450667874 -0.043622313793869362 0.45971530821054696 0 +-0.61177581766558153 0.01231547978343021 1.0519647388559727 0.091104924975985879 0 +-0.70233233848058896 0.0097656493266188599 0.47581588324116286 -0.91353942812763478 0 +-1.1135076777770876 0.0080407104948580742 -0.10020828267320199 0.8131231745105032 0 +-1.2433907109436384 0.007384943574372714 -2.5696646017999734 -0.62040614360084856 0 +-1.1779915799916061 0.0062800163494997029 0.25103128597542718 0.071056660423184592 0 +-0.92112061220387764 0.0056607625345785079 0.72763629887525039 0.24205566472633278 0 +-0.69453298011081666 0.0052636064975866998 0.26401271378727748 0.032498479222634158 0 +-0.40103900163672362 0.0047443273982142164 -0.27448592200679406 0.80529830507718514 0 +-0.20592038032356602 0.0040472577204092057 -0.20155018569857724 -0.84828088071222907 0 +-0.26579570029119248 0.0034988903757912507 -0.18696207616839353 -0.32623935548699534 0 +-0.22033095988856516 0.0029591138783623436 -0.47901030451373378 0.71877764360230145 0 +-0.099953805148432273 0.0027867683292290011 1.6538790735873024 -0.78935170955109335 0 +0.29802040961638565 0.0024704069870557358 -1.8170851968695643 -0.18258162664600186 0 +0.93140930606014916 0.0020537128754347543 0.83912016823515556 0.56390889780467157 0 diff --git a/test/reference/bspline_coefficient_solver/random_n33_sites.txt b/test/reference/bspline_coefficient_solver/random_n33_sites.txt new file mode 100644 index 0000000..3c14220 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n33_sites.txt @@ -0,0 +1,33 @@ +-3 +-2.3324810643917839 +-1.2547273009309645 +-0.85646799710951571 +0.2605098437622102 +0.72473351707865685 +1.1426293422285099 +2.3297901083650734 +2.9196537934908884 +3.5649700872197547 +4.7406718728947759 +5.2315832376970448 +6.2960651660687574 +7.2265999321555601 +7.8648845572070432 +8.5333383939246037 +9.2900114728993444 +9.6662177888468914 +9.9132425261428292 +10.400390393245873 +11.585154985413626 +12.601476874764463 +13.052785650633055 +13.922877470506236 +14.487057707326759 +14.885445453368476 +15.458543397291987 +16.344677958162841 +17.166031267877472 +18.121944088675964 +18.466953692080459 +19.163856364508778 +20.242467855845927 diff --git a/test/reference/bspline_coefficient_solver/random_n6_adjoint.txt b/test/reference/bspline_coefficient_solver/random_n6_adjoint.txt new file mode 100644 index 0000000..9431590 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_adjoint.txt @@ -0,0 +1,6 @@ +0.64878785615531342 -0.14499076144766398 0.19594374058972061 -0.0046985787347383345 -1.9622768154476864 +0.55358764354843393 -1.4362206348837714 -0.13796996090424357 -3.7836721714275146 3.3519737760396056 +2.4310500485838036 1.4804112013812125 -5.7026241327970331 5.9475002232577383 -9.1897908702036322 +-0.74467193911603025 -2.8659842118139989 6.3474020977795371 -3.4369188700922702 12.183817081860344 +-0.72287545067531889 -0.46925884576102594 -1.1879558233266705 -0.59381571062760774 -6.4266986838464026 +0.22657440919866453 2.6861548366185799 1.3027372331278528 -0.97304084804904811 2.5429755115977697 diff --git a/test/reference/bspline_coefficient_solver/random_n6_coefficients.txt b/test/reference/bspline_coefficient_solver/random_n6_coefficients.txt new file mode 100644 index 0000000..dae193f --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_coefficients.txt @@ -0,0 +1,6 @@ +0.29999999999999999 1 0.13930958559509324 -0.95017471350112404 0 +2.1368544339324935 0.1027801926156269 2.7424418767068466 -0.14915564530732736 0 +0.75193777551484087 0.1032445608385677 0.92977211204058696 -0.50024609185961966 0 +-2.1550440983226835 0.023159272584069548 -0.25348125127435078 -0.38327109457602471 0 +1.2093987304180946 0.020257324821281331 -1.7935450789380023 -1.723465654030877 0 +0.93140930606014904 0.012916594924588245 -1.9552535320777509 0.90933503496337365 0 diff --git a/test/reference/bspline_coefficient_solver/random_n6_cotangent.txt b/test/reference/bspline_coefficient_solver/random_n6_cotangent.txt new file mode 100644 index 0000000..0ccf4bd --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_cotangent.txt @@ -0,0 +1,6 @@ +0.78018504983124015 -0.48588594421139281 0.16319578119129372 -0.90277481094344736 -1.1666666666666667 +0.3515469859526773 -0.65302249678639135 -0.25714246525321566 -1.6522639234503333 1.3333333333333333 +1.1548853490180466 -0.20919471310309531 -1.6201013085244533 1.2788881543334238 -1.5 +0.35426827371899428 -1.5455986417052594 1.2659109193587226 0.07220322735202124 1.6666666666666665 +-0.41393358214550968 -0.50269496411330084 0.063300376432942396 -0.61748776793919025 -1.8333333333333335 +0.16550049131941763 2.6465083440127715 1.202369851263873 -1.0232108350259144 2 diff --git a/test/reference/bspline_coefficient_solver/random_n6_dense_adjoint.txt b/test/reference/bspline_coefficient_solver/random_n6_dense_adjoint.txt new file mode 100644 index 0000000..e9c42c5 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_dense_adjoint.txt @@ -0,0 +1,6 @@ +0.64878785615531342 -0.14499076144766404 0.19594374058972061 -0.0046985787347383345 -1.9622768154476864 +0.55358764354843393 -1.4362206348837712 -0.13796996090424357 -3.7836721714275146 3.3519737760396056 +2.4310500485838045 1.480411201381213 -5.7026241327970331 5.9475002232577401 -9.1897908702036304 +-0.74467193911603091 -2.8659842118139993 6.347402097779538 -3.436918870092271 12.183817081860347 +-0.72287545067531878 -0.46925884576102589 -1.1879558233266709 -0.59381571062760774 -6.4266986838464035 +0.22657440919866456 2.6861548366185799 1.3027372331278531 -0.97304084804904822 2.5429755115977697 diff --git a/test/reference/bspline_coefficient_solver/random_n6_dense_coefficients.txt b/test/reference/bspline_coefficient_solver/random_n6_dense_coefficients.txt new file mode 100644 index 0000000..cd592a5 --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_dense_coefficients.txt @@ -0,0 +1,6 @@ +0.29999999999999999 1 0.13930958559509324 -0.95017471350112404 0 +2.1368544339324935 0.10278019261562689 2.7424418767068466 -0.14915564530732736 0 +0.75193777551484087 0.10324456083856773 0.92977211204058696 -0.50024609185961966 0 +-2.1550440983226835 0.023159272584069544 -0.25348125127435078 -0.38327109457602476 0 +1.2093987304180942 0.020257324821281331 -1.7935450789380025 -1.7234656540308768 0 +0.93140930606014916 0.012916594924588246 -1.9552535320777511 0.90933503496337376 0 diff --git a/test/reference/bspline_coefficient_solver/random_n6_rhs.txt b/test/reference/bspline_coefficient_solver/random_n6_rhs.txt new file mode 100644 index 0000000..1885c6f --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_rhs.txt @@ -0,0 +1,6 @@ +0.29999999999999999 1 0.13930958559509324 -0.95017471350112404 0 +1.2451467973763584 0.31375453735900621 1.5972666686555019 -0.43228146991312477 0 +-0.59049761868556716 0.064976917638704584 0.42489186413639091 -0.43269585883266748 0 +-1.2547637102322995 0.038573679002689355 -0.17277021624782918 -0.53781967078644022 0 +-0.20738089138683743 0.023700631549581921 -1.0823272686558922 -0.9099523714000437 0 +0.93140930606014893 0.012916594924588243 -1.9552535320777507 0.90933503496337353 0 diff --git a/test/reference/bspline_coefficient_solver/random_n6_sites.txt b/test/reference/bspline_coefficient_solver/random_n6_sites.txt new file mode 100644 index 0000000..224c77d --- /dev/null +++ b/test/reference/bspline_coefficient_solver/random_n6_sites.txt @@ -0,0 +1,6 @@ +-3 +-2.3649186976690784 +-1.3324383157121527 +-0.9604728296935936 +-0.60286301651299201 +-0.14549587886444559 diff --git a/test/reference/cubic_b_spline/generate_reference.py b/test/reference/cubic_b_spline/generate_reference.py new file mode 100644 index 0000000..297f146 --- /dev/null +++ b/test/reference/cubic_b_spline/generate_reference.py @@ -0,0 +1,96 @@ +import numpy as np +import scipy +from scipy.interpolate import make_interp_spline, BSpline +import sys +import os + +def save_data(filename, data): + # Ensure directory exists if needed, but we run in the same dir + np.savetxt(filename, data, fmt='%.16e') + +def generate(): + # Write metadata + with open("metadata.txt", "w") as f: + f.write(f"Python version: {sys.version}\n") + f.write(f"SciPy version: {scipy.__version__}\n") + f.write(f"NumPy version: {np.__version__}\n") + + # Define a comprehensive query grid for tests (endpoints, out-of-bounds left/right, interior, knots, near-knots) + xq_unif = np.array([-1.0, 0.0, 0.5, 1.0, 1.000001, 2.5, 4.999999, 5.0, 6.0]) + + # 1. uniform sites, default not-a-knot + x_unif = np.linspace(0.0, 5.0, 6) + y_unif = x_unif**3 - 2*x_unif**2 + 3 + spl_unif = make_interp_spline(x_unif, y_unif, k=3) + + save_data("uniform_default_sites.txt", x_unif) + save_data("uniform_default_ordinates.txt", y_unif) + save_data("uniform_default_knots.txt", spl_unif.t) + save_data("uniform_default_coefficients.txt", spl_unif.c) + save_data("uniform_default_query.txt", xq_unif) + save_data("uniform_default_values.txt", spl_unif(xq_unif)) + + # Save design matrix for uniform queries (endpoints/interior only, out of bounds will raise error in BSpline.design_matrix) + xq_valid = np.array([0.0, 0.5, 1.0, 1.000001, 2.5, 4.999999, 5.0]) + save_data("uniform_default_query_valid.txt", xq_valid) + design_mat = BSpline.design_matrix(xq_valid, spl_unif.t, 3).toarray() + save_data("uniform_default_design_matrix.txt", design_mat) + + # 2. nonuniform sites, default not-a-knot + x_non = np.array([0.0, 0.2, 1.5, 2.8, 4.5, 5.0]) + y_non = np.sin(x_non) + spl_non = make_interp_spline(x_non, y_non, k=3) + xq_non = np.array([-0.5, 0.0, 0.1, 1.5, 1.500001, 2.0, 4.5, 5.0, 5.5]) + + save_data("nonuniform_default_sites.txt", x_non) + save_data("nonuniform_default_ordinates.txt", y_non) + save_data("nonuniform_default_knots.txt", spl_non.t) + save_data("nonuniform_default_coefficients.txt", spl_non.c) + save_data("nonuniform_default_query.txt", xq_non) + save_data("nonuniform_default_values.txt", spl_non(xq_non)) + + xq_non_valid = np.array([0.0, 0.1, 1.5, 1.500001, 2.0, 4.5, 5.0]) + save_data("nonuniform_default_query_valid.txt", xq_non_valid) + design_mat_non = BSpline.design_matrix(xq_non_valid, spl_non.t, 3).toarray() + save_data("nonuniform_default_design_matrix.txt", design_mat_non) + + # 3. explicit strongly nonuniform simple internal knots + t_int = np.array([1.0, 4.0]) + t_full = np.concatenate(([x_non[0]]*4, t_int, [x_non[-1]]*4)) + spl_exp = make_interp_spline(x_non, y_non, k=3, t=t_full) + + save_data("explicit_knots_knots.txt", spl_exp.t) + save_data("explicit_knots_coefficients.txt", spl_exp.c) + save_data("explicit_knots_values.txt", spl_exp(xq_non)) + + # 4. legal double internal knot + t_double = np.array([2.0, 2.0]) + t_double_full = np.concatenate(([x_non[0]]*4, t_double, [x_non[-1]]*4)) + spl_double = make_interp_spline(x_non, y_non, k=3, t=t_double_full) + + save_data("double_knots_knots.txt", spl_double.t) + save_data("double_knots_coefficients.txt", spl_double.c) + save_data("double_knots_values.txt", spl_double(xq_non)) + + # 5. legal triple internal knot + t_triple = np.array([2.0, 2.0, 2.0]) + x_non7 = np.array([0.0, 0.2, 1.5, 2.5, 2.8, 4.5, 5.0]) + y_non7 = np.sin(x_non7) + t_triple_full = np.concatenate(([x_non7[0]]*4, t_triple, [x_non7[-1]]*4)) + spl_triple = make_interp_spline(x_non7, y_non7, k=3, t=t_triple_full) + + save_data("triple_knots_knots.txt", spl_triple.t) + save_data("triple_knots_coefficients.txt", spl_triple.c) + save_data("triple_knots_values.txt", spl_triple(xq_non)) + + # 6. matrix values (3 distinct series) + Y_mat = np.column_stack((y_non, x_non**2, np.exp(x_non) * np.cos(x_non))) + spl_mat = make_interp_spline(x_non, Y_mat, k=3) + + save_data("matrix_sites.txt", x_non) + save_data("matrix_ordinates.txt", Y_mat) + save_data("matrix_coefficients.txt", spl_mat.c) + save_data("matrix_values.txt", spl_mat(xq_non)) + +if __name__ == "__main__": + generate() diff --git a/test/reference/cubic_b_spline/matrix_coefficients.txt b/test/reference/cubic_b_spline/matrix_coefficients.txt new file mode 100644 index 0000000..735efcb --- /dev/null +++ b/test/reference/cubic_b_spline/matrix_coefficients.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 0.0000000000000000e+00 1.0000000000000000e+00 +5.0447420805272092e-01 1.7217259417041163e-16 1.5421800257294931e+00 +1.3695331086197453e+00 1.3999999999999979e+00 1.9750703740506510e+00 +2.1490665255248717e-01 8.5666666666666735e+00 -7.7610514023173405e+00 +-1.2293987246747338e+00 1.7666666666666654e+01 -8.3335543803837282e+01 +-9.5892427466313845e-01 2.5000000000000000e+01 4.2099201062538391e+01 diff --git a/test/reference/cubic_b_spline/matrix_ordinates.txt b/test/reference/cubic_b_spline/matrix_ordinates.txt new file mode 100644 index 0000000..212c12f --- /dev/null +++ b/test/reference/cubic_b_spline/matrix_ordinates.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 0.0000000000000000e+00 1.0000000000000000e+00 +1.9866933079506122e-01 4.0000000000000008e-02 1.1970560213558914e+00 +9.9749498660405445e-01 2.2500000000000000e+00 3.1702214358044362e-01 +3.3498815015590511e-01 7.8399999999999990e+00 -1.5494513572132350e+01 +-9.7753011766509701e-01 2.0250000000000000e+01 -1.8975233154958957e+01 +-9.5892427466313845e-01 2.5000000000000000e+01 4.2099201062538391e+01 diff --git a/test/reference/cubic_b_spline/matrix_sites.txt b/test/reference/cubic_b_spline/matrix_sites.txt new file mode 100644 index 0000000..7d1965a --- /dev/null +++ b/test/reference/cubic_b_spline/matrix_sites.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 +2.0000000000000001e-01 +1.5000000000000000e+00 +2.7999999999999998e+00 +4.5000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/matrix_values.txt b/test/reference/cubic_b_spline/matrix_values.txt new file mode 100644 index 0000000..5ea0e66 --- /dev/null +++ b/test/reference/cubic_b_spline/matrix_values.txt @@ -0,0 +1,9 @@ +-5.0361013126983034e-01 2.4999999999999928e-01 4.0545790574368656e-01 +0.0000000000000000e+00 0.0000000000000000e+00 1.0000000000000000e+00 +1.0023113224372629e-01 1.0000000000000018e-02 1.1038905099823368e+00 +9.9749498660405433e-01 2.2499999999999996e+00 3.1702214358044345e-01 +9.9749504579621129e-01 2.2500030000010001e+00 3.1701922945134031e-01 +8.9602899079271636e-01 4.0000000000000018e+00 -2.1705639799444563e+00 +-9.7753011766509701e-01 2.0250000000000000e+01 -1.8975233154958953e+01 +-9.5892427466313845e-01 2.5000000000000000e+01 4.2099201062538391e+01 +-5.7513551504897786e-01 3.0250000000000007e+01 1.5677034339535379e+02 diff --git a/test/reference/cubic_b_spline/metadata.txt b/test/reference/cubic_b_spline/metadata.txt new file mode 100644 index 0000000..f648fa3 --- /dev/null +++ b/test/reference/cubic_b_spline/metadata.txt @@ -0,0 +1,3 @@ +Python version: 3.12.2 | packaged by conda-forge | (main, Feb 16 2024, 20:50:58) [GCC 12.3.0] +SciPy version: 1.18.0 +NumPy version: 2.5.1 diff --git a/test/reference/cubic_b_spline/nonuniform_default_coefficients.txt b/test/reference/cubic_b_spline/nonuniform_default_coefficients.txt new file mode 100644 index 0000000..23200ab --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_coefficients.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 +5.0447420805272092e-01 +1.3695331086197453e+00 +2.1490665255248717e-01 +-1.2293987246747338e+00 +-9.5892427466313845e-01 diff --git a/test/reference/cubic_b_spline/nonuniform_default_design_matrix.txt b/test/reference/cubic_b_spline/nonuniform_default_design_matrix.txt new file mode 100644 index 0000000..09472bb --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_design_matrix.txt @@ -0,0 +1,7 @@ +1.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 +8.1303703703703689e-01 1.8006386999244139e-01 6.8514739229024943e-03 4.7619047619047627e-05 0.0000000000000000e+00 0.0000000000000000e+00 +0.0000000000000000e+00 2.1556122448979587e-01 6.2372448979591832e-01 1.6071428571428570e-01 0.0000000000000000e+00 0.0000000000000000e+00 +0.0000000000000000e+00 2.1556072704119905e-01 6.2372466581572972e-01 1.6071460714307143e-01 6.2794348493136592e-20 0.0000000000000000e+00 +0.0000000000000000e+00 5.0235478806907360e-02 5.8712715855573006e-01 3.5478806907378346e-01 7.8492935635792790e-03 0.0000000000000000e+00 +0.0000000000000000e+00 0.0000000000000000e+00 3.2467532467532465e-03 8.2138640580199013e-02 4.5321340406936628e-01 4.6140120210368157e-01 +0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 1.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/nonuniform_default_knots.txt b/test/reference/cubic_b_spline/nonuniform_default_knots.txt new file mode 100644 index 0000000..75678f9 --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_knots.txt @@ -0,0 +1,10 @@ +0.0000000000000000e+00 +0.0000000000000000e+00 +0.0000000000000000e+00 +0.0000000000000000e+00 +1.5000000000000000e+00 +2.7999999999999998e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/nonuniform_default_ordinates.txt b/test/reference/cubic_b_spline/nonuniform_default_ordinates.txt new file mode 100644 index 0000000..3af850f --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_ordinates.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 +1.9866933079506122e-01 +9.9749498660405445e-01 +3.3498815015590511e-01 +-9.7753011766509701e-01 +-9.5892427466313845e-01 diff --git a/test/reference/cubic_b_spline/nonuniform_default_query.txt b/test/reference/cubic_b_spline/nonuniform_default_query.txt new file mode 100644 index 0000000..79c42c4 --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_query.txt @@ -0,0 +1,9 @@ +-5.0000000000000000e-01 +0.0000000000000000e+00 +1.0000000000000001e-01 +1.5000000000000000e+00 +1.5000009999999999e+00 +2.0000000000000000e+00 +4.5000000000000000e+00 +5.0000000000000000e+00 +5.5000000000000000e+00 diff --git a/test/reference/cubic_b_spline/nonuniform_default_query_valid.txt b/test/reference/cubic_b_spline/nonuniform_default_query_valid.txt new file mode 100644 index 0000000..2b7cb69 --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_query_valid.txt @@ -0,0 +1,7 @@ +0.0000000000000000e+00 +1.0000000000000001e-01 +1.5000000000000000e+00 +1.5000009999999999e+00 +2.0000000000000000e+00 +4.5000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/nonuniform_default_sites.txt b/test/reference/cubic_b_spline/nonuniform_default_sites.txt new file mode 100644 index 0000000..7d1965a --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_sites.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 +2.0000000000000001e-01 +1.5000000000000000e+00 +2.7999999999999998e+00 +4.5000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/nonuniform_default_values.txt b/test/reference/cubic_b_spline/nonuniform_default_values.txt new file mode 100644 index 0000000..d672426 --- /dev/null +++ b/test/reference/cubic_b_spline/nonuniform_default_values.txt @@ -0,0 +1,9 @@ +-5.0361013126983034e-01 +0.0000000000000000e+00 +1.0023113224372629e-01 +9.9749498660405433e-01 +9.9749504579621129e-01 +8.9602899079271636e-01 +-9.7753011766509701e-01 +-9.5892427466313845e-01 +-5.7513551504897786e-01 diff --git a/test/reference/cubic_b_spline/uniform_default_coefficients.txt b/test/reference/cubic_b_spline/uniform_default_coefficients.txt new file mode 100644 index 0000000..e7a5212 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_coefficients.txt @@ -0,0 +1,6 @@ +3.0000000000000000e+00 +3.0000000000000000e+00 +-9.9999999999999944e-01 +1.2333333333333332e+01 +4.1333333333333336e+01 +7.8000000000000000e+01 diff --git a/test/reference/cubic_b_spline/uniform_default_design_matrix.txt b/test/reference/cubic_b_spline/uniform_default_design_matrix.txt new file mode 100644 index 0000000..6ff8efb --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_design_matrix.txt @@ -0,0 +1,7 @@ +1.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 +4.2187500000000000e-01 4.7048611111111110e-01 1.0347222222222222e-01 4.1666666666666666e-03 0.0000000000000000e+00 0.0000000000000000e+00 +1.2500000000000000e-01 5.1388888888888884e-01 3.2777777777777772e-01 3.3333333333333333e-02 0.0000000000000000e+00 0.0000000000000000e+00 +1.2499962500037502e-01 5.1388868055509718e-01 3.2777826111109437e-01 3.3333433333433325e-02 0.0000000000000000e+00 0.0000000000000000e+00 +0.0000000000000000e+00 1.3888888888888888e-02 4.8611111111111105e-01 4.8611111111111105e-01 1.3888888888888888e-02 0.0000000000000000e+00 +0.0000000000000000e+00 0.0000000000000000e+00 3.3333333347311128e-20 4.9999982791755568e-13 1.4999987502099303e-06 9.9999850000074986e-01 +0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 0.0000000000000000e+00 1.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/uniform_default_knots.txt b/test/reference/cubic_b_spline/uniform_default_knots.txt new file mode 100644 index 0000000..93ffa11 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_knots.txt @@ -0,0 +1,10 @@ +0.0000000000000000e+00 +0.0000000000000000e+00 +0.0000000000000000e+00 +0.0000000000000000e+00 +2.0000000000000000e+00 +3.0000000000000000e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/uniform_default_ordinates.txt b/test/reference/cubic_b_spline/uniform_default_ordinates.txt new file mode 100644 index 0000000..4e4a6a0 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_ordinates.txt @@ -0,0 +1,6 @@ +3.0000000000000000e+00 +2.0000000000000000e+00 +3.0000000000000000e+00 +1.2000000000000000e+01 +3.5000000000000000e+01 +7.8000000000000000e+01 diff --git a/test/reference/cubic_b_spline/uniform_default_query.txt b/test/reference/cubic_b_spline/uniform_default_query.txt new file mode 100644 index 0000000..fdd0cc5 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_query.txt @@ -0,0 +1,9 @@ +-1.0000000000000000e+00 +0.0000000000000000e+00 +5.0000000000000000e-01 +1.0000000000000000e+00 +1.0000009999999999e+00 +2.5000000000000000e+00 +4.9999989999999999e+00 +5.0000000000000000e+00 +6.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/uniform_default_query_valid.txt b/test/reference/cubic_b_spline/uniform_default_query_valid.txt new file mode 100644 index 0000000..9b68ebd --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_query_valid.txt @@ -0,0 +1,7 @@ +0.0000000000000000e+00 +5.0000000000000000e-01 +1.0000000000000000e+00 +1.0000009999999999e+00 +2.5000000000000000e+00 +4.9999989999999999e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/uniform_default_sites.txt b/test/reference/cubic_b_spline/uniform_default_sites.txt new file mode 100644 index 0000000..7303f13 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_sites.txt @@ -0,0 +1,6 @@ +0.0000000000000000e+00 +1.0000000000000000e+00 +2.0000000000000000e+00 +3.0000000000000000e+00 +4.0000000000000000e+00 +5.0000000000000000e+00 diff --git a/test/reference/cubic_b_spline/uniform_default_values.txt b/test/reference/cubic_b_spline/uniform_default_values.txt new file mode 100644 index 0000000..04c6ec3 --- /dev/null +++ b/test/reference/cubic_b_spline/uniform_default_values.txt @@ -0,0 +1,9 @@ +2.8310687127941492e-15 +3.0000000000000000e+00 +2.6250000000000000e+00 +2.0000000000000000e+00 +1.9999990000009999e+00 +6.1250000000000000e+00 +7.7999945000013000e+01 +7.8000000000000000e+01 +1.4700000000000000e+02 diff --git a/test/runtests.jl b/test/runtests.jl index e9f40dd..41b8c1f 100644 --- a/test/runtests.jl +++ b/test/runtests.jl @@ -64,6 +64,24 @@ using AbstractCosmologicalEmulators include("test_cubic_spline_ad.jl") include("test_spline_plans.jl") + # Cubic B-Spline interpolation tests + include("test_cubic_b_spline_basis.jl") + include("test_cubic_b_spline_solver.jl") + include("test_cubic_b_spline_host_solver.jl") + include("test_cubic_b_spline.jl") + include("test_cubic_b_spline_plan.jl") + include("test_cubic_b_spline_ad.jl") + include("test_cubic_b_spline_plan_pullback.jl") + include("test_cubic_b_spline_streamed_geometry.jl") + include("test_threads.jl") + include("test_cubic_b_spline_gaps.jl") + include("test_cubic_b_spline_dense_operator.jl") + include("test_cubic_b_spline_one_shot_reactant.jl") + include("test_cubic_b_spline_scalar_reactant.jl") + include("test_cubic_b_spline_affine_reactant.jl") + include("test_cubic_b_spline_abstract_inputs.jl") + include("test_reference_scipy.jl") + # Edge cases and additional coverage tests include("test_edge_cases.jl") diff --git a/test/test_chebyshev.jl b/test/test_chebyshev.jl index 8453464..3cadb1f 100644 --- a/test/test_chebyshev.jl +++ b/test/test_chebyshev.jl @@ -276,10 +276,20 @@ using FiniteDifferences end @testset "FFTW Threads" begin - # Test that we can set the thread count without error - @test set_fft_threads(2) === nothing || typeof(set_fft_threads(2)) <: Any - # Reset to 1 to not affect other tests - set_fft_threads(1) + # set_threads configures FFTW; restore the previous state afterwards so + # later tests are not silently forced serial. + ACE = AbstractCosmologicalEmulators + fftw_before = ACE.FFTW.get_num_threads() + host_before = ACE._HOST_THREADS[] + try + @test set_threads(2) === nothing + @test ACE.FFTW.get_num_threads() == 2 + @test (@test_deprecated set_fft_threads(1)) === nothing + @test ACE.FFTW.get_num_threads() == 1 + finally + ACE.FFTW.set_num_threads(fftw_before) + ACE._HOST_THREADS[] = host_before + end end @testset "Mooncake FFTW rules" begin diff --git a/test/test_cubic_b_spline.jl b/test/test_cubic_b_spline.jl new file mode 100644 index 0000000..121824a --- /dev/null +++ b/test/test_cubic_b_spline.jl @@ -0,0 +1,200 @@ +using AbstractCosmologicalEmulators +using Test +using ForwardDiff + +@testset "Cubic B-Spline Evaluator" begin + @testset "Construction and Knot Defaults" begin + x = collect(0.0:1.0:5.0) + u = x.^2 + + # Default (not-a-knot) + spline = CubicBSpline(u, x) + @test internal_knots(spline.basis) == [2.0, 3.0] + @test cubic_b_spline_interpolation(u, x, x) ≈ spline(x) + @test cubic_b_spline_interpolation(u, x, 1.5) ≈ spline(1.5) + + # Knot placement is fixed by the interpolation sites. Custom knot and + # basis configuration is deliberately not part of the high-level API. + T = [0.0, 0.0, 0.0, 0.0, 1.2, 3.8, 5.0, 5.0, 5.0, 5.0] + basis_custom = CubicBSplineBasis(knot_vector=T) + @test_throws MethodError CubicBSpline(u, x; internal_knots=[1.5, 3.5]) + @test_throws MethodError CubicBSpline(u, x; knot_vector=T) + @test_throws MethodError CubicBSpline(u, x; basis=basis_custom) + + # Dimension checks + @test_throws DimensionMismatch CubicBSpline(u[1:end-1], x) + @test_throws DimensionMismatch CubicBSpline(vcat(u, 1.0), x) + @test_throws DimensionMismatch CubicBSpline(hcat(u, u)[1:end-1, :], x) + @test_throws DimensionMismatch CubicBSpline(hcat(u, u)[1:end, :], x[1:end-1]) + + # Zero-column matrix with correct rows + u_zero = zeros(length(x), 0) + spline_zero_col = CubicBSpline(u_zero, x) + @test size(spline_zero_col(1.5)) == (0,) + + # direct solve dimension checks + basis_valid = CubicBSplineBasis(domain=(0.0, 5.0), internal_knots=[2.0, 3.0]) + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis_valid, x) + @test_throws DimensionMismatch AbstractCosmologicalEmulators.solve(fact, u[1:end-1]) + @test_throws DimensionMismatch AbstractCosmologicalEmulators.solve(fact, hcat(u, u)[1:end-1, :]) + end + + @testset "Exact Reproduction" begin + x = collect(0.0:0.5:5.0) + + # Linear + u_lin = 2.0 .* x .+ 1.0 + spline_lin = CubicBSpline(u_lin, x) + @test spline_lin.(x) ≈ u_lin + @test spline_lin([1.25, 2.75]) ≈ (2.0 .* [1.25, 2.75] .+ 1.0) + + # Cubic + u_cub = 0.5 .* x.^3 .- 2.0 .* x.^2 .+ x .- 1.5 + spline_cub = CubicBSpline(u_cub, x) + @test spline_cub(2.1) ≈ (0.5 * 2.1^3 - 2.0 * 2.1^2 + 2.1 - 1.5) atol=1e-12 + end + + @testset "Matrix Ordinates" begin + x = collect(0.0:1.0:5.0) + U = hcat(x.^2, 2.0 .* x) + spline = CubicBSpline(U, x) + + # Scalar query -> Vector + val = spline(1.5) + @test val ≈ [1.5^2, 2.0 * 1.5] atol=1e-12 + + # Vector query -> Matrix + xq = [1.5, 2.5, 3.5] + val_mat = spline(xq) + @test size(val_mat) == (3, 2) + @test val_mat[:, 1] ≈ xq.^2 atol=1e-12 + @test val_mat[:, 2] ≈ 2.0 .* xq atol=1e-12 + @test cubic_b_spline_interpolation(U, x, xq) ≈ val_mat atol=1e-12 + end + + @testset "Extrapolation Policies" begin + x = [0.0, 1.0, 2.0, 3.0] + u = [0.0, 1.0, 8.0, 27.0] + + spline_throw = CubicBSpline(u, x, extrapolation=:throw) + @test_throws ArgumentError spline_throw(-1.0) + @test_throws ArgumentError spline_throw(4.0) + + spline_clamp = CubicBSpline(u, x, extrapolation=:clamp) + @test spline_clamp(-1.0) ≈ spline_clamp(0.0) + @test spline_clamp(4.0) ≈ spline_clamp(3.0) + + spline_default = CubicBSpline(u, x) + @test spline_default(-1.0) ≈ spline_default(0.0) + @test spline_default(4.0) ≈ spline_default(3.0) + @test cubic_b_spline_interpolation(u, x, [-1.0, 4.0]) ≈ + spline_clamp([-1.0, 4.0]) + + @test_throws ArgumentError cubic_b_spline_interpolation( + u, + x, + -1.0; + extrapolation=:throw, + ) + + spline_zero = CubicBSpline(u, x, extrapolation=:zero) + @test spline_zero(-1.0) ≈ 0.0 + @test spline_zero(4.0) ≈ 0.0 + end + + @testset "Generic Arithmetic and Allocations" begin + x = collect(0.0:1.0:5.0) + u = x.^2 + + # Float32 testing + u32 = Float32.(u) + x32 = Float32.(x) + spline32 = CubicBSpline(u32, x32) + @test eltype(spline32.coefficients) == Float32 + @test typeof(spline32(1.5f0)) == Float32 + @test eltype(spline32(Float32[1.5, 2.5])) == Float32 + + # Dual type (ForwardDiff) + u_dual = ForwardDiff.Dual.(u, 1.0) + spline_dual = CubicBSpline(u_dual, x) + @test eltype(spline_dual.coefficients) <: ForwardDiff.Dual + @test typeof(spline_dual(1.5)) <: ForwardDiff.Dual + @test eltype(spline_dual([1.5, 2.5])) <: ForwardDiff.Dual + end + + @testset "Edge Cases and Verification" begin + x = collect(0.0:1.0:5.0) + + # Empty query vectors + spline = CubicBSpline(x.^2, x) + @test isempty(spline(Float64[])) + + spline_mat = CubicBSpline(hcat(x.^2, x.^3), x) + @test isempty(spline_mat(Float64[])) + + # Scalar query with matrix data + @test size(spline_mat(1.5)) == (2,) + @test spline_mat(1.5)[1] ≈ 1.5^2 + @test spline_mat(1.5)[2] ≈ 1.5^3 + + # Polynomial reproduction + @testset "Constant reproduction" begin + u_const = fill(5.0, length(x)) + spline_const = CubicBSpline(u_const, x) + @test spline_const(1.23) ≈ 5.0 + @test spline_const(4.56) ≈ 5.0 + end + + @testset "Quadratic reproduction" begin + u_quad = 2.0 .* x.^2 .- 3.0 .* x .+ 1.0 + spline_quad = CubicBSpline(u_quad, x) + xq = 2.718 + expected = 2.0 * xq^2 - 3.0 * xq + 1.0 + @test spline_quad(xq) ≈ expected + end + + @testset "Nonfinite queries" begin + spline = CubicBSpline(x.^2, x) + spline_mat = CubicBSpline(hcat(x.^2, x.^3), x) + basis = spline.basis + + for bad_q in (NaN, Inf, -Inf) + # Scalar spline queries + @test_throws ArgumentError spline(bad_q) + @test_throws ArgumentError spline_mat(bad_q) + + # Vector spline queries + @test_throws ArgumentError spline([1.0, bad_q, 2.0]) + @test_throws ArgumentError spline_mat([1.0, bad_q, 2.0]) + + # basis_row and basis_matrix + @test_throws ArgumentError basis_row(basis, bad_q) + @test_throws ArgumentError basis_matrix(basis, [1.0, bad_q, 2.0]) + + # CubicBSplinePlan construction + @test_throws ArgumentError CubicBSplinePlan(x, [1.0, bad_q, 2.0]) + + # All extrapolation policies + for policy in (:throw, :clamp, :zero) + spline_p = CubicBSpline(x.^2, x, extrapolation=policy) + @test_throws ArgumentError spline_p(bad_q) + @test_throws ArgumentError spline_p([1.0, bad_q, 2.0]) + end + end + end + + @testset "basis_support bounds" begin + basis = CubicBSplineBasis(domain=(0.0, 5.0), internal_knots=[2.0, 3.0]) + n = AbstractCosmologicalEmulators.nbasis(basis) + + # Valid indices + @test AbstractCosmologicalEmulators.basis_support(basis, 1) isa Tuple + @test AbstractCosmologicalEmulators.basis_support(basis, n) isa Tuple + + # Invalid indices + @test_throws BoundsError AbstractCosmologicalEmulators.basis_support(basis, 0) + @test_throws BoundsError AbstractCosmologicalEmulators.basis_support(basis, -1) + @test_throws BoundsError AbstractCosmologicalEmulators.basis_support(basis, n + 1) + end + end +end diff --git a/test/test_cubic_b_spline_abstract_inputs.jl b/test/test_cubic_b_spline_abstract_inputs.jl new file mode 100644 index 0000000..d9f29ad --- /dev/null +++ b/test/test_cubic_b_spline_abstract_inputs.jl @@ -0,0 +1,69 @@ +using Test +using AbstractCosmologicalEmulators +using ForwardDiff +using Zygote +using Mooncake +using DifferentiationInterface +import ADTypes: AutoMooncake + +@testset "B-spline range, view, and scalar activity" begin + sites = collect(range(0.0, 6.0; length=7)) + queries = [0.45, 1.25, 2.6, 5.2] + values = sin.(sites) .+ 0.2 .* cos.(1.3 .* sites) + backend = AutoMooncake(; config=Mooncake.Config()) + + for ordinates in (values, hcat(values, cos.(sites))) + shape = size(ordinates) + for scalar_query in (2, 2.0f0, 2.0) + @testset "$(typeof(scalar_query)) scalar $(length(shape))-dimensional values" begin + loss(v) = sum(abs2, CubicBSpline(reshape(v, shape), sites)(scalar_query)) + initial = vec(copy(ordinates)) + prep = prepare_gradient(loss, backend, initial) + for input in (initial, initial .+ 0.07, initial) + @test DifferentiationInterface.gradient(loss, prep, backend, input) ≈ ForwardDiff.gradient(loss, input) atol=1e-8 rtol=1e-8 + end + end + end + + for mode in (:spline, :plan, :coefficients), geometry in (:view, :range, :fixed_range, :integer_range) + @testset "$mode $geometry $(length(shape))-dimensional values" begin + n, nq = length(sites), length(queries) + source_input = geometry == :view ? sites : geometry == :range ? [first(sites), last(sites)] : Float64[] + ng = length(source_input) + fixed_range = geometry == :integer_range ? (0:6) : range(first(sites), last(sites); length=n) + initial = vcat(source_input, queries, vec(ordinates)) + function loss(input) + x = if geometry == :view + view(input, 1:n) + elseif geometry == :range + range(input[1], input[2]; length=n) + else + fixed_range + end + q = view(input, ng+1:ng+nq) + u = reshape(view(input, ng+nq+1:length(input)), shape) + result = if mode == :spline + CubicBSpline(u, x)(q) + elseif mode == :plan + CubicBSplinePlan(x, q)(u) + else + bspline_coefficients(CubicBSplinePlan(x, q), u) + end + return sum(abs2, result) + end + prep = prepare_gradient(loss, backend, initial) + changed = initial .+ 0.025 .* cos.(eachindex(initial)) + for input in (initial, changed, initial) + expected = ForwardDiff.gradient(loss, input) + # Zygote cannot differentiate Base's StepRangeLen constructor + # even for sum(abs2, collect(range(...))). Test its fixed-range + # and fully live view paths; Mooncake also checks live endpoints. + if geometry != :range + @test only(Zygote.gradient(loss, input)) ≈ expected atol=1e-8 rtol=1e-8 + end + @test DifferentiationInterface.gradient(loss, prep, backend, input) ≈ expected atol=1e-8 rtol=1e-8 + end + end + end + end +end diff --git a/test/test_cubic_b_spline_ad.jl b/test/test_cubic_b_spline_ad.jl new file mode 100644 index 0000000..87ec252 --- /dev/null +++ b/test/test_cubic_b_spline_ad.jl @@ -0,0 +1,386 @@ +using AbstractCosmologicalEmulators +using Test +using ForwardDiff +using Zygote +using DifferentiationInterface +using Enzyme +import ADTypes: AutoForwardDiff, AutoZygote, AutoMooncake +using Mooncake +using LinearAlgebra +using ChainRulesCore + +@testset "Cubic B-Spline AD" begin + # Shared fixtures for all testsets below. + x = collect(0.0:1.0:5.0) + xq = [0.5, 1.5, 2.5, 3.5, 4.5] + u = @. x^3 - 2x^2 + 3 + + # ----------------------------------------------------------------- + @testset "Plan gradient (ForwardDiff vs Zygote vs Mooncake)" begin + plan = CubicBSplinePlan(x, xq) + + loss_plan(u_in) = sum(abs2, plan(u_in)) + + grad_fd = ForwardDiff.gradient(loss_plan, u) + grad_zy = Zygote.gradient(loss_plan, u)[1] + grad_mc = DifferentiationInterface.gradient( + loss_plan, AutoMooncake(; config=Mooncake.Config()), u) + + @test grad_zy ≈ grad_fd atol=1e-9 + @test grad_mc ≈ grad_fd atol=1e-9 + end + + # ----------------------------------------------------------------- + @testset "Direct spline gradient (ForwardDiff vs Zygote vs Mooncake)" begin + loss_direct(u_in) = sum(abs2, CubicBSpline(u_in, x)(xq)) + + grad_fd = ForwardDiff.gradient(loss_direct, u) + grad_zy = Zygote.gradient(loss_direct, u)[1] + grad_mc = DifferentiationInterface.gradient( + loss_direct, AutoMooncake(; config=Mooncake.Config()), u) + + @test grad_zy ≈ grad_fd atol=1e-9 + @test grad_mc ≈ grad_fd atol=1e-9 + end + + # ----------------------------------------------------------------- + @testset "DifferentiationInterface backend parity" begin + plan = CubicBSplinePlan(x, xq) + U = hcat(u, sin.(x), x .^ 2) + backends = ( + AutoForwardDiff(), + AutoZygote(), + AutoMooncake(; config=Mooncake.Config()), + ) + + losses_and_inputs = ( + (values -> sum(abs2, plan(values)), u), + (values -> sum(abs2, plan(values)), U), + (values -> sum(abs2, CubicBSpline(values, x)(xq)), u), + (values -> sum(abs2, CubicBSpline(values, x)(xq)), U), + ) + + for (loss, input) in losses_and_inputs + reference = DifferentiationInterface.gradient(loss, AutoForwardDiff(), input) + for backend in backends + result = DifferentiationInterface.gradient(loss, backend, input) + @test result ≈ reference atol=1e-9 rtol=1e-12 + end + end + end + + # ----------------------------------------------------------------- + @testset "ForwardDiff Query-Coordinate Derivatives" begin + # Note: cubic B-splines with simple knots are C² at those knots; + # double knots give C¹, triple knots give C⁰. + # This test uses simple knots, so derivatives exist everywhere in the interior. + x_knots = collect(0.0:1.0:5.0) + u_vals = x_knots.^3 .- 2 .* x_knots.^2 .+ 3 + spline = CubicBSpline(u_vals, x_knots) + + # Test a point away from knots + xq_test = 2.5 + + # Finite-difference reference + eps_fd = 1e-5 + val_plus = spline(xq_test + eps_fd) + val_minus = spline(xq_test - eps_fd) + grad_fd_ref = (val_plus - val_minus) / (2 * eps_fd) + + # ForwardDiff derivative + grad_fwd = ForwardDiff.derivative(spline, xq_test) + + @test grad_fwd ≈ grad_fd_ref atol=1e-5 + + # Test vector query gradient + xq_vec = [1.5, 2.5, 3.5] + loss_xq(xq_v) = sum(spline(xq_v)) + grad_xq_fwd = ForwardDiff.gradient(loss_xq, xq_vec) + + grad_xq_ref = similar(xq_vec) + for i in eachindex(xq_vec) + v_plus = copy(xq_vec) + v_plus[i] += eps_fd + v_minus = copy(xq_vec) + v_minus[i] -= eps_fd + grad_xq_ref[i] = (loss_xq(v_plus) - loss_xq(v_minus)) / (2 * eps_fd) + end + + @test grad_xq_fwd ≈ grad_xq_ref atol=1e-5 + end + + # ----------------------------------------------------------------- + @testset "Zero-gradient propagation" begin + # When the output is multiplied by zero the resulting gradient should be zero. + function f_constant(u_in) + spline = CubicBSpline(u_in, x) + return spline(2.5) * 0.0 + end + grad_zygote_zero = Zygote.gradient(f_constant, u)[1] + @test all(iszero, grad_zygote_zero) + + plan = CubicBSplinePlan(x, xq) + function f_plan_constant(u_in) + sum(plan(u_in)) * 0.0 + end + grad_plan_zero = Zygote.gradient(f_plan_constant, u)[1] + @test all(iszero, grad_plan_zero) + end + + # ----------------------------------------------------------------- + @testset "Direct ZeroTangent pullback dispatch" begin + # Test that custom rrules correctly propagate ZeroTangent objects + # through the pullback, returning the correct tangent types at + # each tuple position. + + basis = CubicBSplineBasis(domain=(0.0, 5.0), internal_knots=x[3:end-2]) + stencil = basis_stencil(basis, xq) + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, x) + c_vec = AbstractCosmologicalEmulators.solve(fact, u) + + # --- _evaluate_stencil: vector --- + _, pb_stencil_vec = ChainRulesCore.rrule( + AbstractCosmologicalEmulators._evaluate_stencil, stencil, c_vec) + tangents_sv = pb_stencil_vec(ZeroTangent()) + @test tangents_sv[1] isa NoTangent # function slot + @test tangents_sv[2] isa NoTangent # stencil (structural) + @test tangents_sv[3] isa ZeroTangent # coefficients + @test pb_stencil_vec(NoTangent())[3] isa ZeroTangent + + # --- _evaluate_stencil: matrix --- + U3 = hcat(u, x.^2, sin.(x)) + c_mat = AbstractCosmologicalEmulators.solve(fact, U3) + _, pb_stencil_mat = ChainRulesCore.rrule( + AbstractCosmologicalEmulators._evaluate_stencil, stencil, c_mat) + tangents_sm = pb_stencil_mat(ZeroTangent()) + @test tangents_sm[1] isa NoTangent + @test tangents_sm[2] isa NoTangent + @test tangents_sm[3] isa ZeroTangent + @test pb_stencil_mat(NoTangent())[3] isa ZeroTangent + + # --- solve --- + _, pb_solve = ChainRulesCore.rrule( + AbstractCosmologicalEmulators.solve, fact, u) + tangents_solv = pb_solve(ZeroTangent()) + @test tangents_solv[1] isa NoTangent # function slot + @test tangents_solv[2] isa NoTangent # factorization (structural) + @test tangents_solv[3] isa ZeroTangent # ordinates + @test pb_solve(NoTangent())[3] isa ZeroTangent + + # --- _evaluate_spline: vector --- + row = basis_row(basis, 2.5) + _, pb_eval_vec = ChainRulesCore.rrule( + AbstractCosmologicalEmulators._evaluate_spline, c_vec, row) + tangents_ev = pb_eval_vec(ZeroTangent()) + @test tangents_ev[1] isa NoTangent + @test tangents_ev[2] isa ZeroTangent # coefficients + @test tangents_ev[3] isa NoTangent # row (structural) + @test pb_eval_vec(NoTangent())[2] isa ZeroTangent + + # --- _evaluate_spline: matrix --- + _, pb_eval_mat = ChainRulesCore.rrule( + AbstractCosmologicalEmulators._evaluate_spline, c_mat, row) + tangents_em = pb_eval_mat(ZeroTangent()) + @test tangents_em[1] isa NoTangent + @test tangents_em[2] isa ZeroTangent + @test tangents_em[3] isa NoTangent + @test pb_eval_mat(NoTangent())[2] isa ZeroTangent + end + + # ----------------------------------------------------------------- + @testset "Matrix Flattened Tests (3 Series) with Nonlinear Loss" begin + U3 = hcat(u, x.^2, sin.(x)) + plan3 = CubicBSplinePlan(x, xq) + + function f_mat_nonlin(U_in) + y = plan3(U_in) + sum(y.^2) + sum(exp.(y)) + end + + # Compare Zygote to ForwardDiff element-wise via flattening + grad_zygote_mat = Zygote.gradient(f_mat_nonlin, U3)[1] + + function f_mat_flat(U_flat) + U_reshaped = reshape(U_flat, size(U3)) + f_mat_nonlin(U_reshaped) + end + + grad_fd_flat = ForwardDiff.gradient(f_mat_flat, vec(U3)) + grad_fd_mat = reshape(grad_fd_flat, size(U3)) + + # The exponential term makes some gradient entries O(1e20); compare + # scale-aware rather than demanding an impossible absolute tolerance. + @test grad_zygote_mat ≈ grad_fd_mat atol=1e-9 rtol=1e-12 + + # Mooncake + grad_mooncake_mat = DifferentiationInterface.gradient( + f_mat_nonlin, AutoMooncake(; config=Mooncake.Config()), U3) + @test grad_mooncake_mat ≈ grad_fd_mat atol=1e-9 rtol=1e-12 + end + + @testset "Complete reverse geometry derivatives" begin + sites = Float64[0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0] + values = @. sin(0.8sites) + 0.2cos(1.3sites) + values_matrix = hcat(values, @. cos(0.4sites) - 0.1sin(sites)) + query = [0.45, 1.25, 2.6, 5.2] + mooncake = AutoMooncake(; config=Mooncake.Config()) + + check_reverse(loss, input; atol=1e-9, rtol=1e-9) = begin + reference = ForwardDiff.gradient(loss, input) + zygote = only(Zygote.gradient(loss, input)) + mooncake_gradient = DifferentiationInterface.gradient( + loss, + mooncake, + input, + ) + @test zygote ≈ reference atol=atol rtol=rtol + @test mooncake_gradient ≈ reference atol=atol rtol=rtol + end + + for ordinates in (values, values_matrix) + one_shot_u(v) = sum(abs2, cubic_b_spline_interpolation(v, sites, query)) + one_shot_t(t) = sum(abs2, cubic_b_spline_interpolation(ordinates, t, query)) + one_shot_q(q) = sum(abs2, cubic_b_spline_interpolation(ordinates, sites, q)) + check_reverse(one_shot_u, ordinates) + check_reverse(one_shot_t, sites) + check_reverse(one_shot_q, query) + + prepared_t(t) = sum(abs2, CubicBSpline(ordinates, t)(query)) + prepared_q(q) = sum(abs2, CubicBSpline(ordinates, sites)(q)) + check_reverse(prepared_t, sites) + check_reverse(prepared_q, query) + + plan_t(t) = sum(abs2, CubicBSplinePlan(t, query)(ordinates)) + plan_q(q) = sum(abs2, CubicBSplinePlan(sites, q)(ordinates)) + check_reverse(plan_t, sites) + check_reverse(plan_q, query) + end + + for ordinates in (values, values_matrix) + scalar_loss(q) = sum(abs2, CubicBSpline(ordinates, sites)(q)) + scalar_reference = ForwardDiff.derivative(scalar_loss, 2.35) + @test only(Zygote.gradient(scalar_loss, 2.35)) ≈ scalar_reference atol=1e-9 rtol=1e-9 + @test DifferentiationInterface.derivative( + scalar_loss, + mooncake, + 2.35, + ) ≈ scalar_reference atol=1e-9 rtol=1e-9 + end + + outside_query = [-0.4, 0.6, 6.7] + for policy in (:clamp, :zero), ordinates in (values, values_matrix) + policy_t(t) = sum(abs2, cubic_b_spline_interpolation( + ordinates, + t, + outside_query; + extrapolation=policy, + )) + policy_q(q) = sum(abs2, cubic_b_spline_interpolation( + ordinates, + sites, + q; + extrapolation=policy, + )) + check_reverse(policy_t, sites) + check_reverse(policy_q, outside_query) + end + + throw_t(t) = sum(abs2, cubic_b_spline_interpolation( + values, + t, + query; + extrapolation=:throw, + )) + throw_q(q) = sum(abs2, cubic_b_spline_interpolation( + values, + sites, + q; + extrapolation=:throw, + )) + check_reverse(throw_t, sites) + check_reverse(throw_q, query) + + sites32 = collect(Float32, range(0.0, 6.0; length=7)) + values32 = @. sin(0.8f0 * sites32) + 0.2f0 * cos(1.3f0 * sites32) + query32 = Float32[0.45, 1.25, 2.6, 5.2] + loss_t32(t) = sum(abs2, CubicBSpline(values32, t)(query32)) + loss_q32(q) = sum(abs2, CubicBSpline(values32, sites32)(q)) + check_reverse(loss_t32, sites32; atol=2e-4, rtol=2e-4) + check_reverse(loss_q32, query32; atol=2e-4, rtol=2e-4) + end + + @testset "Plan helper geometry derivatives" begin + sites = Float64[0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0] + values = @. sin(0.8sites) + 0.2cos(1.3sites) + values_matrix = hcat(values, @. cos(0.4sites) - 0.1sin(sites)) + query = [0.45, 1.25, 2.6, 5.2] + mooncake = AutoMooncake(; config=Mooncake.Config()) + + coefficient_loss_vector(t) = sum(abs2, bspline_coefficients( + CubicBSplinePlan(t, query), + values, + )) + coefficient_loss_matrix(t) = sum(abs2, bspline_coefficients( + CubicBSplinePlan(t, query), + values_matrix, + )) + basis_loss(t) = sum(abs2, knot_vector( + bspline_basis(CubicBSplinePlan(t, query)), + )) + stencil_loss(t) = begin + stencil = CubicBSplinePlan(t, query).stencil + return sum(abs2, stencil.w1) + sum(abs2, stencil.w2) + + sum(abs2, stencil.w3) + sum(abs2, stencil.w4) + end + + for loss in ( + coefficient_loss_vector, + coefficient_loss_matrix, + basis_loss, + stencil_loss, + ) + reference = ForwardDiff.gradient(loss, sites) + zygote = only(Zygote.gradient(loss, sites)) + mooncake_gradient = DifferentiationInterface.gradient( + loss, + mooncake, + sites, + ) + @test zygote ≈ reference atol=1e-9 rtol=1e-9 + @test mooncake_gradient ≈ reference atol=1e-9 rtol=1e-9 + end + + plan = CubicBSplinePlan(sites, query) + for ordinates in (values, values_matrix) + coefficient_u_loss(u) = sum(abs2, bspline_coefficients(plan, u)) + reference = ForwardDiff.gradient(coefficient_u_loss, ordinates) + @test only(Zygote.gradient(coefficient_u_loss, ordinates)) ≈ + reference atol=1e-9 rtol=1e-9 + @test DifferentiationInterface.gradient( + coefficient_u_loss, + mooncake, + ordinates, + ) ≈ reference atol=1e-9 rtol=1e-9 + end + + _, coefficients_pullback = ChainRulesCore.rrule( + bspline_coefficients, + plan, + values, + ) + for zero_cotangent in (ZeroTangent(), NoTangent()) + tangents = coefficients_pullback(zero_cotangent) + @test tangents[1] isa NoTangent + @test tangents[2] isa ZeroTangent + @test tangents[3] isa ZeroTangent + end + end + + # ----------------------------------------------------------------- + @testset "Fixed not-a-knot basis" begin + loss_default(u_in) = sum(CubicBSpline(u_in, x)(xq).^2) + grad_zyg_def = Zygote.gradient(loss_default, u)[1] + grad_fd_def = ForwardDiff.gradient(loss_default, u) + @test grad_zyg_def ≈ grad_fd_def atol=1e-9 + end +end diff --git a/test/test_cubic_b_spline_affine_reactant.jl b/test/test_cubic_b_spline_affine_reactant.jl new file mode 100644 index 0000000..4bac06d --- /dev/null +++ b/test/test_cubic_b_spline_affine_reactant.jl @@ -0,0 +1,62 @@ +using Test +using LinearAlgebra +using AbstractCosmologicalEmulators +using Reactant +using Enzyme +using ForwardDiff + +Reactant.set_default_backend("cpu") + +@testset "Reactant custom-basis coefficient solves" begin + ext = Base.get_extension(AbstractCosmologicalEmulators, :ExtReactant) + for n in (12, 17) + sites = collect(range(0.0, 1.0; length=n)) + basis = CubicBSplineBasis(domain=(0.0, 1.0), internal_knots=collect(1:(n-4)) ./ (n-3)) + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, sites) + A = basis_matrix(basis, sites) + changed_sites = sites .+ 0.002 .* sin.(2π .* sites) + changed_fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, changed_sites) + changed_A = basis_matrix(basis, changed_sites) + b = sin.(1.3 .* sites) .+ cos.(7 .* sites) + + # Also exercise the ordinary-array affine implementation, not just the + # separately dispatched traced version used by compiled public solves. + c1, c2, c3 = 0.2 .* cos.(sites), 0.1 .* sin.(sites), fill(0.07, n) + L = Matrix{Float64}(I, n, n) + for i in 1:n, j in 1:min(3, i-1) + L[i, i-j] = (c1, c2, c3)[j][i] + end + for rhs in (b, hcat(b, cos.(2 .* sites), sites .^ 2)) + @test ext._solve_affine_recurrence_scan(rhs, c1, c2, c3) ≈ L \ rhs atol=1e-12 rtol=1e-12 + @test AbstractCosmologicalEmulators.solve(fact, rhs) ≈ A \ rhs atol=1e-11 rtol=1e-11 + + f_R, rhs_R = Reactant.to_rarray(fact), Reactant.to_rarray(rhs) + solve_coefficients(f, r) = AbstractCosmologicalEmulators.solve(f, r) + compiled = Reactant.@compile sync=true donated_args=:none solve_coefficients(f_R, rhs_R) + rhs_gradient(f, r) = Enzyme.gradient(Reverse, u -> sum(abs2, solve_coefficients(f, u)), r) + compiled_gradient = Reactant.@compile sync=true donated_args=:none rhs_gradient(f_R, rhs_R) + + for (factorization, collocation, values) in ( + (fact, A, rhs), (changed_fact, changed_A, rhs .+ 0.17), (fact, A, rhs), + ) + factorization_R = Reactant.to_rarray(factorization) + values_R = Reactant.to_rarray(values) + result = compiled(factorization_R, values_R) + Reactant.synchronize(result) + @test Array(result) ≈ collocation \ values atol=1e-10 rtol=1e-10 + @test collocation * Array(result) ≈ values atol=1e-11 rtol=1e-11 + # A separately computed dense inverse is the ForwardDiff + # reference, independent of both affine-scan implementations. + inverse = collocation \ Matrix{Float64}(I, n, n) + expected_gradient = ForwardDiff.gradient( + v -> sum(abs2, inverse * reshape(v, size(values))), vec(values), + ) + actual_gradient = compiled_gradient(factorization_R, values_R) + Reactant.synchronize(actual_gradient) + @test vec(Array(only(actual_gradient))) ≈ expected_gradient atol=1e-8 rtol=1e-8 + @test Array(values_R) == values + @test Array(factorization_R.bands) == factorization.bands + end + end + end +end diff --git a/test/test_cubic_b_spline_basis.jl b/test/test_cubic_b_spline_basis.jl new file mode 100644 index 0000000..eb78a11 --- /dev/null +++ b/test/test_cubic_b_spline_basis.jl @@ -0,0 +1,117 @@ +using AbstractCosmologicalEmulators +using Test +using Adapt + +@testset "Cubic B-Spline Basis" begin + @testset "Construction and Properties" begin + # Invalid cases + @test_throws ArgumentError CubicBSplineBasis(knot_vector=rand(7)) + @test_throws ArgumentError CubicBSplineBasis(knot_vector=[1.0, 2.0, 1.5, 3.0, 4.0, 5.0, 6.0, 7.0]) + @test_throws ArgumentError CubicBSplineBasis(knot_vector=[1.0, 1.0, 1.0, 2.0, 3.0, 4.0, 5.0, 5.0]) + @test_throws ArgumentError CubicBSplineBasis(knot_vector=[1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0]) # degeneracy at 2.0 + + # NaN / Inf in knot vector + @test_throws ArgumentError CubicBSplineBasis(knot_vector=[0.0, 0.0, 0.0, 0.0, NaN, 2.0, 3.0, 3.0, 3.0, 3.0]) + @test_throws ArgumentError CubicBSplineBasis(domain=(0.0, NaN)) + @test_throws ArgumentError CubicBSplineBasis(domain=(0.0, 3.0), internal_knots=[Inf, 2.0]) + + # Valid from full knot vector + T = [0.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 3.0, 3.0, 3.0] + basis = CubicBSplineBasis(knot_vector=T) + @test knot_vector(basis) == T + @test nbasis(basis) == 6 + @test bspline_domain(basis) == (0.0, 3.0) + @test internal_knots(basis) == [1.0, 2.0] + @test basis_support(basis, 1) == (0.0, 1.0) + @test basis_support(basis, 2) == (0.0, 2.0) + + # Valid from domain and internal knots + basis2 = CubicBSplineBasis(domain=(0.0, 3.0), internal_knots=[1.0, 2.0]) + @test knot_vector(basis2) == T + + # Default knots + basis3 = CubicBSplineBasis(domain=(0.0, 3.0)) + @test knot_vector(basis3) == [0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 3.0] + @test nbasis(basis3) == 4 + end + + @testset "Site Validation" begin + # Short sites + @test_throws ArgumentError AbstractCosmologicalEmulators._validate_bspline_sites([1.0, 2.0, 3.0]) + # Nonfinite sites + @test_throws ArgumentError AbstractCosmologicalEmulators._validate_bspline_sites([1.0, 2.0, NaN, 4.0]) + @test_throws ArgumentError AbstractCosmologicalEmulators._validate_bspline_sites([1.0, 2.0, 3.0, Inf]) + # Unsorted / Duplicates + @test_throws ArgumentError AbstractCosmologicalEmulators._validate_bspline_sites([1.0, 2.0, 2.0, 3.0]) + @test_throws ArgumentError AbstractCosmologicalEmulators._validate_bspline_sites([1.0, 2.0, 1.5, 3.0]) + end + + @testset "Evaluation: partition of unity and positivity" begin + basis = CubicBSplineBasis(domain=(0.0, 3.0), internal_knots=[1.0, 1.5, 2.0]) + + # Test dense points + x_pts = range(0.0, 3.0, length=100) + for x in x_pts + row = basis_row(basis, x) + # positivity + @test all(row.values .>= -1e-14) + # partition of unity + @test sum(row.values) ≈ 1.0 atol=1e-14 + + # test that out-of-bounds yields zero correctly inside the struct + if x < 0.0 || x > 3.0 + @test all(row.values .== 0.0) + end + end + + # Test endpoints exactly + row_left = basis_row(basis, 0.0) + if row_left.indices[1] == 1 + @test row_left.values[1] ≈ 1.0 atol=1e-14 + else + @test row_left.values[4] ≈ 1.0 atol=1e-14 + end + + row_right = basis_row(basis, 3.0) + # N_B is 7 + # basis 7 should be 1.0 at the right endpoint + # indices should be (4, 5, 6, 7) + @test row_right.indices[4] == 7 + @test row_right.values[4] ≈ 1.0 atol=1e-14 + end + + @testset "Basis stencil and matrix" begin + basis = CubicBSplineBasis(domain=(0.0, 3.0), internal_knots=[1.0, 2.0]) + xq = [0.0, 0.5, 1.5, 2.5, 3.0] + + stencil = basis_stencil(basis, xq, extrapolation=:clamp) + @test size(stencil.i1) == (5,) + @test size(stencil.w1) == (5,) + + # Test matrix + B = basis_matrix(basis, xq) + @test size(B) == (5, 6) + @test B[1, 1] ≈ 1.0 + @test B[5, 6] ≈ 1.0 + + # Test extrapolation + @test_throws ArgumentError basis_stencil(basis, [-1.0], extrapolation=:throw) + + stencil_zero = basis_stencil(basis, [-1.0, 4.0], extrapolation=:zero) + @test all(stencil_zero.w1 .== 0.0) + @test all(stencil_zero.w2 .== 0.0) + @test all(stencil_zero.w3 .== 0.0) + @test all(stencil_zero.w4 .== 0.0) + + stencil_eval = basis_stencil(basis, [1.0, 2.0, 3.0]; extrapolation=:throw) + @test stencil_eval isa AbstractCosmologicalEmulators.CubicBSplineStencil + + # Test Adapt for struct + @test Adapt.adapt(Array, basis) isa CubicBSplineBasis + @test Adapt.adapt(Array, stencil_eval) isa AbstractCosmologicalEmulators.CubicBSplineStencil + + stencil_clamp = basis_stencil(basis, [-1.0, 4.0], extrapolation=:clamp) + @test stencil_clamp.w1[1] ≈ 1.0 # clamps to 0.0, first basis is 1.0 + @test stencil_clamp.w4[2] ≈ 1.0 # clamps to 3.0, last basis is 1.0 + end +end diff --git a/test/test_cubic_b_spline_dense_operator.jl b/test/test_cubic_b_spline_dense_operator.jl new file mode 100644 index 0000000..ab3b6bb --- /dev/null +++ b/test/test_cubic_b_spline_dense_operator.jl @@ -0,0 +1,135 @@ +using Test +using Enzyme +using ForwardDiff +using LinearAlgebra +using Reactant + +Reactant.set_default_backend("cpu") + +@testset "Reactant cubic B-spline dense plan operator" begin + @testset "Adjoint operator construction" begin + cases = ( + ( + Float64[0.0, 0.2, 0.7, 1.4, 2.5, 4.0, 6.0], + collect(range(0.0, 6.0; length=23)), + 1e-12, + ), + ( + Float32[0.0, 0.2, 0.7, 1.4, 2.5, 4.0, 6.0], + collect(range(0.0, 6.0; length=23)), + 1e-5, + ), + ( + Float64[0.0, 0.2, 0.7, 1.4, 2.5, 4.0, 6.0], + Float64[0.3, 2.1, 5.4], + 1e-12, + ), + ( + Float32[0.0, 0.2, 0.7, 1.4, 2.5, 4.0, 6.0], + Float64[0.3, 2.1, 5.4], + 1e-6, + ), + ) + + for (sites, query, tolerance) in cases + plan = CubicBSplinePlan(sites, query) + nsites = length(sites) + old_operator = AbstractCosmologicalEmulators._evaluate_stencil( + plan.stencil, + AbstractCosmologicalEmulators.solve( + plan.factorization, + Matrix{eltype(plan.factorization.bands)}(I, nsites, nsites), + ), + ) + new_operator = + AbstractCosmologicalEmulators._build_cubic_bspline_dense_operator( + plan.factorization, + plan.stencil, + nsites, + ) + + @test new_operator ≈ old_operator atol=tolerance rtol=tolerance + @test eltype(new_operator) == promote_type( + eltype(plan.factorization.bands), + eltype(plan.stencil.w1), + ) + end + + skewed_sites = collect(range(0.0, 1.0; length=2000)) + skewed_plan = CubicBSplinePlan(skewed_sites, [0.5]) + AbstractCosmologicalEmulators._build_cubic_bspline_dense_operator( + skewed_plan.factorization, + skewed_plan.stencil, + length(skewed_sites), + ) + allocated = @allocated AbstractCosmologicalEmulators._build_cubic_bspline_dense_operator( + skewed_plan.factorization, + skewed_plan.stencil, + length(skewed_sites), + ) + @test allocated < 1_000_000 + end + + x = collect(0.0:1.0:7.0) + xq = collect(range(0.0, 7.0; length=12)) + u = sin.(x) .+ 0.1 .* cos.(2 .* x) + U = hcat(u, cos.(x), x .^ 2) + plan = CubicBSplinePlan(x, xq; extrapolation=:clamp) + plan_R = Reactant.to_rarray(plan) + operator = Array(plan_R.operator) + @test !hasproperty(plan, :operator) + @test operator * u ≈ plan(u) atol=1e-10 rtol=1e-10 + @test operator * U ≈ plan(U) atol=1e-10 rtol=1e-10 + + u_R = Reactant.to_rarray(u) + U_R = Reactant.to_rarray(U) + + eval_plan(p, values) = p(values) + compiled_vec = Reactant.@compile sync=true eval_plan(plan_R, u_R) + compiled_mat = Reactant.@compile sync=true eval_plan(plan_R, U_R) + + result_vec = compiled_vec(plan_R, u_R) + result_mat = compiled_mat(plan_R, U_R) + Reactant.synchronize(result_vec) + Reactant.synchronize(result_mat) + @test Array(result_vec) ≈ plan(u) atol=1e-10 rtol=1e-10 + @test Array(result_mat) ≈ plan(U) atol=1e-10 rtol=1e-10 + + u_changed = u .+ 0.37 + U_changed = U .+ 0.37 + changed_vec = compiled_vec(plan_R, Reactant.to_rarray(u_changed)) + changed_mat = compiled_mat(plan_R, Reactant.to_rarray(U_changed)) + Reactant.synchronize(changed_vec) + Reactant.synchronize(changed_mat) + @test Array(changed_vec) ≈ plan(u_changed) atol=1e-10 rtol=1e-10 + @test Array(changed_mat) ≈ plan(U_changed) atol=1e-10 rtol=1e-10 + @test !isapprox(Array(changed_vec), Array(result_vec)) + @test !isapprox(Array(changed_mat), Array(result_mat)) + + loss_host(values) = sum(abs2, plan(values)) + loss_reactant(values) = sum(abs2, plan_R(values)) + grad(values) = Enzyme.gradient(Reverse, loss_reactant, values)[1] + grad_ref = ForwardDiff.gradient(loss_host, copy(U)) + compiled_grad = Reactant.@compile sync=true grad(U_R) + result_grad = compiled_grad(U_R) + Reactant.synchronize(result_grad) + @test Array(result_grad) ≈ grad_ref atol=1e-8 rtol=1e-8 + + # Reactant preparation constructs the dense operator only when converting + # the otherwise lean host plan. + x_emulator = collect(range(0.0, 39.0; length=40)) + xq_emulator = collect(range(0.0, 39.0; length=8192)) + emulator_plan = CubicBSplinePlan(x_emulator, xq_emulator; extrapolation=:clamp) + emulator_plan_R = Reactant.to_rarray(emulator_plan) + @test size(emulator_plan_R.operator) == (8192, 40) + + # 512 * 16385 * sizeof(Float64) is just over the 64 MiB Reactant limit. + x_oversized = collect(range(0.0, 511.0; length=512)) + xq_oversized = collect(range(0.0, 511.0; length=16385)) + oversized_plan = CubicBSplinePlan( + x_oversized, + xq_oversized; + extrapolation=:clamp, + ) + @test_throws ArgumentError Reactant.to_rarray(oversized_plan) +end diff --git a/test/test_cubic_b_spline_gaps.jl b/test/test_cubic_b_spline_gaps.jl new file mode 100644 index 0000000..1f61306 --- /dev/null +++ b/test/test_cubic_b_spline_gaps.jl @@ -0,0 +1,133 @@ +using Test +using AbstractCosmologicalEmulators +using ForwardDiff +using Reactant +using Enzyme + +Reactant.set_default_backend("cpu") + +const ext_reactant = Base.get_extension(AbstractCosmologicalEmulators, :ExtReactant) + +const x = collect(0.0:1.0:7.0) +const u = sin.(2π .* x) .+ 0.1 .* cos.(4π .* x) +const U = hcat(u, x.^2, cos.(x)) +const xq = [0.5, 1.5, 2.5, 3.5, 4.5, 5.5] + +@testset "Cubic B-Spline coverage gaps" begin + + # ===================================================== + # A. Reactant Enzyme gradient through CubicBSplinePlan + # ===================================================== + @testset "Reactant Enzyme grad through CubicBSplinePlan (vector)" begin + plan = CubicBSplinePlan(x, xq) + plan_loss(v) = sum(plan(v)) + grad_ref = ForwardDiff.gradient(plan_loss, copy(u)) + + planR = Reactant.to_rarray(plan) + uR = Reactant.to_rarray(u) + reactant_loss(v) = sum(planR(v)) + grad_fun(v) = Enzyme.gradient(Reverse, reactant_loss, v)[1] + f = Reactant.@compile sync=true grad_fun(uR) + gradR = f(uR) + Reactant.synchronize(gradR) + @test Array(gradR) ≈ grad_ref atol=1e-8 rtol=1e-8 + end + + @testset "Reactant Enzyme grad through CubicBSplinePlan (matrix)" begin + plan = CubicBSplinePlan(x, xq) + plan_loss(M) = sum(plan(M)) + grad_ref = ForwardDiff.gradient(plan_loss, copy(U)) + + planR = Reactant.to_rarray(plan) + UR = Reactant.to_rarray(U) + reactant_loss(M) = sum(planR(M)) + grad_fun(M) = Enzyme.gradient(Reverse, reactant_loss, M)[1] + f = Reactant.@compile sync=true grad_fun(UR) + gradR = f(UR) + Reactant.synchronize(gradR) + @test Array(gradR) ≈ grad_ref atol=1e-8 rtol=1e-8 + end + + # ===================================================== + # B. Reactant Enzyme gradient through stencil evaluation + # ===================================================== + @testset "Reactant Enzyme grad through stencil eval (vector)" begin + spl = CubicBSpline(u, x; extrapolation=:clamp) + c_ref = spl.coefficients + basis = spl.basis + stencil = basis_stencil(basis, xq; extrapolation=:clamp) + + loss_c(cv) = sum(AbstractCosmologicalEmulators._evaluate_stencil(stencil, cv)) + grad_ref = ForwardDiff.gradient(loss_c, copy(c_ref)) + + cR = Reactant.to_rarray(c_ref) + loss_eval(c) = sum(AbstractCosmologicalEmulators._evaluate_stencil(stencil, c)) + grad_fn(c) = Enzyme.gradient(Reverse, loss_eval, c)[1] + f = Reactant.@compile sync=true grad_fn(cR) + gradR = f(cR) + Reactant.synchronize(gradR) + @test Array(gradR) ≈ grad_ref atol=1e-8 rtol=1e-8 + end + + # ===================================================== + # C. Host CubicBSplinePlan with Float32 and ForwardDiff Dual + # ===================================================== + @testset "CubicBSplinePlan with Float32" begin + x32 = Float32.(x) + u32 = Float32.(u) + xq32 = Float32.(xq) + plan32 = CubicBSplinePlan(x32, xq32) + out32 = plan32(u32) + @test eltype(out32) == Float32 + plan64 = CubicBSplinePlan(x, xq) + @test Float64.(out32) ≈ plan64(u) atol=1e-5 rtol=1e-5 + end + + @testset "CubicBSplinePlan with ForwardDiff Dual" begin + u_dual = ForwardDiff.Dual.(u, ones(length(u))) + plan = CubicBSplinePlan(x, xq) + out_dual = plan(u_dual) + @test eltype(out_dual) <: ForwardDiff.Dual + @test ForwardDiff.value.(out_dual) ≈ plan(Float64.(u)) + end + + # ===================================================== + # D. Host matrix plan with extrapolation policies + # ===================================================== + @testset "Matrix plan with :clamp" begin + plan_clamp = CubicBSplinePlan(x, xq; extrapolation=:clamp) + out_clamp = plan_clamp(U) + spl_clamp = CubicBSpline(U, x; extrapolation=:clamp) + @test out_clamp ≈ spl_clamp(xq) + end + + @testset "Matrix plan with :zero" begin + xq_out = [-1.0, 0.5, 3.5, 8.0] + plan_zero = CubicBSplinePlan(x, xq_out; extrapolation=:zero) + out_zero = plan_zero(U) + spl_zero = CubicBSpline(U, x; extrapolation=:zero) + @test out_zero ≈ spl_zero(xq_out) + @test all(out_zero[1, :] .== 0.0) + @test all(out_zero[end, :] .== 0.0) + end + + # ===================================================== + # E. Reactant CubicBSpline with non-uniform sites + # ===================================================== + @testset "Reactant CubicBSpline with non-uniform sites" begin + x_nu = [0.0, 0.4, 1.1, 2.0, 3.2, 4.7, 5.5, 6.8, 8.0, 9.3, 10.0] + u_nu = sin.(x_nu) + spl = CubicBSpline(u_nu, x_nu; extrapolation=:clamp) + xq_nu = [0.5, 2.5, 4.5, 6.5, 8.5] + ref = spl(xq_nu) + + spl_R = Reactant.to_rarray(spl) + xqR = Reactant.to_rarray(xq_nu) + eval_s(s, q) = s(q) + f = Reactant.@compile sync=true eval_s(spl_R, xqR) + out = f(spl_R, xqR) + Reactant.synchronize(out) + @test Array(out) ≈ ref atol=1e-10 rtol=1e-10 + end + +end diff --git a/test/test_cubic_b_spline_host_solver.jl b/test/test_cubic_b_spline_host_solver.jl new file mode 100644 index 0000000..50d1d4e --- /dev/null +++ b/test/test_cubic_b_spline_host_solver.jl @@ -0,0 +1,588 @@ +using AbstractCosmologicalEmulators +using Test +using LinearAlgebra +using Random +using ForwardDiff +using DifferentiationInterface +import ADTypes: AutoForwardDiff, AutoMooncake +using Mooncake + +# Stage A/B host solver tests: tight full-band kernels and the exact guarded +# bordered-tridiagonal path, for both the primal and the transpose solve. +# References never call the optimized kernels: a frozen test-only copy of the +# original (af79449) algorithm, dense `A \ S`, and dense reconstructions of the +# stored L and U factors. + +const ACEH = AbstractCosmologicalEmulators + +# ---- frozen baseline: verbatim original generic kernels ---------------------- +function frozen_band_solve!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + for j in 1:n + for i in (j+1):min(n, j+3) + x[i] -= B[4 + i - j, j] * x[j] + end + end + for j in n:-1:1 + x[j] /= B[4, j] + for i in max(1, j-3):(j-1) + x[i] -= B[4 + i - j, j] * x[j] + end + end + return x +end + +function frozen_band_solve_adjoint!(B::AbstractMatrix, x::AbstractVector) + n = length(x) + for j in 1:n + s = x[j] + for i in max(1, j-3):(j-1) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s / B[4, j] + end + for j in n:-1:1 + s = x[j] + for i in (j+1):min(n, j+3) + s -= B[4 + i - j, j] * x[i] + end + x[j] = s + end + return x +end + +function frozen_solve(B, S, kernel!) + X = similar(S, promote_type(eltype(B), eltype(S))) + copyto!(X, S) + for c in 1:size(X, 2) + kernel!(B, view(X, :, c)) + end + return X +end +frozen_solve(B, S) = frozen_solve(B, S, frozen_band_solve!) +frozen_adjoint(B, S) = frozen_solve(B, S, frozen_band_solve_adjoint!) + +# ---- dense references --------------------------------------------------------- +# Dense L (unit lower) and U from seven-row storage, B[4+i-j, j]. +function dense_LU(B::AbstractMatrix{T}) where {T} + n = size(B, 2) + L = Matrix{T}(I, n, n) + U = zeros(T, n, n) + for j in 1:n, r in 1:7 + i = r - 4 + j + (1 <= i <= n) || continue + if i > j + L[i, j] = B[r, j] + else + U[i, j] = B[r, j] + end + end + return L, U +end + +function make_sites(kind::Symbol, n, rng) + if kind == :uniform + return collect(range(0.0, 10.0; length=n)) + elseif kind == :power + return 2.0 .+ 9000.0 .* collect(range(0, 1; length=n)) .^ 2.3 + elseif kind == :cheb + k = 0:(n - 1) + return sort(2.0 .+ 0.5 .* (cos.(pi .* k ./ (n - 1)) .+ 1) .* 8998) + elseif kind == :random + return cumsum(vcat(-3.0, 0.2 .+ rand(rng, n - 1))) + else # :clustered + t = collect(range(0, 1; length=n)) + return 0.5 .+ 4.0 .* (t .+ 0.35 .* sin.(2pi .* t) ./ (2pi)) + end +end + +function actual_factor(x) + basis = CubicBSplineBasis(domain=(first(x), last(x)), internal_knots=x[3:end-2]) + return ACEH.CubicBSplineFactorization(basis, x), basis +end + +# Well-conditioned synthetic factor with the bordered-tridiagonal pattern and +# arbitrary nonzero endpoint entries and both outer couplings. +function synthetic_bordered(::Type{T}, n, rng) where {T} + B = zeros(T, 7, n) + for j in 1:n + B[4, j] = T(1.5 + rand(rng)) + j > 1 && (B[3, j] = T(0.4 * (rand(rng) - 0.5))) + j < n && (B[5, j] = T(0.4 * (rand(rng) - 0.5))) + end + B[6, n-3] = T(0.3 + 0.2 * rand(rng)) + B[2, 4] = T(-0.3 - 0.2 * rand(rng)) + return B +end + +scaled_err(a, b) = maximum(abs, a .- b; init=0.0) / max(maximum(abs, b; init=0.0), 1.0) + +function column_backward_error(A, C, S) + nA = opnorm(A, Inf) + worst = 0.0 + for j in axes(S, 2) + r = norm(A * C[:, j] - S[:, j], Inf) + den = nA * norm(C[:, j], Inf) + norm(S[:, j], Inf) + if den == 0 + r == 0 || return Inf + else + worst = max(worst, r / den) + end + end + return worst +end + +function read_fixture(name) + path = joinpath(@__DIR__, "reference", "bspline_coefficient_solver", name) + rows = [parse.(Float64, split(l)) for l in eachline(path) if !isempty(strip(l))] + return reduce(vcat, (permutedims(r) for r in rows)) +end + +@testset "Cubic B-spline host solver (Stage A/B)" begin + @testset "Frozen text fixtures (public API, dense, frozen solver)" begin + for name in ("power_n17", "random_n33", "cheb_n9", "clustered_n7", "random_n6") + x = vec(read_fixture("$(name)_sites.txt")) + S = read_fixture("$(name)_rhs.txt") + C0 = read_fixture("$(name)_coefficients.txt") + Cd = read_fixture("$(name)_dense_coefficients.txt") + G = read_fixture("$(name)_cotangent.txt") + L0 = read_fixture("$(name)_adjoint.txt") + Ld = read_fixture("$(name)_dense_adjoint.txt") + fact, basis = actual_factor(x) + A = basis_matrix(basis, x) + plan = CubicBSplinePlan(x, x) + + # frozen revision output vs dense reference (fixture sanity) + @test scaled_err(C0, Cd) <= 1e-12 + @test scaled_err(L0, Ld) <= 1e-12 + + for C in ( + ACEH.solve(fact, S), + bspline_coefficients(plan, S), + bspline_coefficients(CubicBSpline(S, x)), + ) + @test scaled_err(C, C0) <= 1e-12 + @test scaled_err(C, Cd) <= 1e-12 + end + @test plan(S) ≈ CubicBSpline(S, x)(x) atol = 1e-11 + L = ACEH.solve_adjoint(fact, G) + @test scaled_err(L, L0) <= 1e-12 + @test scaled_err(L, Ld) <= 1e-12 + @test transpose(A) * L ≈ G atol = 1e-11 + # vector RHS column by column + for c in 1:size(S, 2) + @test scaled_err(ACEH.solve(fact, S[:, c]), C0[:, c]) <= 1e-12 + @test scaled_err(ACEH.solve_adjoint(fact, G[:, c]), L0[:, c]) <= 1e-12 + end + end + end + + @testset "Eligibility is decided by the actual factor contents" begin + rng = Xoshiro(1) + for n in (6, 7, 8, 17, 33, 65, 128, 129) + B = actual_factor(make_sites(:random, n, rng))[1].bands + @test ACEH._is_bordered_tridiagonal_factor(B) + end + # N = 4, 5 use the general path in this first implementation + for n in (4, 5) + B = actual_factor(make_sites(:random, n, rng))[1].bands + @test !ACEH._is_bordered_tridiagonal_factor(B) + end + B0 = synthetic_bordered(Float64, 12, rng) + @test ACEH._is_bordered_tridiagonal_factor(B0) + # Exact tiny nonzero entries anywhere outside the pattern select the + # general kernel; nonzero endpoint entries and outer couplings do not. + n = 12 + for (r, j) in ((1, 4), (1, 12), (7, 1), (7, 9), (2, 3), (2, 5), (2, 12), + (6, 1), (6, n - 4), (6, n - 2), (6, n)) + B = copy(B0) + B[r, j] = nextfloat(0.0) + @test !ACEH._is_bordered_tridiagonal_factor(B) + B[r, j] = -0.0 + @test ACEH._is_bordered_tridiagonal_factor(B) + end + # non-finite or zero pivots, non-finite used entries + for (r, j, v) in ((4, 5, 0.0), (4, 5, NaN), (4, 5, Inf), (3, 5, NaN), + (5, 5, Inf), (2, 4, NaN), (6, n - 3, Inf)) + B = copy(B0) + B[r, j] = v + @test !ACEH._is_bordered_tridiagonal_factor(B) + end + @test !ACEH._is_bordered_tridiagonal_factor(zeros(6, 12)) + @test !ACEH._is_bordered_tridiagonal_factor(zeros(8, 12)) + @test !ACEH._is_bordered_tridiagonal_factor(B0[:, 1:5]) + end + + @testset "Synthetic factors: both couplings and endpoint entries vs dense" begin + rng = Xoshiro(20261020) + for T in (Float64, Float32), n in (6, 7, 17, 33), m in (1, 2, 7, 9) + B = synthetic_bordered(T, n, rng) + @test B[6, n-3] != 0 && B[2, 4] != 0 && B[3, 2] != 0 && B[5, 1] != 0 + @test B[3, n] != 0 && B[5, n-1] != 0 + L, U = dense_LU(B) + Af = L * U + S = randn(rng, T, n, m) + G = randn(rng, T, n, m) + tol = T == Float64 ? 1e-12 : 2e-5 + fact = ACEH.CubicBSplineFactorization(B) + C = ACEH.solve(fact, S) + Lam = ACEH.solve_adjoint(fact, G) + @test eltype(C) == T && eltype(Lam) == T + @test scaled_err(C, Af \ S) <= tol + @test scaled_err(Lam, transpose(Af) \ G) <= tol + @test scaled_err(C, frozen_solve(B, S)) <= tol + @test scaled_err(Lam, frozen_adjoint(B, G)) <= tol + # dot-product adjoint identity + @test abs(dot(G, C) - dot(Lam, S)) <= 50 * tol * (norm(G) * norm(S)) + end + end + + @testset "Real factors across N, sites and RHS counts" begin + rng = Xoshiro(7) + for n in (4, 5, 6, 7, 8, 17, 33, 49, 65, 81, 97, 128, 129), + kind in (:uniform, :power, :cheb, :random, :clustered) + + x = make_sites(kind, n, rng) + fact, basis = actual_factor(x) + A = basis_matrix(basis, x) + for m in (0, 1, 2, 7, 8, 9, 16, 31, 32, 33, 257) + S = randn(rng, n, m) + G = randn(rng, n, m) + C = ACEH.solve(fact, S) + Lam = ACEH.solve_adjoint(fact, G) + @test size(C) == (n, m) && size(Lam) == (n, m) + m == 0 && continue + @test scaled_err(C, A \ S) <= 1e-12 + @test scaled_err(Lam, transpose(A) \ G) <= 1e-12 + @test column_backward_error(A, C, S) <= 100 * eps() + @test column_backward_error(transpose(A), Lam, G) <= 100 * eps() + @test scaled_err(C, frozen_solve(fact.bands, S)) <= 1e-13 + @test scaled_err(Lam, frozen_adjoint(fact.bands, G)) <= 1e-13 + end + end + end + + @testset "Large batch, non-square tails, bit comparison on the general kernel" begin + rng = Xoshiro(11) + x = make_sites(:power, 65, rng) + fact, basis = actual_factor(x) + A = basis_matrix(basis, x) + S = randn(rng, 65, 8192) + G = randn(rng, 65, 8192) + C = ACEH.solve(fact, S) + Lam = ACEH.solve_adjoint(fact, G) + @test scaled_err(C, A \ S) <= 1e-12 + @test scaled_err(Lam, transpose(A) \ G) <= 1e-12 + @test column_backward_error(A, C, S) <= 100 * eps() + # tight full-band kernel is the same arithmetic as the frozen kernel: + # forbid the structured path with an exactly-tiny nonzero outer entry + # and require bitwise equality with the frozen solver. + Bt = copy(fact.bands) + Bt[7, 2] = nextfloat(0.0) + factt = ACEH.CubicBSplineFactorization(Bt) + @test isequal(ACEH.solve(factt, S), frozen_solve(Bt, S)) + @test isequal(ACEH.solve_adjoint(factt, G), frozen_adjoint(Bt, G)) + # explicit general fallback entry point + Xg = copy(S) + ACEH._solve_band_columns_general!(fact.bands, Xg) + @test isequal(Xg, frozen_solve(fact.bands, S)) + # a single column (matrix or vector) takes the full-band kernel, which + # performs the frozen solver's exact operations: bitwise equality + for c in (1, 2, 4097, 8192) + @test isequal(ACEH.solve(fact, S[:, c:c]), frozen_solve(fact.bands, S[:, c:c])) + @test isequal(ACEH.solve(fact, S[:, c]), frozen_solve(fact.bands, S[:, c:c])[:, 1]) + @test isequal(ACEH.solve_adjoint(fact, G[:, c]), + frozen_adjoint(fact.bands, G[:, c:c])[:, 1]) + end + # odd widths exercise every tail + for m in 1:19 + @test scaled_err(ACEH.solve(fact, S[:, 1:m]), C[:, 1:m]) == 0.0 + end + end + + @testset "Dot-product and adjoint identities" begin + rng = Xoshiro(3) + for n in (6, 9, 33, 128) + fact, _ = actual_factor(make_sites(:random, n, rng)) + g = randn(rng, n, 5) + dS = randn(rng, n, 5) + lhs = dot(g, ACEH.solve(fact, dS)) + rhs = dot(ACEH.solve_adjoint(fact, g), dS) + @test abs(lhs - rhs) <= 1e-11 * (norm(g) * norm(dS)) + end + end + + @testset "Hand-built tiny factors (n = 0:5) match the frozen kernels bitwise" begin + rng = Xoshiro(43) + for T in (Float64, Float32), n in 0:5 + B = 0.3 .* randn(rng, T, 7, n) + for j in 1:n + B[4, j] = T(2 + rand(rng)) + end + fact = ACEH.CubicBSplineFactorization(B) + for m in (1, 2, 3) + S = randn(rng, T, n, m) + @test isequal(ACEH.solve(fact, S), frozen_solve(B, S)) + @test isequal(ACEH.solve_adjoint(fact, S), frozen_adjoint(B, S)) + end + if n >= 1 + v = randn(rng, T, n) + @test isequal(ACEH.solve(fact, v), frozen_solve(B, reshape(v, n, 1))[:, 1]) + @test isequal(ACEH.solve_adjoint(fact, v), + frozen_adjoint(B, reshape(v, n, 1))[:, 1]) + end + end + end + + @testset "Exact outer-band fallback" begin + rng = Xoshiro(5) + x = make_sites(:random, 17, rng) + fact, basis = actual_factor(x) + for (r, j) in ((1, 6), (7, 3), (2, 7), (6, 5)) + B = copy(fact.bands) + B[r, j] = 1e-300 + @test !ACEH._is_bordered_tridiagonal_factor(B) + S = randn(rng, 17, 9) + @test isequal(ACEH.solve(ACEH.CubicBSplineFactorization(B), S), + frozen_solve(B, S)) + @test isequal(ACEH.solve_adjoint(ACEH.CubicBSplineFactorization(B), S), + frozen_adjoint(B, S)) + end + end + + @testset "Nonfinite, overflow, signed zero, subnormal" begin + rng = Xoshiro(13) + for T in (Float64, Float32), n in (6, 9, 17) + x = make_sites(:random, n, rng) + fact, _ = actual_factor(x) + B = T.(fact.bands) + f = ACEH.CubicBSplineFactorization(B) + @test ACEH._is_bordered_tridiagonal_factor(B) + for bad in (T(NaN), T(Inf), -T(Inf)), pos in 1:n + S = randn(rng, T, n, 3) + S[pos, 2] = bad + @test isequal(ACEH.solve(f, S), frozen_solve(B, S)) + @test isequal(ACEH.solve_adjoint(f, S), frozen_adjoint(B, S)) + end + # large finite values that overflow during the solve + S = fill(floatmax(T) / 2, n, 4) + S[:, 3] .= -floatmax(T) + S[:, 4] .= randn(rng, T, n) + @test isequal(ACEH.solve(f, S), frozen_solve(B, S)) + @test isequal(ACEH.solve_adjoint(f, S), frozen_adjoint(B, S)) + # non-finite / zero pivot / NaN in a used factor entry + for (r, j, v) in ((4, 3, T(0)), (4, 3, T(NaN)), (3, 4, T(Inf)), (5, 2, T(NaN))) + Bb = copy(B) + Bb[r, j] = v + S = randn(rng, T, n, 3) + @test isequal(ACEH.solve(ACEH.CubicBSplineFactorization(Bb), S), + frozen_solve(Bb, S)) + @test isequal(ACEH.solve_adjoint(ACEH.CubicBSplineFactorization(Bb), S), + frozen_adjoint(Bb, S)) + end + # signed zeros and subnormals are ordinary finite data + Sz = zeros(T, n, 3) + Sz[:, 2] .= -zero(T) + Sz[:, 3] .= T(1e-310 * (T == Float64)) + nextfloat(zero(T)) + C = ACEH.solve(f, Sz) + @test all(iszero, C[:, 1:2]) + @test C == frozen_solve(B, Sz) + @test ACEH.solve_adjoint(f, Sz) == frozen_adjoint(B, Sz) + @test all(isfinite, C) + end + end + + @testset "Immutability" begin + rng = Xoshiro(17) + fact, _ = actual_factor(make_sites(:power, 33, rng)) + S = randn(rng, 33, 12) + S0, B0 = copy(S), copy(fact.bands) + C = ACEH.solve(fact, S) + Lam = ACEH.solve_adjoint(fact, S) + @test S == S0 && fact.bands == B0 + @test C !== S && Lam !== S + S[3, 3] = NaN + S0 = copy(S) + ACEH.solve(fact, S) + ACEH.solve_adjoint(fact, S) + @test isequal(S, S0) && fact.bands == B0 + v = randn(rng, 33) + v0 = copy(v) + ACEH.solve(fact, v) + ACEH.solve_adjoint(fact, v) + @test v == v0 + end + + @testset "Malformed dimensions and factor storage fail safely" begin + rng = Xoshiro(19) + fact, _ = actual_factor(make_sites(:random, 17, rng)) + @test_throws DimensionMismatch ACEH.solve(fact, randn(16)) + @test_throws DimensionMismatch ACEH.solve(fact, randn(18, 3)) + B = fact.bands + S = randn(rng, 17, 4) + # six-row factor: general code raises BoundsError, never reads invalid memory + bad6 = ACEH.CubicBSplineFactorization(B[1:6, :]) + @test_throws BoundsError ACEH.solve(bad6, S) + @test_throws BoundsError ACEH.solve(bad6, S[:, 1]) + @test_throws BoundsError ACEH.solve_adjoint(bad6, S) + # direct kernels with inconsistent shapes + @test_throws BoundsError ACEH._band_solve!(B[:, 1:10], zeros(17)) + @test_throws BoundsError ACEH._band_solve_adjoint!(B[:, 1:10], zeros(17)) + # extra rows are ignored exactly as before + B8 = vcat(B, ones(1, 17)) + @test ACEH.solve(ACEH.CubicBSplineFactorization(B8), S) == + frozen_solve(B8, S) + # matrix solve with a factor whose order mismatches the RHS + @test_throws DimensionMismatch ACEH.solve( + ACEH.CubicBSplineFactorization(B[:, 1:10]), S) + end + + @testset "Types and representations" begin + rng = Xoshiro(23) + x = make_sites(:random, 33, rng) + fact, basis = actual_factor(x) + A = basis_matrix(basis, x) + S = randn(rng, 33, 9) + ref = ACEH.solve(fact, S) + + # Float32 factor and RHS + fact32 = ACEH.CubicBSplineFactorization(Float32.(fact.bands)) + C32 = ACEH.solve(fact32, Float32.(S)) + @test eltype(C32) == Float32 + @test scaled_err(Float64.(C32), A \ Float64.(Float32.(S))) <= 2e-5 + @test eltype(ACEH.solve_adjoint(fact32, Float32.(S))) == Float32 + # mixed precision follows promotion and the general path + Cm = ACEH.solve(fact, Float32.(S)) + @test eltype(Cm) == Float64 + @test isequal(Cm, frozen_solve(fact.bands, Float32.(S))) + Cm2 = ACEH.solve(fact32, S) + @test eltype(Cm2) == Float64 + @test isequal(Cm2, frozen_solve(fact32.bands, S)) + # integer RHS, ranges and views + Si = rand(rng, -5:5, 33, 4) + @test isequal(ACEH.solve(fact, Si), frozen_solve(fact.bands, Si)) + r = 1:33 + @test isequal(ACEH.solve(fact, r), frozen_solve(fact.bands, reshape(collect(r), :, 1))[:, 1]) + Sv = view(S, :, 2:6) + @test isequal(ACEH.solve(fact, Sv), frozen_solve(fact.bands, Sv)) + @test isequal(ACEH.solve(fact, view(S, :, 3)), ref[:, 3]) + # ForwardDiff duals through the RHS and the factor + D = ForwardDiff.Dual.(S[:, 1:3], 1.0) + Cd = ACEH.solve(fact, D) + @test isequal(Cd, frozen_solve(fact.bands, D)) + @test ForwardDiff.value.(Cd) ≈ ref[:, 1:3] atol = 1e-13 + Bd = ForwardDiff.Dual.(fact.bands, 0.5) + @test isequal(ACEH.solve(ACEH.CubicBSplineFactorization(Bd), S[:, 1:3]), + frozen_solve(Bd, S[:, 1:3])) + # BigFloat reference + xb = BigFloat.(collect(range(0, 1; length=9))) .^ 2 + fb, bb = actual_factor(xb) + Ab = basis_matrix(bb, xb) + Sb = BigFloat.(randn(Xoshiro(4), 9, 3)) + Cb = ACEH.solve(fb, Sb) + @test eltype(Cb) == BigFloat + @test maximum(abs, Ab * Cb - Sb) <= 1e-60 + @test maximum(abs, transpose(Ab) * ACEH.solve_adjoint(fb, Sb) - Sb) <= 1e-60 + end + + @testset "Public coefficient API, plan and one-shot paths" begin + rng = Xoshiro(29) + for n in (6, 17, 65) + x = make_sites(:cheb, n, rng) + q = sort(rand(rng, 40) .* (x[end] - x[1]) .+ x[1]) + S = randn(rng, n, 11) + plan = CubicBSplinePlan(x, q) + fact, basis = actual_factor(x) + C = bspline_coefficients(plan, S) + @test C == ACEH.solve(plan.factorization, S) + @test scaled_err(C, basis_matrix(basis, x) \ S) <= 1e-12 + @test plan(S) ≈ CubicBSpline(S, x)(q) atol = 1e-12 + @test bspline_coefficients(CubicBSpline(S, x)) ≈ C atol = 1e-12 + @test cubic_b_spline_interpolation(S, x, q) ≈ plan(S) atol = 1e-12 + @test bspline_coefficients(plan, S[:, 1]) ≈ C[:, 1] atol = 1e-12 + # forced general fallback gives the same coefficients + Xg = copy(S) + ACEH._solve_band_columns_general!(plan.factorization.bands, Xg) + @test scaled_err(C, Xg) <= 1e-13 + end + end + + @testset "Prepared Mooncake vs ForwardDiff (inputs and live geometry)" begin + rng = Xoshiro(31) + n, m = 9, 4 + sites = [0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0, 7.1, 8.5] + q = [0.45, 1.25, 2.6, 5.2, 7.7] + w = randn(rng, length(q), m) + A1 = hcat((sin.(k .* sites) .+ 0.2 .* cos.(1.3 .* sites) for k in 1:m)...) + B1 = randn(rng, n, m) + plan = CubicBSplinePlan(sites, q) + mc = AutoMooncake(; config=Mooncake.Config()) + fd = AutoForwardDiff() + + loss_u(u) = sum(abs2, w .* plan(u)) + loss_c(u) = sum(abs2, bspline_coefficients(plan, u)) + loss_t(t) = sum(abs2, bspline_coefficients(CubicBSplinePlan(t, q), A1)) + loss_tq(t) = sum(w .* CubicBSplinePlan(t, q)(A1)) + + for (loss, a, b) in ((loss_u, A1, B1), (loss_c, A1, B1), (loss_t, sites, sites .+ 0.05 .* sin.(1:n)), + (loss_tq, sites, sites .+ 0.03 .* cos.(1:n))) + prep = DifferentiationInterface.prepare_gradient(loss, mc, a) + a0, b0 = copy(a), copy(b) + g_a1 = DifferentiationInterface.gradient(loss, prep, mc, a) + g_b = DifferentiationInterface.gradient(loss, prep, mc, b) + g_a2 = DifferentiationInterface.gradient(loss, prep, mc, a) + @test g_a1 ≈ DifferentiationInterface.gradient(loss, fd, a) atol = 1e-9 rtol = 1e-9 + @test g_b ≈ DifferentiationInterface.gradient(loss, fd, b) atol = 1e-9 rtol = 1e-9 + @test g_a2 ≈ g_a1 atol = 1e-12 rtol = 1e-12 + @test a == a0 && b == b0 + end + + # interleave two independent plans / preparations + sites2 = sites .+ 0.1 .* sin.(1:n) + plan2 = CubicBSplinePlan(sites2, q) + l1(u) = sum(abs2, bspline_coefficients(plan, u)) + l2(u) = sum(abs2, bspline_coefficients(plan2, u)) + p1 = DifferentiationInterface.prepare_gradient(l1, mc, A1) + p2 = DifferentiationInterface.prepare_gradient(l2, mc, A1) + r1 = DifferentiationInterface.gradient(l1, p1, mc, A1) + r2 = DifferentiationInterface.gradient(l2, p2, mc, A1) + @test DifferentiationInterface.gradient(l1, p1, mc, A1) == r1 + @test DifferentiationInterface.gradient(l2, p2, mc, A1) == r2 + @test r1 ≈ DifferentiationInterface.gradient(l1, fd, A1) atol = 1e-9 + @test r2 ≈ DifferentiationInterface.gradient(l2, fd, A1) atol = 1e-9 + end + + @testset "Larger-batch adjoint against independent dense reference" begin + rng = Xoshiro(37) + n, m = 33, 64 + sites = make_sites(:power, n, rng) + plan = CubicBSplinePlan(sites, sites) + S = randn(rng, n, m) + G = randn(rng, n, m) + A = basis_matrix(plan.basis, sites) + mc = AutoMooncake(; config=Mooncake.Config()) + loss(u) = dot(G, bspline_coefficients(plan, u)) + prep = DifferentiationInterface.prepare_gradient(loss, mc, S) + grad = DifferentiationInterface.gradient(loss, prep, mc, S) + @test scaled_err(grad, transpose(A) \ G) <= 1e-11 + d = randn(rng, n, m) + dd = ForwardDiff.derivative(h -> loss(S .+ h .* d), 0.0) + @test dd ≈ dot(grad, d) rtol = 1e-10 + @test grad ≈ DifferentiationInterface.gradient(loss, prep, mc, S) atol = 1e-13 + end + + @testset "Concurrent read-only plan use" begin + rng = Xoshiro(41) + x = make_sites(:random, 33, rng) + plan = CubicBSplinePlan(x, x) + Ss = [randn(rng, 33, 64) for _ in 1:8] + expected = [bspline_coefficients(plan, S) for S in Ss] + results = Vector{Matrix{Float64}}(undef, 8) + @sync for i in 1:8 + Threads.@spawn begin + results[i] = bspline_coefficients(plan, Ss[i]) + end + end + @test all(results[i] == expected[i] for i in 1:8) + end +end diff --git a/test/test_cubic_b_spline_one_shot_reactant.jl b/test/test_cubic_b_spline_one_shot_reactant.jl new file mode 100644 index 0000000..010c5c4 --- /dev/null +++ b/test/test_cubic_b_spline_one_shot_reactant.jl @@ -0,0 +1,64 @@ +using Test +using Enzyme +using ForwardDiff +using Reactant + +Reactant.set_default_backend("cpu") + +@testset "Reactant public one-shot cubic B-spline" begin + sites = Float64[0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0] + values = @. sin(0.8sites) + 0.2cos(1.3sites) + values_matrix = hcat(values, @. cos(0.4sites) - 0.1sin(sites)) + + for (policy, query) in ( + (:clamp, [0.45, 1.25, 2.6, 5.2]), + (:zero, [-0.4, 0.45, 2.6, 6.5]), + ) + for ordinates in (values, values_matrix) + one_shot(v, q) = cubic_b_spline_interpolation( + v, + sites, + q; + extrapolation=policy, + ) + ordinates_R = Reactant.to_rarray(ordinates) + query_R = Reactant.to_rarray(query) + compiled = Reactant.@compile sync=true one_shot(ordinates_R, query_R) + + result = compiled(ordinates_R, query_R) + Reactant.synchronize(result) + @test Array(result) ≈ one_shot(ordinates, query) atol=1e-10 rtol=1e-10 + + changed_ordinates = ordinates .+ 0.17 + changed_query = query .+ 0.03 + changed = compiled( + Reactant.to_rarray(changed_ordinates), + Reactant.to_rarray(changed_query), + ) + Reactant.synchronize(changed) + @test Array(changed) ≈ one_shot(changed_ordinates, changed_query) atol=1e-10 rtol=1e-10 + @test !isapprox(Array(changed), Array(result)) + + loss(v, q) = sum(abs2, one_shot(v, q)) + gradient(v, q) = Enzyme.gradient(Reverse, loss, v, q) + compiled_gradient = Reactant.@compile sync=true gradient(ordinates_R, query_R) + result_gradient = compiled_gradient(ordinates_R, query_R) + Reactant.synchronize(result_gradient) + + ordinates_reference = if ordinates isa AbstractVector + ForwardDiff.gradient(v -> loss(v, query), ordinates) + else + reshape( + ForwardDiff.gradient( + v -> loss(reshape(v, size(ordinates)), query), + vec(ordinates), + ), + size(ordinates), + ) + end + query_reference = ForwardDiff.gradient(q -> loss(ordinates, q), query) + @test Array(result_gradient[1]) ≈ ordinates_reference atol=1e-8 rtol=1e-8 + @test Array(result_gradient[2]) ≈ query_reference atol=1e-8 rtol=1e-8 + end + end +end diff --git a/test/test_cubic_b_spline_plan.jl b/test/test_cubic_b_spline_plan.jl new file mode 100644 index 0000000..e1c944b --- /dev/null +++ b/test/test_cubic_b_spline_plan.jl @@ -0,0 +1,63 @@ +using AbstractCosmologicalEmulators +using Test + +@testset "Cubic B-Spline Plan" begin + @testset "Plan Construction and Application" begin + x = collect(0.0:1.0:5.0) + xq = [0.5, 1.5, 2.5, 3.5, 4.5] + u = x.^3 .- 2 .* x.^2 .+ 3 + + # Reference one-shot spline + spline = CubicBSpline(u, x) + yq_ref = spline(xq) + + # Plan + plan = CubicBSplinePlan(x, xq) + + custom_basis = CubicBSplineBasis( + domain=(first(x), last(x)), + internal_knots=x[3:end-2], + ) + @test_throws MethodError CubicBSplinePlan(x, xq; internal_knots=x[3:end-2]) + @test_throws MethodError CubicBSplinePlan(x, xq; knot_vector=knot_vector(custom_basis)) + @test_throws MethodError CubicBSplinePlan(x, xq; basis=custom_basis) + yq_plan = plan(u) + + @test yq_plan ≈ yq_ref atol=1e-12 + + # Matrix Ordinates + U = hcat(u, x.^2) + spline_mat = CubicBSpline(U, x) + Yq_ref = spline_mat(xq) + + Yq_plan = plan(U) + @test Yq_plan ≈ Yq_ref atol=1e-12 + + # Test bspline_coefficients extraction + c_plan = bspline_coefficients(plan, u) + @test c_plan ≈ bspline_coefficients(spline) atol=1e-12 + end + + @testset "Extrapolation with Plan" begin + x = collect(0.0:1.0:3.0) + xq = [-1.0, 4.0] + u = x.^2 + + # :throw applies during construction of the plan since xq is out of bounds + @test_throws ArgumentError CubicBSplinePlan(x, xq, extrapolation=:throw) + + # :clamp + plan_clamp = CubicBSplinePlan(x, xq, extrapolation=:clamp) + yq_clamp = plan_clamp(u) + @test yq_clamp ≈ [0.0^2, 3.0^2] atol=1e-12 + + plan_default = CubicBSplinePlan(x, xq) + @test plan_default(u) ≈ yq_clamp atol=1e-12 + + # :zero + plan_zero = CubicBSplinePlan(x, xq, extrapolation=:zero) + yq_zero = plan_zero(u) + @test yq_zero ≈ [0.0, 0.0] atol=1e-12 + end + +end diff --git a/test/test_cubic_b_spline_plan_pullback.jl b/test/test_cubic_b_spline_plan_pullback.jl new file mode 100644 index 0000000..9ae2cd4 --- /dev/null +++ b/test/test_cubic_b_spline_plan_pullback.jl @@ -0,0 +1,373 @@ +using AbstractCosmologicalEmulators +using Test +using LinearAlgebra +using Random +using ForwardDiff +using Zygote +using DifferentiationInterface +import ADTypes: AutoForwardDiff, AutoMooncake, AutoZygote +using Mooncake +using ChainRulesCore + +# Plan coefficient and evaluation pullbacks reuse the plan's cached collocation +# factorization; ordinary splines, which retain none, rebuild it. Reuse is +# observed through the public API without instrumenting the package: a plan +# whose stored factor belongs to deliberately moved ("marked") sites has the +# forward map A_marked⁻¹u. Only a pullback that reads the stored factor returns +# its exact transpose A_marked⁻ᵀ; a rebuilt factor would return A⁻ᵀ instead. + +const ACEP = AbstractCosmologicalEmulators + +pullback_err(a, b) = maximum(abs, a .- b; init=0.0) / max(maximum(abs, b; init=0.0), 1.0) + +# Nonuniform sites on [0, 9] with bounded jitter, well conditioned for all n. +function pullback_sites(n, rng) + t = collect(range(0.0, 1.0; length=n)) + t[2:end-1] .+= (0.3 / (n - 1)) .* (rand(rng, n - 2) .- 0.5) + return 9.0 .* t .^ 1.3 +end + +# Same basis, sites and stencil; only the stored factor comes from other sites. +function marked_plan(plan, marked_sites) + fact = ACEP.CubicBSplineFactorization(plan.basis, marked_sites) + return CubicBSplinePlan(plan.sites, plan.basis, fact, plan.stencil, plan.extrapolation) +end + +# Dense stencil operator S, so plan(u) == S * coefficients. +stencil_matrix(plan) = ACEP._evaluate_stencil( + plan.stencil, + Matrix{Float64}(I, length(plan.sites), length(plan.sites)), +) + +function plan_snapshot(plan) + s = plan.stencil + return ( + copy(plan.sites), copy(knot_vector(plan.basis)), copy(plan.factorization.bands), + copy(s.query), copy(s.w1), copy(s.w2), copy(s.w3), copy(s.w4), + copy(s.i1), copy(s.i2), copy(s.i3), copy(s.i4), + ) +end + +@testset "Cubic B-spline plan pullback factor reuse" begin + mc = AutoMooncake(; config=Mooncake.Config()) + zy = AutoZygote() + fd = AutoForwardDiff() + + @testset "Stored factorization drives coefficient and evaluation pullbacks" begin + rng = Xoshiro(101) + for n in (7, 17), policy in (:clamp, :zero), m in (0, 1, 3) + sites = pullback_sites(n, rng) + spacing = minimum(diff(sites)) + moved = copy(sites) + moved[2:end-1] .+= 0.15 .* spacing .* sin.(1:n-2) + q = vcat(-0.3, sort(rand(rng, 6)) .* 9.0, 9.4) + plan = CubicBSplinePlan(sites, q; extrapolation=policy) + mplan = marked_plan(plan, moved) + A = basis_matrix(plan.basis, sites) + Am = basis_matrix(plan.basis, moved) + S = stencil_matrix(plan) + U = m == 0 ? randn(rng, n) : randn(rng, n, m) + G = randn(rng, size(U)...) + W = randn(rng, length(q), size(U)[2:end]...) + + # The marked plan really solves with the stored factor. + @test pullback_err(bspline_coefficients(mplan, U), Am \ U) <= 1e-11 + @test pullback_err(mplan(U), S * (Am \ U)) <= 1e-11 + + loss_c(u) = dot(G, bspline_coefficients(mplan, u)) + loss_e(u) = dot(W, mplan(u)) + for (loss, stored, rebuilt) in ( + (loss_c, transpose(Am) \ G, transpose(A) \ G), + (loss_e, transpose(Am) \ (transpose(S) * W), transpose(A) \ (transpose(S) * W)), + ) + # The two hypotheses are numerically distinguishable. + @test pullback_err(rebuilt, stored) > 1e-4 + reference = DifferentiationInterface.gradient(loss, fd, U) + @test pullback_err(reference, stored) <= 1e-11 + for backend in (zy, mc) + g = DifferentiationInterface.gradient(loss, backend, U) + @test pullback_err(g, stored) <= 1e-11 + @test g ≈ reference atol = 1e-9 rtol = 1e-9 + end + end + end + end + + @testset "Default plans match the rebuilding path exactly" begin + rng = Xoshiro(103) + n = 17 + sites = pullback_sites(n, rng) + q = vcat(-0.2, sort(rand(rng, 9)) .* 9.0, 9.3) + plan = CubicBSplinePlan(sites, q) + @test ACEP.CubicBSplineFactorization(plan.basis, plan.sites).bands == + plan.factorization.bands + for U in (randn(rng, n), randn(rng, n, 4)) + G = randn(rng, size(U)...) + W = randn(rng, length(q), size(U)[2:end]...) + C = bspline_coefficients(plan, U) + spline = CubicBSpline(plan.sites, plan.basis, C, plan.extrapolation) + + # Coefficient rule versus the reconstructing implementation. + old_u, old_sites, old_knots = ACEP._collocation_geometry_vjp(spline, G) + ACEP._map_not_a_knot_bar!(old_sites, old_knots) + _, pullback = ChainRulesCore.rrule(bspline_coefficients, plan, U) + tangents = pullback(G) + @test tangents[3] == old_u + @test tangents[2].sites == old_sites + + # Evaluation rule versus the reconstructing implementation. + c_bar, eval_sites, eval_knots, eval_query = + ACEP._evaluation_geometry_vjp(spline, plan.stencil.query, W) + old_u, colloc_sites, colloc_knots = ACEP._collocation_geometry_vjp(spline, c_bar) + eval_sites .+= colloc_sites + eval_knots .+= colloc_knots + ACEP._map_not_a_knot_bar!(eval_sites, eval_knots) + _, pullback = ChainRulesCore.rrule(ACEP._apply_cubic_b_spline_plan, plan, U) + tangents = pullback(W) + @test tangents[3] == old_u + @test tangents[2].sites == eval_sites + @test tangents[2].stencil.query == eval_query + + # Native Mooncake primitives return the same cotangents. + loss_c(u) = dot(G, bspline_coefficients(plan, u)) + loss_e(u) = dot(W, plan(u)) + @test DifferentiationInterface.gradient(loss_c, mc, U) ≈ + ChainRulesCore.rrule(bspline_coefficients, plan, U)[2](G)[3] rtol = 1e-14 + @test DifferentiationInterface.gradient(loss_e, mc, U) ≈ old_u rtol = 1e-14 + end + end + + @testset "Ordinary splines rebuild their factorization" begin + rng = Xoshiro(107) + n = 11 + sites = pullback_sites(n, rng) + q = sort(rand(rng, 7)) .* 9.0 + for U in (randn(rng, n), randn(rng, n, 3)) + spline = CubicBSpline(U, sites) + @test !hasproperty(spline, :factorization) + G = randn(rng, size(U)...) + fact = ACEP.CubicBSplineFactorization(spline.basis, spline.sites) + @test ACEP._collocation_geometry_vjp(spline, G) == + ACEP._collocation_geometry_vjp(spline, G, fact) + + W = randn(rng, length(q), size(U)[2:end]...) + loss_u(u) = dot(W, CubicBSpline(u, sites)(q)) + loss_t(t) = dot(W, CubicBSpline(U, t)(q)) + for (loss, x) in ((loss_u, U), (loss_t, sites)) + reference = DifferentiationInterface.gradient(loss, fd, x) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss, backend, x) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + end + end + end + + @testset "Live sites and queries keep their derivatives" begin + rng = Xoshiro(109) + n = 17 + sites = pullback_sites(n, rng) + q = vcat(-0.25, sort(rand(rng, 8)) .* 9.0, 9.2) + for policy in (:clamp, :zero), U in (randn(rng, n), randn(rng, n, 3)) + G = randn(rng, size(U)...) + W = randn(rng, length(q), size(U)[2:end]...) + coeff_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q; extrapolation=policy), U)) + eval_t(t) = dot(W, CubicBSplinePlan(t, q; extrapolation=policy)(U)) + eval_q(x) = dot(W, CubicBSplinePlan(sites, x; extrapolation=policy)(U)) + coeff_q(x) = dot(G, bspline_coefficients(CubicBSplinePlan(sites, x; extrapolation=policy), U)) + for (loss, x) in ((coeff_t, sites), (eval_t, sites), (eval_q, q), (coeff_q, q)) + reference = DifferentiationInterface.gradient(loss, fd, x) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss, backend, x) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + end + # Coefficients do not depend on the query coordinates. + @test iszero(DifferentiationInterface.gradient(coeff_q, zy, q)) + @test iszero(DifferentiationInterface.gradient(coeff_q, mc, q)) + + # A plan passed or captured as a value still receives geometry + # cotangents: it is not silently treated as frozen. + plan = CubicBSplinePlan(sites, q; extrapolation=policy) + coeff_plan(p, u) = dot(G, bspline_coefficients(p, u)) + eval_plan(p, u) = dot(W, p(u)) + for (f, site_ref, query_ref) in ( + (coeff_plan, DifferentiationInterface.gradient(coeff_t, fd, sites), nothing), + (eval_plan, DifferentiationInterface.gradient(eval_t, fd, sites), + DifferentiationInterface.gradient(eval_q, fd, q)), + ) + plan_zy = Zygote.gradient(f, plan, U)[1] + @test plan_zy.sites ≈ site_ref atol = 1e-9 rtol = 1e-9 + cache = Mooncake.prepare_gradient_cache(f, plan, U) + _, (_, plan_mc, _) = Mooncake.value_and_gradient!!(cache, f, plan, U) + @test plan_mc.fields.sites ≈ site_ref atol = 1e-9 rtol = 1e-9 + if query_ref !== nothing + @test plan_zy.stencil.query ≈ query_ref atol = 1e-9 rtol = 1e-9 + @test plan_mc.fields.stencil.fields.query ≈ query_ref atol = 1e-9 rtol = 1e-9 + end + end + end + end + + @testset "Zero cotangents, projection and ownership" begin + rng = Xoshiro(113) + n = 9 + sites = pullback_sites(n, rng) + q = sort(rand(rng, 5)) .* 9.0 + plan = CubicBSplinePlan(sites, q) + U = randn(rng, n, 2) + snapshot = plan_snapshot(plan) + + for rule in (bspline_coefficients, ACEP._apply_cubic_b_spline_plan) + _, pullback = ChainRulesCore.rrule(rule, plan, U) + for zero_cotangent in (ZeroTangent(), NoTangent()) + tangents = pullback(zero_cotangent) + @test tangents[1] isa NoTangent + @test tangents[2] isa ZeroTangent + @test tangents[3] isa ZeroTangent + end + numeric_zero = zeros(rule === bspline_coefficients ? n : length(q), 2) + tangents = pullback(numeric_zero) + @test iszero(tangents[3]) + @test iszero(tangents[2].sites) + @test iszero(numeric_zero) + + cotangent = randn(rng, size(numeric_zero)...) + cotangent0 = copy(cotangent) + pullback(cotangent) + @test cotangent == cotangent0 + end + + # Abstract ordinates: gradients flow back into the parent array. + P = randn(rng, n + 2, 4) + G = randn(rng, n, 2) + W = randn(rng, length(q), 2) + view_c(p) = dot(G, bspline_coefficients(plan, view(p, 2:n+1, 2:3))) + view_e(p) = dot(W, plan(view(p, 2:n+1, 2:3))) + for loss in (view_c, view_e) + reference = DifferentiationInterface.gradient(loss, fd, P) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss, backend, P) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + end + + # Float32 storage with Float64 ordinates uses the stored Float32 factor. + plan32 = CubicBSplinePlan(Float32.(sites), Float32.(q)) + loss32(u) = dot(G, bspline_coefficients(plan32, u)) + reference = DifferentiationInterface.gradient(loss32, fd, U) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss32, backend, U) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + + @test plan_snapshot(plan) == snapshot + end + + @testset "Prepared A/B/A reuse and interleaved preparations" begin + rng = Xoshiro(127) + n, m = 13, 5 + sites = pullback_sites(n, rng) + q = sort(rand(rng, 8)) .* 9.0 + plan = CubicBSplinePlan(sites, q) + plan2 = CubicBSplinePlan(sites .+ 0.05 .* sin.(1:n) .* (1 .< (1:n) .< n), q) + snapshot = plan_snapshot(plan) + W = randn(rng, length(q), m) + G = randn(rng, n, m) + UA, UB = randn(rng, n, m), randn(rng, n, m) + sB = sites .+ 0.04 .* cos.(1:n) .* (1 .< (1:n) .< n) + + loss_c(u) = dot(G, bspline_coefficients(plan, u)) + loss_e(u) = dot(W, plan(u)) + loss_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q), UA)) + loss_tq(t) = dot(W, CubicBSplinePlan(t, q)(UA)) + for backend in (zy, mc) + for (loss, a, b) in ((loss_c, UA, UB), (loss_e, UA, UB), (loss_t, sites, sB), (loss_tq, sites, sB)) + a0, b0 = copy(a), copy(b) + prep = DifferentiationInterface.prepare_gradient(loss, backend, a) + g_a1 = DifferentiationInterface.gradient(loss, prep, backend, a) + g_b = DifferentiationInterface.gradient(loss, prep, backend, b) + g_a2 = DifferentiationInterface.gradient(loss, prep, backend, a) + @test g_a1 ≈ DifferentiationInterface.gradient(loss, fd, a) atol = 1e-9 rtol = 1e-9 + @test g_b ≈ DifferentiationInterface.gradient(loss, fd, b) atol = 1e-9 rtol = 1e-9 + @test g_a2 == g_a1 + @test a == a0 && b == b0 + end + + l1(u) = dot(W, plan(u)) + l2(u) = dot(W, plan2(u)) + p1 = DifferentiationInterface.prepare_gradient(l1, backend, UA) + p2 = DifferentiationInterface.prepare_gradient(l2, backend, UA) + r1 = DifferentiationInterface.gradient(l1, p1, backend, UA) + r2 = DifferentiationInterface.gradient(l2, p2, backend, UA) + @test DifferentiationInterface.gradient(l1, p1, backend, UA) == r1 + @test DifferentiationInterface.gradient(l2, p2, backend, UA) == r2 + @test r1 ≈ DifferentiationInterface.gradient(l1, fd, UA) atol = 1e-9 rtol = 1e-9 + @test r2 ≈ DifferentiationInterface.gradient(l2, fd, UA) atol = 1e-9 rtol = 1e-9 + end + @test plan_snapshot(plan) == snapshot + end + + @testset "Larger batch against dense transpose and directional derivatives" begin + rng = Xoshiro(131) + n, m = 81, 256 + sites = pullback_sites(n, rng) + q = sort(rand(rng, 40)) .* 9.0 + plan = CubicBSplinePlan(sites, q) + A = basis_matrix(plan.basis, sites) + S = stencil_matrix(plan) + U = randn(rng, n, m) + G = randn(rng, n, m) + W = randn(rng, length(q), m) + D = randn(rng, n, m) + loss_c(u) = dot(G, bspline_coefficients(plan, u)) + loss_e(u) = dot(W, plan(u)) + for (loss, dense) in ((loss_c, transpose(A) \ G), (loss_e, transpose(A) \ (transpose(S) * W))) + directional = ForwardDiff.derivative(h -> loss(U .+ h .* D), 0.0) + for backend in (zy, mc) + prep = DifferentiationInterface.prepare_gradient(loss, backend, U) + g = DifferentiationInterface.gradient(loss, prep, backend, U) + @test pullback_err(g, dense) <= 1e-10 + @test dot(g, D) ≈ directional rtol = 1e-10 + end + end + + loss_t(t) = dot(W, CubicBSplinePlan(t, q)(U)) + dt = randn(rng, n) .* (1 .< (1:n) .< n) .* 1e-3 + directional = ForwardDiff.derivative(h -> loss_t(sites .+ h .* dt), 0.0) + for backend in (zy, mc) + g = DifferentiationInterface.gradient(loss_t, backend, sites) + @test dot(g, dt) ≈ directional rtol = 1e-8 + end + end + + @testset "Concurrent gradients on a shared read-only plan" begin + rng = Xoshiro(137) + n, m, ntasks = 33, 16, 8 + sites = pullback_sites(n, rng) + q = sort(rand(rng, 20)) .* 9.0 + plan = CubicBSplinePlan(sites, q) + snapshot = plan_snapshot(plan) + Us = [randn(rng, n, m) for _ in 1:ntasks] + Ws = [randn(rng, length(q), m) for _ in 1:ntasks] + for backend in (zy, mc) + losses = [u -> dot(Ws[i], plan(u)) for i in 1:ntasks] + # Independent preparation per task; only the plan is shared. + preps = [DifferentiationInterface.prepare_gradient(losses[i], backend, Us[i]) + for i in 1:ntasks] + expected = [DifferentiationInterface.gradient(losses[i], preps[i], backend, Us[i]) + for i in 1:ntasks] + results = Vector{Matrix{Float64}}(undef, ntasks) + @sync for i in 1:ntasks + Threads.@spawn begin + for _ in 1:3 + results[i] = DifferentiationInterface.gradient( + losses[i], preps[i], backend, Us[i]) + end + end + end + @test all(results[i] == expected[i] for i in 1:ntasks) + end + @test plan_snapshot(plan) == snapshot + end +end diff --git a/test/test_cubic_b_spline_scalar_reactant.jl b/test/test_cubic_b_spline_scalar_reactant.jl new file mode 100644 index 0000000..70e7134 --- /dev/null +++ b/test/test_cubic_b_spline_scalar_reactant.jl @@ -0,0 +1,53 @@ +using Test +using AbstractCosmologicalEmulators +using Enzyme +using ForwardDiff +using Reactant + +Reactant.set_default_backend("cpu") + +@testset "Reactant dynamic scalar B-spline queries" begin + sites = [0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0] + values = sin.(0.8 .* sites) .+ 0.2 .* cos.(1.3 .* sites) + matrix_values = hcat(values, cos.(0.4 .* sites) .- 0.1 .* sin.(sites)) + for policy in (:clamp, :zero), ordinates in (values, matrix_values) + @testset "$policy $(ndims(ordinates))-dimensional ordinates" begin + spline = CubicBSpline(ordinates, sites; extrapolation=policy) + spline_R = Reactant.to_rarray(spline) + ordinates_R = Reactant.to_rarray(ordinates) + query_R = Reactant.to_rarray(0.45; track_numbers=true) + evaluate(s, q) = s(q) + one_shot(u, q) = cubic_b_spline_interpolation(u, sites, q; extrapolation=policy) + compiled = Reactant.@compile sync=true donated_args=:none evaluate(spline_R, query_R) + compiled_one_shot = Reactant.@compile sync=true donated_args=:none one_shot(ordinates_R, query_R) + query_gradient(s, q) = Enzyme.gradient(Reverse, p -> sum(abs2, s(p)), q) + one_shot_gradient(u, q) = Enzyme.gradient(Reverse, (v, p) -> sum(abs2, one_shot(v, p)), u, q) + compiled_gradient = Reactant.@compile sync=true donated_args=:none query_gradient(spline_R, query_R) + compiled_one_shot_gradient = Reactant.@compile sync=true donated_args=:none one_shot_gradient(ordinates_R, query_R) + + for query in (0.45, 1.25, -0.4, 6.5) + q_R = Reactant.to_rarray(query; track_numbers=true) + expected = spline(query) + for result in (compiled(spline_R, q_R), compiled_one_shot(ordinates_R, q_R)) + Reactant.synchronize(result) + @test size(result) == size(expected) + host_result = ordinates isa AbstractVector ? Float64(result) : Array(result) + @test host_result ≈ expected atol=1e-10 rtol=1e-10 + end + expected_query_gradient = ForwardDiff.derivative(q -> sum(abs2, spline(q)), query) + actual = compiled_gradient(spline_R, q_R) + actual_one_shot = compiled_one_shot_gradient(ordinates_R, q_R) + Reactant.synchronize(actual) + Reactant.synchronize(actual_one_shot) + @test Float64(only(actual)) ≈ expected_query_gradient atol=1e-8 rtol=1e-8 + @test Float64(actual_one_shot[2]) ≈ expected_query_gradient atol=1e-8 rtol=1e-8 + expected_values_gradient = ForwardDiff.gradient( + v -> sum(abs2, one_shot(reshape(v, size(ordinates)), query)), vec(ordinates), + ) + @test vec(Array(actual_one_shot[1])) ≈ expected_values_gradient atol=1e-8 rtol=1e-8 + end + @test Array(ordinates_R) == ordinates + @test Array(spline_R.coefficients) == spline.coefficients + end + end +end diff --git a/test/test_cubic_b_spline_solver.jl b/test/test_cubic_b_spline_solver.jl new file mode 100644 index 0000000..e1104ce --- /dev/null +++ b/test/test_cubic_b_spline_solver.jl @@ -0,0 +1,46 @@ +using AbstractCosmologicalEmulators +using Test +using LinearAlgebra + +@testset "Cubic B-Spline Solver" begin + @testset "Band LU Factorization" begin + # Create a simple basis and points + x = [0.0, 1.0, 2.0, 3.0, 4.0, 5.0] + basis = CubicBSplineBasis(domain=(0.0, 5.0), internal_knots=[1.0, 3.0]) + + # Test constructor + fact = AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, x) + @test size(fact.bands) == (7, 6) + + # Test against dense matrix + A = basis_matrix(basis, x) + + # Test vector solve + u = [1.0, 2.5, 1.2, -0.5, 3.0, 1.0] + c = AbstractCosmologicalEmulators.solve(fact, u) + + @test A * c ≈ u atol=1e-12 + + # Test matrix solve + U = [1.0 2.0; 2.5 1.0; 1.2 0.5; -0.5 -1.0; 3.0 2.0; 1.0 1.0] + C = AbstractCosmologicalEmulators.solve(fact, U) + + @test A * C ≈ U atol=1e-12 + end + + @testset "Schoenberg-Whitney and Singularities" begin + x_bad = [0.0, 1.0, 1.1, 1.2, 4.0, 5.0] + basis = CubicBSplineBasis(domain=(0.0, 5.0), internal_knots=[2.0, 3.0]) + # x_bad[3] = 1.1, but T[3] = 0, T[7] = 3.0. + # Wait, for i=4, x_bad[4] = 1.2. T[4]=0, T[8]=5.0. That's fine. + # Let's make a real S-W violation: x_i not in (T_i, T_{i+4}) + # T = [0, 0, 0, 0, 2, 3, 5, 5, 5, 5] + # For i=2, support is (0, 3). So x_2 must be in (0, 3). + # For i=5, support is (2, 5). So x_5 must be in (2, 5). + # If we put x_5 = 1.0, it violates S-W. + x_sw_violation = [0.0, 1.0, 1.5, 1.8, 1.9, 5.0] + # x_sw_violation[5] = 1.9. But support for B_5 is (T[5], T[9]) = (2, 5). + # So x_5 = 1.9 < T[5] = 2.0. This violates S-W. + @test_throws ArgumentError AbstractCosmologicalEmulators.CubicBSplineFactorization(basis, x_sw_violation) + end +end diff --git a/test/test_cubic_b_spline_streamed_geometry.jl b/test/test_cubic_b_spline_streamed_geometry.jl new file mode 100644 index 0000000..ecbd50e --- /dev/null +++ b/test/test_cubic_b_spline_streamed_geometry.jl @@ -0,0 +1,504 @@ +using AbstractCosmologicalEmulators +using Test +using LinearAlgebra +using Random +using ForwardDiff +using Zygote +using DifferentiationInterface +import ADTypes: AutoForwardDiff, AutoMooncake, AutoZygote +using Mooncake +using ChainRulesCore + +# Dense Float64 batches with at least _STREAMED_GEOMETRY_MIN_COLUMNS columns +# form the collocation geometry reduction column by column. References: +# - a verbatim copy of the previous dot-based routine, which ineligible and +# unsafe inputs must reproduce exactly; +# - an independent sequential streaming oracle, which identifies the fast +# branch bitwise without instrumenting the package; +# - BigFloat reductions with cancellation-aware bounds (error relative to +# Σ|λc|, not to the possibly cancelled result), dense transposes and ForwardDiff. + +const ACES = AbstractCosmologicalEmulators +const SG_MIN_M = ACES._STREAMED_GEOMETRY_MIN_COLUMNS +const SG_ETA = nextfloat(0.0) + +# Previous implementation, verbatim apart from qualified names. +function sg_frozen_dot_vjp(spline, c_bar, fact) + c = spline.coefficients + sites = spline.sites + ordinates_bar = ACES.solve_adjoint(fact, c_bar) + T = knot_vector(spline.basis) + V = promote_type(eltype(c), eltype(c_bar), eltype(T), eltype(sites)) + sites_bar = zeros(V, length(sites)) + knot_bar = zeros(V, length(T)) + for i in eachindex(sites) + row = basis_row(spline.basis, sites[i]) + if c isa AbstractVector + values_bar = ntuple(k -> -ordinates_bar[i] * c[row.indices[k]], 4) + else + values_bar = ntuple( + k -> -dot(@view(ordinates_bar[i, :]), @view(c[row.indices[k], :])), + 4, + ) + end + span = row.indices[4] + x_bar, local_knot_bar = ACES._cubic_basis_vjp(T, span, sites[i], values_bar) + sites_bar[i] += x_bar + ACES._accumulate_local_knot_bar!(knot_bar, span, local_knot_bar) + end + return ordinates_bar, sites_bar, knot_bar +end + +sg_rows(spline) = [basis_row(spline.basis, x).indices for x in spline.sites] + +# Float64 assembly of given local cotangents (4×n), as in the VJP. +function sg_assemble(spline, rows, values_bar) + T = knot_vector(spline.basis) + sites_bar = zeros(length(spline.sites)) + knot_bar = zeros(length(T)) + for i in eachindex(spline.sites) + x_bar, local_knot_bar = ACES._cubic_basis_vjp( + T, rows[i][4], spline.sites[i], Tuple(values_bar[:, i])) + sites_bar[i] += x_bar + ACES._accumulate_local_knot_bar!(knot_bar, rows[i][4], local_knot_bar) + end + return sites_bar, knot_bar +end + +# Independent sequential column-order reduction of Λ = A⁻ᵀC̄. +function sg_streamed_reference(spline, Λ) + C = spline.coefficients + n, M = size(C) + rows = sg_rows(spline) + P = zeros(4, n) + for s in 1:M, i in 1:n, k in 1:4 + P[k, i] += Λ[i, s] * C[rows[i][k], s] + end + return -P, rows +end + +function sg_streamed_vjp(spline, c_bar, fact) + Λ = ACES.solve_adjoint(fact, c_bar) + values_bar, rows = sg_streamed_reference(spline, Λ) + return (Λ, sg_assemble(spline, rows, values_bar)...) +end + +# Exact local values_bar and Σ|λc| for sites `idx`, rounded once to Float64. +function sg_exact_values_bar(spline, Λ, idx) + C = spline.coefficients + rows = sg_rows(spline) + vb = zeros(4, length(idx)) + absum = zeros(4, length(idx)) + setprecision(BigFloat, 256) do + for (col, i) in enumerate(idx), k in 1:4 + s = big(0.0) + a = big(0.0) + for t in axes(Λ, 2) + p = big(Λ[i, t]) * big(C[rows[i][k], t]) + s += p + a += abs(p) + end + vb[k, col] = Float64(-s) + absum[k, col] = Float64(a) + end + end + return vb, absum +end + +# Recursive-summation error allowance for one local entry, M terms. +sg_entry_bound(absum, M) = (M + 16) * eps() .* absum .+ 2M * SG_ETA + +# Absolute allowance for underflow in the at most ~40 rounded assembly and +# knot-accumulation operations behind one output entry. +const SG_ASSEMBLY_ETA = 64 * SG_ETA + +# Propagate per-entry bounds W (4×n) through |local basis partials|. +function sg_propagate(spline, W) + T = knot_vector(spline.basis) + rows = sg_rows(spline) + sb = zeros(length(spline.sites)) + kb = zeros(length(T)) + for i in eachindex(spline.sites) + span = rows[i][4] + jets = ACES._cubic_basis_jets(T, span, spline.sites[i], Float64) + for k in 1:4 + D = jets[k].partials + sb[i] += abs(D[1]) * W[k, i] + for m in 1:6 + kb[span-3+m] += abs(D[m+1]) * W[k, i] + end + end + end + return sb, kb +end + +within(a, b, bound) = all(abs.(a .- b) .<= bound) + +# Full BigFloat check: new and previous VJPs each lie within the propagated +# cancellation-aware reduction bound of the exact reduction (same assembly). +function sg_check_against_exact(spline, c_bar, fact) + new = ACES._collocation_geometry_vjp(spline, c_bar, fact) + old = sg_frozen_dot_vjp(spline, c_bar, fact) + M = size(c_bar, 2) + vb, absum = sg_exact_values_bar(spline, new[1], eachindex(spline.sites)) + ref_sites, ref_knots = sg_assemble(spline, sg_rows(spline), vb) + sb, kb = sg_propagate(spline, sg_entry_bound(absum, M)) + streamed_vb, _ = sg_streamed_reference(spline, new[1]) + return ( + reduction=within(streamed_vb, vb, sg_entry_bound(absum, M)), + new=within(new[2], ref_sites, sb .+ SG_ASSEMBLY_ETA) && + within(new[3], ref_knots, kb .+ SG_ASSEMBLY_ETA), + old=within(old[2], ref_sites, sb .+ SG_ASSEMBLY_ETA) && + within(old[3], ref_knots, kb .+ SG_ASSEMBLY_ETA), + finite=all(isfinite, new[2]) && all(isfinite, new[3]), + ) +end + +# Large cases: new versus previous with twice the per-entry allowance +# (Float64 absolute sums), plus BigFloat on a sample of sites. +function sg_check_against_previous(spline, c_bar, fact; sample=12) + new = ACES._collocation_geometry_vjp(spline, c_bar, fact) + old = sg_frozen_dot_vjp(spline, c_bar, fact) + Λ = new[1] + C = spline.coefficients + rows = sg_rows(spline) + n, M = size(C) + absum = [sum(abs, Λ[i, :] .* C[rows[i][k], :]) for k in 1:4, i in 1:n] + sb, kb = sg_propagate(spline, 2 .* sg_entry_bound(1.01 .* absum, M)) + idx = unique(round.(Int, range(1, n; length=sample))) + vb, ab = sg_exact_values_bar(spline, Λ, idx) + streamed_vb, _ = sg_streamed_reference(spline, Λ) + return ( + pair=within(new[2], old[2], sb .+ 2SG_ASSEMBLY_ETA) && + within(new[3], old[3], kb .+ 2SG_ASSEMBLY_ETA), + sampled=within(streamed_vb[:, idx], vb, sg_entry_bound(ab, M)), + ordinates=new[1] == old[1], + ) +end + +function sg_fast_branch(spline, c_bar, fact) + Λ = ACES.solve_adjoint(fact, c_bar) + sb = zeros(length(spline.sites)) + kb = zeros(length(knot_vector(spline.basis))) + return ACES._streamed_collocation_geometry!(sb, kb, spline, c_bar, Λ) +end + +sg_uniform(n) = collect(range(0.0, 9.0; length=n)) +sg_cheb(n) = sort(2.0 .+ 0.5 .* (cos.(pi .* (0:n-1) ./ (n - 1)) .+ 1) .* 8998) +sg_adaptive_k(n) = parse.(Float64, readlines(joinpath( + @__DIR__, "reference", "bspline_adaptive_sites", "adaptive_design_N$(n).txt"))) +sg_adaptive_logk(n) = log.(sg_adaptive_k(n)) + +function sg_case(sites, M, rng; C=nothing, c_bar=nothing) + plan = CubicBSplinePlan(sites, sites[2:end-1]) + coefficients = C === nothing ? + bspline_coefficients(plan, randn(rng, eltype(sites), length(sites), M)) : C + spline = CubicBSpline(plan.sites, plan.basis, coefficients, plan.extrapolation) + G = c_bar === nothing ? randn(rng, size(coefficients)...) : c_bar + return spline, G, plan.factorization, plan +end + +sg_snapshot(spline, G, fact) = deepcopy(( + G, spline.coefficients, spline.sites, knot_vector(spline.basis), fact.bands)) + +function sg_mapped(sites_bar, knot_bar) + s = copy(sites_bar) + ACES._map_not_a_knot_bar!(s, copy(knot_bar)) + return s +end + +@testset "Cubic B-spline streamed collocation geometry" begin + mc = AutoMooncake(; config=Mooncake.Config()) + zy = AutoZygote() + fd = AutoForwardDiff() + + @testset "Ineligible inputs keep the previous routine exactly" begin + rng = Xoshiro(201) + for M in (1, 7, 256, SG_MIN_M - 1) + spline, G, fact, _ = sg_case(sg_adaptive_logk(81), M, rng) + @test !sg_fast_branch(spline, G, fact) + @test isequal(ACES._collocation_geometry_vjp(spline, G, fact), + sg_frozen_dot_vjp(spline, G, fact)) + end + + sites = sg_cheb(17) + spline, G, fact, plan = sg_case(sites, SG_MIN_M, rng) + cases = Any[] + vector_spline = CubicBSpline(plan.sites, plan.basis, spline.coefficients[:, 1], plan.extrapolation) + push!(cases, (vector_spline, G[:, 1], fact)) + push!(cases, (spline, view(hcat(G, G), :, 1:SG_MIN_M), fact)) + view_spline = CubicBSpline(plan.sites, plan.basis, view(spline.coefficients, :, :), plan.extrapolation) + push!(cases, (view_spline, G, fact)) + s32, G32, f32, _ = sg_case(Float32.(sites), SG_MIN_M, rng; c_bar=randn(rng, Float32, 17, SG_MIN_M)) + push!(cases, (s32, G32, f32)) + p32 = CubicBSplinePlan(Float32.(sites), Float32.(sites[2:end-1])) + mixed = CubicBSpline(p32.sites, p32.basis, bspline_coefficients(p32, randn(rng, 17, SG_MIN_M)), p32.extrapolation) + push!(cases, (mixed, G, p32.factorization)) + setprecision(BigFloat, 128) do + sb = big.(sg_uniform(6)) + pb = CubicBSplinePlan(sb, sb[2:end-1]) + Cb = bspline_coefficients(pb, big.(randn(rng, 6, SG_MIN_M))) + push!(cases, (CubicBSpline(pb.sites, pb.basis, Cb, pb.extrapolation), + big.(randn(rng, 6, SG_MIN_M)), pb.factorization)) + end + for (sp, cb, f) in cases + before = sg_snapshot(sp, cb, f) + @test !sg_fast_branch(sp, cb, f) + @test isequal(ACES._collocation_geometry_vjp(sp, cb, f), sg_frozen_dot_vjp(sp, cb, f)) + @test isequal(sg_snapshot(sp, cb, f), before) + end + end + + @testset "Eligible batches take the streamed branch" begin + rng = Xoshiro(203) + grids = (sg_uniform(4), sg_uniform(5), sg_cheb(6), sg_cheb(7), sg_cheb(17), + sg_adaptive_logk(81), sg_adaptive_k(81), sg_adaptive_logk(97)) + for sites in grids, M in (SG_MIN_M, 1031) + spline, G, fact, _ = sg_case(sites, M, rng) + before = sg_snapshot(spline, G, fact) + @test sg_fast_branch(spline, G, fact) + new = ACES._collocation_geometry_vjp(spline, G, fact) + @test isequal(new, sg_streamed_vjp(spline, G, fact)) + @test new[1] == sg_frozen_dot_vjp(spline, G, fact)[1] + @test isequal(sg_snapshot(spline, G, fact), before) + end + + # Ordinary splines (rebuilding entry point) use the same branch. + sites = sg_cheb(9) + U = randn(rng, 9, SG_MIN_M) + spline = CubicBSpline(U, sites) + G = randn(rng, 9, SG_MIN_M) + fact = ACES.CubicBSplineFactorization(spline.basis, spline.sites) + @test isequal(ACES._collocation_geometry_vjp(spline, G), sg_streamed_vjp(spline, G, fact)) + + # Large production shape. + spline, G, fact, _ = sg_case(sg_adaptive_logk(129), 8192, rng) + @test sg_fast_branch(spline, G, fact) + @test isequal(ACES._collocation_geometry_vjp(spline, G, fact), sg_streamed_vjp(spline, G, fact)) + end + + @testset "Cancellation-aware agreement with exact reductions" begin + rng = Xoshiro(207) + for sites in (sg_uniform(4), sg_uniform(5), sg_cheb(6), sg_cheb(7), sg_cheb(17), + sg_adaptive_logk(81), sg_adaptive_k(81)) + spline, G, fact, _ = sg_case(sites, SG_MIN_M, rng) + r = sg_check_against_exact(spline, G, fact) + @test r.reduction + @test r.new + @test r.old + @test r.finite + end + for (sites, M) in ((sg_adaptive_logk(81), 8192), (sg_adaptive_logk(97), 2048), + (sg_adaptive_logk(129), 8192), (sg_adaptive_k(129), 8192)) + spline, G, fact, _ = sg_case(sites, M, rng) + r = sg_check_against_previous(spline, G, fact) + @test r.pair + @test r.sampled + @test r.ordinates + end + end + + @testset "Extreme ranges, cancellation, nonfinite values and tiny spacings" begin + rng = Xoshiro(211) + sites = sg_uniform(7) + M = SG_MIN_M + _, _, fact, plan = sg_case(sites, M, rng) + signs = rand(rng, (-1.0, 1.0), 7, M) + + # Huge, strongly cancelling products below the bound: streamed, finite + # and within the cancellation-aware allowance of the exact reduction. + for (C_scale, G_scale) in ((1e150, 1e148), (1.0, 1e290)) + C = C_scale .* signs .* (1 .+ 0.01 .* rand(rng, 7, M)) + spline, G, _, _ = sg_case(sites, M, rng; C=C, c_bar=G_scale .* randn(rng, 7, M)) + @test sg_fast_branch(spline, G, fact) + r = sg_check_against_exact(spline, G, fact) + @test r.reduction && r.new && r.old && r.finite + end + + # Beyond the bound, nonfinite or overflow-prone: the previous routine, + # bit for bit, including its NaN/Inf pattern. + C = randn(rng, 7, M) + unsafe = Any[ + (C, 1e306 .* randn(rng, 7, M)), + (1e200 .* C, 1e120 .* randn(rng, 7, M)), + ] + for (i, j, value) in ((3, 5, NaN), (1, 1, Inf), (7, M, -Inf)) + G = randn(rng, 7, M); G[i, j] = value + push!(unsafe, (C, G)) + Cn = copy(C); Cn[i, j] = value + push!(unsafe, (Cn, randn(rng, 7, M))) + end + Cinf = copy(C); Cinf[4, 2] = Inf + G0 = randn(rng, 7, M); G0[:, 2] .= 0 + push!(unsafe, (Cinf, G0)) + for (Cu, Gu) in unsafe + spline, G, _, _ = sg_case(sites, M, rng; C=Cu, c_bar=Gu) + @test !sg_fast_branch(spline, G, fact) + @test isequal(ACES._collocation_geometry_vjp(spline, G, fact), + sg_frozen_dot_vjp(spline, G, fact)) + end + nan_spline, nan_G, _, _ = sg_case(sites, M, rng; C=C, c_bar=unsafe[3][2]) + @test any(isnan, ACES._collocation_geometry_vjp(nan_spline, nan_G, fact)[2]) + + # Order-dependent overflow: sequential partial sums exceed floatmax + # although the exact sum is zero. The bound rejects it. + big_value = 0.6 * floatmax(Float64) + Λ = zeros(7, M) + Λ[1, :] .= [isodd(cld(s, 2)) ? big_value : -big_value for s in 1:M] + spline, G, _, _ = sg_case(sites, M, rng; C=ones(7, M), c_bar=randn(rng, 7, M)) + sb, kb = zeros(7), zeros(11) + @test !ACES._streamed_collocation_geometry!(sb, kb, spline, G, Λ) + @test iszero(sb) && iszero(kb) + + # Subnormal products and zero cotangents. + spline, G, _, _ = sg_case(sites, M, rng; C=1e-160 .* randn(rng, 7, M), + c_bar=1e-160 .* randn(rng, 7, M)) + @test sg_fast_branch(spline, G, fact) + r = sg_check_against_exact(spline, G, fact) + @test r.reduction && r.new && r.old && r.finite + spline, G, _, _ = sg_case(sites, M, rng; c_bar=zeros(7, M)) + @test sg_fast_branch(spline, G, fact) + result = ACES._collocation_geometry_vjp(spline, G, fact) + @test iszero(result[1]) && iszero(result[2]) && iszero(result[3]) + + # Tiny nonzero knot intervals. + for gap in (1e-6, 1e-9) + tiny = collect(range(0.0, 1.0; length=9)) + tiny[5] = tiny[4] + gap + spline, G, f, _ = sg_case(tiny, M, rng) + @test sg_fast_branch(spline, G, f) + r = sg_check_against_exact(spline, G, f) + @test r.reduction && r.new && r.old && r.finite + end + end + + @testset "Public coefficient and evaluation gradients" begin + rng = Xoshiro(213) + M = SG_MIN_M + for n in (4, 5, 6, 7) + sites = sg_cheb(n) + q = vcat(sites[1] - 50.0, (sites[1:end-1] .+ sites[2:end]) ./ 2, sites[end] + 30.0) + plan = CubicBSplinePlan(sites, q) + U = randn(rng, n, M) + G = randn(rng, n, M) + W = randn(rng, length(q), M) + coeff_u(u) = dot(G, bspline_coefficients(plan, u)) + eval_u(u) = dot(W, plan(u)) + coeff_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q), U)) + eval_t(t) = dot(W, CubicBSplinePlan(t, q)(U)) + eval_q(x) = dot(W, CubicBSplinePlan(sites, x)(U)) + spline_t(t) = dot(W, CubicBSpline(U, t)(q)) + spline_u(u) = dot(W, CubicBSpline(u, sites)(q)) + for (loss, x) in ((coeff_u, U), (eval_u, U), (coeff_t, sites), (eval_t, sites), + (eval_q, q), (spline_t, sites), (spline_u, U)) + reference = DifferentiationInterface.gradient(loss, fd, x) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss, backend, x) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + end + + # The public rules return the streamed cotangents. + C = bspline_coefficients(plan, U) + spline = CubicBSpline(plan.sites, plan.basis, C, plan.extrapolation) + expected = sg_streamed_vjp(spline, G, plan.factorization) + tangents = ChainRulesCore.rrule(bspline_coefficients, plan, U)[2](G) + @test tangents[3] == expected[1] + @test tangents[2].sites == sg_mapped(expected[2], expected[3]) + f(p, u) = dot(G, bspline_coefficients(p, u)) + cache = Mooncake.prepare_gradient_cache(f, plan, U) + _, (_, plan_mc, u_mc) = Mooncake.value_and_gradient!!(cache, f, plan, U) + @test plan_mc.fields.sites == sg_mapped(expected[2], expected[3]) + @test u_mc == expected[1] + end + + # Production shapes on saved adaptive log-k sites. + for (n, M) in ((81, 8192), (97, 1024), (129, 8192)) + sites = sg_adaptive_logk(n) + q = collect(range(sites[1], sites[end]; length=2n)) + plan = CubicBSplinePlan(sites, q) + A = basis_matrix(plan.basis, sites) + S = ACES._evaluate_stencil(plan.stencil, Matrix{Float64}(I, n, n)) + U = randn(rng, n, M) + G = randn(rng, n, M) + W = randn(rng, length(q), M) + D = randn(rng, n, M) + dt = randn(rng, n) .* (1 .< (1:n) .< n) .* (1e-3 * minimum(diff(sites))) + coeff_u(u) = dot(G, bspline_coefficients(plan, u)) + eval_u(u) = dot(W, plan(u)) + coeff_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q), U)) + eval_t(t) = dot(W, CubicBSplinePlan(t, q)(U)) + dense_c = transpose(A) \ G + dense_e = transpose(A) \ (transpose(S) * W) + for (loss, dense) in ((coeff_u, dense_c), (eval_u, dense_e)) + directional = ForwardDiff.derivative(h -> loss(U .+ h .* D), 0.0) + for backend in (zy, mc) + g = DifferentiationInterface.gradient(loss, backend, U) + @test maximum(abs, g .- dense) / max(1, maximum(abs, dense)) <= 1e-10 + @test dot(g, D) ≈ directional rtol = 1e-10 + end + end + for loss in (coeff_t, eval_t) + directional = ForwardDiff.derivative(h -> loss(sites .+ h .* dt), 0.0) + g_zy = DifferentiationInterface.gradient(loss, zy, sites) + g_mc = DifferentiationInterface.gradient(loss, mc, sites) + @test dot(g_zy, dt) ≈ directional rtol = 1e-8 + @test dot(g_mc, dt) ≈ directional rtol = 1e-8 + @test g_zy ≈ g_mc rtol = 1e-12 + end + end + end + + @testset "Prepared reuse, ownership and concurrent caches" begin + rng = Xoshiro(217) + n, M = 9, SG_MIN_M + sites = sg_cheb(n) + q = sort(sites[1] .+ rand(rng, 12) .* (sites[end] - sites[1])) + plan = CubicBSplinePlan(sites, q) + snapshot = deepcopy((plan.sites, knot_vector(plan.basis), plan.factorization.bands, + plan.stencil.query, plan.stencil.w1, plan.stencil.w4)) + G = randn(rng, n, M) + W = randn(rng, length(q), M) + UA, UB = randn(rng, n, M), randn(rng, n, M) + sB = sites .+ 5.0 .* sin.(1:n) .* (1 .< (1:n) .< n) + loss_c(u) = dot(G, bspline_coefficients(plan, u)) + loss_e(u) = dot(W, plan(u)) + loss_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q), UA)) + loss_tq(t) = dot(W, CubicBSplinePlan(t, q)(UA)) + for backend in (zy, mc) + for (loss, a, b) in ((loss_c, UA, UB), (loss_e, UA, UB), (loss_t, sites, sB), (loss_tq, sites, sB)) + a0, b0 = copy(a), copy(b) + prep = DifferentiationInterface.prepare_gradient(loss, backend, a) + g_a1 = DifferentiationInterface.gradient(loss, prep, backend, a) + g_b = DifferentiationInterface.gradient(loss, prep, backend, b) + g_a2 = DifferentiationInterface.gradient(loss, prep, backend, a) + @test g_a1 ≈ DifferentiationInterface.gradient(loss, fd, a) atol = 1e-9 rtol = 1e-9 + @test g_b ≈ DifferentiationInterface.gradient(loss, fd, b) atol = 1e-9 rtol = 1e-9 + @test g_a2 == g_a1 + @test a == a0 && b == b0 + end + end + @test isequal(deepcopy((plan.sites, knot_vector(plan.basis), plan.factorization.bands, + plan.stencil.query, plan.stencil.w1, plan.stencil.w4)), snapshot) + + # Eight tasks (not necessarily eight threads), one preparation each, + # sharing one read-only plan. + ntasks = 8 + Us = [randn(rng, n, M) for _ in 1:ntasks] + Ws = [randn(rng, length(q), M) for _ in 1:ntasks] + for backend in (zy, mc) + losses = [u -> dot(Ws[i], plan(u)) for i in 1:ntasks] + preps = [DifferentiationInterface.prepare_gradient(losses[i], backend, Us[i]) for i in 1:ntasks] + expected = [DifferentiationInterface.gradient(losses[i], preps[i], backend, Us[i]) for i in 1:ntasks] + results = Vector{Matrix{Float64}}(undef, ntasks) + @sync for i in 1:ntasks + Threads.@spawn for _ in 1:3 + results[i] = DifferentiationInterface.gradient(losses[i], preps[i], backend, Us[i]) + end + end + @test all(results[i] == expected[i] for i in 1:ntasks) + end + @test isequal(deepcopy((plan.sites, knot_vector(plan.basis), plan.factorization.bands, + plan.stencil.query, plan.stencil.w1, plan.stencil.w4)), snapshot) + end +end diff --git a/test/test_ext_reactant.jl b/test/test_ext_reactant.jl index 3327f8a..5299189 100644 --- a/test/test_ext_reactant.jl +++ b/test/test_ext_reactant.jl @@ -292,7 +292,278 @@ end @test Array(grad_tq_R) ≈ grad_tq_ref atol=atol rtol=atol end - @testset "Reusable spline object and plan gradients" begin + @testset "Cubic B-Spline _evaluate_stencil" begin + # 1D Case + x_sites = collect(0.0:1.0:7.0) + basis = CubicBSplineBasis(domain=(first(x_sites), last(x_sites)), internal_knots=x_sites[3:end-2]) + stencil = basis_stencil(basis, [2.5, 3.5, 4.5]) + + # Deterministic coefficient vectors for reproducibility + c_vec = collect(Float64, 1:length(x_sites)) + c_vec2 = collect(Float64, length(x_sites):-1:1) + + ref_out = AbstractCosmologicalEmulators._evaluate_stencil(stencil, c_vec) + ref_out2 = AbstractCosmologicalEmulators._evaluate_stencil(stencil, c_vec2) + + function f_stencil(c) + AbstractCosmologicalEmulators._evaluate_stencil(stencil, c) + end + + c_vec_R = Reactant.to_rarray(c_vec) + c_vec2_R = Reactant.to_rarray(c_vec2) + f_stencil_R = Reactant.@compile sync=true f_stencil(c_vec_R) + + out_R = f_stencil_R(c_vec_R) + Reactant.synchronize(out_R) + @test Array(out_R) ≈ ref_out + + # Verify dynamic coefficients + out2_R = f_stencil_R(c_vec2_R) + Reactant.synchronize(out2_R) + @test Array(out2_R) ≈ ref_out2 + @test !isapprox(Array(out2_R), Array(out_R)) + + # 2D Case - Matrix (3 series), deterministic + c_mat = hcat(c_vec, c_vec .^ 2, sin.(c_vec)) + c_mat2 = hcat(c_vec2, c_vec2 .^ 2, cos.(c_vec2)) + ref_out_mat = AbstractCosmologicalEmulators._evaluate_stencil(stencil, c_mat) + ref_out_mat2 = AbstractCosmologicalEmulators._evaluate_stencil(stencil, c_mat2) + + c_mat_R = Reactant.to_rarray(c_mat) + c_mat2_R = Reactant.to_rarray(c_mat2) + f_stencil_mat_R = Reactant.@compile sync=true f_stencil(c_mat_R) + + out_mat_R = f_stencil_mat_R(c_mat_R) + Reactant.synchronize(out_mat_R) + @test Array(out_mat_R) ≈ ref_out_mat + + out_mat2_R = f_stencil_mat_R(c_mat2_R) + Reactant.synchronize(out_mat2_R) + @test Array(out_mat2_R) ≈ ref_out_mat2 + @test !isapprox(Array(out_mat2_R), Array(out_mat_R)) + end + + @testset "Cubic B-Spline structural adaptation and public API" begin + x_sites = collect(0.0:1.0:7.0) + u_sites = sin.(x_sites) + u_mat = hcat(u_sites, cos.(x_sites)) + xq_sites = [2.5, 3.5, 4.5] + + eval_spline(spl, x) = spl(x) + eval_plan(plan, u) = plan(u) + + # Solver Correctness + plan_for_solve = CubicBSplinePlan(x_sites, xq_sites) + fact = plan_for_solve.factorization + fact_R = Reactant.to_rarray(fact) + + b_vec_for_solve = rand(length(x_sites)) + b_vec_R = Reactant.to_rarray(b_vec_for_solve) + b_mat_for_solve = rand(length(x_sites), 2) + b_mat_R = Reactant.to_rarray(b_mat_for_solve) + + do_solve(f, b) = AbstractCosmologicalEmulators.solve(f, b) + + solve_vec_R = Reactant.@compile sync=true do_solve(fact_R, b_vec_R) + out_solve_vec = solve_vec_R(fact_R, b_vec_R) + Reactant.synchronize(out_solve_vec) + @test Array(out_solve_vec) ≈ AbstractCosmologicalEmulators.solve(fact, b_vec_for_solve) + + solve_mat_R = Reactant.@compile sync=true do_solve(fact_R, b_mat_R) + out_solve_mat = solve_mat_R(fact_R, b_mat_R) + Reactant.synchronize(out_solve_mat) + @test Array(out_solve_mat) ≈ AbstractCosmologicalEmulators.solve(fact, b_mat_for_solve) + + b_vec_for_solve2 = rand(length(x_sites)) + b_vec_R2 = Reactant.to_rarray(b_vec_for_solve2) + out_solve_vec_R2 = solve_vec_R(fact_R, b_vec_R2) + Reactant.synchronize(out_solve_vec_R2) + @test Array(out_solve_vec_R2) ≈ AbstractCosmologicalEmulators.solve(fact, b_vec_for_solve2) + @test !isapprox(Array(out_solve_vec_R2), Array(out_solve_vec)) + + b_mat_for_solve2 = rand(length(x_sites), 2) + b_mat_R2 = Reactant.to_rarray(b_mat_for_solve2) + out_solve_mat_R2 = solve_mat_R(fact_R, b_mat_R2) + Reactant.synchronize(out_solve_mat_R2) + @test Array(out_solve_mat_R2) ≈ AbstractCosmologicalEmulators.solve(fact, b_mat_for_solve2) + @test !isapprox(Array(out_solve_mat_R2), Array(out_solve_mat)) + + @testset "Large nonuniform-solve parity (vector and matrix)" begin + n_nu = 127 + increments_nu = @. 0.25 + 0.03 * sin(0.37 * (1:n_nu))^2 + x_sites_nu = cumsum(increments_nu) + u_sites_nu = @. sin(1.3 * x_sites_nu) + 0.2 * cos(0.7 * x_sites_nu) + xq_sites_nu = range( + x_sites_nu[1] + 0.1, + x_sites_nu[end] - 0.1; + length = 32, + ) + + plan_for_solve_nu = CubicBSplinePlan(x_sites_nu, collect(xq_sites_nu)) + fact_nu = plan_for_solve_nu.factorization + fact_nu_R = Reactant.to_rarray(fact_nu) + + b_vec_for_solve_nu = @. sin(0.41 * x_sites_nu) + 0.1 * cos(0.13 * x_sites_nu) + b_vec_nu_R = Reactant.to_rarray(b_vec_for_solve_nu) + b_mat_for_solve_nu = hcat( + b_vec_for_solve_nu, + cos.(0.23 .* x_sites_nu), + sin.(0.17 .* x_sites_nu), + x_sites_nu ./ last(x_sites_nu), + exp.(-x_sites_nu ./ last(x_sites_nu)), + ) + b_mat_nu_R = Reactant.to_rarray(b_mat_for_solve_nu) + + solve_vec_nu_R = Reactant.@compile sync=true do_solve(fact_nu_R, b_vec_nu_R) + out_solve_vec_nu = solve_vec_nu_R(fact_nu_R, b_vec_nu_R) + Reactant.synchronize(out_solve_vec_nu) + @test Array(out_solve_vec_nu) ≈ AbstractCosmologicalEmulators.solve( + fact_nu, + b_vec_for_solve_nu, + ) + + solve_mat_nu_R = Reactant.@compile sync=true do_solve(fact_nu_R, b_mat_nu_R) + out_solve_mat_nu = solve_mat_nu_R(fact_nu_R, b_mat_nu_R) + Reactant.synchronize(out_solve_mat_nu) + @test Array(out_solve_mat_nu) ≈ AbstractCosmologicalEmulators.solve( + fact_nu, + b_mat_for_solve_nu, + ) + end + + # 1. CubicBSpline (vector) + spl_vec = CubicBSpline(u_sites, x_sites; extrapolation=:clamp) + spl_vec_R = Reactant.to_rarray(spl_vec) + xq_R = Reactant.to_rarray(xq_sites) + + f_spl_vec = Reactant.@compile sync=true eval_spline(spl_vec_R, xq_R) + out_spl_vec_R = f_spl_vec(spl_vec_R, xq_R) + Reactant.synchronize(out_spl_vec_R) + @test Array(out_spl_vec_R) ≈ spl_vec(xq_sites) + + # 2. CubicBSpline (matrix) + spl_mat = CubicBSpline(u_mat, x_sites; extrapolation=:clamp) + spl_mat_R = Reactant.to_rarray(spl_mat) + f_spl_mat = Reactant.@compile sync=true eval_spline(spl_mat_R, xq_R) + out_spl_mat_R = f_spl_mat(spl_mat_R, xq_R) + Reactant.synchronize(out_spl_mat_R) + @test Array(out_spl_mat_R) ≈ spl_mat(xq_sites) + + # 3. CubicBSplinePlan (vector) + plan = CubicBSplinePlan(x_sites, xq_sites) + plan_R = Reactant.to_rarray(plan) + u_R = Reactant.to_rarray(u_sites) + u2_sites = cos.(x_sites) + u2_R = Reactant.to_rarray(u2_sites) + + f_plan_vec = Reactant.@compile sync=true eval_plan(plan_R, u_R) + out_plan_vec_R = f_plan_vec(plan_R, u_R) + Reactant.synchronize(out_plan_vec_R) + @test Array(out_plan_vec_R) ≈ plan(u_sites) + + # Dynamic input check for plan (vector) + out2_plan_vec_R = f_plan_vec(plan_R, u2_R) + Reactant.synchronize(out2_plan_vec_R) + @test Array(out2_plan_vec_R) ≈ plan(u2_sites) + @test !isapprox(Array(out2_plan_vec_R), Array(out_plan_vec_R)) + + # 4. CubicBSplinePlan (matrix) + u_mat_R = Reactant.to_rarray(u_mat) + u_mat2 = hcat(cos.(x_sites), sin.(x_sites)) + u_mat2_R = Reactant.to_rarray(u_mat2) + + f_plan_mat = Reactant.@compile sync=true eval_plan(plan_R, u_mat_R) + out_plan_mat_R = f_plan_mat(plan_R, u_mat_R) + Reactant.synchronize(out_plan_mat_R) + @test Array(out_plan_mat_R) ≈ plan(u_mat) + + # Dynamic input check for plan (matrix) + out2_plan_mat_R = f_plan_mat(plan_R, u_mat2_R) + Reactant.synchronize(out2_plan_mat_R) + @test Array(out2_plan_mat_R) ≈ plan(u_mat2) + @test !isapprox(Array(out2_plan_mat_R), Array(out_plan_mat_R)) + + # Dynamic input check for spline (vector) + spl_vec2 = CubicBSpline(u2_sites, x_sites; extrapolation=:clamp) + spl_vec2_R = Reactant.to_rarray(spl_vec2) + out2_spl_vec_R = f_spl_vec(spl_vec2_R, xq_R) + Reactant.synchronize(out2_spl_vec_R) + @test Array(out2_spl_vec_R) ≈ spl_vec2(xq_sites) + @test !isapprox(Array(out2_spl_vec_R), Array(out_spl_vec_R)) + + # Dynamic input check for spline (matrix) + spl_mat2 = CubicBSpline(u_mat2, x_sites; extrapolation=:clamp) + spl_mat2_R = Reactant.to_rarray(spl_mat2) + out2_spl_mat_R = f_spl_mat(spl_mat2_R, xq_R) + Reactant.synchronize(out2_spl_mat_R) + @test Array(out2_spl_mat_R) ≈ spl_mat2(xq_sites) + @test !isapprox(Array(out2_spl_mat_R), Array(out_spl_mat_R)) + + # Extrapolation endpoints and out-of-domain + xq_out = [-1.0, 0.0, 7.0, 8.0] + xq_out_R = Reactant.to_rarray(xq_out) + + # Test :throw error on compilation + spl_throw = CubicBSpline(u_sites, x_sites; extrapolation=:throw) + spl_throw_R = Reactant.to_rarray(spl_throw) + @test_throws ErrorException Reactant.@compile sync=true eval_spline(spl_throw_R, xq_R) + + # Test :clamp extrapolation (vector) + spl_clamp = CubicBSpline(u_sites, x_sites; extrapolation=:clamp) + spl_clamp_R = Reactant.to_rarray(spl_clamp) + f_clamp = Reactant.@compile sync=true eval_spline(spl_clamp_R, xq_out_R) + out_clamp_R = f_clamp(spl_clamp_R, xq_out_R) + Reactant.synchronize(out_clamp_R) + @test Array(out_clamp_R) ≈ spl_clamp(xq_out) + + # Test :zero extrapolation (vector) + spl_zero = CubicBSpline(u_sites, x_sites; extrapolation=:zero) + spl_zero_R = Reactant.to_rarray(spl_zero) + f_zero = Reactant.@compile sync=true eval_spline(spl_zero_R, xq_out_R) + out_zero_R = f_zero(spl_zero_R, xq_out_R) + Reactant.synchronize(out_zero_R) + @test Array(out_zero_R) ≈ spl_zero(xq_out) + + # Test :clamp extrapolation (matrix) + spl_mat_clamp = CubicBSpline(u_mat, x_sites; extrapolation=:clamp) + spl_mat_clamp_R = Reactant.to_rarray(spl_mat_clamp) + f_mat_clamp = Reactant.@compile sync=true eval_spline(spl_mat_clamp_R, xq_out_R) + out_mat_clamp_R = f_mat_clamp(spl_mat_clamp_R, xq_out_R) + Reactant.synchronize(out_mat_clamp_R) + @test Array(out_mat_clamp_R) ≈ spl_mat_clamp(xq_out) + + # Test :zero extrapolation (matrix) + spl_mat_zero = CubicBSpline(u_mat, x_sites; extrapolation=:zero) + spl_mat_zero_R = Reactant.to_rarray(spl_mat_zero) + f_mat_zero = Reactant.@compile sync=true eval_spline(spl_mat_zero_R, xq_out_R) + out_mat_zero_R = f_mat_zero(spl_mat_zero_R, xq_out_R) + Reactant.synchronize(out_mat_zero_R) + @test Array(out_mat_zero_R) ≈ spl_mat_zero(xq_out) + + @testset "CubicBSpline scan Float32 matrix path" begin + x_sites_32 = Float32[0.0, 0.2, 0.7, 1.4, 2.5, 4.0, 6.0] + xq_sites_32 = collect(range(first(x_sites_32), last(x_sites_32); length=11)) + u_sites_32 = @. sin(1.3f0 * x_sites_32) + 0.2f0 * cos(0.7f0 * x_sites_32) + U_sites_32 = hcat(u_sites_32, cos.(x_sites_32), x_sites_32 .^ 2) + plan_32 = CubicBSplinePlan(x_sites_32, xq_sites_32; extrapolation=:clamp) + fact_32_R = Reactant.to_rarray(plan_32.factorization) + plan_32_R = Reactant.to_rarray(plan_32) + U_sites_32_R = Reactant.to_rarray(U_sites_32) + + do_solve_32(fact, rhs) = AbstractCosmologicalEmulators.solve(fact, rhs) + solve_32_R = Reactant.@compile sync=true do_solve_32(fact_32_R, U_sites_32_R) + @test Array(solve_32_R(fact_32_R, U_sites_32_R)) ≈ + AbstractCosmologicalEmulators.solve(plan_32.factorization, U_sites_32) atol=1e-5 rtol=1e-5 + + eval_plan_32(plan, rhs) = plan(rhs) + plan_mat_32_R = Reactant.@compile sync=true eval_plan_32(plan_32_R, U_sites_32_R) + @test Array(plan_mat_32_R(plan_32_R, U_sites_32_R)) ≈ + plan_32(U_sites_32) atol=1e-5 rtol=1e-5 + end + end + + + @testset "Reusable spline object and plan gradients" begin if SKIP_REACTANT_REUSABLE_SPLINES @test_skip false else @@ -323,6 +594,31 @@ end Reactant.synchronize(plan_grad_R) @test Array(plan_grad_R) ≈ plan_grad_ref atol=1e-8 rtol=1e-8 end + + # Matrix plan Enzyme gradient test + plan_mat = AbstractCosmologicalEmulators.CubicBSplinePlan(t, tq) + plan_mat_R = Reactant.to_rarray(plan_mat) + UR = Reactant.to_rarray(U) + plan_loss_mat_host = U_ -> sum(plan_mat(U_)) + plan_loss_mat_R = U_ -> sum(plan_mat_R(U_)) + plan_grad_ref_mat = ForwardDiff.gradient(plan_loss_mat_host, copy(U)) + plan_grad_fun_mat = U_ -> Enzyme.gradient(Reverse, plan_loss_mat_R, U_)[1] + plan_grad_compiled_mat = Reactant.@compile sync=true plan_grad_fun_mat(UR) + plan_grad_R_mat = plan_grad_compiled_mat(UR) + Reactant.synchronize(plan_grad_R_mat) + @test Array(plan_grad_R_mat) ≈ plan_grad_ref_mat atol=1e-8 rtol=1e-8 + + # Also test vector B-spline plan gradient + plan_vec_bs = AbstractCosmologicalEmulators.CubicBSplinePlan(t, tq) + plan_vec_bs_R = Reactant.to_rarray(plan_vec_bs) + plan_loss_vec_host = u_ -> sum(plan_vec_bs(u_)) + plan_loss_vec_R = u_ -> sum(plan_vec_bs_R(u_)) + plan_grad_ref_vec = ForwardDiff.gradient(plan_loss_vec_host, copy(u)) + plan_grad_fun_vec = u_ -> Enzyme.gradient(Reverse, plan_loss_vec_R, u_)[1] + plan_grad_compiled_vec = Reactant.@compile sync=true plan_grad_fun_vec(uR) + plan_grad_R_vec = plan_grad_compiled_vec(uR) + Reactant.synchronize(plan_grad_R_vec) + @test Array(plan_grad_R_vec) ≈ plan_grad_ref_vec atol=1e-8 rtol=1e-8 end end end diff --git a/test/test_reference_scipy.jl b/test/test_reference_scipy.jl new file mode 100644 index 0000000..410daca --- /dev/null +++ b/test/test_reference_scipy.jl @@ -0,0 +1,103 @@ +using Test +using AbstractCosmologicalEmulators +using DelimitedFiles + +@testset "SciPy Reference Verification" begin + ref_dir = joinpath(@__DIR__, "reference", "cubic_b_spline") + + function load_txt(filename) + return readdlm(joinpath(ref_dir, filename), Float64)[:] + end + + function load_txt_mat(filename) + return readdlm(joinpath(ref_dir, filename), Float64) + end + + # Track maximum errors for IMPLEMENTATION.md + max_knot_err = Ref(0.0) + max_coeff_err = Ref(0.0) + max_val_err = Ref(0.0) + max_design_err = Ref(0.0) + + function update_errs(spl, knots, c, vals, xq, val_ref) + max_knot_err[] = max(max_knot_err[], maximum(abs.(knot_vector(spl.basis) .- knots))) + max_coeff_err[] = max(max_coeff_err[], maximum(abs.(spl.coefficients .- c))) + # values are checked clamped or 0 outside, so we only compare where scipy returned a value + max_val_err[] = max(max_val_err[], maximum(abs.(spl(xq) .- val_ref))) + end + + @testset "1. Uniform sites, default not-a-knot" begin + x = load_txt("uniform_default_sites.txt") + y = load_txt("uniform_default_ordinates.txt") + knots_scipy = load_txt("uniform_default_knots.txt") + c_scipy = load_txt("uniform_default_coefficients.txt") + xq = load_txt("uniform_default_query.txt") + vals_scipy = load_txt("uniform_default_values.txt") + + # Design matrix data + xq_valid = load_txt("uniform_default_query_valid.txt") + design_mat = load_txt_mat("uniform_default_design_matrix.txt") + + valid_idx = (xq .>= x[1]) .& (xq .<= x[end]) + + spl = CubicBSpline(y, x) + + update_errs(spl, knots_scipy, c_scipy, spl(xq[valid_idx]), xq[valid_idx], vals_scipy[valid_idx]) + + @test knot_vector(spl.basis) ≈ knots_scipy atol=1e-13 + @test spl.coefficients ≈ c_scipy atol=1e-13 + @test spl(xq[valid_idx]) ≈ vals_scipy[valid_idx] atol=1e-13 + + our_design = basis_matrix(spl.basis, xq_valid) + max_design_err[] = max(max_design_err[], maximum(abs.(our_design .- design_mat))) + @test our_design ≈ design_mat atol=1e-13 + end + + @testset "2. Nonuniform sites, default not-a-knot" begin + x = load_txt("nonuniform_default_sites.txt") + y = load_txt("nonuniform_default_ordinates.txt") + knots_scipy = load_txt("nonuniform_default_knots.txt") + c_scipy = load_txt("nonuniform_default_coefficients.txt") + xq = load_txt("nonuniform_default_query.txt") + vals_scipy = load_txt("nonuniform_default_values.txt") + + xq_valid = load_txt("nonuniform_default_query_valid.txt") + design_mat = load_txt_mat("nonuniform_default_design_matrix.txt") + + spl = CubicBSpline(y, x) + valid_idx = (xq .>= x[1]) .& (xq .<= x[end]) + + update_errs(spl, knots_scipy, c_scipy, spl(xq[valid_idx]), xq[valid_idx], vals_scipy[valid_idx]) + + @test knot_vector(spl.basis) ≈ knots_scipy atol=1e-13 + @test spl.coefficients ≈ c_scipy atol=1e-13 + @test spl(xq[valid_idx]) ≈ vals_scipy[valid_idx] atol=1e-13 + + our_design = basis_matrix(spl.basis, xq_valid) + max_design_err[] = max(max_design_err[], maximum(abs.(our_design .- design_mat))) + @test our_design ≈ design_mat atol=1e-13 + end + + @testset "3. Matrix values (3 series)" begin + x = load_txt("matrix_sites.txt") + Y = load_txt_mat("matrix_ordinates.txt") + c_scipy = load_txt_mat("matrix_coefficients.txt") + xq = load_txt("nonuniform_default_query.txt") + vals_scipy = load_txt_mat("matrix_values.txt") + + spl = CubicBSpline(Y, x) + valid_idx = (xq .>= x[1]) .& (xq .<= x[end]) + + # Max errors for matrix + max_coeff_err[] = max(max_coeff_err[], maximum(abs.(spl.coefficients .- c_scipy))) + max_val_err[] = max(max_val_err[], maximum(abs.(spl(xq[valid_idx]) .- vals_scipy[valid_idx, :]))) + + @test spl.coefficients ≈ c_scipy atol=1e-13 + @test spl(xq[valid_idx]) ≈ vals_scipy[valid_idx, :] atol=1e-13 + end + + @info "Max knot error: $(max_knot_err[])" + @info "Max coeff error: $(max_coeff_err[])" + @info "Max val error: $(max_val_err[])" + @info "Max design matrix error: $(max_design_err[])" +end diff --git a/test/test_spline_plans.jl b/test/test_spline_plans.jl index b554681..f21f07f 100644 --- a/test/test_spline_plans.jl +++ b/test/test_spline_plans.jl @@ -75,4 +75,91 @@ import ADTypes: AutoForwardDiff, AutoMooncake, AutoZygote @test plan_matrix_gradient ≈ pure_matrix_gradient atol=1e-10 rtol=1e-10 end end + + @testset "Cubic plan independent field cotangents" begin + plan = CubicSplinePlan(t, t_new) + n, nq = length(t), length(t_new) + for ordinates in (u1, U) + initial = vcat(vec(plan.second_derivative_operator), + plan.left_value_weights, plan.right_value_weights, + plan.left_curve_weights, plan.right_curve_weights, vec(ordinates)) + function loss(p) + k = n * n + raw_plan = CubicSplinePlan(t, t_new, reshape(p[1:k], n, n), + plan.interval_indices, p[k+1:k+nq], p[k+nq+1:k+2nq], + p[k+2nq+1:k+3nq], p[k+3nq+1:k+4nq]) + return sum(abs2, raw_plan(reshape(p[k+4nq+1:end], size(ordinates)))) + end + backend = AutoMooncake(; config=Mooncake.Config()) + prep = prepare_gradient(loss, backend, initial) + for input in (initial, initial .+ 0.003 .* sin.(eachindex(initial)), initial) + @test DifferentiationInterface.gradient(loss, prep, backend, input) ≈ + ForwardDiff.gradient(loss, input) atol=1e-8 rtol=1e-8 + end + # Noncanonical plan storage must also retain generic AD. All these + # field views share a parent but refer to disjoint parameter blocks. + function field_view_loss(p) + k = n * n + raw_plan = CubicSplinePlan(t, t_new, reshape(view(p, 1:k), n, n), + plan.interval_indices, view(p, k+1:k+nq), view(p, k+nq+1:k+2nq), + view(p, k+2nq+1:k+3nq), view(p, k+3nq+1:k+4nq)) + return sum(abs2, raw_plan(reshape(p[k+4nq+1:end], size(ordinates)))) + end + field_prep = prepare_gradient(field_view_loss, backend, initial) + @test DifferentiationInterface.gradient(field_view_loss, field_prep, backend, initial) ≈ + ForwardDiff.gradient(field_view_loss, initial) atol=1e-8 rtol=1e-8 + # A view must still use the generic path, not the dense fdata rule. + view_loss(v) = sum(abs2, plan(view(reshape(v, size(ordinates)), axes(ordinates)...))) + input = vec(ordinates) + view_prep = prepare_gradient(view_loss, backend, input) + @test DifferentiationInterface.gradient(view_loss, view_prep, backend, input) ≈ + ForwardDiff.gradient(view_loss, input) atol=1e-8 rtol=1e-8 + # The native rule also accepts machine-float ordinates whose + # precision differs from the stored Float64 plan geometry. + input32 = Float32.(input) + mixed_loss(v) = sum(abs2, plan(reshape(v, size(ordinates)))) + mixed_prep = prepare_gradient(mixed_loss, backend, input32) + for v in (input32, input32 .+ 0.03f0, input32) + actual = DifferentiationInterface.gradient(mixed_loss, mixed_prep, backend, v) + @test eltype(actual) == Float32 + @test actual ≈ ForwardDiff.gradient(mixed_loss, v) atol=5e-5 rtol=5e-5 + end + end + end + + @testset "Geometry and values with prepared reverse-mode reuse" begin + sites = [0.0, 0.3, 0.9, 1.8, 3.0, 4.7, 6.0] + query = [0.45, 1.25, 2.6, 5.2] + values = sin.(sites) .+ 0.2 .* cos.(1.3 .* sites) + n, nq = length(sites), length(query) + for Plan in (AkimaSplinePlan, CubicSplinePlan), matrix in (false, true) + ordinates = matrix ? hcat(values, cos.(0.7 .* sites) .- 0.1 .* sites) : values + initial = vcat(sites, query, vec(ordinates)) + function loss(p) + s = p[1:n] + q = p[n+1:n+nq] + u = matrix ? reshape(p[n+nq+1:end], n, 2) : p[n+nq+1:end] + return sum(abs2, Plan(s, q)(u)) + end + changed = copy(initial) + changed[1:n] .+= [0.0, 0.01, -0.02, 0.03, -0.03, 0.02, 0.0] + # Cross source intervals and reorder queries without changing shape. + changed[n+1:n+nq] .+= [0.6, 0.8, 0.9, -1.8] + changed[n+nq+1:end] .+= 0.07 .* cos.(1:length(ordinates)) + + fd = AutoForwardDiff() + fd_prep = prepare_gradient(loss, fd, initial) + for backend in (AutoZygote(), AutoMooncake(; config=Mooncake.Config())) + prep = prepare_gradient(loss, backend, initial) + for p in (initial, changed, initial) + expected = DifferentiationInterface.gradient(loss, fd_prep, fd, p) + actual = DifferentiationInterface.gradient(loss, prep, backend, p) + @test all(isfinite, actual) + @test maximum(abs, expected[1:n]) > 1e-6 + @test maximum(abs, expected[n+1:n+nq]) > 1e-6 + @test actual ≈ expected atol=1e-9 rtol=1e-9 + end + end + end + end end diff --git a/test/test_threads.jl b/test/test_threads.jl new file mode 100644 index 0000000..de3da95 --- /dev/null +++ b/test/test_threads.jl @@ -0,0 +1,338 @@ +using AbstractCosmologicalEmulators +using Test +using LinearAlgebra +using Random +using ForwardDiff +using Zygote +using DifferentiationInterface +import ADTypes: AutoForwardDiff, AutoMooncake, AutoZygote +using Mooncake + +# set_threads: one setting for FFTW and the host B-spline column-task budget. +# The column split is checked three ways: the planned task count, a test-only +# recording kernel passed to the production driver (distinct tasks really run +# disjoint contiguous blocks), and bitwise equality of public results and +# gradients with the serial solve. Works under -t1 (everything serial) and +# multi-threaded runs. Settings are always restored afterwards. + +const ACET = AbstractCosmologicalEmulators +const TH_POOL = Threads.nthreads(:default) + +# Run f under set_threads(n) (or the automatic default for n = 0), then restore +# FFTW's count and ACE's budget exactly. +function th_with_threads(f, n) + fftw_before = ACET.FFTW.get_num_threads() + host_before = ACET._HOST_THREADS[] + try + n == 0 ? (ACET._HOST_THREADS[] = 0) : set_threads(n) + return f() + finally + ACET.FFTW.set_num_threads(fftw_before) + ACET._HOST_THREADS[] = host_before + end +end + +th_expected_tasks(n, m, budget) = + clamp(div(n * m, ACET._HOST_SOLVE_MIN_TASK_ENTRIES), 1, min(min(budget, TH_POOL), m)) + +th_sites(::Type{T}, n) where {T} = T.(sort(2 .+ 0.5 .* (cos.(pi .* (0:n-1) ./ (n - 1)) .+ 1) .* 8998)) +th_logk(n) = log.(parse.(Float64, readlines(joinpath( + @__DIR__, "reference", "bspline_adaptive_sites", "adaptive_design_N$(n).txt")))) + +# Forward and transpose solves of `S` under budget `k`. +th_solves(fact, S, k) = th_with_threads(k) do + (ACET.solve(fact, S), ACET.solve_adjoint(fact, S)) +end + +@testset "Unified thread setting" begin + @testset "set_threads validation and FFTW integration" begin + th_with_threads(1) do + for n in (1, 2, TH_POOL + 3) + @test set_threads(n) === nothing + @test ACET.FFTW.get_num_threads() == n + @test ACET._HOST_THREADS[] == n + @test ACET._host_thread_budget() == min(n, TH_POOL) + end + set_threads(2) + for bad in (0, -1, Int(typemax(Cint)) + 1, big(2)^70, UInt128(2)^100) + @test_throws ArgumentError set_threads(bad) + @test ACET.FFTW.get_num_threads() == 2 + @test ACET._HOST_THREADS[] == 2 + end + @test (@test_deprecated set_fft_threads(3)) === nothing + @test ACET.FFTW.get_num_threads() == 3 + @test ACET._HOST_THREADS[] == 3 + end + th_with_threads(0) do + @test ACET._host_thread_budget() == TH_POOL + end + + # FFT plans created before a change stay usable; later plans agree. + f(x) = exp(-x^2) * cos(3x) + th_with_threads(1) do + before = prepare_chebyshev_plan(-1.0, 1.0, 64) + reference = chebyshev_decomposition(before, f.(before.nodes[1])) + set_threads(2) + after = prepare_chebyshev_plan(-1.0, 1.0, 64) + @test chebyshev_decomposition(before, f.(before.nodes[1])) == reference + @test chebyshev_decomposition(after, f.(after.nodes[1])) ≈ reference rtol = 1e-13 + end + end + + @testset "Importing leaves FFTW alone; automatic budget resolved at run time" begin + code = """ + const FFTW = Base.require(Base.PkgId( + Base.UUID("7a1cc6ca-52ef-59f5-83cd-3a7055c09341"), "FFTW")) + FFTW.set_num_threads(3) + using AbstractCosmologicalEmulators + const A = AbstractCosmologicalEmulators + print(FFTW.get_num_threads(), " ", A._HOST_THREADS[], " ", + A._host_thread_budget(), " ", Threads.nthreads(:default)) + """ + cmd = `$(Base.julia_cmd()) --startup-file=no --threads=2 --project=$(Base.active_project()) -e $code` + @test readchomp(cmd) == "3 0 2 2" + end + + @testset "Task count follows the budget and the work threshold" begin + for k in (1, 2, 4, 0) + th_with_threads(k) do + budget = k == 0 ? TH_POOL : k + @test ACET._host_column_tasks(81, 8192) == th_expected_tasks(81, 8192, budget) + @test ACET._host_column_tasks(81, 7) == 1 + @test ACET._host_column_tasks(81, 1) == 1 + @test ACET._host_column_tasks(129, 8192) <= min(budget, TH_POOL) + end + end + if TH_POOL >= 2 + th_with_threads(4) do + @test ACET._host_column_tasks(81, 8192) == min(4, TH_POOL) + end + else + th_with_threads(4) do + @test ACET._host_column_tasks(81, 8192) == 1 + end + end + end + + @testset "Production driver runs disjoint contiguous blocks on separate tasks" begin + rng = Xoshiro(301) + n, m = 81, 4099 + plan = CubicBSplinePlan(th_logk(n), th_logk(n)[2:end-1]) + B = plan.factorization.bands + @test ACET._is_bordered_tridiagonal_factor(B) + S = randn(rng, n, m) + for (bordered_kernel, label) in ((true, "bordered"), (false, "full band")) + for k in (1, 2, 4) + owner = Vector{UInt}(undef, m) + thread = zeros(Int, m) + record(c) = (owner[c] = objectid(current_task()); thread[c] = Threads.threadid()) + full!(B, X, c, n) = (record(c); ACET._full_band_solve_column!(B, X, c, n)) + bordered!(B, X, c, n) = (record(c); ACET._bordered_solve_column!(B, X, c, n)) + Bk = bordered_kernel ? B : (Bf = copy(B); Bf[2, 7] = 1e-30; Bf) + @test ACET._is_bordered_tridiagonal_factor(Bk) == bordered_kernel + X = copy(S) + th_with_threads(k) do + ACET._solve_band_columns_host!(full!, bordered!, + ACET._solve_band_columns_general!, Bk, X, S) + end + expected = th_expected_tasks(n, m, k) + blocks = [findall(==(id), owner) for id in unique(owner)] + @test length(blocks) == expected + @test all(b -> b == first(b):last(b), blocks) + @test sort(reduce(vcat, blocks)) == 1:m + @test X == th_solves(ACET.CubicBSplineFactorization(Bk), S, 1)[1] + end + end + + # With more than one pool thread, blocks are actually spread over threads. + if TH_POOL >= 2 + seen = 0 + for _ in 1:20 + thread = zeros(Int, m) + full!(B, X, c, n) = (thread[c] = Threads.threadid(); ACET._full_band_solve_column!(B, X, c, n)) + bordered!(B, X, c, n) = (thread[c] = Threads.threadid(); ACET._bordered_solve_column!(B, X, c, n)) + th_with_threads(TH_POOL) do + ACET._solve_band_columns_host!(full!, bordered!, + ACET._solve_band_columns_general!, B, copy(S), S) + end + seen = max(seen, length(unique(thread))) + seen >= 2 && break + end + @test seen >= 2 + end + end + + @testset "Threaded public solves equal serial solves bitwise" begin + rng = Xoshiro(303) + shapes = ((5, 20001), (6, 13001), (7, 9999), (81, 4099), (81, 8192), (129, 8191)) + for T in (Float64, Float32), (n, m) in shapes + sites = th_sites(T, n) + plan = CubicBSplinePlan(sites, sites[2:end-1]) + S = randn(rng, T, n, m) + S0 = copy(S) + bands0 = copy(plan.factorization.bands) + serial = th_solves(plan.factorization, S, 1) + serial_eval = th_with_threads(1) do + plan(S) + end + for k in (2, 4, 0) + @test isequal(th_solves(plan.factorization, S, k), serial) + th_with_threads(k) do + @test isequal(bspline_coefficients(plan, S), serial[1]) + @test isequal(plan(S), serial_eval) + end + end + @test S == S0 + @test plan.factorization.bands == bands0 + end + + # Full-band factors (a tiny nonzero outer coupling) and malformed storage. + sites = th_sites(Float64, 81) + plan = CubicBSplinePlan(sites, sites) + S = randn(rng, 81, 4099) + Bf = copy(plan.factorization.bands) + Bf[2, 7] = 1e-30 + @test !ACET._is_bordered_tridiagonal_factor(Bf) + full_fact = ACET.CubicBSplineFactorization(Bf) + for k in (2, 4) + @test isequal(th_solves(full_fact, S, k), th_solves(full_fact, S, 1)) + end + malformed = ACET.CubicBSplineFactorization(plan.factorization.bands[1:6, :]) + @test_throws BoundsError th_solves(malformed, S, 4) + + # Vectors and generic element types keep their serial paths. Public + # views are densified, so they may use the threaded dense path. + u = randn(rng, 81) + V = view(hcat(S, S), :, 1:4099) + Sb = big.(S[:, 1:3]) + serial_u, serial_b = th_with_threads(1) do + bspline_coefficients(plan, u), bspline_coefficients(plan, Sb) + end + th_with_threads(4) do + @test bspline_coefficients(plan, u) == serial_u + @test bspline_coefficients(plan, V) == th_solves(plan.factorization, S, 1)[1] + @test bspline_coefficients(plan, Sb) == serial_b + end + end + + @testset "Nonfinite and overflow fallback patterns are unchanged" begin + rng = Xoshiro(305) + n, m = 81, 4099 + sites = th_logk(n) + plan = CubicBSplinePlan(sites, sites[2:end-1]) + S = randn(rng, n, m) + for (c, value) in ((1, NaN), (410, Inf), (411, -Inf), (2050, NaN), (m, Inf)) + S[rand(rng, 1:n), c] = value + end + S[:, 1000] .= 1e308 + S[1:2:end, 3000] .= -1e308 + serial = th_solves(plan.factorization, S, 1) + @test any(isnan, serial[1]) && any(isinf, serial[1]) + for k in (2, 4, 0) + @test isequal(th_solves(plan.factorization, S, k), serial) + end + end + + @testset "Reverse gradients are independent of the budget" begin + rng = Xoshiro(307) + mc = AutoMooncake(; config=Mooncake.Config()) + zy = AutoZygote() + fd = AutoForwardDiff() + + # Small grids, batches large enough to split, full ForwardDiff for geometry. + n, m = 7, 12000 + sites = th_sites(Float64, n) + q = vcat(sites[1] - 40.0, (sites[1:end-1] .+ sites[2:end]) ./ 2, sites[end] + 25.0) + plan = CubicBSplinePlan(sites, q) + A = basis_matrix(plan.basis, sites) + Sq = ACET._evaluate_stencil(plan.stencil, Matrix{Float64}(I, n, n)) + U, G, W = randn(rng, n, m), randn(rng, n, m), randn(rng, length(q), m) + coeff_u(u) = dot(G, bspline_coefficients(plan, u)) + eval_u(u) = dot(W, plan(u)) + coeff_t(t) = dot(G, bspline_coefficients(CubicBSplinePlan(t, q), U)) + eval_t(t) = dot(W, CubicBSplinePlan(t, q)(U)) + eval_q(x) = dot(W, CubicBSplinePlan(sites, x)(U)) + spline_t(t) = dot(W, CubicBSpline(U, t)(q)) + th_with_threads(4) do + @test ACET._host_column_tasks(n, m) == th_expected_tasks(n, m, 4) + for (loss, x) in ((coeff_t, sites), (eval_t, sites), (eval_q, q), (spline_t, sites)) + reference = DifferentiationInterface.gradient(loss, fd, x) + for backend in (zy, mc) + @test DifferentiationInterface.gradient(loss, backend, x) ≈ + reference atol = 1e-9 rtol = 1e-9 + end + end + D = randn(rng, n, m) + for (loss, dense) in ((coeff_u, transpose(A) \ G), (eval_u, transpose(A) \ (transpose(Sq) * W))) + directional = ForwardDiff.derivative(h -> loss(U .+ h .* D), 0.0) + for backend in (zy, mc) + g = DifferentiationInterface.gradient(loss, backend, U) + @test maximum(abs, g .- dense) / max(1, maximum(abs, dense)) <= 1e-10 + @test dot(g, D) ≈ directional rtol = 1e-10 + end + end + end + + # A preparation reused under budgets 1 → 4 → 2 → 1 stays numerically + # correct. Task-splitting evidence is tested separately above; equality + # of results alone cannot prove which execution policy ran. + for (n, m) in ((81, 8192), (129, 8192)) + sites = th_logk(n) + q = collect(range(sites[1], sites[end]; length=2n)) + plan = CubicBSplinePlan(sites, q) + U, G, W = randn(rng, n, m), randn(rng, n, m), randn(rng, length(q), m) + losses = ( + (u -> dot(G, bspline_coefficients(plan, u)), U), + (u -> dot(W, plan(u)), U), + (t -> dot(G, bspline_coefficients(CubicBSplinePlan(t, q), U)), sites), + (t -> dot(W, CubicBSplinePlan(t, q)(U)), sites), + ) + for backend in (zy, mc), (loss, x) in losses + prep = th_with_threads(1) do + DifferentiationInterface.prepare_gradient(loss, backend, x) + end + results = map((1, 4, 2, 1)) do k + th_with_threads(k) do + DifferentiationInterface.gradient(loss, prep, backend, x) + end + end + @test all(==(results[1]), results) + end + dt = randn(rng, n) .* (1 .< (1:n) .< n) .* (1e-3 * minimum(diff(sites))) + loss_t = losses[4][1] + directional = ForwardDiff.derivative(h -> loss_t(sites .+ h .* dt), 0.0) + th_with_threads(4) do + @test dot(DifferentiationInterface.gradient(loss_t, mc, sites), dt) ≈ directional rtol = 1e-8 + @test dot(DifferentiationInterface.gradient(loss_t, zy, sites), dt) ≈ directional rtol = 1e-8 + end + end + end + + @testset "Concurrent preparations on one read-only plan" begin + rng = Xoshiro(311) + n, m, ntasks = 81, 4099, 8 + sites = th_logk(n) + q = collect(range(sites[1], sites[end]; length=100)) + plan = CubicBSplinePlan(sites, q) + bands0 = copy(plan.factorization.bands) + Us = [randn(rng, n, m) for _ in 1:ntasks] + Ws = [randn(rng, length(q), m) for _ in 1:ntasks] + for backend in (AutoZygote(), AutoMooncake(; config=Mooncake.Config())) + losses = [u -> dot(Ws[i], plan(u)) for i in 1:ntasks] + preps = [DifferentiationInterface.prepare_gradient(losses[i], backend, Us[i]) for i in 1:ntasks] + serial = th_with_threads(1) do + [DifferentiationInterface.gradient(losses[i], preps[i], backend, Us[i]) for i in 1:ntasks] + end + results = Vector{Matrix{Float64}}(undef, ntasks) + th_with_threads(4) do + @sync for i in 1:ntasks + Threads.@spawn for _ in 1:2 + results[i] = DifferentiationInterface.gradient(losses[i], preps[i], backend, Us[i]) + end + end + end + @test all(results[i] == serial[i] for i in 1:ntasks) + end + @test plan.factorization.bands == bands0 + end +end diff --git a/test/test_type_stability.jl b/test/test_type_stability.jl index 99fe5d7..3c818b8 100644 --- a/test/test_type_stability.jl +++ b/test/test_type_stability.jl @@ -6,6 +6,12 @@ using JET using Lux using Random +_construct_cubic_bspline(values, sites) = CubicBSpline(values, sites) +_construct_cubic_bspline_plan(sites, query) = CubicBSplinePlan(sites, query) +_apply_cubic_bspline(spline, query) = spline(query) +_apply_cubic_bspline_plan(plan, values) = plan(values) +_cubic_bspline_plan_coefficients(plan, values) = bspline_coefficients(plan, values) + @testset "Type Stability" begin # Create fresh dictionary for type stability tests (since NN_dict gets modified above) fresh_NN_dict = JSON.parsefile(joinpath(@__DIR__, "testNN.json")) @@ -69,6 +75,56 @@ using Random JET.test_opt(akima_interpolation, (typeof(y_vals), typeof(x_nodes), typeof(x_new_scalar))) JET.test_opt(akima_interpolation, (typeof(y_vals), typeof(x_nodes), typeof(x_new_vec))) + @testset "Cubic B-Spline type stability" begin + for T in (Float32, Float64) + x_bs = collect(range(T(0), T(1); length=8)) + xq_bs = T[0.15, 0.35, 0.65, 0.85] + u_bs = sin.(x_bs) + U_bs = hcat(u_bs, cos.(x_bs), x_bs .^ 2) + spline_vec = CubicBSpline(u_bs, x_bs) + spline_mat = CubicBSpline(U_bs, x_bs) + plan_bs = CubicBSplinePlan(x_bs, xq_bs) + + @test @inferred(_apply_cubic_bspline(spline_vec, xq_bs)) isa Vector{T} + @test @inferred(_apply_cubic_bspline(spline_mat, xq_bs)) isa Matrix{T} + @test @inferred(_apply_cubic_bspline_plan(plan_bs, u_bs)) isa Vector{T} + @test @inferred(_apply_cubic_bspline_plan(plan_bs, U_bs)) isa Matrix{T} + @test @inferred(_cubic_bspline_plan_coefficients(plan_bs, u_bs)) isa Vector{T} + @test @inferred(_cubic_bspline_plan_coefficients(plan_bs, U_bs)) isa Matrix{T} + + JET.test_opt( + _construct_cubic_bspline, + (typeof(u_bs), typeof(x_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + JET.test_opt( + _construct_cubic_bspline_plan, + (typeof(x_bs), typeof(xq_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + JET.test_opt( + _apply_cubic_bspline, + (typeof(spline_vec), typeof(xq_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + JET.test_opt( + _apply_cubic_bspline, + (typeof(spline_mat), typeof(xq_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + JET.test_opt( + _apply_cubic_bspline_plan, + (typeof(plan_bs), typeof(u_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + JET.test_opt( + _apply_cubic_bspline_plan, + (typeof(plan_bs), typeof(U_bs)); + target_modules=(AbstractCosmologicalEmulators,), + ) + end + end + # Chebyshev polynomial staging should remain concretely typed. # In particular, this catches regressions such as Vector{Any} # temporaries inside chebyshev_polynomials.