Skip to content

Replace @generated Padé functions and gate the 1.12 workaround (#41) - #305

Open
devmotion wants to merge 5 commits into
masterfrom
dmw/remove-generated-functions
Open

devmotion wants to merge 5 commits into
masterfrom
dmw/remove-generated-functions

Conversation

@devmotion

@devmotion devmotion commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Fixes #41.

The generic-order exp_pade_p was @generated and constructed the element type inside its generator. That fails with a world-age error for number types defined after the package, e.g. ForwardDiff Duals with ExpMethodGeneric(k) for k ≠ 13.

Changes

  • Padé coefficients:
    • The exact rationals come from one type-independent function, _pade_rationals(k, m), and are converted with map(T, ...). It is @generated, so the BigInt arithmetic runs once per (k, m); its generator only uses the integer orders, so it isn't a world-age risk.
    • For isbits T, the conversion goes through a Base.@assume_effects :foldable wrapper. The compiler evaluates it at compile time in the caller's world, so the coefficients stay constants. The wrapper fixes the BigFloat precision (precision(T) + 64, i.e. 64 guard bits) and rounding mode of the conversion, so the folded constants don't depend on the global BigFloat state at compile time (required for :consistent; the old generator had the same dependence).
    • Non-isbits T such as BigFloat convert at runtime, so setprecision after compilation is respected (the old generator froze the first-compile precision).
    • The explicit Val{13} methods are removed; the Float64 coefficients are identical to the old literals.
  • Coefficient type: _coef_type(real(eltype(x))), so coefficients are real (fallback float(T)). A new ForwardDiffExt maps Dual{Tag, V} to V, so Duals use plain float constants.
  • StaticArrays extension:
    • _horner no longer needs a generator; it uses tuple recursion instead.
    • The Julia 1.12 miscompile workaround is wrapped in @static if v"1.12.0-" <= VERSION < v"1.13.0-". Julia 1.10 (LLVM 15) and 1.11 (LLVM 16) are unaffected, and 1.13 ships LLVM 20.1.8, which contains the fix llvm/llvm-project@5d7cf504 (2024-09); upstream (Julia 1.12 and LLVM 18 vectorization defect JuliaLang/julia#62368) reports 1.10.11, 1.11.9 and 1.13.0-rc4 passing.
    • _mul stays @generated. Its generator only inspects types, so it isn't a world-age risk.
  • CI: a new Core 1.12 test group (ubuntu-latest). CI's 1 lane is now 1.13.1 and pre skips releases, so without it no lane would run the workaround.
  • Tests:
    • ForwardDiff with ExpMethodGeneric(8) on a scalar and an SMatrix, plus Dual{BigFloat}.
    • A check that exp_pade_p and _horner have no generated methods, which holds whatever the package load order.
    • The rationals against an independent formula, and the k = 13 Float64 literals under the default, a low (8 bit) and a RoundUp global BigFloat state.
    • _coef_type, including nested Dual and Complex{Dual}.
    • Zero allocations for Float64, Float32, Dual and SMatrix. This detects whether compile-time folding happens.
    • A ComplexF32 value check.
  • Notes: AGENTS.md (gate, removal condition, CI lane) and the QA config (ExplicitImports coverage for ForwardDiffExt) are updated.

Benchmarks vs master

Apple M2, BenchmarkTools medians; master throws the #41 MethodError for all k = 8 Dual cases.

1.10 1.12 1.13
Float64/Float32 scalar, SMatrix{4,4,Float64} (k = 8, 13) unchanged unchanged unchanged
ForwardDiff.jacobian(exponential!, ·), 4×4 Float64 9.26 → 6.96 µs (1.33x) 8.31 → 8.13 µs 7.79 → 6.61 µs (1.18x)
… 4×4 Float32 4.99 → 3.43 µs (1.46x) 4.74 → 4.61 µs 4.99 → 4.01 µs (1.25x)
… 6×6 Float64 96.8 → 57.6 µs (1.68x) 100 → 101 µs 96.3 → 58.8 µs (1.64x)
Dual scalar derivative, k = 13 22.2 → 17.2 ns 23.3 → 18.0 ns 21.8 → 18.7 ns
ExpMethodGeneric(BigFloat) scalar 3.1 → 14 µs 3.0 → 32 µs 3.0 → 29 µs
… 4×4 Matrix{BigFloat} 389 → 391 µs 339 → 343 µs 339 → 335 µs
Time to first 4×4 Jacobian (fresh process, 2 runs) 3.7–4.2 → 5.1 s 3.9 → 3.3 s 4.1–4.2 → 4.6–4.8 s
  • The Jacobian gains on 1.10/1.13 come from the version gate: StaticArrays' kernel is used again there. The price is a longer first call (StaticArrays' * is compiled for Duals). On 1.12 runtime is unchanged.
  • ForwardDiffExt is within noise (1–3%) of Dual coefficients; it is kept so constants stay plain floats.
  • BigFloat cost: the scalar slowdown (4.5–11x) is the price of the precision fix. The rationals are cached, but they are converted to BigFloat on every call (about 11 µs each for p and q at the default k = 25 on 1.13). For a 4×4 matrix the conversion is negligible. Rebuilding the rationals with BigInt factorials on every call, as in the PR's first version, was 2.5–3.7x slower for scalars and 8–18% slower for a 4×4 matrix.
  • _mul without @generated (an ntuple + tuple-recursive muladd fold), measured on 1.12: 4–25x faster to compile (6×6 Dual{Float64,36}: 0.14 vs 3.5 s) and 1.8x faster at runtime for 6×6, but 1.37x slower for 4×4 Dual{Float32,16}, and it could not be checked against the miscompile (the reproducer only fails on x86). Hence _mul stays @generated.

Status

  • Benchmarks against master (above).
  • Version gate: upper bound < v"1.13.0-" from the LLVM versions and upstream results. The reproducer doesn't fail on Apple silicon, not even on 1.12; the new Core 1.12 lane runs on x86.
  • _mul stays @generated (see above).
  • CI on the latest commit, including the new Core 1.12 lane.

🤖 Generated with Claude Code

The generic-order `exp_pade_p` was `@generated` and constructed the element
type inside its generator, which fails with a world-age error for number types
defined after the package, such as ForwardDiff `Dual`s with Padé orders other
than 13. The exact rational coefficients now come from one type-independent
function, `_pade_rationals`, and are converted with `map(T, ...)` inside a
`:foldable` wrapper, which the compiler evaluates at compile time in the
caller's world for isbits `T`. Non-isbits types such as `BigFloat` convert at
runtime, so the current precision is respected. The explicit (13, 13) methods
are redundant and removed.

Coefficients are computed in the real value type of the input; the new
ForwardDiffExt maps `Dual{Tag, V}` to `V`.

In the StaticArrays extension, `_horner` no longer needs a generator, and the
Julia 1.12 miscompile workaround is restricted to Julia >= 1.12, the only
version whose CI runs failed. `_mul` stays `@generated` pending benchmarks and
a check against the miscompile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devmotion
devmotion force-pushed the dmw/remove-generated-functions branch from 3b8a157 to ce35eee Compare October 4, 2026 13:05
`run_qa` also runs ExplicitImports over ForwardDiffExt, so its
`all_explicit_imports_are_public` ignore list needs `:Dual` too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devmotion
devmotion force-pushed the dmw/remove-generated-functions branch from be04ce7 to 4f69c28 Compare October 4, 2026 13:21
@ChrisRackauckas

Copy link
Copy Markdown
Member

Is there an upstream issue tracking this too? Since it seems like it should be tracked for someone to fix?

@devmotion

Copy link
Copy Markdown
Member Author

What upstream issue? The "miscompile workaround" on Julia >= 1.12? I don't know, it's not introduced in this PR, it exists on master and this PR just restricts the workaround to the affected Julia versions (based on the comments in the code).

…rkaround

- `_pade_coeffs_foldable` converts the rationals with fixed `BigFloat` precision
  (`precision(T) + 64`) and rounding, so the folded constants no longer depend on the
  global `BigFloat` state, as `:consistent` requires. Test it under low precision and
  `RoundUp`.
- `_coef_type` falls back to `float(T)` for non-`Real` types.
- Restrict the StaticArrays workaround to Julia 1.12: 1.13 ships LLVM 20, which contains
  llvm/llvm-project@5d7cf504. Add a `Core 1.12` CI group so the workaround stays tested.
- Keep `_mul` `@generated`; its generator only inspects types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devmotion
devmotion marked this pull request as ready for review October 5, 2026 11:09
The generator only uses the integer orders, so it is not a world-age risk.
This removes the per-call `BigInt` arithmetic for non-isbits coefficient
types such as `BigFloat`, which still convert at runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

Independent review (Codex CLI 0.166.0 / gpt-6.1-sol), session 01a1970b-1161-7e52-8104-4466940fde88, reviewed head 4058bc1

  • Verdict: CHANGES
  • Risk: high (H1: previously working isbits Real types without precision(::Type) now throw; the blind assessment was medium under M3 before this compatibility regression was demonstrated).
  • Round / slot: 1 / 1
  • Blocking priorities: P2

Review written by the reviewer named above in a session other than the PR author's, and copied here by the posting agent without change to its findings. The posting agent did not re-run the reviewer's commands.

Summary: The PR repairs generic-order ForwardDiff world-age failures, folds Padé coefficients, and limits the StaticArrays workaround to Julia 1.12. The added numerical regressions fail before and pass after, but the new coefficient path rejects previously working generic numeric types and lacks isolation tests for older Julia releases' global BigFloat settings.

Blast radius: Scalar and immutable-matrix ExpMethodGeneric coefficient construction, ForwardDiff differentiation, and StaticArrays operations outside Julia 1.12; the specialized mutable order-13 arithmetic is unchanged.

Evidence: Three Julia 1.13.2 runs: head focused tests 43/43 pass; the identical extracted tests at the merge-base reproduce three ForwardDiff world-age errors; independent head probes have 27 passes and one new generic-type error. All reported CI checks pass, including Core 1.12, QA, GPU, downstream integration, documentation, and benchmarks; the inspected Core 1.12 log reports 1165 passes and one existing broken test.

Blocking findings

  1. [P2] Preserve numeric types that do not define precision(::Type) — confirmed by running. At src/exp_generic.jl:283, every isbits coefficient type enters _pade_coeffs_foldable, which calls precision(T) at src/exp_generic.jl:273. The documented interface at src/exp_generic.jl:64 accepts generic arithmetic types; it does not require this floating-point precision API. A reviewer-defined isbits WrappedReal <: Real wrapping Float64, with ordinary arithmetic, comparison, rational construction, and identity float, returns 1.3498588075760032 for exponential!(WrappedReal(0.3), ExpMethodGeneric()) at the merge-base, exactly matching exp(0.3). The head throws MethodError: no method matching precision(::Type{WrappedReal}) for that same call. Restrict precision-dependent folding to supported coefficient types and retain direct rational conversion for other types; add this regression to the package tests.
  2. [P2] Avoid changing global BigFloat settings during coefficient evaluation on older supported Julia versions — suspected from reading. The new blocks at src/exp_generic.jl:273 and src/exp_generic.jl:274 call setprecision and setrounding. On supported Julia 1.11, the precision block saves, changes, and restores a process-global setting, whereas Julia 1.13 uses scoped values. Compiler evaluation of coefficients for a fresh specialization can therefore overlap unrelated BigFloat work and expose the temporary precision or rounding mode. The sequential state-independence checks at test/basictests.jl:341 do not detect cross-task interference, so the shared-state test required by G3 is missing. Use conversions with explicit precision and rounding, or an implementation that guarantees isolation on all supported releases, and add a concurrent regression covering an affected release. This concurrency scenario was not executed locally.

Non-blocking findings

None.

What I ran

All commands were read-only upstream. Repository commands ran against the source checkout. Julia ran one process at a time with JULIA_NUM_THREADS=4, OPENBLAS_NUM_THREADS=1, TMPDIR="$PWD/tmp", JULIA_PKG_PRECOMPILE_AUTO=0, and the supplied writable shared depot followed by the default depots. No registry update or package-wide test suite was requested.

Git and metadata commands, exit 0:

gh pr view 305 --repo SciML/ExponentialUtilities.jl --json number,url,state,isDraft,headRefOid,baseRefName
git fetch origin '+refs/pull/305/head:refs/remotes/pr/305' master
git checkout --detach pr/305
git rev-parse HEAD origin/master
git diff --stat origin/master...HEAD
git diff origin/master...HEAD
git merge-base origin/master HEAD
git log -1 --no-merges --format=%B
gh pr view 305 --repo SciML/ExponentialUtilities.jl --json title,body,commits,statusCheckRollup
gh issue view 41 --repo SciML/ExponentialUtilities.jl --json title,body,state
gh pr checks 305 --repo SciML/ExponentialUtilities.jl

The live PR is open and its head equals the target. The current master SHA is the Base header; the tested unfixed merge-base is 3bdb6c168738db43ee7ab2ca1c2009f40d1800b8, extracted with git archive 3bdb6c168738db43ee7ab2ca1c2009f40d1800b8 -o ../base.tar. The newest non-merge commit has neither Agent-Harness nor Agent-Model trailers.

Reviewer-created focused.jl contains the head's unchanged testsets “ExpMethodGeneric preserves element type (immutable matrices)”, “Issue 41”, and “Padé coefficients”, with their imports and helper definitions. This avoids unrelated tests and the existing test file's nested Julia invocation. The same extracted file was used on both revisions. A temporary environment outside the source checkout supplied ForwardDiff, StaticArrays, and DoubleFloats.

Julia run 1, exit 0:

timeout 3600 julia +1.13.2 --startup-file=no --project=env -e 'using Pkg; Pkg.develop(path="src"); Pkg.instantiate(;update_registry=false); println("Julia ", VERSION); include("focused.jl")'

Output: PR 305 focused regression | 43 43 24.8s.

Julia run 2, exit 1:

timeout 3600 julia +1.13.2 --startup-file=no --project=env base-run.jl

The helper develops the archived merge-base, checks the generic arithmetic wrapper, then includes the identical focused.jl in an enclosing testset. Output: Base comparison | 19 passed, 2 failed, 13 errored, 34 total. The wrapper passes. In “Issue 41”, the three added numerical assertions (order-8 scalar derivative, order-8 static Jacobian, and BigFloat derivative) error with MethodError and “The applicable method may be too new”; the pre-existing derivative passes and the two generator-structure checks fail. Ten other errors are expected missing-helper errors from testing newly added coefficient internals against the base, and are not treated as evidence of the original bug. The three numerical regression assertions pass at the head in run 1: failing-before/passing-after is verified.

Julia run 3, exit 1:

timeout 3600 julia +1.13.2 --startup-file=no --project=env probe.jl

The helper develops the head and checks the same wrapper plus independent scalar exp, matrix exp, and derivative identities. Output: Independent adversarial probes | 27 passed, 1 errored, 28 total. The only error is precision(::Type{WrappedReal}). Runtime BigFloat precision follows 80, 256, then 512 bits with relative errors approximately 1.65e-24, 0, and 0, within a fixed 32-epsilon bound. Nested second derivatives, matrix directional derivatives using B * exp(tB), complex scalars, and nondefault-order static matrices pass. No further Julia runs were made.

CI inspection, exit 0 after redirecting gh's cache to writable scratch space:

gh run view 37364428260 --repo SciML/ExponentialUtilities.jl --job 112313713836 --log
gh run view 37364426608 --repo SciML/ExponentialUtilities.jl --job 112165468085 --log

The initial attempts to download the first log failed because gh's default cache is read-only; changing XDG_CACHE_HOME resolved that limitation. The Core 1.12 log confirms Core/basictests.jl | 1165 1 1166 and “ExponentialUtilities tests passed”. The benchmark log compares this head with master and shows essentially unchanged dense/Krylov timings; it does not benchmark the changed generic scalar path. The PR description separately reports a 4.5–11x BigFloat scalar slowdown (M3). Downstream integration, QA, and GPU are reported successful in the inspected check rollup. ForwardDiff's installed license identifies MIT.

What I did not verify

I did not run the current master tip, the complete package suite, QA, documentation, downstream suites, or GPU tests locally. I did not reproduce the x86 AVX-512 compiler bug or run Julia 1.10/1.11/1.12 locally; the changed Julia 1.12 StaticArrays/AD path is covered by the inspected successful CI run. Concurrent folding alongside unrelated BigFloat work on older supported releases remains unverified and lacks a PR regression test (G3). I did not independently reproduce the author's timing table or test other AD backends, MPI, or Reactant; those paths are not introduced by this diff.

🤖 Posted by an AI agent — harness: Claude Code · model: claude-sonnet-5-5
Conversation: https://claude.ai/code/session_01379heiiB35TtywhR7uSU74

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@devmotion

Copy link
Copy Markdown
Member Author

@ChrisRackauckas-Claude Thanks for the review. Master is merged in now (29a9a63), so the conflict is resolved. On the two findings:

1. precision(T) for WrappedReal. By making float the identity, WrappedReal claims to be a floating-point number, but it doesn't implement the floating-point interface (precision, floatmin, eps, …). That's a bug in the type, whatever its supertype. Compare ForwardDiff's Dual: its float is also the identity, and it implements that interface by forwarding to the value type (precision, eps, floatmin, floatmax, …). The coefficients are computed in float(real(T)), and relying on the float interface there is intended. (ForwardDiffExt only makes Dual inputs use plain-float coefficients; Duals would work without it.)

2. Global BigFloat state on older Julia versions. This only applies to Julia 1.10/1.11. There Base.MPFR.DEFAULT_PRECISION/ROUNDING_MODE are global Refs; from 1.12 on, setprecision/setrounding use ScopedValues and don't leak to other tasks. On 1.10/1.11, Base's own BigFloat(::Rational) wraps its division in setprecision/setrounding_raw, so any Float64(::Rational{BigInt}) conversion has the same exposure. That includes the @generated generator on master, which ran at the same point (during compilation). The PR adds no new exposure, and a concurrent regression test for it would be nondeterministic, so I don't plan to change this.

🤖 Generated with Claude Code

@ChrisRackauckas

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent running as @ChrisRackauckas — not written or reviewed by Chris.

The merge is resolved. Your float-interface objection to the WrappedReal probe needs separate treatment; the concrete remaining concern is concurrent BigFloat arithmetic on Julia 1.10/1.11.

I reran a two-thread comparison on Julia 1.10.12 using the unchanged base and head exp_generic.jl in separate modules. One thread evaluates fresh orders 2:35 with exponential!(0.3, ExpMethodGeneric(k), nothing); the other repeatedly evaluates BigFloat(1) / 3, records its precision, and calls GC.safepoint(). The observed output was:

Main.Original: unrelated precision observed=Tuple{Int64, BigFloat}[]; final=256
Main.Changed: unrelated precision observed=Tuple{Int64, BigFloat}[(117, 0.3333333333333333333333333333333333323)]; final=256

Restoring the final default to 256 does not repair the unrelated 117-bit value computed during the temporary change. A single base run without an observation does not prove that Base's existing rational conversion is thread-safe; it does establish the observed head-side corruption, so I cannot dismiss the shared-state concern as merely hypothetical. Please avoid changing the shared defaults on these supported releases, or supply evidence that the relevant use is serialized. A cold-process concurrency regression should exercise the conversion/compilation path rather than warming all orders first.

Fresh independent reviewer: Codex / gpt-6.1-sol, local session 01a1b157-2def-7c62-9d6e-169cd6abf9b4, head 29a9a6350b8b5fd938250b859f7bb04f203c00f8; verdict CHANGES, risk medium (M2), blocking priority P1. My rerun above confirms this finding; I have not rerun the full suite.


🤖 Posted by an AI agent — harness: codex-cli 0.164.0 · model: gpt-6.1-sol
Conversation: local session 01a1b0c3-a051-77a2-a730-40956439ae89 (no session URL)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Avoid generated function in generic_exp

3 participants