Skip to content

Bind array variables read by the output of optimize rules - #5417

Open
singhharsh1708 wants to merge 28 commits into
SciML:masterfrom
singhharsh1708:hs/rules-bind-arrays
Open

singhharsh1708 wants to merge 28 commits into
SciML:masterfrom
singhharsh1708:hs/rules-bind-arrays

Conversation

@singhharsh1708

@singhharsh1708 singhharsh1708 commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Fixes #5416.

An optimize rule whose output reads a whole array variable, for example sum(x) on a scalarized x, gave an f that throws UndefVarError: x: build_function_wrapper only binds the arrays the expressions read before the rules run, and the rules run later inside Symbolics.codegen_function. When rules are given it now binds every array variable the arguments can rebuild. Without rules the generated code is unchanged. With rules a function carries a few unused bindings, and those bindings become requirements: a state passed as a tuple can't be viewed into, and the cached parameter-array layout of a system is reused even when a later call passes different parameters. An array split between the state and a cache buffer still isn't rebuilt, as before.

Binding those arrays exposed two gaps in the cache-array reconstruction: the multi-buffer branch read from the wrong arguments (missing buffer_offset), and merging the cache buffers shifted missing elements so an incomplete array was no longer skipped. Both are fixed. The new tests fail on master with the UndefVarError, give 12.0 instead of 62.0 without the offset fix, and throw a BoundsError without the merge fix.

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

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

PR: #5417

Reviewed head: 74aeb9d
Raw SHA-256: af7db10091ae17e75c673bbe97a99025faae3b479d18eaf8c90105dc9908e196
Source SHA-256: 4c95e3758f057edd146a069fcf33bf60de620ec8bb31f61dd0bb629e19a53e20
Source: standard-review-v1 (harness-log)
Reviewer session: 01a1f3ab-8a33-7353-a4af-6ed9b66f7e61
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: medium (M2)
  • Verdict: CHANGES
  • Reviewed head: 74aeb9d

Review report

VERDICT: CHANGES
Round: 2
Head: 74aeb9d
Slot: 1
CI: CI is not green
Session: 01a1f3ab-8a33-7353-a4af-6ed9b66f7e61
Reviewer: codex-cli 0.170.0; model: gpt-6.2-sol

Risk

medium (M2: opt-in optimization silently changes a previously correct preface result)

Blocking findings

  • Blocking priorities: P1, P2, P2
  • [P1] Array reconstruction overwrites a system preface assignment (lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1145). I generated a function with scalarized inputs x[1:4], a preface assigning x = [10.0, 20.0, 30.0, 40.0], and a rule replacing sin(x[1]) + 1 with sum(x) + 1. For input [2.0, 4.0, 6.0, 8.0], the optimized function returned 101.0 on the base and 21.0 on both PR heads. Generating sum(x) + 1 directly returned 101.0 on all three revisions. The inner wrapper rebinds x from the input after the preface runs. Emit the rule-introduced reconstructions alongside the existing reconstructions, before extra assignments and the preface, and add a regression that asserts 101.0.
  • [P2] Tuple-valued observed functions miss rule-introduced array reads (lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1141, :1157). With y ~ sin(x[1]), I generated the observed output (y, x[2]) and applied a rule yielding (sum(x), x[2]). The tuple control returned (0.9092974268256817, 4.0) and the optimized vector control returned [20.0, 4.0]. The optimized tuple threw UndefVarError: x not defined. The post-rule search skips the elements of MakeTuple. Scan the tuple elements against the optimized IR and test that the optimized tuple returns (20.0, 4.0).
  • [P2] The post-rule scan and the regression use non-public SymbolicUtils APIs (lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1141, lib/ModelingToolkitBase/test/code_generation.jl:5). On SymbolicUtils 4.56.1, Base.ispublic returned false for IRStructureSearchBuffer and replace_node!, and true for search_variables! and Code.OptimizationRule. The IR-aware public search_variables! overload can scan each symbolic leaf. Use public IR operations in the regression or have replace_node! made public upstream.

Non-blocking findings

  • lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1135 relies on a maximum-priority rule running last. In the installed SymbolicUtils 4.56.1 source, the IR optimizer sorts priorities in ascending order. The OptimizationRule docstring specifies higher priorities first. Use a supported post-optimization hook or establish the ordering in the dependency's public contract.

What I ran

  • The delta initializes the array map before selecting a layout (lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1053). A direct build_function_wrapper probe with non_standard_param_layout = true and a rule introducing sum(x) + 1 returned the expected 21.0 on both PR heads. The preface, observed-output and public-API probes produced the results above.
  • Julia 1.12.4 with scratch manifests resolving Symbolics 7.49.0, SymbolicUtils 4.56.1 and OrdinaryDiffEq 7.8.1. The focused SafeTestsets run passed code generation (83/83) and function chunking (56/56). The added regression alone exited 1 on the base with UndefVarError: x not defined.
  • GROUP=InterfaceII julia --startup-file=no --project=lib/ModelingToolkitBase -e 'using Pkg; Pkg.test()' from a scratch snapshot also passed code generation (83/83) and function chunking (56/56). It exited 1 at JumpSystem Test (4,279 passed, 1 failed). I ran the failing @test_nowarn assertion at lib/ModelingToolkitBase/test/jumpsystem.jl:604 in isolation with --check-bounds=yes --depwarn=yes. Both base and head exited 1 with the same JumpProcesses 10.2.0 deprecation warning for the dependency-map keywords.
  • git diff --check passed for the complete diff and the delta. Runic's check of both edited Julia files and typos on added lines exited 0. The checkout was clean. The newest commit had neither an Agent-Harness nor an Agent-Model trailer.
  • uv run --locked python --version printed Python 3.13.13 and warned that --locked has no effect outside a project. The checkout has no Python lockfile.

What I did not verify

  • The tests after JumpSystem in InterfaceII, other test groups, minimum supported Julia and dependency versions, and CI details.

AUTHOR_GRADE: {"task":"bugfix","score":2,"difficulty":3,"rounds":2,"author_harness":"unknown","author_model":"unknown","note":"The added ODE regression distinguishes base and head. All three prior blockers reproduce, including the silent preface result regression."}

Head link: 74aeb9d


🤖 Posted by an AI agent — harness: codex-cli 0.170.0 · model: gpt-6.2-sol
Conversation: local session 01a1f3ab-8a33-7353-a4af-6ed9b66f7e61 (no session URL)

@singhharsh1708

Copy link
Copy Markdown
Member Author

Fixed: rule-read arrays are now bound before extra_assignments and the preface (the case gives 101.0), and tuple, nested and codegen-container outputs are scanned. I kept IRStructureSearchBuffer, which this function already uses for the search before the rules and test/qa/aqua.jl already allows: one public search_variables! call per element walks shared subexpressions again for each element, which took codegen with a rule from 1.22 s to 3.70 s on a right-hand side whose 2000 elements share one 2000-term sum. The test now uses a rule that returns a new IRStructure instead of replace_node!, and the output is recorded at both priority ends, so it doesn't depend on the sort order.

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

PR: #5417

Reviewed head: 6f9ef68
Raw SHA-256: b051b77986ec2bc86f95040249cf5fd85c8f19be65347619205f26c2a71389b3
Source SHA-256: 7497e723eb73d258223d54c911cbe10eefbf4f0790df1ca442a0ab6afe2bc1c7
Source: standard-review-v1 (harness-log)
Reviewer session: 01a1fa9e-0c9a-7a30-811c-be4f05acd816
Slot: 1
Confidence: unknown
Own risk fixed before author rating/discussion: yes
Redaction: ran (substitutions=0)

Risk assessment

  • Risk: low (L6)
  • Verdict: CHANGES
  • Reviewed head: 6f9ef68

Review report

VERDICT: CHANGES
Round: 3
Head: 6f9ef68
Slot: 1
CI: noregress
Session: 01a1fa9e-0c9a-7a30-811c-be4f05acd816
Reviewer: codex-cli 0.169.0; model: gpt-6.2-astra

Risk

low (L6: opt-in array rewrites that errored on the merge base now return the expected values. The preface result and the generated code in the no-rule control match the base.)

Blocking findings

  • Blocking priorities: P2
  • [P2] The new scans at lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1167 and :1169 still construct the private SymbolicUtils.IRStructureSearchBuffer. The tests removed replace_node! but now use the private aliases Symbolics.SymbolicT and Symbolics.SConst at lib/ModelingToolkitBase/test/code_generation.jl:509 and :522. I confirmed all three names return false from Base.ispublic in the resolved dependencies. Use the public search_variables!(set, ir, leaf; ...) overload on each symbolic leaf. It found x in the optimized sum in my probe. The tests can use the public SymbolicUtils.BasicSymbolic and SymbolicUtils.Const for the type check and constructor.

Non-blocking findings

  • lib/ModelingToolkitBase/src/systems/codegen_utils.jl:1158 captured the final tuple output at priorities typemin(Int), 1 and typemax(Int) with SymbolicUtils 4.56.1. I observed ascending execution order. The rule docstring specifies descending order, under which a user rule tied at typemin(Int) would run after the minimum-priority recorder. Putting both recorders after the user rules in the input list covers that tie with either stable sort direction.

What I ran

  • I used Julia 1.13.2 with identical scratch manifests for head and merge base a640aa9fdf11e8524dc2fafff6cd16eabadc3433. They resolved Symbolics 7.49.0, SymbolicUtils 4.56.1 and OrdinaryDiffEq 7.8.1 from the sublibrary's declared dependencies and test target. The added test set passed 16/16 on head. On the merge base its first optimized in-place call threw UndefVarError: x not defined.
  • With explicit unwrap.(collect(x)) inputs and values [2, 4, 6, 8], the preface assignment made both the rewritten function and the direct sum(x) + 1 control return 101.0 on head and base. For the observed output (y, x[2]) with y ~ sin(x[1]), the optimized head returned (20.0, 4.0) and the base threw UndefVarError. The unoptimized control returned (0.9092974268256817, 4.0) on both.
  • For [x[2], sum(x) + 1, x[4] - x[1]], both generated functions returned or wrote [4.0, 21.0, 6.0] on each revision. With either optimize=nothing or an empty rule vector, cmp found the base and head expressions byte-identical after line-number removal.
  • GROUP=InterfaceII julia --startup-file=no --compiled-modules=existing --check-bounds=yes --depwarn=yes --project=. lib/ModelingToolkitBase/test/runtests.jl passed Code Generation 95/95 and Function Chunking 56/56. It stopped at lib/ModelingToolkitBase/test/jumpsystem.jl:604 with 4,279 passes and one failure in JumpSystem. I reran that assertion on the merge base and reproduced the same JumpProcesses 10.2.0 dependency-map deprecation warning inside @test_nowarn. I then ran the nine remaining head test sets in runner order with the preceding package imports loaded. They recorded 2,225 passes and two existing @test_broken assertions.
  • git diff --check passed for the full diff and the delta. Runic passed on both changed files and typos passed on the added lines. The checkout was clean. uv run --locked python --version printed Python 3.15.0 and warned that --locked has no effect outside a project. The repository has no Python lockfile or tracked Julia manifest.

What I did not verify

I did not rerun other test groups, test minimum supported versions, benchmark code generation, or independently inspect remote CI.

AUTHOR_GRADE: {"task":"bugfix","score":4,"difficulty":3,"rounds":3,"author_harness":"unknown","author_model":"unknown","note":"The preface and tuple reproducers now pass, and the new regression distinguishes base from head. The post-rule scan and tests still use private dependency names."}

