Repository navigation
JIT setup cost: memoised unwrap, real fields with a real-stand-in derivative, power-mean sharpness atom (#823) - #830
Merged
Conversation
…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
🔍 Architectural Review ChecklistThank you for submitting an architectural review! Reviewers should validate: Design & Architecture
Implementation
Testing & Validation
Documentation
Review Process: See CODE-REVIEW-PROCESS.md Approval: This PR merge = Review formally approved |
Member
Author
Adversarial review, three roundsEach round ran against the installed build of the commits it reviewed. The full record, with the attacks that failed, is Round 1 (memoised unwrap, first realness commit)
Round 2 (the stand-in)
Round 3 (the power-mean sharpness atom)
Checked and sound
Out of scope, filed
|
|
✅ Test Suite: success |
lmoresi
changed the base branch from
bugfix/jit-petsc-include-dirs
to
development
October 7, 2026 11:51
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Fixes #823. Stacked on #829 (the JIT include-path fix, which this needs to compile against a custom PETSc). Retarget to
developmentonce #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 inPow.__new__, profiled the other model families, and checked the generated headers byte for byte.Changes
Memoised unwrap.
unwrap_expression(depth=None)repeatedsubspasses 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:Derivativeof an atom whose content depends on the variable came back asSubs(...);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 anre().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 throughre/im.Differentiating with respect to a field.
sympy.diffswaps a non-Symbol variable for an assumption-freeDummy, so a real field turned complex while it was differentiated, and|u − c|leftDerivative(u, u), which cannot be compiled. Every Jacobian in the solvers now differentiates throughuw.function.diff_wrt_field/derive_by_array_wrt_field(new, public), whose stand-in is real: 38sympy.diffand 9derive_by_arraycalls, plus the free-surface conservation rate. This also fixes a defect already ondevelopment: an explicitAbsof 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)madePow.__new__evaluatesign(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.sfollows δ throughconstants[], so changing δ does not recompile.Identity and numbers
sympy.diff.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 ondevelopmentand with every change here switched off.Tests
New in
tests/test_0022_unwrap_memoised_matches_fixed_point.pyandtests/test_0023_field_realness_and_derivatives.py. Each was shown to fail without its fix.xreplace.sqrtof a square,Abs, a symbolic power, a heldDerivative, the array layout.sympy.diff.Docs updated:
docs/developer/subsystems/petsc-jacobian-layout.mdand the plasticity-solvers guide teachdiff_wrt_field;docs/api/function.mdlists both helpers;docs/reviews/2026-10/jit-setup-cost-823-adversarial-review.md.Behaviour to know
sympy.diffwith respect to a field now leavesDerivative(u, u)beside a fieldAbs. The guides direct such code touw.function.diff_wrt_field.BaseScalar, so it covers every coordinate system created afterimport underworld3.s, from which δ follows.Underworld development team with AI support from Claude Code