Skip to content

Resolve every renewal modifier through one inferred seam - #456

Merged
seabbs merged 3 commits into
claude/cr-redesign-portfrom
claude/static-modifier-seam
Dec 2, 2026
Merged

seabbs merged 3 commits into
claude/cr-redesign-portfrom
claude/static-modifier-seam

Conversation

@seabbs-bot

@seabbs-bot seabbs-bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

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.gradient of the linked log joint, in µs.

1. The prefix was a runtime value.
The seam called prefix(model, Symbol(:modifier_, index)).
DynamicPPL.prefix turns a Symbol into VarName{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 VarName and Val{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:

Model ForwardDiff Mooncake rev Mooncake fwd Enzyme rev Enzyme fwd Primal Alloc
inlined tilde 0.06 0.11 0.17 0.05 0.04 0.025 0 B
unprefixed submodel 0.07 0.11 0.25 0.05 0.04 0.025 0 B
to_submodel(m) (left-hand prefix) 0.07 0.11 0.18 0.06 0.04 0.025 0 B
prefix(m, :a) literal 0.06 0.12 0.17 0.05 0.04 0.025 0 B
prefix(m, @varname(a)) 0.07 0.10 0.18 0.05 0.04 0.025 0 B
prefix from a type parameter 0.06 0.10 0.18 0.05 0.04 0.024 0 B
prefix(m, Symbol(:a_, i)) 0.53 4.78 2.14 2.65 1.27 0.48 352 B
prefix(m, Symbol(str)) 0.44 5.24 2.08 2.58 1.24 0.39 96 B
runtime prefix, nothing drawn 0.51 4.47 2.02 2.34 1.36 0.47 352 B
static prefix, nothing drawn 0.06 0.12 0.18 0.06 0.05 0.02 0 B

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_types gives Tuple{Any, Any} for the seam and I_t::Any for 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 Submodel and VarName when it looks more complex.
Three things made it look more complex here: the position counter going up (Val{2} after Val{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 of vn.
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:

Option ForwardDiff Mooncake rev Enzyme rev Names
Runtime positional prefix (before) 6.61 144.4 54.7 modifier_1.import_rates
A. Unprefixed submodel 1.72 4.32 2.76 import_rates
B. Static positional prefix (this PR) 1.75 4.56 2.78 modifier_1.import_rates
C. Draws inlined in the renewal's model as A as A as A chosen by the modifier
  • A, unprefixed. This is the directive's standard.
    Two modifiers of one type then collide.
    Two ImportedCases(Normal(...)) share one import_rates and the log density changes silently (−888.27 against −803.75 at the same point).
    ImportedCases(Normal()) with ImportedCases(RandomWalk()) errors in DynamicPPL.
    Keeping them apart needs a prefix wrapper from the user, and chain names change.
  • B, static positional prefix. Names are as they are now.
    The cost is the same as A.
  • C, inlined. An inlined tilde costs the same as a static submodel (first table), so there is nothing to gain.
    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 old prefix_submodel sites).
The modifier seam is not on that list, so it is a deviation in letter.
It is the same kind of component as Split and CombineInfections: 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 prefix call in the one-modifier method.

What changed

src/infection_models/renewal/modifiers.jl:

  • _modifier_names(Val(N)) builds the tuple of names modifier_1 … modifier_N as singleton VarNames, folded at compile time.
  • _resolve_modifiers(mods, n) has three methods: the empty tuple, one modifier (its as_turing_model under 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.
  • _FixedModifier and _fixed_modifier are removed.
    SusceptibleDepletion and the ComposableRecurrences modifiers passed directly go through as_turing_model like any other.
  • A modifier written outside the package takes the same path and is inferred the same way.

test/unit/infection_models/modifier_seam.jl checks 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:

Modifiers ForwardDiff Mooncake rev Mooncake fwd Enzyme rev Enzyme fwd
none 1.21 → 1.38 5.13 → 4.59 21.1 → 22.1 3.03 → 2.31 2.75 → 2.99
SusceptibleDepletion 1.79 → 1.69 6.43 → 4.64 22.5 → 22.2 3.52 → 2.86 3.19 → 2.84
CR.Depletion passed directly 2.26 → 1.84 4.45 → 4.32 22.7 → 24.4 2.49 → 2.77 3.25 → 3.24
CR.Transform(+, 0.1) passed directly 1.66 → 2.10 5.19 → 4.08 23.6 → 30.5 2.68 → 2.53 2.53 → 3.89
ImportedCases 6.61 → 1.75 144.4 → 4.56 402.5 → 26.5 54.7 → 2.78 46.5 → 3.31
SusceptibleDepletion + ImportedCases 7.32 → 1.96 134.1 → 4.89 403.8 → 27.5 59.2 → 2.93 61.1 → 4.03
ImportedCases × 2 8.24 → 1.52 182.1 → 5.03 506.4 → 28.7 87.5 → 3.04 51.0 → 4.97
ImportedCases(RandomWalk()) 21.8 → 4.43 229.0 → 6.48 693.5 → 64.0 109.9 → 3.98 103.1 → 11.3
depletion + imports + imports(RandomWalk) 18.8 → 5.46 – → 6.95 1067.8 → 75.8 – → 6.74 150.5 → 12.1
five modifiers, three drawing 24.6 → 6.33 – → 8.77 1146.8 → 109.3 – → 5.96 188.9 → 14.3

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 d1051df changes comments and swaps only for first in one method; on it I re-ran the seam and ImportedCases test 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):

Backend Pass Broken Error Base (#453)
ForwardDiff 1008 0 0 1008 / 0 / 0
ReverseDiff (tape) 987 1 0 987 / 1 / 0
ReverseDiff (compiled) 987 1 0 987 / 1 / 0
Mooncake reverse 987 1 0 987 / 1 / 0
Mooncake forward 988 0 0 988 / 0 / 0
Enzyme reverse 966 1 1 966 / 1 / 1
Enzyme forward 967 1 0 967 / 1 / 0

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.
Split builds 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 on d1051df.

CI: test (pre, …) fails at package resolution on Julia 1.14.0-beta2, and Downgrade Compat fails on the unregistered ComposableRecurrences pin.
Both are red with the same errors on the base branch.

Not done

  • Other components build their prefix at run time in the same way: PrefixLatentModel, PrefixObservationModel, Split and CombineInfections call prefix(model, Symbol(string)), and CombineLatentModels, ConcatLatentModels and Ascertainment go through PrefixLatentModel.
    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.
  • The AD-fixture scenario timings from Run on the redesigned ComposableRecurrences and cut glue #453 were not repeated; only the seam table was.
  • The docs build was not run. No docs page changed, since names are unchanged.

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 Any from the second level.

using DynamicPPL, Distributions

@model function one(d)
    x ~ d
    return x
end

@model function each(ds::Tuple{}, names::Tuple{})
    return ()
end
@model function each(ds::Tuple, names::Tuple)
    a ~ to_submodel(DynamicPPL.prefix(one(first(ds)), first(names)), false)
    rest ~ to_submodel(each(Base.tail(ds), Base.tail(names)), false)
    return (a, rest...)
end

function return_type(model)
    vi = VarInfo(model)
    T = only(Base.return_types(
        DynamicPPL.evaluate!!, (typeof(model), typeof(vi))))
    return T.parameters[1]
end

ds = (Normal(), Exponential(), Beta(2, 2))
names = (@varname(m1), @varname(m2), @varname(m3))
return_type(each(ds[1:1], names[1:1]))  # Tuple{Float64}
return_type(each(ds[1:2], names[1:2]))  # Tuple{Float64, Any}
return_type(each(ds, names))            # Tuple{Float64, Any, Any}

DynamicPPL 0.42.14, Julia 1.12.7.

The widening happens in tilde_assume!!(context, right::Submodel, vn, ::Any, vi).
Both tilde statements in each call that method from the same caller, so at the second level Julia's recursion limit compares the a call with the rest call that is on the stack.
Compiler.limit_type_size widens right to Submodel and vn to VarName, because VarName{:a} against VarName{:rest} and the two Model types differ in value parameters (the argument-name tuple, the context).
Setting recursion_relation on 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:

@model function each2(ds::Tuple{}, names::Tuple{})
    return ()
end
@model function each2(ds::Tuple{Any}, names::Tuple{Any})
    a ~ to_submodel(DynamicPPL.prefix(one(only(ds)), only(names)), false)
    return (a,)
end
@model function each2(ds::Tuple, names::Tuple)
    part ~ to_submodel(each2((first(ds),), (first(names),)), false)
    head = part
    part ~ to_submodel(each2(Base.tail(ds), Base.tail(names)), false)
    return (head..., part...)
end
return_type(each2(ds, names))  # Tuple{Float64, Float64, Float64}

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

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
@seabbs-bot
seabbs-bot requested a review from seabbs as a code owner December 1, 2026 17:33
seabbs-review-bot[bot]

This comment was marked as resolved.

@seabbs-review-bot seabbs-review-bot Bot added the llm-reviewed Reviewed by seabbs-review-bot label Dec 1, 2026

Copy link
Copy Markdown
Collaborator Author

test (pre, windows-latest) fails before any test runs: on Julia 1.14.0-beta2 Pkg cannot resolve the environment (the ComposableRecurrences pin against the other dependencies).
The same job is red on the base branch claude/cr-redesign-port, as is test (pre, ubuntu-latest), so it is not from this change.
The Julia 1 and 1.11 Windows jobs pass.


Generated by Claude Code

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Try this Pull Request!

Option 1: Julia Package Manager

Open Julia and type:

import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableTuringIDModels.jl", rev="claude/static-modifier-seam")
using ComposableTuringIDModels

Option 2: Local Checkout

If you have the repo locally:

git checkout claude/static-modifier-seam
julia --project=. -e "using Pkg; Pkg.instantiate()"

Copy link
Copy Markdown
Collaborator Author

Downgrade Compat fails with could not find manifest entry for package with uuid 4e7e49c6-…, which is the unregistered ComposableRecurrences pin.
The job fails with the same error on the base branch claude/cr-redesign-port, so it is not from this change.


Generated by Claude Code

@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

Flag Coverage Δ
ad-forwarddiff 61.89% <93.33%> (+0.28%) ⬆️
ad-mooncake-forward 61.89% <93.33%> (+0.28%) ⬆️
ad-mooncake-reverse 61.89% <93.33%> (+0.28%) ⬆️
ad-reversediff 61.94% <93.33%> (+0.28%) ⬆️
ad-reversediff-compiled 61.94% <93.33%> (+0.28%) ⬆️
unit 93.84% <100.00%> (+0.13%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/infection_models/Renewal.jl 100.00% <ø> (ø)
src/infection_models/renewal/modifiers.jl 96.55% <100.00%> (+8.55%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Collaborator Author

ad / Enzyme forward fails with 925 passed, 2 errored, 1 broken: IllegalTypeAnalysisException in Renewal+UncertainLatentDelay posterior and Renewal+UncertainGenInterval posterior.
The same job on the base branch claude/cr-redesign-port fails with the same two scenarios and the same counts, so it is not from this change.
Neither scenario has a renewal modifier.
Locally on Julia 1.12.7 the Enzyme forward suite passes (967 passed, 1 broken), so the failure depends on the CI Julia version.


Generated by Claude Code

Copy link
Copy Markdown
Collaborator Author

ad / Enzyme reverse fails with 945 passed, 2 errored, 1 broken, in Renewal+UncertainGenInterval posterior and Renewal+UncertainLatentDelay posterior.
The same job on the base branch claude/cr-redesign-port fails in the same two scenarios with the same counts, so it is not from this change.
Neither scenario has a renewal modifier.


Generated by Claude Code

@github-actions

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

📖 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.

@seabbs
seabbs merged commit 06cbd97 into claude/cr-redesign-port Dec 2, 2026
27 of 34 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

llm-reviewed Reviewed by seabbs-review-bot

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants