Repository navigation
Resolve every renewal modifier through one inferred seam - #456
Conversation
The seam prefixed each modifier's draws with a name built at run time, so the type of a resolved modifier that draws a parameter was unknown and the recurrence ran through dynamic dispatch. The names are now folded at compile time, and the recursion over the modifier tuple is written so that it is inferred for any number of modifiers. Every modifier, drawing or not, goes through its own as_turing_model, and the list of modifiers resolved by a plain function is removed. Variable names are unchanged. Claude-Session: https://claude.ai/code/session_01WwC7iuwuZLXNcJgDZ4xwpc
|
Generated by Claude Code |
Try this Pull Request!Option 1: Julia Package ManagerOpen Julia and type: import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="claude/static-modifier-seam")
using ComposableTuringIDModelsOption 2: Local CheckoutIf you have the repo locally: git checkout claude/static-modifier-seam
julia --project=. -e "using Pkg; Pkg.instantiate()" |
|
Generated by Claude Code |
Codecov Report✅ All modified and coverable lines are covered by tests.
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
Generated by Claude Code |
|
Generated by Claude Code |
|
📖 Documentation preview is ready! View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR456/ This preview will be updated automatically when you push new commits. |
Summary
Answers the question left open in #453: can the per-modifier prefixed submodel be removed?
The submodel does not need to go.
A prefixed submodel costs nothing when the compiler can infer it.
The seam had two things that stopped inference, and both are fixed here.
Every modifier now resolves through its own
as_turing_model, drawing or not, and the list of modifier types resolved by a plain function is removed.Variable names do not change.
Diagnosis
Julia 1.12.7, DynamicPPL 0.42.14 (the latest release), Mooncake 0.5.74, Enzyme 0.13.221, 4 cores.
Timings are the minimum of 200 calls to a prepared
DifferentiationInterface.gradientof the linked log joint, in µs.1. The prefix was a runtime value.
The seam called
prefix(model, Symbol(:modifier_, index)).DynamicPPL.prefixturns aSymbolintoVarName{sym}, so the type of the prefixed model depends on a value.Its docstring says this form "will introduce runtime overheads so is not recommended unless absolutely necessary" and gives
VarNameandVal{sym}as the static forms, so the cost is known upstream and is not a bug.Minimal DynamicPPL models, one scalar draw and one observation:
to_submodel(m)(left-hand prefix)prefix(m, :a)literalprefix(m, @varname(a))prefix(m, Symbol(:a_, i))prefix(m, Symbol(str))A submodel, a prefix and a submodel that draws nothing are all free when the prefix is static.
The runtime prefix costs a few µs by itself.
In a renewal it costs far more, because the resolved modifiers come back as
Any:Base.return_typesgivesTuple{Any, Any}for the seam andI_t::Anyfor the renewal.The recurrence, the observation model and the log density that follow are then dispatched at run time, which is the 115 to 145 µs under Mooncake.
The modifier's own model, and the same model under a constant prefix, are both fully inferred.
2. The recursion over the modifier tuple was not inferred for two or more modifiers.
This shows once the prefix is static, and also with no prefix at all.
A model that calls itself as a submodel trips Julia's recursion limit in
DynamicPPL.tilde_assume!!(ctx, ::Submodel, vn, ...).The limit compares each inner call with the one on the stack and widens it to
SubmodelandVarNamewhen it looks more complex.Three things made it look more complex here: the position counter going up (
Val{2}afterVal{1}), the resolved tuple growing as it was passed down, and the two tilde statements having different left-hand names, since the name is a type parameter ofvn.Relaxing the recursion relation on that one DynamicPPL method makes every form infer, which pins it down, but that is not something a package should do.
The tuple the seam builds was not the problem, and nor is the submodel call.
Options
Single
ImportedCases, Renewal + Poisson, n = 8:modifier_1.import_ratesimport_ratesmodifier_1.import_ratesTwo modifiers of one type then collide.
Two
ImportedCases(Normal(...))share oneimport_ratesand the log density changes silently (−888.27 against −803.75 at the same point).ImportedCases(Normal())withImportedCases(RandomWalk())errors in DynamicPPL.Keeping them apart needs a prefix wrapper from the user, and chain names change.
The cost is the same as A.
It would need a second protocol next to
as_turing_model, which the directive rules out.The directive lists the components that prefix on purpose (
PrefixLatentModel,PrefixObservationModel,Split, the oldprefix_submodelsites).The modifier seam is not on that list, so it is a deviation in letter.
It is the same kind of component as
SplitandCombineInfections: it holds several components that may be of one type, and prefixes each so they cannot collide.The directive asks for that prefixing to be explicit through
DynamicPPL.prefix, which it is.What departed from the intent was the cost, not the prefix.
I chose B because it removes the cost, keeps names stable and keeps two modifiers of one type safe with no wrapper.
A is one line away if flat names are preferred: drop the
prefixcall in the one-modifier method.What changed
src/infection_models/renewal/modifiers.jl:_modifier_names(Val(N))builds the tuple of namesmodifier_1 … modifier_Nas singletonVarNames, folded at compile time._resolve_modifiers(mods, n)has three methods: the empty tuple, one modifier (itsas_turing_modelunder its name), and several (the first, then the rest).The method for several is shaped to pass the recursion limit: it calls only its own model on shorter tuples, uses one left-hand name for both statements, and joins the results on the way back up.
A comment says why.
_FixedModifierand_fixed_modifierare removed.SusceptibleDepletionand the ComposableRecurrences modifiers passed directly go throughas_turing_modellike any other.test/unit/infection_models/modifier_seam.jlchecks that the seam and the renewal are inferred for ten modifier tuples, up to five modifiers and including a modifier defined in the test.That test is the guard for the recursion shape, since it depends on a compiler heuristic.
For users: no chain name changes, no API changes.
Evidence
Modifier seam, Renewal + Poisson, n = 8, before → after, µs:
SusceptibleDepletionCR.Depletionpassed directlyCR.Transform(+, 0.1)passed directlyImportedCasesSusceptibleDepletion+ImportedCasesImportedCases× 2ImportedCases(RandomWalk())The first six rows are the table from #453; the last four are added.
The rows that draw nothing were already fast and now take the same path as the rest.
Two of them looked slower in the first run (
CR.Transform: Mooncake forward 23.6 → 30.5, Enzyme forward 2.53 → 3.89), so I timed ForwardDiff, Mooncake forward and Enzyme forward again, before and after, with nothing else running.That gave 24.2 → 20.9 and 3.17 → 3.91 for the same cells, and across the four non-drawing rows the Enzyme forward times range over 2.5 to 3.9 µs in both directions.
I read that as noise of about 1 µs, not a regression, but it is not resolved more finely than that.
The last two rows were added after the baseline; their three "before" values come from that second run, and Mooncake reverse and Enzyme reverse have none.
The primal for a drawing modifier went from 4.5 to 0.55 µs and its allocations from 3776 to 1088 B.
Log density and gradients.
For the eight rows with a baseline, on all five backends (40 comparisons), the log density (8 decimals) and every gradient entry (6 decimals) are identical before and after.
Tests.
Local, Julia 1.12.7, Linux, 4 cores.
Main suite (
julia --project=test test/runtests.jl, includes QA, JET and formatting): 2534 passed, 4 broken, 0 failed.The 4 broken are the QA entries already broken on the base branch.
The count is up from 2497 on the base because of the new seam tests.
That run was on
526cfc4.The head
d1051dfchanges comments and swapsonlyforfirstin one method; on it I re-ran the seam andImportedCasestest files (103 passed) and the Runic check (clean), not the whole suite.AD suite (
julia --project=test/ad test/ad/runtests.jl <tag>, one backend per process):The broken entries are the listed ODE scenario.
The Enzyme reverse error is
Renewal+Split cascade posterior(IllegalTypeAnalysisException), the same error #453 reports as pre-existing.Splitbuilds its prefixes at run time (see "Not done"); I did not test whether that is the cause.ForwardDiff and Mooncake reverse ran on
526cfc4, the other five ond1051df.CI:
test (pre, …)fails at package resolution on Julia 1.14.0-beta2, andDowngrade Compatfails on the unregistered ComposableRecurrences pin.Both are red with the same errors on the base branch.
Not done
PrefixLatentModel,PrefixObservationModel,SplitandCombineInfectionscallprefix(model, Symbol(string)), andCombineLatentModels,ConcatLatentModelsandAscertainmentgo throughPrefixLatentModel.The minimal models above say each pays the same cost.
Their prefixes are user strings held in fields, so a fix means carrying the name in the type, which is a change to those structs and is left for a separate PR.
I did not measure them in place.
Upstream note
Not a blocker, since the seam is inferred with public API.
A model that recurses over a tuple of components is a natural thing to write and is not inferred as most people would write it.
Suggested issue for DynamicPPL:
A model that calls itself as a submodel is not inferred
A model that recurses over a tuple, drawing one component per level, has its return type widened to
Anyfrom the second level.DynamicPPL 0.42.14, Julia 1.12.7.
The widening happens in
tilde_assume!!(context, right::Submodel, vn, ::Any, vi).Both tilde statements in
eachcall that method from the same caller, so at the second level Julia's recursion limit compares theacall with therestcall that is on the stack.Compiler.limit_type_sizewidensrighttoSubmodelandvntoVarName, becauseVarName{:a}againstVarName{:rest}and the twoModeltypes differ in value parameters (the argument-name tuple, the context).Setting
recursion_relationon that one method makes the model infer at every depth.It is the same limiter as in the nested-submodel fix (DynamicPPL #1427, Turing #2844), reached by a different route.
A workaround with public API is to give the two statements one left-hand name and put the draw in a one-element method, so every submodel call in the recursive method is the same model on a shorter tuple:
Could the submodel
tilde_assume!!path be made robust to this, as the_evaluate!!path was?https://claude.ai/code/session_01WwC7iuwuZLXNcJgDZ4xwpc
Generated by Claude Code