Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 \
Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -107,21 +121,30 @@ 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))
# `b` was overwritten, so its incoming adjoint is exactly λ, and the shadow that
# 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
6 changes: 3 additions & 3 deletions lib/ModelingToolkitTearing/src/diagnostics.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
151 changes: 106 additions & 45 deletions lib/ModelingToolkitTearing/src/reassemble.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

"""
Expand All @@ -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

Expand All @@ -761,64 +801,82 @@ 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
copyto!(b, CommonSolve.solve!(cache).u)
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
Expand All @@ -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
Expand All @@ -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},
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading