From a9f1d9689d41bc3e4b7b0c4ad8291aec9b236972 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 26 Nov 2026 05:08:45 +0000 Subject: [PATCH 1/2] ModelingToolkitTearing: concretely type the inline linear SCC solve cache `numeric_ldiv!` took its `LinearCache` from a `Dict` with `Any` values, so the `solve_into!` call after the lookup was a runtime dispatch. A `juliac --trim` build of generated code that inlines a numeric linear SCC then fails: `--trim=safe` reports the call as unresolved, and an `unsafe-warn` binary throws a `MethodError` on the first solve, for both `Float64` and `ForwardDiff.Dual` arguments. Assert the type a new cache infers to for the argument types, and key the cache by the type of `b` as well as `A` so the assertion always holds. License: AGPL-3.0-only Copyright: JuliaHub, Inc. Co-Authored-By: Claude Opus 5.5 --- lib/ModelingToolkitTearing/src/reassemble.jl | 24 ++++++++++------- lib/ModelingToolkitTearing/test/runtests.jl | 27 ++++++++++++++++++++ 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/lib/ModelingToolkitTearing/src/reassemble.jl b/lib/ModelingToolkitTearing/src/reassemble.jl index 9c16768..164734a 100644 --- a/lib/ModelingToolkitTearing/src/reassemble.jl +++ b/lib/ModelingToolkitTearing/src/reassemble.jl @@ -781,18 +781,24 @@ function get_inline_linsolve_cache(A::AbstractMatrix, b::AbstractVector) # (an `IdDict{Any, Any}`) would be boxed on every call caches = get!(InlineLinsolveCachesT, task_local_storage(), INLINE_LINSOLVE_CACHE)::InlineLinsolveCachesT - cache = get(caches, (typeof(A), size(A)), nothing) - return cache === nothing ? init_inline_linsolve_cache!(caches, A, b) : cache + cache = get(caches, (typeof(A), typeof(b), size(A)), nothing) + cache === nothing && return init_inline_linsolve_cache!(caches, A, b) + # The `Dict` holds caches of every array type, so its values are untyped. Asserting the + # type a new cache infers to lets the solve after this dispatch statically, which + # `juliac --trim` needs. The key includes both array types, so the assertion holds. + return cache::Base.promote_op(new_inline_linsolve_cache, typeof(A), typeof(b)) end +# `A` and `b` are views into the diffcache buffers of whichever problem happens to call +# first, and the cache keeps what it is handed, so it needs copies it owns. `copy` rather +# than `Matrix`/`Vector` so the cache keeps the array type it was given, which matters for +# anything living off the CPU. +new_inline_linsolve_cache(A, b) = CommonSolve.init(LinearProblem(copy(A), copy(b))) + # out of line, since inlined it slows every inline solve by ~25 ns on Julia 1.13 @noinline function init_inline_linsolve_cache!(caches, A::AbstractMatrix, b::AbstractVector) - # `A` and `b` are views into the diffcache buffers of whichever problem happens - # to call first, and the cache keeps what it is handed, so it needs copies it owns. - # `copy` rather than `Matrix`/`Vector` so the cache keeps the array type it was - # given, which matters for anything living off the CPU. - cache = CommonSolve.init(LinearProblem(copy(A), copy(b))) - caches[(typeof(A), size(A))] = cache + cache = new_inline_linsolve_cache(A, b) + caches[(typeof(A), typeof(b), size(A))] = cache return cache end @@ -836,7 +842,7 @@ Key of this package's entry in task local storage, which holds the `LinearCache` """ const INLINE_LINSOLVE_CACHE = :ModelingToolkitTearing_inline_linsolve_cache -const InlineLinsolveCachesT = Dict{Tuple{DataType, Dims{2}}, Any} +const InlineLinsolveCachesT = Dict{Tuple{DataType, DataType, Dims{2}}, Any} """ $TYPEDSIGNATURES diff --git a/lib/ModelingToolkitTearing/test/runtests.jl b/lib/ModelingToolkitTearing/test/runtests.jl index 942a715..5bfe3e6 100644 --- a/lib/ModelingToolkitTearing/test/runtests.jl +++ b/lib/ModelingToolkitTearing/test/runtests.jl @@ -213,6 +213,33 @@ end @test MTKTearing.numeric_ldiv_again!(S, [3.0, 1.0]) ≈ pinv(S) * [3.0, 1.0] end +@testset "Inline linear SCC solve is statically typed for Float64 and Dual" begin + # `A` depends on the state, so the SCC is solved by `numeric_ldiv!` at runtime + @variables x(t) y(t) z(t) + @parameters k = 2.0 + eqs = [ + D(x) ~ -x + y + z, + 0 ~ (k + x^2) * y + (1 + x^2) * z - 1, + 0 ~ (1 + x^2) * y - (3 + x^2) * z - x, + ] + reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; + inline_linear_sccs = true, analytical_linear_scc_limit = 1) + @mtkcompile sys = System(eqs, t) reassemble_alg = reassemble_alg + prob = ODEProblem(sys, [x => 0.5], (0.0, 1.0)) + rhs(xv) = (du = [zero(xv)]; prob.f.f(du, [xv], prob.p, 0.0); du[1]) + ref(xv) = -xv + sum([2 + xv^2 1 + xv^2; 1 + xv^2 -3 - xv^2] \ [1, xv]) + @test rhs(0.5) ≈ ref(0.5) + @test ForwardDiff.derivative(rhs, 0.5) ≈ ForwardDiff.derivative(ref, 0.5) + + # the cache lookup has to infer concretely, or the solve after it is a runtime + # dispatch, which `juliac --trim` cannot compile + for T in (Float64, ForwardDiff.Dual{Nothing, Float64, 1}) + A, b = T[2 1; 1 3], T[1, 2] + MTKTearing.numeric_ldiv!(copy(A), copy(b)) + @inferred MTKTearing.get_inline_linsolve_cache(A, b) + end +end + @testset "Inline linear SCC derivatives stay correct across repeated solves" begin @variables x(t) = 1.0 y(t) = 1.0 z(t) = 1.0 w(t) = 1.0 q(t) = 1.0 reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; inline_linear_sccs = true) From 93ab862839976972f86b39cec1103cabda239315 Mon Sep 17 00:00:00 2001 From: Anshul Singhvi Date: Thu, 26 Nov 2026 06:06:44 +0000 Subject: [PATCH 2/2] ModelingToolkitTearing: don't let an inline solve overwrite a shared right-hand side `numeric_ldiv!` writes its solution into `b`, on the assumption that `b` belongs to its solve site alone. It does not: CSE merges the `b` buffers of two inline linear SCCs whose right-hand sides are equal, fills the merged buffer once, and passes it to both solves. The second solve then reads the first one's solution as its right-hand side, and both the RHS and its derivatives come back wrong without an error. Have `safe_ldiv`, the operation the generated code calls, solve a copy of `b`. That costs one allocation of the size of `b` per solve. `A` needs no copy: CSE shares it the same way, but `numeric_ldiv!` only copies it into the cache's own matrix and never writes to it. License: AGPL-3.0-only Copyright: JuliaHub, Inc. Co-Authored-By: Claude Opus 5.5 --- lib/ModelingToolkitTearing/src/reassemble.jl | 11 ++++-- lib/ModelingToolkitTearing/test/runtests.jl | 35 ++++++++++++++++++++ 2 files changed, 43 insertions(+), 3 deletions(-) diff --git a/lib/ModelingToolkitTearing/src/reassemble.jl b/lib/ModelingToolkitTearing/src/reassemble.jl index 164734a..b250221 100644 --- a/lib/ModelingToolkitTearing/src/reassemble.jl +++ b/lib/ModelingToolkitTearing/src/reassemble.jl @@ -712,7 +712,11 @@ function safe_ldiv(A, b) shape = SU.promote_shape(safe_ldiv, SU.shape(A), SU.shape(b)) ) end - return numeric_ldiv!(A, b) + # CSE can hand the same `b` buffer to several solves: two SCCs whose right-hand sides + # are equal share one. `numeric_ldiv!` writes its solution into `b`, so solve a copy, + # or every later solve on the buffer reads this solution as its right-hand side. `A` + # needs no copy, since `numeric_ldiv!` only reads it. + return numeric_ldiv!(A, copy(b)) end """ @@ -729,8 +733,9 @@ The cache is task local because the emitted expression is shared by every proble from it, while `A` and `b` are not. One cache is kept per array type and size, so a solve site can share with another of the -same shape. The solution is therefore copied back into `b`, which belongs to this solve -site alone, rather than returning the cache's own buffer. +same shape. The solution is therefore copied back into `b` rather than returned in the +cache's own buffer. `A` is only read. The emitted code can share `b` between solve sites, +so [`safe_ldiv`](@ref) passes a copy. """ function numeric_ldiv!(A::AbstractMatrix, b::AbstractVector) # the lookup is necessarily type unstable, so the solve goes behind a function barrier diff --git a/lib/ModelingToolkitTearing/test/runtests.jl b/lib/ModelingToolkitTearing/test/runtests.jl index 5bfe3e6..48a7ec5 100644 --- a/lib/ModelingToolkitTearing/test/runtests.jl +++ b/lib/ModelingToolkitTearing/test/runtests.jl @@ -308,6 +308,41 @@ end @test du[1] ≈ refdu[1] end +@testset "Inline linear SCCs whose right-hand sides CSE to one buffer" begin + # Both SCCs have the right-hand side `[x, x]`, so CSE fills one `b` buffer and passes + # it to both solves. The first solve must not leave its solution in that buffer. + @variables x(t) y(t) z(t) u(t) v(t) + @parameters k = 2.0 + eqs = [ + D(x) ~ -x + y + z + 2u - v, + 0 ~ (k + x^2) * y + (1 + x^2) * z - x, + 0 ~ (1 + x^2) * y - (3 + x^2) * z - x, + 0 ~ (5 + x^2) * u + (2 + x^2) * v - x, + 0 ~ (1 - x^2) * u - (4 + x^2) * v - x, + ] + reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; + inline_linear_sccs = true, analytical_linear_scc_limit = 1) + @mtkcompile sys = System(eqs, t) reassemble_alg = reassemble_alg + @test length(MTKTearing.inline_linear_systems(sys)) == 2 + prob = ODEProblem(sys, [x => 0.5], (0.0, 1.0)) + rhs(xv) = (du = [zero(xv)]; prob.f.f(du, [xv], prob.p, 0.0); du[1]) + function ref(xv) + yz = [2 + xv^2 1 + xv^2; 1 + xv^2 -3 - xv^2] \ [xv, xv] + uv = [5 + xv^2 2 + xv^2; 1 - xv^2 -4 - xv^2] \ [xv, xv] + return -xv + yz[1] + yz[2] + 2uv[1] - uv[2] + end + for xv in (0.5, 1.3) + @test rhs(xv) ≈ ref(xv) + @test ForwardDiff.derivative(rhs, xv) ≈ ForwardDiff.derivative(ref, xv) + end + + # the generated code calls `safe_ldiv`, which must leave both of its arguments alone + A, b = [2.0 1.0; 1.0 3.0], [1.0, 2.0] + @test MTKTearing.safe_ldiv(A, b) ≈ [2.0 1.0; 1.0 3.0] \ [1.0, 2.0] + @test A == [2.0 1.0; 1.0 3.0] + @test b == [1.0, 2.0] +end + include("enzyme.jl") @testset "`inline_linear_systems` diagnostic" begin