Skip to content

Make array operating-point evaluation linear without changing substitution semantics - #5190

Draft
ChrisRackauckas-Claude wants to merge 12 commits into
SciML:masterfrom
ChrisRackauckas-Claude:agent/5187-varmap-linear
Draft

ChrisRackauckas-Claude wants to merge 12 commits into
SciML:masterfrom
ChrisRackauckas-Claude:agent/5187-varmap-linear

Conversation

@ChrisRackauckas-Claude

@ChrisRackauckas-Claude ChrisRackauckas-Claude commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

The quadratic cost in #5187 comes from the non-IR evaluate_varmap! method, which builds du0 for DAEProblem. It maps every element u[i, j] in vars to the whole array u, and get on an array key scans all of its elements. So a 10k-element array costs 10k × 10k. This PR restores both evaluate_varmap! methods to master's code and makes one change: the non-IR method records keys whose value was absent or constant when visited, and skips their later visits.

Why this is exactly master's behavior. The loop only ever writes the key it is substituting. A key that was skipped is never written, so its value cannot change, and every later visit would also have skipped it. Substitution order, repeated fixpoint passes on unresolved keys, and all results are unchanged. The IR method (u0) is byte-for-byte master's. The grouping and whole-array evaluation from earlier revisions of this PR are gone, and with them the three review-round regressions: reverse-ordered chains, interleaved parents, and the TypeError for unknown-size array parameters.

