Skip to content

Commit fed8cdb

Browse files
Address review: drop gensym, splats and tuple groups in map codegen
Names embedded in the generated initialization maps are now fixed sentinels instead of `gensym`s. A `gensym` embeds a process-global counter, so lowering the same system twice produced two distinct `RuntimeGeneratedFunction` types and never hit the RGF Expr-hash cache. Added a regression asserting the two lowerings share a type. `Expr`s are built by pushing onto `args` rather than splatting, and the parameter groups are a concretely typed `Vector{Vector{Vector{SymbolicT}}}` rather than a tuple of tuples, which forced the buffer loop to specialize on each system's shape. Co-Authored-By: Chris Rackauckas <[email protected]> Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Agent-Harness: Claude Code 2.0.14 Agent-Model: claude-opus-5[1m] Agent-Session: https://claude.ai/code/session_01GdSpCLd7NBZuuePJmcDzU7 Claude-Session: https://claude.ai/code/session_01GdSpCLd7NBZuuePJmcDzU7
1 parent 9a65200 commit fed8cdb

2 files changed

Lines changed: 70 additions & 25 deletions

File tree

‎lib/ModelingToolkitBase/src/systems/problem_utils.jl‎

Lines changed: 53 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1633,6 +1633,17 @@ function (map::InitializationMap{true})(x)
16331633
return __iip_u0_ad_wrapper(map.u0_constructor(map.map(x)))
16341634
end
16351635

1636+
# Locals of the generated initialization maps are fixed sentinel names, never `gensym`.
1637+
# A `gensym` embeds a process-global counter, so the same system would lower to a
1638+
# different `Expr` in the precompile process than in the user session, defeating the
1639+
# `RuntimeGeneratedFunctions` Expr-hash cache. The `__mtk_` prefix matches
1640+
# `generated_argument_name` and makes a collision with a user symbol implausible.
1641+
const INITMAP_VALUES = :__mtk_initialization_map_values
1642+
const INITMAP_ELTYPE = :__mtk_initialization_map_eltype
1643+
const INITMAP_SOLUTION = :__mtk_initialization_solution
1644+
const INITMAP_PROBLEM = :__mtk_initialization_problem
1645+
const INITMAP_OUTER_PARAMETERS = :__mtk_initialization_outer_parameters
1646+
16361647
function _generated_map_expr(finish, expr::Expr, map_args::Vector{Symbol}, sources::Vector{Expr})
16371648
@assert expr.head === :function
16381649
signature = expr.args[1]
@@ -1644,10 +1655,11 @@ function _generated_map_expr(finish, expr::Expr, map_args::Vector{Symbol}, sourc
16441655
for (arg, source) in zip(generated_args, sources)
16451656
push!(body.args, :(local $arg = $source))
16461657
end
1647-
raw = gensym(:initialization_map_values)
1648-
push!(body.args, :(local $raw = $(expr.args[2])))
1649-
push!(body.args, finish(raw))
1650-
return Expr(:function, Expr(:tuple, map_args...), body)
1658+
push!(body.args, :(local $INITMAP_VALUES = $(expr.args[2])))
1659+
push!(body.args, finish(INITMAP_VALUES))
1660+
fn_args = Expr(:tuple)
1661+
append!(fn_args.args, map_args)
1662+
return Expr(:function, fn_args, body)
16511663
end
16521664

16531665
function _generated_map_sources(valp::Symbol, time_dependent::Bool)
@@ -1670,12 +1682,12 @@ function _construct_fullspecialize_initializeprobmap(
16701682
initsys, solved_unknowns;
16711683
expression = Val(true), output_type = SVector, compiler_options, kwargs...
16721684
)
1673-
sol = gensym(:initialization_solution)
1685+
sol = INITMAP_SOLUTION
16741686
sources = _generated_map_sources(sol, is_time_dependent(initsys))
16751687
n = length(solved_unknowns)
16761688
static_type = iip ? MVector : SVector
16771689
map_expr = _generated_map_expr(expr, [sol], sources) do raw
1678-
T = gensym(:initialization_map_eltype)
1690+
T = INITMAP_ELTYPE
16791691
p = Expr(:call, GlobalRef(SymbolicIndexingInterface, :parameter_values), sol)
16801692
tunable_eltype = Expr(:call, GlobalRef(@__MODULE__, :_tunable_eltype), p)
16811693
promoted = Expr(:call, promote_type, Expr(:call, eltype, raw), tunable_eltype, floatT)
@@ -1700,12 +1712,15 @@ function _static_initialization_buffer(prototype, values)
17001712
elseif isbitstype(T)
17011713
return MVector{length(values), T}(values)
17021714
else
1703-
return SizedVector{length(values), T}(T[values...])
1715+
return SizedVector{length(values), T}(collect(T, values))
17041716
end
17051717
end
17061718

17071719
function _parameter_buffer_expr(prototype, raw::Symbol, idxs, p_constructor)
1708-
values = Expr(:tuple, [Expr(:ref, raw, i) for i in idxs]...)
1720+
values = Expr(:tuple)
1721+
for i in idxs
1722+
push!(values.args, Expr(:ref, raw, i))
1723+
end
17091724
buffer = Expr(
17101725
:call, GlobalRef(@__MODULE__, :_static_initialization_buffer), prototype, values
17111726
)
@@ -1719,12 +1734,21 @@ function _construct_fullspecialize_initializeprobpmap(
17191734
compiler_options::CompilerOptions = CompilerOptions(), kwargs...
17201735
)
17211736
ps = parameters(sys; initial_parameters = true)
1722-
groups = if is_split(sys)
1737+
# One entry per `MTKParameters` portion, each holding that portion's buffers. Kept a
1738+
# concretely typed `Vector` rather than a tuple of tuples: the portions are iterated,
1739+
# not indexed heterogeneously, and a tuple here would force the whole loop below to
1740+
# specialize per system.
1741+
groups = Vector{Vector{SymbolicT}}[]
1742+
if is_split(sys)
17231743
grouped = reorder_parameters(sys, ps; flatten = false)
1724-
initial_syms = _unwrap_initial_symbols!(copy(grouped[2]), initsys)
1725-
((grouped[1],), (initial_syms,), grouped[3:5]...)
1744+
push!(groups, Vector{SymbolicT}[grouped[1]::Vector{SymbolicT}])
1745+
initial_syms = _unwrap_initial_symbols!(copy(grouped[2]::Vector{SymbolicT}), initsys)
1746+
push!(groups, Vector{SymbolicT}[initial_syms])
1747+
for i in 3:5
1748+
push!(groups, grouped[i]::Vector{Vector{SymbolicT}})
1749+
end
17261750
else
1727-
((ps,),)
1751+
push!(groups, Vector{SymbolicT}[ps])
17281752
end
17291753
flat_syms = SymbolicT[]
17301754
for group in groups, buffer in group
@@ -1734,11 +1758,11 @@ function _construct_fullspecialize_initializeprobpmap(
17341758
initsys, Tuple(flat_syms);
17351759
expression = Val(true), compiler_options, kwargs...
17361760
)
1737-
prob = gensym(:problem)
1738-
sol = gensym(:initialization_solution)
1761+
prob = INITMAP_PROBLEM
1762+
sol = INITMAP_SOLUTION
17391763
sources = _generated_map_sources(sol, is_time_dependent(initsys))
17401764
map_expr = _generated_map_expr(expr, [prob, sol], sources) do raw
1741-
outer_p = gensym(:outer_parameters)
1765+
outer_p = INITMAP_OUTER_PARAMETERS
17421766
p = Expr(:call, GlobalRef(SymbolicIndexingInterface, :parameter_values), prob)
17431767
if !is_split(sys)
17441768
result = _parameter_buffer_expr(outer_p, raw, eachindex(flat_syms), p_constructor)
@@ -1759,24 +1783,28 @@ function _construct_fullspecialize_initializeprobpmap(
17591783
buffer = _parameter_buffer_expr(prototype, raw, idxs, p_constructor)
17601784
if field === :discrete
17611785
sizes = get_index_cache(sys).discrete_buffer_sizes[buffer_idx]
1762-
block_sizes = Expr(
1763-
:call, Expr(:curly, SVector, length(sizes), Int),
1764-
map(size -> size.length, sizes)...
1765-
)
1786+
block_sizes = Expr(:call, Expr(:curly, SVector, length(sizes), Int))
1787+
for sz in sizes
1788+
push!(block_sizes.args, sz.length)
1789+
end
17661790
p_constructor === identity ||
17671791
(block_sizes = Expr(:call, QuoteNode(p_constructor), block_sizes))
17681792
buffer = Expr(:call, BlockedArray, buffer, block_sizes)
17691793
end
17701794
push!(buffers, buffer)
17711795
end
1772-
portion = field === :tunable || field === :initials ? only(buffers) :
1773-
Expr(:tuple, buffers...)
1796+
portion = if field === :tunable || field === :initials
1797+
only(buffers)
1798+
else
1799+
tup = Expr(:tuple)
1800+
append!(tup.args, buffers)
1801+
tup
1802+
end
17741803
push!(portions, portion)
17751804
end
1776-
result = Expr(
1777-
:call, MTKParameters, portions...,
1778-
:($map($copy, $outer_p.caches))
1779-
)
1805+
result = Expr(:call, MTKParameters)
1806+
append!(result.args, portions)
1807+
push!(result.args, :($map($copy, $outer_p.caches)))
17801808
return Expr(:block, :(local $outer_p = $p), result)
17811809
end
17821810
return eval_or_rgf(map_expr; eval_module, compiler_options)

‎lib/ModelingToolkitBase/test/initializationsystem.jl‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1944,6 +1944,23 @@ end
19441944
@test u == adata.initializeprobmap(adata.initializeprob)
19451945
@test p == adata.initializeprobpmap(auto, adata.initializeprob)
19461946
end
1947+
1948+
# The generated maps name their locals with fixed sentinels, so lowering the same
1949+
# system twice has to produce the same `Expr` and hence the same `RuntimeGeneratedFunction`
1950+
# type. A `gensym`ed local makes each lowering a fresh type, defeating the RGF cache.
1951+
second_prob = ODEProblem{true, SciMLBase.FullSpecialize}(
1952+
mtkcompile(
1953+
System(
1954+
[D(map_x) ~ -map_rate * map_x, D(map_y) ~ -map_scale * map_y], t;
1955+
name = nameof(map_sys),
1956+
initialization_eqs = [map_x^3 + map_x ~ 2, map_y ~ 2map_x + 1]
1957+
)
1958+
), [], (0.0, 1.0); guesses
1959+
)
1960+
second_data = second_prob.f.initialization_data
1961+
@test typeof(second_data.initializeprobmap) === typeof(full_data.initializeprobmap)
1962+
@test typeof(second_data.initializeprobpmap) === typeof(full_data.initializeprobpmap)
1963+
@test second_data.initializeprobmap(second_data.initializeprob) == full_u
19471964
end
19481965

19491966
@testset "Issue#3570, #3552: `Initial`s/guesses are copied to `u0` during `solve`/`init`" begin

0 commit comments

Comments
 (0)