diff --git a/lib/ModelingToolkitTearing/ext/ModelingToolkitTearingEnzymeCoreExt.jl b/lib/ModelingToolkitTearing/ext/ModelingToolkitTearingEnzymeCoreExt.jl index 27f9464..03a09bd 100644 --- a/lib/ModelingToolkitTearing/ext/ModelingToolkitTearingEnzymeCoreExt.jl +++ b/lib/ModelingToolkitTearing/ext/ModelingToolkitTearingEnzymeCoreExt.jl @@ -44,9 +44,9 @@ function check_activity(A, b, W) return nothing end -function solve_and_warn_if_singular!(A, b) - MTKTearing.numeric_ldiv!(A, b) - if MTKTearing.inline_linsolve_fell_back(A, b) +function solve_and_warn_if_singular!(A, b, site_id::UInt64 = UInt64(0)) + MTKTearing.numeric_ldiv!(A, b, site_id) + if MTKTearing.inline_linsolve_fell_back(A, b, site_id) @warn """ Differentiating an inline linear solve with a singular matrix. The solve returned \ the minimum norm least squares solution, and the derivative is computed as if the \ @@ -57,17 +57,24 @@ function solve_and_warn_if_singular!(A, b) end function EnzymeRules.forward( - config::EnzymeRules.FwdConfig, ::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector + config::EnzymeRules.FwdConfig, fn::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector + ) + return EnzymeRules.forward(config, fn, RT, A, b, Const(UInt64(0))) +end + +function EnzymeRules.forward( + config::EnzymeRules.FwdConfig, ::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector, + site_id::Const{UInt64} ) W = Val(EnzymeRules.width(config)) check_activity(A, b, W) - solve_and_warn_if_singular!(A.val, b.val) + solve_and_warn_if_singular!(A.val, b.val, site_id.val) if !isconstant(b, W) for (i, db) in enumerate(shadows(b, W)) isconstant(A, W) || mul!(db, shadows(A, W)[i], b.val, -1, 1) # nothing else is solved between the primal and its tangents, so they share # its factorization - MTKTearing.numeric_ldiv_again!(A.val, db) + MTKTearing.numeric_ldiv_again!(A.val, db, site_id.val) end end primal = EnzymeRules.needs_primal(config) @@ -86,14 +93,21 @@ function EnzymeRules.forward( end function EnzymeRules.augmented_primal( - config::EnzymeRules.RevConfig, ::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector + config::EnzymeRules.RevConfig, fn::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector + ) + return EnzymeRules.augmented_primal(config, fn, RT, A, b, Const(UInt64(0))) +end + +function EnzymeRules.augmented_primal( + config::EnzymeRules.RevConfig, ::NumericLdiv, RT::Type, A::RealMatrix, b::RealVector, + site_id::Const{UInt64} ) W = Val(EnzymeRules.width(config)) check_activity(A, b, W) # `A` is a scratch buffer that the caller refills before the reverse pass runs, so the # tape needs its own copy. It is stored transposed, ready for the adjoint solve. tape = isconstant(b, W) ? nothing : (permutedims(A.val), similar(b.val)) - solve_and_warn_if_singular!(A.val, b.val) + solve_and_warn_if_singular!(A.val, b.val, site_id.val) tape === nothing || copyto!(tape[2], b.val) primal = EnzymeRules.needs_primal(config) ? b.val : nothing shadow = if !EnzymeRules.needs_shadow(config) @@ -107,10 +121,18 @@ function EnzymeRules.augmented_primal( end function EnzymeRules.reverse( - config::EnzymeRules.RevConfig, ::NumericLdiv, RT::Type, tape, A::RealMatrix, + config::EnzymeRules.RevConfig, fn::NumericLdiv, RT::Type, tape, A::RealMatrix, b::RealVector ) - tape === nothing && return (nothing, nothing) + EnzymeRules.reverse(config, fn, RT, tape, A, b, Const(UInt64(0))) + return (nothing, nothing) +end + +function EnzymeRules.reverse( + config::EnzymeRules.RevConfig, ::NumericLdiv, RT::Type, tape, A::RealMatrix, + b::RealVector, site_id::Const{UInt64} + ) + tape === nothing && return (nothing, nothing, nothing) At, x = tape W = Val(EnzymeRules.width(config)) for (i, db) in enumerate(shadows(b, W)) @@ -118,10 +140,11 @@ function EnzymeRules.reverse( # holds x̄ is the one that has to end up holding it. The cache has seen other # solves since the primal, so the first of a batch factorizes `At` and the rest # reuse that. - i == 1 ? MTKTearing.numeric_ldiv!(At, db) : MTKTearing.numeric_ldiv_again!(At, db) + i == 1 ? MTKTearing.numeric_ldiv!(At, db, site_id.val) : + MTKTearing.numeric_ldiv_again!(At, db, site_id.val) isconstant(A, W) || mul!(shadows(A, W)[i], db, transpose(x), -1, 1) end - return (nothing, nothing) + return (nothing, nothing, nothing) end end diff --git a/lib/ModelingToolkitTearing/src/diagnostics.jl b/lib/ModelingToolkitTearing/src/diagnostics.jl index ff47112..8fc3f55 100644 --- a/lib/ModelingToolkitTearing/src/diagnostics.jl +++ b/lib/ModelingToolkitTearing/src/diagnostics.jl @@ -23,9 +23,9 @@ struct InlineLinearSystem """ variables::Vector{SymbolicT} """ - The symbolic solve expression `A \\ b` (its `arguments` are the coefficient - matrix `A` and the right-hand side `b`), retained so callers can inspect or - numerically evaluate `A`, e.g. to check its conditioning. + The symbolic solve expression `A \\ b` (its `arguments` start with the coefficient + matrix `A`, the right-hand side `b`, and the solve-site id), retained so callers can + inspect or numerically evaluate `A`, e.g. to check its conditioning. """ expression::SymbolicT end diff --git a/lib/ModelingToolkitTearing/src/reassemble.jl b/lib/ModelingToolkitTearing/src/reassemble.jl index 9c16768..76c61ee 100644 --- a/lib/ModelingToolkitTearing/src/reassemble.jl +++ b/lib/ModelingToolkitTearing/src/reassemble.jl @@ -490,7 +490,7 @@ function generate_system_equations!(state::TearingState, neweqs::Vector{Equation # algebraic variables. linsol_result = nothing if !is_disc && inline_linear_sccs - linsol_result = get_linear_scc_linsol(state, escc, vscc, neweqs, var_eq_matching, full_var_eq_matching, total_sub, analytical_linear_scc_limit, simplify) + linsol_result = get_linear_scc_linsol(state, escc, vscc, neweqs, var_eq_matching, full_var_eq_matching, total_sub, analytical_linear_scc_limit, simplify; site_id = UInt64(scc_idx)) end if linsol_result isa Tuple{SymbolicT, BitVector, BitVector} linsol, eqs_mask, vars_mask = linsol_result @@ -701,18 +701,38 @@ function dump_linear_scc_to_file(fname, A, x) return nothing end -function safe_ldiv(A, b) +""" +Key of this package's entry in task local storage, which holds the `LinearCache`s of +[`numeric_ldiv!`](@ref) by array type, size, and solve site id. +""" +const INLINE_LINSOLVE_CACHE = :ModelingToolkitTearing_inline_linsolve_cache + +const InlineLinsolveCacheKeyT = Tuple{DataType, DataType, Dims{2}, UInt64} +const InlineLinsolveCachesT = Dict{InlineLinsolveCacheKeyT, Any} + +mutable struct InlineLinsolveCacheEntry{C, M} + const cache::C + const A_prev::M + initialized::Bool +end + +function safe_ldiv(A, b, site_id::UInt64 = UInt64(0)) A = unwrap(A) b = unwrap(b) if A isa SymbolicT || A isa AbstractMatrix{Num} || A isa AbstractMatrix{SymbolicT} || b isa SymbolicT || b isa AbstractVector{Num} || b isa AbstractVector{SymbolicT} return Symbolics.STerm( - safe_ldiv, Symbolics.SArgsT((A, b)); + safe_ldiv, Symbolics.SArgsT((A, b, SU.Const{VartypeT}(site_id))); type = Vector{Real}, 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. The copy lives here rather than + # in `numeric_ldiv!` because the Enzyme rules rely on `numeric_ldiv!` overwriting `b`. + return numeric_ldiv!(A, copy(b), site_id) end """ @@ -728,29 +748,49 @@ is kept in task local storage and reused, so a steady state call neither builds The cache is task local because the emitted expression is shared by every problem built 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. +One cache is kept per array types, size, and solve site (`site_id`), so distinct solve +sites of the same shape do not clobber each other's `LinearCache` and skip +refactorization when `A` is unchanged. The solution is 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) +function numeric_ldiv!(A::AbstractMatrix, b::AbstractVector, site_id::UInt64 = UInt64(0)) # the lookup is necessarily type unstable, so the solve goes behind a function barrier - return solve_into!(get_inline_linsolve_cache(A, b), A, b) + return solve_into!(get_inline_linsolve_cache(A, b, site_id), A, b) end -function solve_into!(cache, A::AbstractMatrix, b::AbstractVector) +function _entries_identical(A::AbstractMatrix, B::AbstractMatrix) + @inbounds for i in eachindex(A, B) + A[i] === B[i] || return false + end + return true +end + +function solve_into!(entry::InlineLinsolveCacheEntry, A::AbstractMatrix, b::AbstractVector) # Fill the cache's own buffers and assign them back, rather than writing through # `cache.A` in place. The assignment is what runs LinearSolve's invalidation. Under # `ForwardDiff` that matters twice over: a `DualLinearCache` keeps the primal matrix in # a separate array and the partials behind their own validity flag, and an in place # write reaches neither. The next solve then silently uses the previous call's matrix # and partials, so both the values and the derivatives come back wrong. - Awork = cache.A - copyto!(Awork, A) - cache.A = Awork + # + # Since `LinearSolve.solve!` mutates `cache.A` in place during factorization, we compare + # `A` against `entry.A_prev` (using `===` so `ForwardDiff.Dual` partials are also + # checked) and skip reassigning `cache.A` when `A` is unchanged. + cache = entry.cache + A_prev = entry.A_prev + if !entry.initialized || !_entries_identical(A_prev, A) + copyto!(A_prev, A) + Awork = cache.A + copyto!(Awork, A) + cache.A = Awork + entry.initialized = false + end bwork = cache.b copyto!(bwork, b) cache.b = bwork copyto!(b, CommonSolve.solve!(cache).u) + entry.initialized = true return b end @@ -761,14 +801,16 @@ Solve for another right-hand side `b` with the matrix of the last [`numeric_ldiv reusing its factorization. `b` is overwritten with the solution. `A` only identifies the cache: its entries are not read. The matrix solved with is whatever -the last solve of this array type and size on the current task left in the cache, so -nothing else of that shape may be solved between the `numeric_ldiv!` and this call. +the last solve of this array type, size, and `site_id` on the current task left in the +cache, so nothing else with the same key may be solved between the `numeric_ldiv!` and +this call. """ -function numeric_ldiv_again!(A::AbstractMatrix, b::AbstractVector) - return solve_again_into!(get_inline_linsolve_cache(A, b), b) +function numeric_ldiv_again!(A::AbstractMatrix, b::AbstractVector, site_id::UInt64 = UInt64(0)) + return solve_again_into!(get_inline_linsolve_cache(A, b, site_id), b) end -function solve_again_into!(cache, b::AbstractVector) +function solve_again_into!(entry::InlineLinsolveCacheEntry, b::AbstractVector) + cache = entry.cache bwork = cache.b copyto!(bwork, b) cache.b = bwork @@ -776,49 +818,65 @@ function solve_again_into!(cache, b::AbstractVector) return b end -function get_inline_linsolve_cache(A::AbstractMatrix, b::AbstractVector) +function get_inline_linsolve_cache(A::AbstractMatrix, b::AbstractVector, site_id::UInt64 = UInt64(0)) # one typed `Dict` under a `Symbol` key, since a tuple key into task local storage # (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 + key = (typeof(A), typeof(b), size(A), site_id) + entry = get(caches, key, nothing) + entry === nothing && return init_inline_linsolve_cache!(caches, A, b, key) + # The `Dict` holds entries of every array type, so its values are untyped. Asserting + # the type a new entry infers to lets the solve after this dispatch statically, which + # `juliac --trim` needs. The key includes both array types, so the assertion holds. + return entry::Base.promote_op(new_inline_linsolve_cache, typeof(A), typeof(b)) end -# 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. +# `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. +function new_inline_linsolve_cache(A, b) cache = CommonSolve.init(LinearProblem(copy(A), copy(b))) - caches[(typeof(A), size(A))] = cache - return cache + return InlineLinsolveCacheEntry(cache, copy(A), false) +end + +# 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, key::InlineLinsolveCacheKeyT + ) + entry = new_inline_linsolve_cache(A, b) + caches[key] = entry + return entry end """ $TYPEDSIGNATURES -Whether the last [`numeric_ldiv!`](@ref) of this array type and size on the current task -found `A` singular, so that it returned the minimum norm least squares solution instead of -`A \\ b`. +Whether the last [`numeric_ldiv!`](@ref) of this array type, size, and `site_id` on the +current task found `A` singular, so that it returned the minimum norm least squares +solution instead of `A \\ b`. This reads the flag LinearSolve's default algorithm sets when the LU factorization fails and it redoes the solve with a column pivoted QR. The flag is internal to LinearSolve, so the answer is `false` whenever it is not there to read. """ -function inline_linsolve_fell_back(A::AbstractMatrix, b::AbstractVector) - cacheval = get_inline_linsolve_cache(A, b).cacheval +function inline_linsolve_fell_back(A::AbstractMatrix, b::AbstractVector, site_id::UInt64 = UInt64(0)) + cacheval = get_inline_linsolve_cache(A, b, site_id).cache.cacheval hasfield(typeof(cacheval), :fell_back_to_qr) || return false return getfield(cacheval, :fell_back_to_qr)::Bool end -numeric_ldiv!(A, b) = CommonSolve.solve(LinearProblem(A, b)).u +numeric_ldiv!(A, b, site_id::UInt64 = UInt64(0)) = CommonSolve.solve(LinearProblem(A, b)).u function SU.promote_symtype(::typeof(safe_ldiv), TA::SU.TypeT, TB::SU.TypeT) return Vector{Real} end +function SU.promote_symtype(::typeof(safe_ldiv), TA::SU.TypeT, TB::SU.TypeT, TSite::SU.TypeT) + return Vector{Real} +end + function SU.promote_shape(::typeof(safe_ldiv), sha::SU.ShapeT, shb::SU.ShapeT) @nospecialize sha shb if sha isa SU.Unknown @@ -828,15 +886,12 @@ function SU.promote_shape(::typeof(safe_ldiv), sha::SU.ShapeT, shb::SU.ShapeT) end end -const INLINE_LINEAR_SCC_OP = safe_ldiv - -""" -Key of this package's entry in task local storage, which holds the `LinearCache`s of -[`numeric_ldiv!`](@ref) by array type and size. -""" -const INLINE_LINSOLVE_CACHE = :ModelingToolkitTearing_inline_linsolve_cache +function SU.promote_shape(::typeof(safe_ldiv), sha::SU.ShapeT, shb::SU.ShapeT, shsite::SU.ShapeT) + @nospecialize sha shb shsite + return SU.promote_shape(safe_ldiv, sha, shb) +end -const InlineLinsolveCachesT = Dict{Tuple{DataType, Dims{2}}, Any} +const INLINE_LINEAR_SCC_OP = safe_ldiv """ $TYPEDSIGNATURES @@ -849,6 +904,11 @@ If the SCC identified by `alg_eqs` and `alg_vars` warrants a linear solve, retur - A `BitVector` indicating the indices of `alg_vars` used in the linear system. All equations not used in the linear system must be solved as normal. + +`site_id` identifies the solve site and is embedded in the returned expression, where it +selects the task local `LinearCache` of the solve. The caller derives it from the SCC's +position in the system rather than from global state, so that compiling the same system +twice gives equal expressions. """ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int}, alg_vars::Vector{Int}, neweqs::Vector{Equation}, @@ -857,7 +917,8 @@ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int}, total_sub::MTKBase.ExpandDerivativeDict{SymbolicT, Dict{SymbolicT, SymbolicT}}, analytical_linear_scc_limit::Int, simplify::Bool; allow_symbolic::Bool = false, - allow_parameter::Bool = true) + allow_parameter::Bool = true, + site_id::UInt64 = UInt64(0)) (; fullvars, sys, structure) = state (; graph, solvable_graph, var_to_diff) = structure diff_to_var = invview(var_to_diff) @@ -1036,7 +1097,7 @@ function get_linear_scc_linsol(state::TearingState, alg_eqs::Vector{Int}, b = SU.Code.with_allocator(b_allocator, SU.Const{VartypeT}(b)) state.sys = sys - return (INLINE_LINEAR_SCC_OP(A, b), eqs_mask, vars_mask) + return (INLINE_LINEAR_SCC_OP(A, b, site_id), eqs_mask, vars_mask) end function __reduce_linear_system!(A::StateSelection.CLIL.SparseMatrixCLIL{Num, Int}, b::Vector{SymbolicT}, var_eq_matching::StateSelection.VarEqMatchingT, alg_eqs::Vector{Int}, alg_vars::Vector{Int}, eqs_mask::BitVector, vars_mask::BitVector) diff --git a/lib/ModelingToolkitTearing/test/runtests.jl b/lib/ModelingToolkitTearing/test/runtests.jl index 942a715..b8b73ca 100644 --- a/lib/ModelingToolkitTearing/test/runtests.jl +++ b/lib/ModelingToolkitTearing/test/runtests.jl @@ -180,6 +180,81 @@ end @test du[1] ≈ refdu[1] end +@testset "Per-site cache avoids clobbering and skips refactorization when A is unchanged" begin + A1 = [3.0 1.0; 1.0 4.0] + A2 = [5.0 2.0; 1.0 6.0] + b1 = [1.0, 2.0] + b2 = [3.0, -1.0] + site1, site2 = UInt64(101), UInt64(102) + + @test MTKTearing.numeric_ldiv!(copy(A1), copy(b1), site1) ≈ A1 \ b1 + @test MTKTearing.numeric_ldiv!(copy(A2), copy(b2), site2) ≈ A2 \ b2 + + e1 = MTKTearing.get_inline_linsolve_cache(A1, b1, site1) + e2 = MTKTearing.get_inline_linsolve_cache(A2, b2, site2) + @test e1 !== e2 + @test e1.initialized && e2.initialized + + # Interleaving site2 must not clobber site1's factorization + b1_next = [4.0, -2.0] + @test MTKTearing.numeric_ldiv_again!(A1, copy(b1_next), site1) ≈ A1 \ b1_next + @test MTKTearing.numeric_ldiv_again!(A2, copy(b1_next), site2) ≈ A2 \ b1_next + + # Calling numeric_ldiv! with unchanged A skips invalidating cache.A (zero allocations) + b1_work = copy(b1_next) + @test MTKTearing.numeric_ldiv!(A1, b1_work, site1) ≈ A1 \ b1_next + @test @allocated(MTKTearing.numeric_ldiv!(A1, b1_work, site1)) == 0 + + # End-to-end: two 2x2 inline linear SCCs (one parameter-only A, one state-dependent A) + @variables x(t) = 1.0 q(t) = 1.0 + @variables y(t) = 1.0 z(t) = 1.0 w(t) = 1.0 + @variables a(t) = 1.0 c(t) = 1.0 d(t) = 1.0 + @parameters p1 = 2.0 p2 = 3.0 + reassemble_alg = MTKTearing.DefaultReassembleAlgorithm(; + inline_linear_sccs = true, analytical_linear_scc_limit = 0 + ) + eqs = [ + D(x) ~ 2t + 1, + # Parameter-only A (3x3 -> reduces to 2x2) + (p1 + 1) * y + p2 * z + w ~ 4 + x, + 4y + 3z + 2w ~ 7, + 2y + (3 + p1) * z + w ~ 10 - x, + # Mixed state/parameter A (3x3 -> reduces to 2x2) + (2 + x) * a + x * c + d ~ 5, + (4 + x) * a + 3c + p2 * d ~ 8, + 2x * a + (3 + x) * c + d ~ 11, + D(q) ~ 2w + 3z + y + 2d + 3c + a, + ] + @mtkcompile sys = System(eqs, t) reassemble_alg = reassemble_alg + blks = MTKTearing.inline_linear_systems(sys) + @test length(blks) == 2 + @test all(blk -> blk.size == 2, blks) + site_ids = [unwrap(last(SU.arguments(unwrap(blk.expression)))) for blk in blks] + @test length(unique(site_ids)) == 2 + + # the site id is derived from the system, so compiling it again gives the same + # observed equations, while the two blocks keep distinct caches + @mtkcompile sys2 = System(eqs, t) reassemble_alg = reassemble_alg + @test isequal(observed(sys), observed(sys2)) + site_ids2 = [unwrap(last(SU.arguments(unwrap(blk.expression)))) for blk in MTKTearing.inline_linear_systems(sys2)] + @test isequal(site_ids, site_ids2) + + prob = ODEProblem(sys, [], (0.0, 1.0)) + du = similar(prob.u0) + dx_idx = findfirst(isequal(x), unknowns(sys)) + dq_idx = findfirst(isequal(q), unknowns(sys)) + for xv in (1.0, 2.5, -0.5) + u = zeros(length(prob.u0)) + u[dx_idx] = xv + u[dq_idx] = 1.0 + prob.f.f(du, u, prob.p, 0.2) + yzw = [3.0 3.0 1.0; 4.0 3.0 2.0; 2.0 5.0 1.0] \ [4.0 + xv, 7.0, 10.0 - xv] + acd = [2.0 + xv xv 1.0; 4.0 + xv 3.0 3.0; 2.0 * xv 3.0 + xv 1.0] \ [5.0, 8.0, 11.0] + @test du[dx_idx] ≈ 2 * 0.2 + 1 + @test du[dq_idx] ≈ 2 * yzw[3] + 3 * yzw[2] + yzw[1] + 2 * acd[3] + 3 * acd[2] + acd[1] + end +end + @testset "`numeric_ldiv!` solves in place and stays rank tolerant" begin A = [2.0 1.0; 1.0 3.0] b = [1.0, 2.0] @@ -213,6 +288,44 @@ 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) + # per-site entries too, and the entry type is the concrete one a new cache has + for site in (UInt64(1), UInt64(7)) + MTKTearing.numeric_ldiv!(copy(A), copy(b), site) + entry = @inferred MTKTearing.get_inline_linsolve_cache(A, b, site) + @test entry isa MTKTearing.InlineLinsolveCacheEntry + @test isconcretetype(typeof(entry)) + end + # the generated code passes views of the diffcache buffers + Av, bv = view(A, :, :), view(b, :) + MTKTearing.numeric_ldiv!(copy(Av), copy(bv), UInt64(3)) + @inferred MTKTearing.get_inline_linsolve_cache(Av, bv, UInt64(3)) + 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) @@ -281,6 +394,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 @@ -305,9 +453,9 @@ include("enzyme.jl") @test blk.size == 2 @test length(blk.variables) == blk.size @test issubset(blk.variables, Set([y, z, w])) - # the retained expression is the solve term `A \ b` + # the retained expression is the solve term `A \ b` (with solve-site id) @test SU.operation(unwrap(blk.expression)) === MTKTearing.INLINE_LINEAR_SCC_OP - @test length(SU.arguments(unwrap(blk.expression))) == 2 + @test length(SU.arguments(unwrap(blk.expression))) == 3 # a system with no inline linear solve yields no blocks @mtkcompile sys2 = System([D(x) ~ x], t)