Head link: 6f9ef68


🤖 Posted by an AI agent — harness: codex-cli 0.169.0 · model: gpt-6.2-astra
Conversation: local session 01a1fa9e-0c9a-7a30-811c-be4f05acd816 (no session URL)

@singhharsh1708

Copy link
Copy Markdown
Member Author

Switched the scan to one public search_variables!(set, ir, leaves) call over a Const of all the rule-output leaves, moved both recorders after the user rules, and the tests now use SymbolicUtils.BasicSymbolic and SymbolicUtils.Const. The one private name left is replace_node! in two tests: there's no public way to rewrite a node inside an IR while keeping its roots, and that's exactly what DyadCompilerPasses' rules do.

@ChrisRackauckas

Copy link
Copy Markdown
Member

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

Thanks @singhharsh1708. At head 14a3e54 the job lib/ModelingToolkitBase [Initialization] / Julia 1 fails, and the same job passes on master (6 other failures on this head also occur on master, so this is the only one that looks specific to the PR). The failing assertion, from run https://github.com/SciML/ModelingToolkit.jl/actions/runs/44905958109/job/136852423327:

Initialization problem type is shared across models, use_scc = true: Test Failed
  lib/ModelingToolkitBase/test/initializationsystem.jl:2072
  Expression: ≈((ForwardDiff.gradient(loss, [1.5]))[1], fd, rtol = 0.0001)
   Evaluated: -5.923329591483093e165 ≈ -1.15389356836193 (rtol=0.0001)
Some tests did not pass: 794 passed, 1 failed, 0 errored, 12 broken.

The ForwardDiff gradient blows up to about -6e165 where the finite difference gives -1.15. Could you check whether the new binding of array variables read by optimize rules changes this use_scc = true initialization path, or whether this is intermittent (a rerun of the job on this head would show that)? A review round at this head waits until the job is green or shown to fail the same way on master.


🤖 Posted by an AI agent — harness: Claude Code 2.1.325 · model: claude-sonnet-5-5
Conversation: local session 3878b54e-28f2-4a01-a176-a8f5468d1997 (no session URL)

@singhharsh1708

Copy link
Copy Markdown
Member Author

It doesn't reproduce here: GROUP=Initialization on 14a3e54 passes locally (Julia 1.12.7), InitializationSystem Test 795 passed, 12 broken, including that gradient. The same group passed on Julia lts in this CI run, and that test gives no optimize rules, which is the only path this PR touches. Looks intermittent; could someone rerun the job?

@DhairyaLGandhi

Copy link
Copy Markdown
Member

Could you show the generated code beforethese changes to motivate what the error is. This seems like a lot of machinery.

@singhharsh1708

Copy link
Copy Markdown
Member Author

A rule that rewrites x[1]'s equation into sum(x) + 1, on D(x[i]) ~ sin(x[i]) + 1. Before, the generated f reads a global x, because MTK only binds the arrays the expressions read before the rules run:

local var"##cse#2" = x
local var"##cse#4" = var"##cse#2"(t)
local var"##cse#5" = mapreduce(identity, Base.add_sum, var"##cse#4")
# f throws UndefVarError: `x` not defined

After, it binds x from the state and gives [11.0, ...]:

x = reshape(view(___mtkunknowns___, 4:-1:1), (4,))
local var"##cse#3" = mapreduce(identity, Base.add_sum, x)

Agreed it was too much machinery. Most of it came from following the automated review round by round, which I've stopped doing. I've cut it down to binding every array the arguments can rebuild whenever rules are given, which the existing helpers already do with filter_vars = nothing, plus a missing buffer offset in their multi-buffer branch that this exposed. The cost is a few unused views in functions built with rules.

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.

optimize rules whose output reads a whole array variable give UndefVarError

4 participants