Scaling (scratch/scaling.jl: DAEProblem(complete(sys), [u => U, D(u) => dU], ...; build_initializeprob = false) with @variables u(t)[1:n, 1:n]; every row asserts prob.u0 == vec(U) and prob.du0 == vec(dU). Both runs use the same environment on this machine; baseline overrides the evaluator with master's code.)

Elements Master time / allocation This PR time / allocation
625 0.380 s / 75.0 MiB 0.119 s / 9.4 MiB
2,500 3.572 s / 1,087.0 MiB 0.265 s / 38.0 MiB
10,000 91.672 s / 16,938.2 MiB 1.064 s / 153.7 MiB

Going from 625 to 10,000 elements (16×), allocations grow 226× on master and 16.4× with this PR.

Tests: failing on the previous head, passing now. New testsets in test/array_equation_dae.jl:

  • decreasing-order and interleaved-parent chains longer than substitution_limit, together with the increasing chain from round 2. Each runs on the IR path, the non-IR path and through ODEProblem.
  • a symbolic value for @parameters p::Vector{Float64}, on both paths and through ODEProblem.
  • the round-1 partial-array cases, with the fully specified case now on both paths.

The round-1 end-to-end initialization test stays in test/initializationsystem.jl. I ran the new testsets in scratch/r4_newtests.jl in three modes: this commit, the previous head bc7a50d (its evaluator replayed over this build), and master (its evaluator replayed).

# previous head bc7a50d
array operating points resolve dependencies in any visitation order |    3     4      2      9
  increasing  |  3        3
  decreasing  |     2  1  3     (IR/non-IR values x[1:8] == -999.0; ODEProblem errors)
  interleaved |     2  1  3     (a[2] == -999.0; ODEProblem errors)
symbolic values of unknown-size array parameters are substituted | Error 1
  TypeError: in typeassert, expected SymbolicUtils.ShapeVecT, got a value of type Unknown
# this commit, and master
array-keyed DAE operating points preserve element order             |    2      2
array operating points substitute specified symbolic elements       |    9      9
array operating points resolve dependencies in any visitation order |    9      9
symbolic values of unknown-size array parameters are substituted    |    3      3

Initialization test fix: the CI failure on 896d693. The top-level Initialization (Julia 1) job failed symbolic guesses for partial array unknowns reach initialization with z1_index !== nothing evaluating to nothing and successful_retcode([2.0, 0.0]). The cause is the test, not the evaluator:

  • Tearing picks different unknowns across Julia versions. That job includes MTKBase's initializationsystem.jl with ModelingToolkit loaded, so mtkcompile does full tearing. With D(z) ~ -z, tearing may keep either z[1] or zˍt[1] = -z[1], and the choice differs by Julia version.
  • On Julia 1.13.1, z[1] is observed. The init unknowns are [zˍt[1], zˍt[2]], so the unknown-index lookup returned nothing, and z[1]'s guess never reached zˍt[1], which started at a hashed random 0.418.
  • The solve stalls. zˍt[2] starts at the derivative guess 0, where zˍt[2]^2 ~ 8 has a singular Jacobian (Stalled).
  • It is not a dependency-version change. The MTK run on 1.11 with the same package versions also stalled. I reproduced the exact CI output locally with Julia 1.13.1 and CI's resolved versions (SymbolicUtils 4.48.0, Symbolics 7.41.1, SciMLBase 3.56.1). MTKBase-only runs passed on both versions.

The test now uses D(z) ~ -z.^3. z[1] then enters every equation nonlinearly, so tearing must keep it an iteration variable and its guess decides the root. z[2]'s initialization equation is linear, so the solve is well posed. It reads initprob[z[1]] == -8.0 by symbol instead of by unknown index, and adds init_sol[z[2]] ≈ 8.

revised test (scratch/mtkrepro/repro3.jl) Julia 1.11 Julia 1.13.1
with ModelingToolkit loaded 4/4 pass 4/4 pass
MTKBase only 4/4 pass 4/4 pass
MTKBase with the round-1 buggy evaluator replayed (a74b747) 2 fail (initprob[z[1]] = 0.499, z[1] ≈ 2.0) 2 fail (0.355, 2.0)

So the test still discriminates the round-1 regression on both versions. Full groups on the pushed head:

  • GROUP=Initialization julia +1 --project=. -e 'using Pkg; Pkg.test()', top-level, Julia 1.13.1, CI's package versions: Initialization | 930 passed, 12 broken, 942 total, 46m20.6s, Testing ModelingToolkit tests passed.
  • GROUP=Initialization julia +1.11 in lib/ModelingToolkitBase: InitializationSystem Test | 743 passed, 12 broken, Initial Values Test | 65/65, exit 0.

Open CI failure, needs a decision: lib/ModelingToolkitBase [Initialization] / Julia lts. On 896d693 and 1e90ccc, initializationsystem.jl:2521 ("Initialization problem type is shared across models, use_scc = true") fails. The ForwardDiff gradient is 9.898834314793689e154, against a finite-difference value of -1.1538935724475508. It fails on both heads with the same value. Other PRs pass that job with the same package versions, and bc7a50d passed it. What I established on Julia 1.10.12, with the same package versions as CI:

  • The changed function never runs in this test. A counter shows the non-IR evaluate_varmap! (the only function this PR changes) is called 0 times during problem construction and 0 times during the gradient.

  • The failure follows the compiled package image, not the evaluator code. I ran the extracted testset against each ModelingToolkitBase image:

    package image evaluator loaded gradient
    master master's correct (-1.15389357)
    master this PR's, via @eval correct
    master + one unused function master's correct
    this branch this PR's wrong (1.3172268582515041e153)
    this branch master's, via @eval wrong (same value)
  • The fault is in the Dual initialization path. With a Dual a[1], solve(..., Rodas5P(); abstol = 1e-10, reltol = 1e-10) returns Unstable at step 1. The algebraic y entries of the initialized state carry partials around ±2.5e154, though a[1] does not enter the y equations. Calling SciMLBase.get_initial_values(...; nlsolve_alg = nothing, abstol = 1e-10) directly gives the correct zero partials. So does passing initializealg = OverrideInit(nlsolve = NewtonRaphson()) to init, or omitting the tolerances.

  • It is specific to Julia 1.10. The same standalone script is correct on Julia 1.11. The full GROUP=Initialization runs pass locally on 1.10.12 for both master and this branch (exit 0), so CI's result depends on CI's build.

My reading: this is a latent Julia-1.10 bug in the ForwardDiff/DefaultInit initialization path of OrdinaryDiffEq/NonlinearSolve, and its outcome depends on the compiled package image. This PR's code is not executed when it fails. I did not find the faulty function, and I have not filed an issue. Changing this PR's code to dodge it would only hide the bug.

Other red checks on 1e90ccc also fail on master's latest run (0459027) (https://github.com/SciML/ModelingToolkit.jl/actions/runs/36188481402, /36188481437, /36188481315, /36188480913):

  • the Optimization groups (top-level Julia 1 and LTS, sublibrary Julia 1 and LTS, and downgrade);
  • the QA groups (top-level and sublibrary, Julia 1);
  • the downstream jobs NeuralPDE NNPDE2, SciMLBase SymbolicIndexingInterface and SciMLSensitivity Core8.

Verification (Julia 1.11.9, run from lib/ModelingToolkitBase). I used a private first depot (JULIA_DEPOT_PATH=<job>/scratch/r4_depot:~/.julia). The shared depot was being precompiled concurrently by other jobs, and a first InterfaceI attempt sat on its pidfile lock for 50 minutes without starting.

  • GROUP=InterfaceI julia +1.11 --project=. -e 'using Pkg; Pkg.test()': InterfaceI | 1769 passed, 5 broken, 1774 total, 45m45.1s, Testing ModelingToolkitBase tests passed. The 5 broken tests are pre-existing on master.
  • GROUP=QA ...: JET Tests | 54 54, Aqua Tests | 21 21, Testing ModelingToolkitBase tests passed.
  • Runic --check, typos and git diff --check on the three changed files: all exit 0.

Not verified:

  • other test groups, Julia 1.10/1.12, the docs build (no docstring or public API changes);
  • MethodOfLines/NeuralPDE end-to-end timing on this tip.

What a reviewer should push back on:

  • The speedup covers keys whose value is numeric, or becomes numeric after one substitution pass.
  • Arrays that stay symbolic (unresolvable values under allow_symbolic, or guesses that never resolve) are still re-substituted once per element on the non-IR path, as on master. Removing that would change master's repeated fixpoint behavior on substitution_limit-bound chains.
  • The IR path is unchanged, so arrays with many symbolic element values still pay an O(length) write per element there.
  • One earlier revision also changed the non-IR path to substitute specified elements of partially filled arrays. That changed master's behavior, and this PR no longer includes it. If it is wanted, it should be a separate PR.
  • No new dependencies, and no public API change.
  • The initialization test no longer asserts that z[1] is an unknown of the initialization problem. It asserts the same value (initprob[z[1]] == -8.0) by symbol, and uses dynamics under which tearing cannot make z[1] observed.
  • Separate finding, not addressed here and present on master: under ModelingToolkit, when tearing makes a guessed variable observed (z[1] = -zˍt[1]), its guess is not carried over to the unknown it depends on. The old test hit this on Julia 1.13.1.

Closes #5187

Please ignore this draft until reviewed by @ChrisRackauckas.

Risk assessment

  • Risk: low
  • Blast radius: evaluate_varmap! (non-IR method), which serves varmap_to_vars without ir: du0, bounds, parameters, and linearization operating points. Internal, not public API. Results are provably identical to master's; only redundant skipped lookups are removed.
  • Evidence: new tests fail on the previous head and pass on both master and this commit. InterfaceI and QA are green. Scaling table above.
  • Independent review: pending. Rounds 1–3 were Claude Code (claude-opus-5-5) and Codex (gpt-6-astra) on earlier designs.
  • Merge: needs human review until a different-harness reviewer rates this redesign.

🤖 Generated with Claude Code 2.1.283 (model: claude-opus-5-5); local session, transcript at /log-cont4.txt. Earlier commits on this branch are by Codex CLI 0.156.0 (gpt-6-luna) and Cursor Agent CLI (model auto).

  • Independent review (latest): Cursor (claude-fable-5-thinking-high), round 5 at 1e90ccc: MERGE, with maintainer sign-off needed for one red job.
    • The rewritten testset is not weaker. It still fails 2/4 against the round-1 evaluator bug.
    • The MTKBase Initialization (Julia lts) failure at initializationsystem.jl:2521 (gradient ~1e154) is in a test that predates this PR. The changed function is called 0 times there (checked with a counter).
    • The failure appears only with the full head configuration on Julia 1.10, and only under some build flags or hosts. Head src with master's tests passes, and master src with head's tests passes.
    • It looks like a latent, perturbation-sensitive Julia 1.10 codegen bug. Merging will likely leave master's sublibrary lts Initialization job red until that bug is fixed upstream.
    • Correction to this PR body: the full group does fail on some 1.10.12 machines.

Risk assessment (independent review, codex-cli gpt-6-astra, reviewed head bcba0fe)

  • Risk: low
  • Blast radius: non-IR operating-point substitution when scalar array elements repeatedly refer to the same whole-array key; no public signature or substitution-order change.
  • Evidence: Julia 1.13.1 full affected array-DAE test file exited 0, 55/55 assertions. A same-process original-evaluator comparison verified u0/du0 ordering and reduced allocations at 1600 elements from 427,690,480 to 18,039,704 bytes. The disclosed Julia 1.10 gradient test passed 23/23 locally with compiled modules disabled. Current CI failures match master; primary jobs remain pending.
  • Independent review: codex-cli 0.163.0 gpt-6-astra rated it low, high confidence: only absent/constant keys are memoized, so unresolved substitutions retain their original revisit order; local correctness and allocation checks support the claimed fix.
  • Merge: needs human review — the historical LTS compiled-image failure is not cleared by a source-mode probe, and current primary CI is pending. No blocking source-level finding.

🤖 Posted by an AI agent — harness: codex-cli · model: gpt-6-astra (independent reviewer; appended by Claude Code 2.1.301 · claude-opus-5-5)
Conversation: https://claude.ai/code/session_01VZjwf7Ux9YtTzwHGHMqnsq

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

Risk assessment (independent review, Codex gpt-6.1-sol, head 5b22168)

  • Verdict: MERGE
  • Rating: Codex gpt-6.1-sol rated it medium-low (ML3) at head 5b22168
  • Risk: medium-low (ML3: measured performance-only change on the peripheral non-IR operating-point path, with unchanged results). L2 and L7 also match; ML3 sets the highest level. This does not change the rubric's ModelingToolkit main lanes, mtkcompile or System construction, or the IR evaluator used for ordinary u0 evaluation.
  • Blast radius: Non-IR evaluate_varmap!, reached for DAE du0, unsplit parameters, bounds, and linearization operating points. Only absent or constant keys enter a fresh local set; substitutions write their own key, and unresolved keys retain the original order and repeated visits. No production dependency, exported name, public signature, numerical default, or SemVer-breaking change. New tests strengthen coverage without deleting, skipping, or loosening existing assertions.
  • Evidence: Read the full three-file git diff origin/HEAD...HEAD, the linked issue, evaluator callers, and the atomic-array dictionary implementation. git diff --check origin/HEAD...HEAD passed; checkout status stayed clean.
    • Local commands used Julia 1.13.1 at <local path>, --compiled-modules=no -O1, JULIA_NUM_THREADS=4, the requested JULIA_DEPOT_PATH, scratch TMPDIR, and timeout 3600. Ran --project=<local path> <local path>: head 27/27, base-evaluator replay 27/27, exit 0. These are all newly added array and initialization assertions, with analytic/algebraic expected values. The base comparison redefines the exact evaluator extracted by git show origin/HEAD:lib/ModelingToolkitBase/src/systems/problem_utils.jl; it is not a separate clean base checkout. The new correctness tests do not fail on base, consistent with this being a performance-only change.

    • Ran the same Julia invocation with <local path>, exit 0. After warming each size, the corrected probe explicitly uses Base.invokelatest following evaluator replacement. Every base/head sample asserts exact u0 == vec(U) and du0 == vec(dU):

      Elements Base seconds / bytes Head seconds / bytes
      100 0.030386 / 3,471,160 0.006873 / 1,690,720
      400 0.077032 / 31,823,992 0.021863 / 6,214,968
      1,600 1.000557 / 433,605,816 0.092212 / 23,989,904

      For 4× elements, allocations grow 13.63× on base versus 3.86× on head. These are single warmed samples, not statistical timing estimates. The initial nested timing probe did not honor evaluator replacement and is excluded from the evidence.

    • Read-only GitHub checks at this head show InterfaceI, top-level Initialization (Julia 1 and LTS), QA, Downstream, MethodOfLines DAE/2D diffusion/interface, and SciMLSensitivity Core8 passing. The sole failing check, SciMLBase SymbolicIndexingInterface, has 3,747 passed, two errors: identical BoundsError: attempt to access 1-element Vector{Float64} at index [[1, 2]] failures at downstream comprehensive_indexing.jl:127 and :164 in both the PR log and default-branch commit 91fd79ea485807e783bc2dc341e930ad39241e5a. This comparison is supported by both downloaded logs, not the author's assertion.

    • G1: not applicable — production numerical behavior is unchanged; the initialization assertions additionally use independent roots/values (-2 and 8).

    • G2: not applicable — no GPU kernel, AD rule, Reactant tracing, or MPI implementation changes. The changed CPU evaluator is exercised locally and by passing downgrade InterfaceI CI; SciMLSensitivity Core8 is also green.

    • G3: not applicable — the set is allocated per invocation, with no shared or persistent cache. Increasing, decreasing, and interleaved dependency tests exercise revisitation rather than prematurely settling unresolved values.

  • Merge: merge (no blocking findings). This is an independent code-review recommendation; the rubric's medium-low requirement for two qualifying independent reviews and outstanding CI checks still applies.

🤖 Posted by an AI agent — harness: Codex CLI 0.162.1 · model: gpt-6.1-sol
Conversation: local headless review run (no public session URL); transcript kept by the fleet master.

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

Risk assessment (independent review, Codex gpt-6.1-sol, head 5b22168)

  • Independent review: Codex CLI (gpt-6.1-sol) rated it medium-low (ML3), high confidence: VERDICT MERGE at head 5b22168. No blocking source-level defect found; the per-call settled-key set preserves unresolved substitutions and removes redundant array lookups. Independent targeted checks preserve operating-point values and confirm substantially reduced allocation growth.
  • Risk: medium-low (ML3: measured performance-only change on the peripheral non-IR operating-point path, with unchanged results). L2 and L7 also match; ML3 sets the highest level. This does not change the rubric's ModelingToolkit main lanes, mtkcompile or System construction, or the IR evaluator used for ordinary u0 evaluation.
  • Blast radius: Non-IR evaluate_varmap!, reached for DAE du0, unsplit parameters, bounds, and linearization operating points. Only absent or constant keys enter a fresh local set; substitutions write their own key, and unresolved keys retain the original order and repeated visits. No production dependency, exported name, public signature, numerical default, or SemVer-breaking change. New tests strengthen coverage without deleting, skipping, or loosening existing assertions.
  • Merge: merge (no blocking findings). This is an independent code-review recommendation; the rubric's medium-low requirement for two qualifying independent reviews and outstanding CI checks still applies.

🤖 Posted by an AI agent — harness: Claude Code 2.1.302 (fleet master, relaying a Codex CLI gpt-6.1-sol review) · model: claude-opus-5-5
Conversation: https://claude.ai/code/session_0133iSjsLBByPU93BDEQkNDF

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Risk assessment (independent review, Devin (fusion-gpt-6-1-sol-high-sidekick-swe-2-medium), local job oss-reviews-2026-10-22-SciML-ModelingToolkit-jl-5190-devin-5b22168 (no session URL), head 5b22168)

  • Verdict: MERGE
  • Risk: medium (M3)
  • Summary: The change preserves operating-point semantics and removes quadratic numeric-array lookups, with a measured scalar-evaluator overhead and no blocking correctness findings.
  • Merge: ready to merge

Executed review notes (head 5b22168):

Findings

  1. lib/ModelingToolkitBase/src/systems/problem_utils.jl:539 — nit — The new set also tracks distinct scalar keys, where there are no repeated array parents to eliminate. A warmed, alternating head/base microbenchmark measures approximately 23 versus 13 microseconds for 100 scalar keys and 2.77 versus 1.89 milliseconds for 10,000, with additional allocations. Consider avoiding memoization for scalar-only keys or disclosing this tradeoff. This is non-blocking: values remain identical, the absolute overhead is small in the tested scalar DAE constructors, and the intended array case improves substantially.

Evidence

Independent risk assessment: Before opening pr.json or reading any author/reviewer rating, I recorded a provisional medium-high (MH1) assessment in tmp/risk-before-body.txt, conservatively treating this as a main-lane constructor change. Caller tracing established that the changed non-IR evaluator is peripheral: ordinary u0 construction uses the unchanged IR overload, and default System construction/mtkcompile do not change. Final matched criteria are L2 (added, meaningful tests), L7 (small internal refactor on exercised paths), ML3 (measured peripheral performance improvement), and M3 (measured slowdown on the scalar non-IR path). M3 sets the highest level: medium. No H1/H4 API break or removed verification. No production numerical behavior changes requiring new G1 reference evidence, or changed GPU/AD-rule/Reactant/MPI implementation requiring G2 execution. The per-call set introduces no persistent shared cache; dependency-order tests and consecutive absent/constant lookup probes cover premature settling and leaked memoization.

  • Reviewed supplied pr.diff, pr.json, the complete affected evaluator, its callers and the atomic-array dictionary implementation. Head is 5b22168f530be6cb476bc9a153a0c0c065f415e1; merge-base is 9082f85877d65b42af0ce8800c334bef52fb472d.
  • git -C repo diff 9082f85877d65b42af0ce8800c334bef52fb472d HEAD > tmp/actual.diff; cmp pr.diff tmp/actual.diff: exit 0. git diff --check also exited 0. Production diff: 10 insertions, 2 deletions in one method; tests add 146 lines. A source comparison prints IR evaluator and subsequent file byte-identical: True. Final checkout status is clean.
  • Correctness invariant: the loop only writes the whole-array parent currently being substituted. The wrapper's whole-array setter writes only that dictionary key. A key skipped for an absent/constant value cannot be modified by another iteration, while unresolved keys retain every original revisit. The set is fresh per invocation.
  • Ordinary unknown and initialization vectors explicitly pass ir to the unchanged overload. Changed callers cover DAE derivative vectors, unsplit parameters, bounds, linearization and explicit respecialize. No exported/public name, signature, default, dependency, compat or licence change. No tests/assertions deleted, skipped or loosened. The new expected values come from supplied operating points, explicit dependency chains and algebraic roots, rather than implementation output.

Local Julia: 1.12.7, JULIA_NUM_THREADS=4, scratch archive tmp/head and project tmp/env. Resolved Symbolics 7.47.0, SymbolicUtils 4.53.0, SciMLBase 3.58.0, NonlinearSolve 4.32.0, OrdinaryDiffEqBDF 2.4.13. Successful retry/performance runs used a private first depot tmp/depot, the existing shared depot as fallback, scratch TMPDIR=tmp/runtime, and a 2,400-second timeout per run.

Commands and real output:

**These two commands additionally used the scratch depot/TMPDIR described above.**
timeout 2400 julia --startup-file=no --compiled-modules=existing -O1 --project=tmp/env tmp/targeted.jl
MODE=head Julia=1.12.7 threads=4
Full affected array DAE file and new initialization | 59 59 2m53.1s
**exit 0**

REVIEW_MODE=base timeout 2400 julia --startup-file=no --compiled-modules=existing -O1 --project=tmp/env tmp/targeted.jl
MODE=base Julia=1.12.7 threads=4
Full affected array DAE file and new initialization | 59 59 2m52.5s
**exit 0**

These execute the full affected array-DAE file, including existing analytic heat-equation solves, plus the new initialization test. Base mode replays the exact old non-IR method extracted with git show into the scratch head package before running the tests. All 27 newly added assertions also pass base: this is expected for a performance-only fix, not evidence of a correctness regression fixed by this diff. Initial harness attempts stopped before assertions because the scratch project omitted direct test dependency DiffEqBase; the existing manifest dependency was then added to the scratch project's direct dependencies. Logs are retained as tmp/{head,base}-tests.log and successful tmp/{head,base}-tests-retry.log.

timeout 2400 julia --startup-file=no --compiled-modules=no -O1 --project=tmp/env -e 'include("tmp/count_get.jl"); include("tmp/bench.jl")'
MODE=head constant=false get_calls=1
MODE=head constant=true get_calls=1
One lookup per settled array | 2 2
Warmed DAE construction and default ODE control | 36 36
**exit 0**

REVIEW_MODE=base timeout 2400 julia --startup-file=no --compiled-modules=no -O1 --project=tmp/env -e 'include("tmp/bench.jl"); include("tmp/count_get.jl")'
Warmed DAE construction and default ODE control | 36 36
MODE=base constant=false get_calls=100
MODE=base constant=true get_calls=100
Expression: counted.lookups == 1
Evaluated: 100 == 1
One lookup per settled array | Fail 2 Total 2
**exit 1, deliberately demonstrating the two failing-before optimization assertions**

Every construction sample asserts exact u0 ordering and, for DAEs, exact du0 ordering. Three warmed samples per case give:

Elements Base DAE seconds / bytes Head DAE seconds / bytes
100 0.009703 / 2,923,472 0.005647 / 1,320,752
400 0.068719 / 30,540,864 0.018796 / 4,928,544
1,600 1.020706 / 428,819,928 0.075795 / 19,431,360

For the final 4x increase in element count, allocation grows 14.04x on base versus 3.94x on head. Ordinary ODE controls also pass all exact-value assertions; at 1,600 elements they allocate 28,602,352 bytes on base and 28,602,320 on head (0.043349/0.044087 seconds). Runs overlap other compilation work, so small timing differences are not statistical performance claims.

timeout 2400 julia --startup-file=no --compiled-modules=existing -O1 --project=tmp/env tmp/scalar_and_mtk.jl
Julia=1.12.7 threads=4 ModelingToolkit loaded
symbolic guesses for partial array unknowns reach initialization | 4 4 2m31.3s
Scalar DAE control | 108 108 25.0s
**exit 0**

The full-ModelingToolkit initialization test confirms guess -8, negative root -2 and second state 8. The scalar DAE head/base/head comparison preserves all values. At 100 states it allocates 3,341,840 versus 3,338,440 bytes; median times were 0.011511/0.010965/0.011643 seconds. At 500 states the final head/base times are essentially equal, 0.049467/0.049442 seconds, with about 12.8 KB extra allocation on head.

The additional isolated scalar benchmark uses nine warmed samples of 100 evaluations per mode, alternating head/base/head/base in one process, with Base.invokelatest after method replacement. All 12 isequal assertions preserving the input maps pass:

timeout 2400 julia --startup-file=no --compiled-modules=existing -O1 --project=tmp/env tmp/scalar-evaluator-perf.jl
**exit 0; full output: tmp/scalar-evaluator-perf-retry.log**
SCALAR EVALUATOR mode=head n=100 median_seconds=0.000023061 bytes=8200
SCALAR EVALUATOR mode=base n=100 median_seconds=0.000013421 bytes=4800
SCALAR EVALUATOR mode=head n=500 median_seconds=0.000113380 bytes=36754
SCALAR EVALUATOR mode=base n=500 median_seconds=0.000077604 bytes=24000
SCALAR EVALUATOR mode=head n=10000 median_seconds=0.002769741 bytes=677301
SCALAR EVALUATOR mode=base n=10000 median_seconds=0.001889461 bytes=480000

These are the second head/base pair; the first pair shows the same direction and similar magnitudes. This establishes the non-default-path slowdown used for M3, rather than inferring it from noisy end-to-end timings. The first probe attempt used == on symbolic dictionaries and errored in the harness assertion; it was corrected to isequal before the successful run.

The supplied CI snapshot has 107 successful, 3 skipped matrix placeholders and 1 failed check. InterfaceI, Initialization (including LTS), QA, Downstream, MethodOfLines DAE/2D diffusion/interface, NeuralPDE and SciMLSensitivity Core8 checks succeed. Independently downloaded both the PR failed job and the merge-base failed job using read-only gh api repos/SciML/ModelingToolkit.jl/actions/jobs/<id>/logs --allow-escape-sequences. Both show:

comprehensive_indexing.jl:127: State indexing: Error During Test
BoundsError: attempt to access 1-element Vector{Float64} at index [[1, 2]]
comprehensive_indexing.jl:164: Observed: Error During Test
BoundsError: attempt to access 1-element Vector{Float64} at index [[1, 2]]
Some tests did not pass: 3747 passed, 0 failed, 2 errored, 0 broken.

The failure therefore predates this PR. The body’s numeric-array scaling and preserved-substitution claims are supported. Its historical “open” LTS-initialization failure is superseded by the successful current-head checks in the supplied snapshot. Symbolic arrays that never settle still incur repeated work, as the body explicitly discloses.

Not verified

  • The complete test suite and full test groups were not rerun locally; CI evidence is the supplied head snapshot plus independently fetched failure logs. Each local run was limited to 40 minutes.
  • Julia versions other than 1.12.7, platform variants, and fresh default-compiled package images were not tested locally. The historical Julia-1.10 image-sensitive gradient issue was not reproduced; current-head LTS Initialization checks are successful in the supplied snapshot.
  • Base comparison replays the exact changed method over the scratch head package; it is not a separate full base checkout or a comparison of separately compiled base/head package images.
  • The author's 10,000-element timings, the reported 46,000-state MethodOfLines example, and the docs build were not rerun. Local scaling tests cover up to 1,600 array elements, and scalar evaluator tests cover up to 10,000 keys. Permanently symbolic arrays remain outside this optimization, as disclosed in the body.

repo remained clean. No commits, pushes, GitHub posts or source edits were made.


🤖 Posted by an AI agent — harness: Devin · model: fusion-gpt-6-1-sol-high-sidekick-swe-2-medium (independent reviewer; appended by Antigravity CLI · model: gemini-4-argon-high)
Conversation: local job oss-reviews-2026-10-22-SciML-ModelingToolkit-jl-5190-devin-5b22168 (no session URL)

🤖 Automated review section from an AI agent running as Chris Rackauckas's account — not written or reviewed by Chris.

Risk assessment (independent review, Codex CLI 0.164.0 gpt-6.1-sol, slot 1, head 5b22168)

  • Risk: medium (M3: The non-IR evaluator has a measured scalar-only slowdown despite a large Any-array speedup; the per-call settled set is not shared state.)
  • Verdict: MERGE
  • Session: 01a18da8-3a3a-7620-b234-342bf3d4309e
  • Blocking priorities: none

Review round 2, written by the reviewer named above (Codex CLI 0.164.0 / gpt-6.1-sol) 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: Avoids repeated constant/absent array lookups in the non-IR operating-point evaluator. Local correctness tests pass on both refs and Any-array costs drop sharply, while measured scalar overhead keeps the medium M3 classification.

Blast radius: Non-IR evaluate_varmap! used for DAE derivatives, parameter/bounds maps and operating-point construction; the IR evaluator is unchanged.

Evidence: Julia 1.13.2: the complete array-equation file and the exact added initialization testset pass 55+4 assertions on both refs. With 2500 Any-typed numeric array elements, helper time/allocation drops from 1.955871481 s / 1002194976 bytes on the base to 0.010467947 s / 2075424 bytes on the head; independent input-value assertions pass. For 20000 distinct scalar keys, time increases from 0.005370016 s to 0.009097294 s and bytes from 1517336 to 2304488. G1 uses explicit substitution values, analytic heat solutions and root checks; G2 is exercised locally for both evaluator forms and constructor/initialization integration; G3 has no persistent/shared cache because settled is allocated per call. M3 captures the documented non-IR scalar tradeoff.

Blocking findings

None.

Non-blocking findings

  1. lib/ModelingToolkitBase/src/systems/problem_utils.jl:534: Preserve the limitation that unresolved symbolic array values may still be revisited; the settled set removes repeat lookups only for absent or constant values.

  2. lib/ModelingToolkitBase/src/systems/problem_utils.jl:539: Consider avoiding the settled set for distinct scalar-only keys or explicitly document the measured tradeoff. The local 20000-key probe increases from 5.37 ms / 1.52 MB to 9.10 ms / 2.30 MB. This is a non-IR helper cost, not evidence that the default IR constructor becomes quadratic.

What I ran

First-round read-only inspection, retained for this unchanged head. Repository commands below ran in the isolated checkout and exited 0; rev-parse HEAD matched the live head metadata. Base is the fetched target-branch tip at review time, while the three-dot diff uses the merge base. Newest non-merge commit trailers, rather than body attribution, supply AUTHOR_GRADE provenance.

git fetch origin +refs/pull/5190/head:refs/remotes/pr/5190 +refs/heads/master:refs/remotes/origin/master
git checkout --detach pr/5190
git rev-parse HEAD
git rev-parse origin/master
git diff --check origin/master...HEAD
git log -1 --no-merges --format=%B
git diff origin/master...HEAD

Read-only GitHub inspection (PR views exit 0; pr checks exits 1 because failures exist):

gh pr view 5190 --repo SciML/ModelingToolkit.jl --json number,url,state,isDraft,headRefOid,baseRefName,baseRefOid,title,files,commits,statusCheckRollup
gh pr view 5190 --repo SciML/ModelingToolkit.jl --json body,closingIssuesReferences
gh pr checks 5190 --repo SciML/ModelingToolkit.jl
gh issue view 5187 --repo SciML/ModelingToolkit.jl --json number,title,body,state,url
gh run view 39042927146 --repo SciML/ModelingToolkit.jl --log-failed
gh run list --repo SciML/ModelingToolkit.jl --branch master --event push --limit 5 --json databaseId,headSha,conclusion,url,name
gh run view 38950292025 --repo SciML/ModelingToolkit.jl --log-failed
gh run view --repo SciML/ModelingToolkit.jl --job 117450258558 --log

CI check rollup at the captured head: {"FAILURE": 1, "SKIPPED": 3, "SUCCESS": 107}. Log-retrieval exit codes are retrieval status, not test exit codes: successful retrieved jobs report tests passed; failed jobs remain failed. Failed-run logs were retrieved with a writable scratch XDG_CACHE_HOME. Unavailable logs are disclosed above. The recent default-branch five-run listing was also read; exact historical comparisons are identified in the evidence paragraph.

MTKBase InterfaceI CI passed 1826 assertions with 5 existing broken markers. Initialization, Downstream and SciMLSensitivity Core8 checks pass; SII remains red with the exact comprehensive_indexing BoundsErrors in historical master 38950292025. The author reports 10k-element allocation reduction from 16938.2 to 153.7 MiB; I inspected the methodology but did not rerun timings, so this is not reviewer-measured performance. After comparison, caller tracing at problem_utils.jl:362-370 confirms ordinary u0 takes the unchanged IR overload; this optimization is an auxiliary non-IR path rather than System construction/mtkcompile. The provisional MH1 rating is therefore revised to medium/M3; no old numerical benchmark is claimed as my execution.

Inspected CI URLs: https://github.com/SciML/ModelingToolkit.jl/actions/runs/39042927146, https://github.com/SciML/ModelingToolkit.jl/actions/runs/39042927628/job/117450258558, https://github.com/SciML/ModelingToolkit.jl/actions/runs/38950292025.

After freezing the complete initial review, compared the latest same-head review and re-read the evaluator dispatch at problem_utils.jl:362-370. This supports peripheral non-IR scope and replaces the provisional MH1 rating with M3 for the scalar hot-path cost. The prior scalar timings are not my measurements.

Round 2 local execution:

All 20 live PRs were checked OPEN with unchanged reviewed heads before Julia execution. Each run checked out the exact detached SHA shown below. Julia 1.13.2 ran directly inside the inherited resource scope, with one Julia invocation at a time, four Julia threads and one BLAS thread. The isolated environment was created with Pkg.activate(temp=true) and Pkg.develop(path=...) for the checkout and its MTKBase subpackage, then persisted outside the checkout for dependency reuse. No test project or source was edited in the checkout.

The driver activates that environment, resolves compatible registered dependencies without updating registries, and includes each selected script in a fresh module. It catches only at the test-file boundary to record every selected result, then exits nonzero if any selected case failed. Assertions and tolerances are unchanged. --compiled-modules=existing reuses available dependency caches and loads uncached PR source; it does not disable tests.

base-master-rootcontext-retry: detached 550a27cca63cbe6d7b64bcb2920440aaff9eaa55 (origin/master), process exit 1, 487.54 s.

git -C ModelingToolkit.jl checkout --detach origin/master
REVIEW_CASES='5182,5190,5190-bench,5202,5205-root,5205-contract,5205-ad,5213,5221,5202-bench,5221-bench' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 10.0.1, NonlinearSolve 4.32.0, ModelingToolkit 11.47.0, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.79.0, OptimizationBase 5.10.0.

extra-base-checks: detached 550a27cca63cbe6d7b64bcb2920440aaff9eaa55 (origin/master), process exit 1, 323.45 s.

git -C ModelingToolkit.jl checkout --detach origin/master
REVIEW_ENV_DIR=tmp/rerun/env-extra \
REVIEW_CASES='5121-sentinel,5190-scalar-bench,5190-array-helper-bench,5195-noad,5221-oracle,5215' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 10.0.1, NonlinearSolve 4.32.0, ModelingToolkit 11.47.0, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.79.0, OptimizationBase 5.10.0.

head-5190: detached 5b22168f530be6cb476bc9a153a0c0c065f415e1 (pr/5190), process exit 1, 251.73 s.

git -C ModelingToolkit.jl checkout --detach pr/5190
REVIEW_CASES='5190,5190-bench,5190-scalar-bench,5190-array-helper-bench' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 9.33.1, NonlinearSolve 4.32.0, ModelingToolkit 11.45.4, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.77.4, OptimizationBase 5.10.0.

rerun-head-5190-scalar: detached 5b22168f530be6cb476bc9a153a0c0c065f415e1 (pr/5190), process exit 0, 43.5 s.

git -C ModelingToolkit.jl checkout --detach pr/5190
REVIEW_CASES='5190-scalar-bench' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 9.33.1, NonlinearSolve 4.32.0, ModelingToolkit 11.45.4, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.77.4, OptimizationBase 5.10.0.

rerun-base-5190-any: detached 550a27cca63cbe6d7b64bcb2920440aaff9eaa55 (origin/master), process exit 0, 55.24 s.

git -C ModelingToolkit.jl checkout --detach origin/master
REVIEW_CASES='5190-any-helper-bench' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 10.0.1, NonlinearSolve 4.32.0, ModelingToolkit 11.47.0, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.79.0, OptimizationBase 5.10.0.

rerun-head-5190-elements: detached 5b22168f530be6cb476bc9a153a0c0c065f415e1 (pr/5190), process exit 0, 47.38 s.

git -C ModelingToolkit.jl checkout --detach pr/5190
REVIEW_CASES='5190-element-helper-bench,5190-any-helper-bench' \
JULIA_DEPOT_PATH="$PWD/depot:" JULIA_NUM_THREADS=4 OPENBLAS_NUM_THREADS=1 \
TMPDIR="$PWD/tmp" JULIA_NUM_PRECOMPILE_TASKS=1 JULIA_PKG_PRECOMPILE_AUTO=0 \
timeout 3600 julia --startup-file=no --compiled-modules=existing --depwarn=yes tmp/rerun/driver.jl

Resolved versions: SymbolicUtils 4.54.0, Symbolics 7.47.0, SciMLBase 3.58.0, JumpProcesses 9.33.1, NonlinearSolve 4.32.0, ModelingToolkit 11.45.4, ModelingToolkitTearing 1.20.7, ModelingToolkitBase 1.77.4, OptimizationBase 5.10.0.

Included the complete changed lib/ModelingToolkitBase/test/array_equation_dae.jl and extracted the exact added initialization testset: 55+4 assertions pass on each ref. Direct DAE construction at 625/2500 elements retains exact input values on both refs. The initial head process exits 1 only because my scalar benchmark used symbolic dictionary ==, which does not yield Bool; the benchmark was corrected to structural isequal and rerun successfully without changing a PR assertion.

Measured helper output (minimum of repeated timed calls):

base scalar n=5000  seconds=0.001135812 bytes=379544
head scalar n=5000  seconds=0.001886860 bytes=576760
base scalar n=20000 seconds=0.005370016 bytes=1517336
head scalar n=20000 seconds=0.009097294 bytes=2304488
base Any-array n=625  seconds=0.105046561 bytes=63045040
head Any-array n=625  seconds=0.002383065 bytes=515488
base Any-array n=2500 seconds=1.955871481 bytes=1002194976
head Any-array n=2500 seconds=0.010467947 bytes=2075424

Numeric whole-array and per-element fixtures also return identical specified values. Current master already has a separate numeric-constant-array fast path; the Any-typed fixture is the remaining repeated-scan case this settled-set optimization improves. All dedicated corrected scalar/Any benchmark processes exit 0. The mixed base batch exits 1 for later reviewer-probe/context errors, and the initial root base batch for other requested PR regressions; the #5190 correctness cases themselves pass.

Exact reviewer script 5190-scalar-bench.jl:

using ModelingToolkitBase, Symbolics, Test
@independent_variables t
@variables x(t)
function scalar_bench(n)
    vars = [Symbolics.unwrap(ModelingToolkitBase.renamespace(Symbol("scalar",i),x)) for i in 1:n]
    op = Dict{Symbolics.SymbolicT,Symbolics.SymbolicT}(vars .=> collect(1.0:n))
    function run()
        work=copy(op)
        ModelingToolkitBase.evaluate_varmap!(work,vars)
        return work
    end
    @test isequal(run(),op)
    times=Float64[]; bytes=Int[]
    for _ in 1:10
        stat=@timed run()
        push!(times,stat.time);push!(bytes,stat.bytes)
    end
    println("SCALAR_BENCH n=",n," min_seconds=",minimum(times)," min_bytes=",minimum(bytes))
end
for n in [5000,20000];scalar_bench(n);end

Exact reviewer script 5190-any-helper-bench.jl:

using ModelingToolkitBase, Symbolics, Test
@independent_variables t
function array_helper_bench(n)
    @variables x(t)[1:n]
    vars=Symbolics.unwrap.(collect(x))
    expected=collect(1.0:n)
    op=Dict(x=>Any[expected...])
    make()=ModelingToolkitBase.varmap_to_vars(op,vars)
    @test make()==expected
    times=Float64[];bytes=Int[]
    for _ in 1:3
        stat=@timed make()
        @test stat.value==expected
        push!(times,stat.time);push!(bytes,stat.bytes)
    end
    println("ANY_HELPER_BENCH n=",n," min_seconds=",minimum(times)," min_bytes=",minimum(bytes))
end
for n in [625,2500];array_helper_bench(n);end

What I did not verify

No whole suite, GPU, Reactant, MPI or exhaustive operating-point type/shape matrix was run. Measurements are targeted single-host helper/constructor runs, not a universal solve-throughput claim. Unresolved symbolic arrays may still require repeated substitution. The first scalar benchmark harness error is explicitly superseded by the successful structural-equality rerun. A clean native-precompile cycle was not verified: the initial batch dependency workload errored during NonlinearSolveFirstOrder AD-backend selection. The recorded test commands use existing caches and JIT-load uncached PR source; no assertion was disabled.

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

ChrisRackauckas and others added 8 commits September 22, 2026 23:31
Evaluate indexed variable-map entries once per array parent. Add a DAE regression test for array-keyed initial values.

Co-Authored-By: Chris Rackauckas <[email protected]>

Co-Authored-By: Codex <[email protected]>

Agent-Harness: Codex CLI 0.156.0

Agent-Model: gpt-6-luna

Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log.txt on amdci2.julia.csail.mit.edu
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Codex <[email protected]>
Agent-Harness: Codex CLI 0.156.0
Agent-Model: gpt-6-luna
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log.txt on amdci2.julia.csail.mit.edu
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Codex <[email protected]>
Agent-Harness: Codex CLI 0.156.0
Agent-Model: gpt-6-luna
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log.txt on amdci2.julia.csail.mit.edu
Whole-array lookup on a partially specified array returns the default
when any element is a hole, silently dropping user-supplied symbolic
element values. Evaluate specified elements individually when holes or
partial coverage make the whole-array substitution unsafe, keep the
single whole-array fixpoint pass otherwise, treat a whole-array key in
vars as requesting every element, and route the non-IR wrapper through
the same element-aware evaluation.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.1
Agent-Model: swe-2-max
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log-cont1.txt on amdci2.julia.csail.mit.edu
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.1
Agent-Model: swe-2-max
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log-cont1.txt on amdci2.julia.csail.mit.edu
Whole-array fixpoint substitution for fully covered symbolic arrays
drops acyclic cross-element resolution (e.g. x[i] => x[i-1]+1 beyond
the iteration limit). Keep the once-per-parent early return for numeric
arrays, and write symbolic elements back immediately. Replace the
non-public SymbolicUtils.as_linear_idx call with LinearIndices.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Cursor Agent <[email protected]>
Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe
Agent-Model: auto
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log-cont3.txt on amdci2.julia.csail.mit.edu
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Cursor Agent <[email protected]>
Agent-Harness: Cursor Agent CLI 2026.09.26-dd393fe
Agent-Model: auto
Agent-Session: local session, transcript at /home/crackauc/sandbox/agent-jobs/ModelingToolkit.jl/jobs/5187-codex/log-cont3.txt on amdci2.julia.csail.mit.edu
Returns both `evaluate_varmap!` methods to master's code and keeps a single
change: the generic (non-IR) method remembers keys whose value was absent or
constant when visited and skips their later visits. Only the key being
substituted is ever written, so a skipped key's value cannot change and every
later visit would skip it too. Substitution order and results are therefore
identical to master on every input, while an array key visited once per
element no longer pays an O(length) lookup on each visit.

Adds regression tests for decreasing-order and interleaved-parent dependency
chains and for symbolic values of unknown-size array parameters, on the IR and
non-IR paths and through `ODEProblem`. Drops the test asserting the non-IR
partial-array behavior change, which is not master's behavior.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude <[email protected]>
Agent-Harness: Claude Code 2.1.283
Agent-Model: claude-opus-5-5
Agent-Session: local session, transcript at /home/crackauc/sandbox/aj/m5187/log-cont4.txt on amdci2.julia.csail.mit.edu
@ChrisRackauckas-Claude ChrisRackauckas-Claude changed the title Fix array operating point evaluation scaling Make array operating-point evaluation linear without changing substitution semantics Sep 27, 2026
Under ModelingToolkit's `mtkcompile`, `D(z) ~ -z` lets tearing replace `z[1]`
by `-zˍt[1]`, and which of the two it keeps depends on the Julia version. On
Julia 1.13 `z[1]` became observed, so the test's unknown-index lookup returned
`nothing` and its guess did not reach the initialization problem. The
`z[2]^2` equation also left a derivative unknown starting at the singular
point 0, so the initialization stalled. Cubic dynamics keep `z[1]` an iteration
variable under any tearing order, and a linear `z[2]` equation keeps the solve
well posed. Values are read by symbol, and `z[2]` is now also checked.

Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Claude <[email protected]>
Agent-Harness: Claude Code 2.1.283
Agent-Model: claude-opus-5-5
Agent-Session: local session, transcript at /home/crackauc/sandbox/aj/m5187/log-cont4.txt on amdci2.julia.csail.mit.edu
Co-Authored-By: Chris Rackauckas <[email protected]>
Co-Authored-By: Devin <[email protected]>
Agent-Harness: Devin CLI 3000.11.3 (conflict resolution), Claude Code 2.1.285 (orchestration)
Agent-Model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Agent-Session: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master); Devin log /Users/chrisrackauckas/sandbox/master/fusion-fixes/SciML_ModelingToolkit.jl-5190/log.txt
@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Merged the default branch into this PR (clean merge, no conflicts; head 41acdad) so CI runs on current master.


🤖 Posted by an AI agent — harness: Devin CLI 3000.11.3 (merge), Claude Code 2.1.285 (posting) · model: fusion-claude-opus-5-5-high-sidekick-swe-2-medium
Conversation: local Claude session 3c311569-dda6-4687-bc9f-65febb212c33 (fleet master)

@xtalax

xtalax commented Oct 19, 2026

Copy link
Copy Markdown
Member

Benchmark data point from closed #5280, which made an equivalent per-array dedupe of the same evaluate_varmap! loop. On a 46k-state MethodOfLines 2D TM DAE, DAEProblem construction went from 394 s and 316 GiB allocated on master to 2.6 s and 1.2 GiB. I haven't timed this PR's head on that problem.

🤖 Posted by an AI agent · harness: Claude Code 2.1.304 · model: claude-opus-5-5
Review: unreviewed
Session: aa65e380-52df-443a-9f57-8c20c56babb9

AayushSabharwal pushed a commit that referenced this pull request Oct 30, 2026
evaluate_varmap! rewrote the whole array value on every element write, and the non-IR method re-substituted an array whose value stayed symbolic once per element, so a symbolic array initial condition cost O(N^2) (62 s at N = 8000 on the IR path). The IR method now buffers element writes per array and stores the array back only when it is next read, and the non-IR method settles a key whose substitution reached a fixpoint. Substitution order and results are unchanged. Independent of, and complementary to, #5190.

