Skip to content

JIT setup cost: memoised unwrap, real fields with a real-stand-in derivative, power-mean sharpness atom (#823) - #830

Merged
lmoresi merged 8 commits into
developmentfrom
bugfix/jit-setup-cost-823
Oct 7, 2026
Merged

lmoresi merged 8 commits into
developmentfrom
bugfix/jit-setup-cost-823

Conversation

@lmoresi

@lmoresi lmoresi commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

Fixes #823. Stacked on #829 (the JIT include-path fix, which this needs to compile against a custom PETSc). Retarget to development once #829 merges.

Setting up a Newton solve on the Spiegelman notch took 616 s (sqrt law) and 1,352 s (power mean) on development. A setup that also unwrapped the flux for the linearity check took hours. On this branch it takes 10 s and 13 s, or 18 s and 25 s including the C build. Everything here works within the current code generator; the graph-based rewrite is a separate project. That project's session found the field-realness Jacobian break, located the power-mean cost in Pow.__new__, profiled the other model families, and checked the generated headers byte for byte.

Changes

Memoised unwrap. unwrap_expression(depth=None) repeated subs passes to a fixed point. In keep-constants mode it ran _is_truly_constant, itself a full unwrap, for every atom on every pass. The notch viscosity is a 130-node graph that expands to a 9,913-node tree, and its unwrap took 563 s. It now expands each atom once, memoised by identity, and takes 0.11 s. The result is srepr-identical to the fixed point, except in two cases where the loop was wrong:

  • a held Derivative of an atom whose content depends on the variable came back as Subs(...);
  • a cycle returned a meaningless result after 100 passes; it now raises ValueError.

The JIT's symbol scans, the Jacobian's sqrt guard and the constants substitution visit each shared node once. Debug text is built only when debugging, and the printer's re() rewrite runs only when a kernel holds an re().

Realness. Field values, gradients, coordinates, JIT constant slots and unit-carrying parameters (UWQuantity) are declared real. Without that, SymPy evaluated every power over a sum through re/im.

Differentiating with respect to a field. sympy.diff swaps a non-Symbol variable for an assumption-free Dummy, so a real field turned complex while it was differentiated, and |u − c| left Derivative(u, u), which cannot be compiled. Every Jacobian in the solvers now differentiates through uw.function.diff_wrt_field / derive_by_array_wrt_field (new, public), whose stand-in is real: 38 sympy.diff and 9 derive_by_array calls, plus the free-surface conservation rate. This also fixes a defect already on development: an explicit Abs of the unknown in any Jacobian could not be printed.

DiracDelta. With real coordinates, differentiating a kink twice gives a DiracDelta, and so does differentiating a step of the unknown once in a Newton tangent. The JIT and every evaluate path share one rule: the delta is taken as 0, its value away from the zero, and a warning names the user's call.

Power-mean sharpness. s = 1/(δ + 0.001) is now its own constant atom, built and reset with δ like the yield offset. Written inline, a**(-s) made Pow.__new__ evaluate sign(im(base)) over the whole base on every rebuild (its test for a power of E). That was 40 s of the notch Newton source, now 0.05 s. s follows δ through constants[], so changing δ does not recompile.

Identity and numbers

  • The generated header for the notch, VEP and TI fixtures is byte-identical across the last two commits (md5 over all kernels). Where both compile, the C is byte-identical to plain sympy.diff.
  • Five reference models are bit-identical to the build without the realness declarations, except the power mean: 6.8e-13 relative, same 18 iterations.
  • Across 18 models, realness on vs off changes no iteration count, and the largest relative difference is 6.2e-16.
  • Full serial suite: 3,014 passed. The np=2 parallel suite passes except test_1063 [ti], which is test_1063 [ti]: constrained free-slip topography 1.8% off its recorded anchor on the anchor's own mesh #826: identical on development and with every change here switched off.

Tests

New in tests/test_0022_unwrap_memoised_matches_fixed_point.py and tests/test_0023_field_realness_and_derivatives.py. Each was shown to fail without its fix.

  • Identity with the algorithm replaced: the unwrap in all four modes, the sqrt guard, the symbol walk and xreplace.
  • The memoisation itself: a constancy-call count (25, against 103 for the old loop).
  • The declarations, both directions: a plain SymPy symbol stays unknown.
  • The stand-in: sqrt of a square, Abs, a symbolic power, a held Derivative, the array layout.
  • Newton Poisson with k = 1 + |u − 0.2|: against its Kirchhoff solution, to 1e-7.
  • Newton Drucker-Prager with a yield floor at softness 0: solved and equal to the viscous solve while unyielded.
  • Newton through a Heaviside of the unknown.
  • DiracDelta: a source compiles bit-for-bit like the solve without it, and the evaluate paths (FE, pure SymPy, Clement) take it as 0.
  • Unit-carrying parameters: known real.
  • The power-mean sharpness: follows δ without a recompile.
  • A source census: fails if any solver differentiates with plain sympy.diff.

Docs updated:

  • docs/developer/subsystems/petsc-jacobian-layout.md and the plasticity-solvers guide teach diff_wrt_field;
  • docs/api/function.md lists both helpers;
  • review record: docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md.

Behaviour to know

  • A user's own sympy.diff with respect to a field now leaves Derivative(u, u) beside a field Abs. The guides direct such code to uw.function.diff_wrt_field.
  • The coordinate realness declaration is on sympy.vector's BaseScalar, so it covers every coordinate system created after import underworld3.
  • For VEP and TI power-mean models, the constants manifest (and the step transcript) records s, from which δ follows.

Underworld development team with AI support from Claude Code

…uard (#823)

unwrap_expression(depth=None) iterated subs() passes to a fixed point, and in
symbolic_keep_constants mode ran _is_truly_constant (itself a full unwrap) for
every atom on every pass. On the Spiegelman notch viscosity that took 563 s:
the 130-node expression DAG expands to a 9,913-node tree, and each pass
re-walked it. The replacement expands each UW atom once, memoised by identity,
and rebuilds with one xreplace per level.

The result is srepr-identical to the fixed point, except in two cases where
the passes were wrong. An unevaluated Derivative of an atom whose content
depends on the differentiation variable came back as Subs(Derivative(a*T, x),
a, x**2), i.e. x**2 dT/dx; it is now the derivative of the content, as
uw.function.derivative gives. A cyclic expression stopped after 100 passes
with a meaningless result; it now raises ValueError.

The JIT's constant collection and manifest checks used atoms(Symbol), which
walks the expanded tree; _unique_symbols walks the DAG by identity and returns
the same set. The Jacobian's sqrt guard (.replace with simultaneous=True) is a
memoised bottom-up rebuild with the same semantics. debugging_text is built
only when debug output is asked for.

Notch (sqrt law) setup_pointwise: 616 s -> 11.6 s (23 s with the C build).
tests/test_0022 holds each replacement to the algorithm it replaced, on the VP
(min/sqrt/powermean), VEP and k(u) Poisson laws, in all four unwrap modes, and
counts the constancy tests on a 12-level chain: one per distinct atom (25),
where the passes made 103.

Underworld development team with AI support from Claude Code
SymPy treats an undefined function, a sympy.vector coordinate and a plain
Symbol as possibly complex, so a power with a symbolic exponent sent it into
as_real_imag/re/im before combining powers. Field values and their gradients
are now real (UndefinedFunction built with real=True), mesh coordinates real
and finite (BaseScalar handlers registered in _prop_handler), and JIT constant
slots real. A UW expression already reads is_extended_real and is_finite from
its content, so one built on fields and coordinates reports real too.

Every derivative with respect to a field now goes through _diff_wrt_field
(and _derive_by_array_wrt_field): all 38 sympy.diff and 9 derive_by_array
calls in the solvers' Jacobians, and the free-surface conservation rate.
sympy.diff differentiates with respect to a non-Symbol by swapping it for an
assumption-free Dummy, so a real field became complex again while it was
differentiated. With realness, sqrt(g**2) is Abs(g), and differentiating that
left Derivative(u, u) unevaluated (Drucker-Prager with a yield-stress floor
at softness 0; found by the tier-2 session). The stand-in carries the field's
realness; otherwise it is SymPy's own swap, diff and substitution back. It
also fixes a defect older than this branch: an explicit Abs of the unknown in
any Jacobian came back in re() and im(), which C cannot print.

With real coordinates, differentiating a kink twice gives a DiracDelta. The
JIT prints it as 0, its value away from the zero, and warns, because a
DiracDelta written as a point source is dropped the same way.

The constant slots and coordinates declare realness at construction or on
the class rather than through a per-instance handler: Symbols with the same
declared assumptions share one knowledge base, so a handler's answer can be
pre-empted by a plain Symbol's cached None. A plain SymPy Symbol stays
unknown. The coordinate declaration is on sympy.vector's BaseScalar, so it
covers every coordinate system created after underworld3 is imported.

Tests (test_0022): the declarations, both directions; the stand-in on a field
value and a gradient (sqrt of a square, Abs, a power with a symbolic
exponent) and the derive_by_array layout; Newton Poisson with
k = 1 + |u - 0.2| against its Kirchhoff solution; Newton Drucker-Prager with
a yield floor at softness 0; and a DiracDelta source, which compiles to the
solve without it, bit for bit, and warns. Each fails on development or on
the previous version of this commit.

Underworld development team with AI support from Claude Code
A UW expression reports is_extended_real and is_finite from its content, and
a parameter given with units holds a UWQuantity, which had neither, so the
answer was None. Every power over a sum containing such a parameter was then
evaluated in the complex plane (Pow.__new__ -> as_real_imag): on the
Spiegelman notch, 36 s of the 43 s Newton source came from six Pow(Add, -1)
and 6 s from eight Pow(Add, 1/2), each base not known real only because of
a unit-carrying constant (measured by the tier-2 session).

UWQuantity is a number with units, so it is real when its value is
(np.isrealobj, or the value's own answer when it is a sympy object) and
finite when its value is finite (yield_stress = oo is real, not finite). No
sign is declared: #696 still keeps a parameter's sign unknown.

test_0022: every constant atom kept in a units-model Drucker-Prager Newton
flux reports real; it lists the five unit-carrying parameters without this.

Underworld development team with AI support from Claude Code
… solvers do

The Newton-term check used plain sympy.derive_by_array with respect to the
velocity gradients. With field values and gradients declared real (#823), a
yield floor at softness 0 contains Abs, and SymPy's assumption-free stand-in
leaves Derivative(u, u) unevaluated in it. The recipe now calls
_derive_by_array_wrt_field, as the solvers do, and says why.

Underworld development team with AI support from Claude Code
… tests

- DiracDelta: uw.function.evaluate raised NameError on one (real coordinates
  make sqrt((x - a)**2) an Abs, and its second derivative a delta) while the
  JIT compiled it to 0. One rule now serves the JIT printer and both
  evaluators (_without_dirac_deltas), applied at each evaluator's entry so a
  constant that remains keeps its broadcast shape. The warning is issued on
  rank 0 and names both origins: a step of the unknown differentiated once
  (a Heaviside or sign in a Newton tangent, which then leaves out the jump;
  that tangent could not be printed before) and a kink differentiated twice.
- diff_wrt_field and derive_by_array_wrt_field are public in uw.function: a
  hand-written tangent or flux_jacobian needs them, and plain sympy.diff with
  respect to a real field leaves Derivative(u, u) in any Abs. They hand an
  expression holding an unevaluated Derivative (found by an identity walk)
  and a plain number to sympy.diff, which the swap got wrong.
  uw.function.derivative goes through them.
- UWQuantity realness: None (unknown) for NaN and for a value numpy cannot
  read, instead of True or a TypeError; Fraction and Decimal values work.
- Docs: the Jacobian-layout subsystem doc and the plasticity guide teach
  diff_wrt_field. A solver comment kept a sympy.diff measurement under the
  new name; it now says which.
- Tests: the realness tests move to test_0023. Kirchhoff's accuracy gate is
  1e-7, not 1e-4 (measured 1.3e-9). Drucker-Prager with a floor now compiles
  and solves, against the viscous solve it must equal while unyielded. A
  source census fails if any solver differentiates with plain sympy.diff.
  New: Newton through a Heaviside of the unknown, evaluate of a delta with and
  without a field, Fraction and NaN quantities.

Underworld development team with AI support from Claude Code
The power mean wrote its sharpness inline, s = 1/(delta + 0.001), so a**(-s)
had an exponent whose denominator is a sum. For such an exponent SymPy's
Pow.__new__ tests whether the power is one of E, which evaluates
sign(im(base)) over the whole base; the unwrap rebuilds every Pow, so the
test re-ran each time. On the Spiegelman notch (power-mean fixture) that was
41 of the 43 s Newton source: four im() calls of about 10 s each.

s is now a constant atom built with delta, like the yield offset, and reset
with it. Its value tracks delta through constants[], so a delta continuation
needs no recompile. Notch, power mean: Newton source 40.1 s -> 0.1 s, full
Newton setup 181.4 s -> 15.8 s.

test_0023: the atom reaches the Newton flux; a solve after changing delta
equals a fresh model at that delta (1e-7), and differs from the solve at the
first delta (1e-3), so the test fails if s stops tracking delta.

Underworld development team with AI support from Claude Code
…s only when needed; third review (#823)

Two more output-identical costs from the notch C generation, measured by the
tier-2 session:
- the constants[] substitution in generate_c_source and prepare_for_cache_key
  used xreplace, which rebuilds every occurrence of the kernel's shared
  sub-expressions (4.3 s). _xreplace_shared visits each node object once and
  builds the same expression, so the C and the cache key are unchanged
  (test_0022 holds it to xreplace on the VP and VEP laws).
- SymPy's code printer rewrites re(UnevaluatedExpr(real)) with a whole-tree
  replace on every kernel (2.9 s). With fields and coordinates real a kernel
  seldom holds an re(); the rewrite now runs only when one is there, found by
  an identity walk (_holds_instance, which diff_wrt_field also uses).

Third review:
- the Clement evaluation path (evaluate with rbf=True over a derivative) still
  raised NameError on a DiracDelta; it applies the shared rule too.
- the DiracDelta warning is attributed to the user's call (the first frame
  outside underworld3), names the count rather than the delta, so a time loop
  warns once per call site, and is limited to rank 0 only for the collective
  JIT: an evaluation is rank-local.
- diff_wrt_field: with an unevaluated Derivative in the expression it takes
  SymPy's path and now sets the d(u)/d(u) left beside a sign to 1, so a field
  Abs elsewhere still differentiates. Both public helpers have complete NumPy
  docstrings with runnable examples and are in docs/api/function.md.
- the power-mean sharpness writes its floor as Rational(1, 1000) (Charter §6).
- tests: the solver census drops its exact count and scans systems/ too; the
  sharpness test asserts that a delta change does not recompile; new cases for
  the Clement delta path, the warning's attribution, and an Abs beside a held
  Derivative.

Underworld development team with AI support from Claude Code
…hat failed, filed items

Underworld development team with AI support from Claude Code
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

🔍 Architectural Review Checklist

Thank you for submitting an architectural review! Reviewers should validate:

Design & Architecture

  • Design rationale is clear and well-justified
  • Trade-offs are documented with alternatives considered
  • System architecture is comprehensible
  • Integration points are clearly identified

Implementation

  • Implementation matches documented design
  • Code quality meets project standards
  • Breaking changes are identified and justified
  • Backward compatibility is properly addressed

Testing & Validation

  • Testing strategy is adequate for the changes
  • Test coverage is sufficient
  • Edge cases are properly covered
  • Performance impact has been assessed

Documentation

  • Known limitations are clearly documented
  • Benefits are quantified with metrics
  • User-facing changes are documented
  • Migration guide provided (if needed)

Review Process: See CODE-REVIEW-PROCESS.md

Approval: This PR merge = Review formally approved

@lmoresi

lmoresi commented Oct 7, 2026

Copy link
Copy Markdown
Member Author

Adversarial review, three rounds

Each round ran against the installed build of the commits it reviewed. The full record, with the attacks that failed, is docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md. Every finding the branch could fix was fixed on it.

Round 1 (memoised unwrap, first realness commit)

  • Declaring field values real broke the Newton Jacobian. sqrt(g**2) becomes Abs(g), and sympy.diff with respect to a field goes through an assumption-free Dummy, leaving Derivative(u, u). Drucker-Prager with a yield floor at softness 0 failed to compile. The tier-2 session found it first. Fixed in 32bb219 by differentiating through a real stand-in in every solver Jacobian.
  • Coordinate realness turns a twice-differentiated kink into an unprintable DiracDelta. Fixed: it is taken as 0, with a warning.
  • Two tests could not fail. The unwrap equivalence passed on the old algorithm, and the include test passed wherever the headers sat on the default path. Replaced by a constancy-call count (25 vs 103) and by a check of the generated setup.py.
  • Smaller: a guard on a hard dependency, the process-global coordinate patch undocumented, and the identity claim overstated, since the old loop was wrong for a held Derivative and for a cycle.

Round 2 (the stand-in)

  • uw.function.evaluate raised NameError on a DiracDelta that the JIT compiled. Fixed with one shared rule.
  • The Jacobian-layout doc and the plasticity guide taught plain sympy.diff and pointed at private helpers. The helpers are now public, and both docs use them.
  • UWQuantity realness raised on a Fraction and called NaN real. Fixed.
  • The helper mishandled a held Derivative and a plain number. Fixed.
  • Tests: an accuracy gate of 1e-4 for a 1.3e-9 error is now 1e-7. A "compiles" test that never compiled now solves against the viscous answer. A source census was added.

Round 3 (the power-mean sharpness atom)

  • The Clement evaluate path still raised on a delta. Fixed.
  • The warning pointed at library frames and repeated in loops. It now points at the user's call and warns once per call site.
  • An Abs beside a held Derivative lost its derivative. Fixed.
  • The census test's exact count was a drift detector. Dropped, and the scan widened to systems/. The sharpness test now asserts no recompile.
  • Float(0.001) was used for an exact constant. Now Rational(1, 1000).

Checked and sound

  • The memoised unwrap equals the fixed point on Piecewise, Subs, matrix .sym, a diamond DAG, and units with scaling on and off, in all four modes.
  • The symbol walk and the sqrt guard equal the operations they replace (18 and 161 cases).
  • The C is identical across hash seeds 1, 2 and 3 for 13 models, and no Dummy name reaches the C.
  • The sharpness atom follows δ through the property, the homotopy control and the anchor reset. Two models get distinct atoms, and a δ change keeps the JIT key.
  • No VP or VEP Newton solve at softness 0 warns spuriously.

Out of scope, filed

@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown

✅ Test Suite: success

@lmoresi
lmoresi changed the base branch from bugfix/jit-petsc-include-dirs to development October 7, 2026 11:51
@lmoresi
lmoresi merged commit f4c19cf into development Oct 7, 2026
4 checks passed
lmoresi added a commit that referenced this pull request Oct 7, 2026
, tier 2)

Tier 2 of #823, measured against tier 1 (#830) as the competitor. The note sets out
where the JIT should be (named quantities as the unit of compilation, SymPy acting
locally, one walk for C and manifest, canonical and readable C), the mechanism (each
named quantity an applied function of its leaves whose fdiff gives the partial per
argument slot, so SymPy's chain rule serves every derivative call site), the scorecard
against tier 1, the risks with the test that closes each, the benchmark plan and the
staging.

scripts/sessions/jit_graph holds the prototype that the measurements come from:
kernel_graph.py (the lowering and canonical emission), graph_vs_library.py (residual,
Picard and Newton kernels compiled both ways and compared), fixtures.py,
library_setup_profile.py and graph_size_probe.py.

Underworld development team with AI support from Claude Code
lmoresi added a commit that referenced this pull request Oct 8, 2026
, tier 2)

Tier 2 of #823, measured against tier 1 (#830) as the competitor. The note sets out
where the JIT should be (named quantities as the unit of compilation, SymPy acting
locally, one walk for C and manifest, canonical and readable C), the mechanism (each
named quantity an applied function of its leaves whose fdiff gives the partial per
argument slot, so SymPy's chain rule serves every derivative call site), the scorecard
against tier 1, the risks with the test that closes each, the benchmark plan and the
staging.

scripts/sessions/jit_graph holds the prototype that the measurements come from:
kernel_graph.py (the lowering and canonical emission), graph_vs_library.py (residual,
Picard and Newton kernels compiled both ways and compared), fixtures.py,
library_setup_profile.py and graph_size_probe.py.

Underworld development team with AI support from Claude Code
lmoresi added a commit that referenced this pull request Oct 10, 2026
, tier 2)

Tier 2 of #823, measured against tier 1 (#830) as the competitor. The note sets out
where the JIT should be (named quantities as the unit of compilation, SymPy acting
locally, one walk for C and manifest, canonical and readable C), the mechanism (each
named quantity an applied function of its leaves whose fdiff gives the partial per
argument slot, so SymPy's chain rule serves every derivative call site), the scorecard
against tier 1, the risks with the test that closes each, the benchmark plan and the
staging.

scripts/sessions/jit_graph holds the prototype that the measurements come from:
kernel_graph.py (the lowering and canonical emission), graph_vs_library.py (residual,
Picard and Newton kernels compiled both ways and compared), fixtures.py,
library_setup_profile.py and graph_size_probe.py.

Underworld development team with AI support from Claude Code
lmoresi added a commit to gthyagi/underworld3 that referenced this pull request Oct 12, 2026
test_no_solver_differentiates_with_plain_sympy_diff (underworldcode#830) scans
petsc_generic_snes_solvers.pyx and systems/*.py. It does not scan
constitutive_models.py, which is where its own stated risk is authored: the
docstring says a plain sympy.diff site "would pass every other test here until
a law put an Abs or a sign of a field in its flux", and a law is written in
constitutive_models.py, not in the solvers.

Nothing is wrong today -- that file has no sympy.diff( or
sympy.derive_by_array( call, only three comments that mention the name without
a paren, which the census already discriminates correctly. The gap is that
tomorrow's law is unguarded.

Shown to fail: appending a commented-out `sympy.diff(_probe, _probe)` call to
constitutive_models.py turns the test red, and it is green again once removed.

Underworld development team with AI support from Claude Code
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.

1 participant