Agent-Harness: Claude Code 2.1.310
Agent-Model: claude-sonnet-5-5
Agent-Session: de59b94f-0227-49ea-adb5-b158639dad0b
Agent-Review: unreviewed
Co-authored-by: Claude Code <[email protected]>
@xtalax-droid

Copy link
Copy Markdown
Contributor

Checked against current master (60fb2a7ecf), with timings from a local run of DAEProblem on an array-keyed u:

  • Master now has an equivalent per-array settled set in the non-IR evaluate_varmap! (problem_utils.jl:597-606), and the IR method goes through PendingWritesWrapper (Resolve symbolic array operating points in linear time #5327). DAEProblem construction is linear on master: 625 / 2,500 / 10,000 elements take 0.019 / 0.111 / 0.295 s and 6.6 / 25 / 112 MiB.
  • This PR's four new array_equation_dae.jl testsets (element order, specified symbolic elements, any visitation order, unknown-size array parameters) pass unchanged on master. The new initializationsystem.jl test was not run, since it needs the full Initialization group.
  • The remaining difference is that settled is not updated for keys whose value is absent or constant. varmap_to_vars(Dict(x => Any[1.0:n...]), vars) without ir is still quadratic on master: n = 625 / 2,500 / 10,000 take 0.08 / 0.65 / 10.9 s and 60 MiB / 956 MiB / 15.3 GiB. This PR's head does the same cases in 0.002 s / 0.5 MiB (n = 625) and 0.010 s / 2 MiB (n = 2,500).
  • The one failed check on this PR, SciMLBase.jl/SymbolicIndexingInterface/1, ran on the old base; the same job is green on master's latest run.

A rebase onto master would shrink this to a one-hunk change (push!(settled, arr) on that branch) plus the tests. The conflict is in that same settled hunk.


🤖 Posted by an AI agent · harness: Claude Code 2.1.325 · model: claude-sonnet-5-5
Review: unreviewed
Session: de59b94f-0227-49ea-adb5-b158639dad0b

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.

varmap_to_vars is quadratic in the element count of array unknowns (DAEProblem construction)

4 participants