Skip to content

Run on the redesigned ComposableRecurrences and cut glue - #453

Merged
seabbs merged 3 commits into
composable-recurrencesfrom
claude/cr-redesign-port
Dec 1, 2026
Merged

seabbs merged 3 commits into
composable-recurrencesfrom
claude/cr-redesign-port

Conversation

@seabbs-bot

Copy link
Copy Markdown
Collaborator

Summary

Runs CTIDM on the redesigned ComposableRecurrences (CR) and cuts the glue around it.
CR is pinned at ba059035c6b820fa73bce60b96a735c5cce9181c, the head of claude/amazing-shannon-6nrow8 (CR PR #907) that was tested.

CTIDM needed no source change to run on the redesign.
It defines no CR pieces of its own in src/ (no forward!, pullback! or hand pullback), so the move to pure steps did not touch it.
I found no CR regressions.

Changes:

  • Pin: Project.toml, test/Project.toml and docs/Project.toml point at ba05903.
  • Docs for custom modifiers (src/infection_models/renewal/modifiers.jl): a new step-level behaviour is now described as a pure ComposableRecurrences.step(m, θ, v, s) with an optional init. It no longer says forward! for the Step role, and it says no pullback is needed.
  • Tutorial coupling (docs/src/tutorials/patch-models.md): the Ring coupling declares CR.islinear(::Ring) = true. Its gradient then takes the dense-coupling rule rather than plain AD of the whole operator, and CR no longer logs the "plain AD" note.
    Couplings keep forward! for the Pressure role in the redesign, so the method itself is unchanged.
  • expected_Rt uses Convolution instead of a hand-written loop.
  • Modifier seam (_resolve_modifiers): a modifier that draws nothing (SusceptibleDepletion, or a CR Depletion, Redistribute, Allocate or Transform passed directly) is now resolved by a plain function instead of a prefixed submodel. That submodel level was the main cost of a Mooncake reverse gradient for any renewal with a modifier (timings below).

Test results (local, Julia 1.12.7, Linux, 4 cores)

Main suite (julia --project=test test/runtests.jl, includes QA, JET and formatting):

Code Pass Broken Fail/Error
unchanged CTIDM, new CR 2497 4 0
this branch, new CR 2497 4 0

The 4 broken results are in the managed QA testset and are pre-existing: quality_only at the old pin (142ae78) gives 302 passed, 4 broken, the same as this branch.

AD suite (julia --project=test/ad test/ad/runtests.jl <tag>, one backend per process), this branch:

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

The broken entries are the listed ODE scenario.
The Enzyme reverse error is Renewal+Split cascade posterior (IllegalTypeAnalysisException in DynamicPPL's submodel tilde_assume!!).
It is pre-existing: it reproduces identically at the old CR pin with the original CTIDM, and on new CR with the original CTIDM.
CI on composable-recurrences (run 46495803209) already fails both Enzyme jobs on the Split scenarios.
Before the seam change, ForwardDiff (1008/1008) and ReverseDiff tape (987 pass, 1 broken) gave the same counts.

Not run: the docs build (DocumenterVitepress with CairoMakie).
I checked the edited Ring snippet against CR directly: with and without islinear the outputs agree.

Timings

All are the minimum of 200 calls to a prepared DifferentiationInterface.gradient of the AD-fixture log densities, in µs.
Gradients agree to 1e-4 between each pair.

Old CR (142ae78) vs new CR (ba05903), CTIDM unchanged, Mooncake reverse:

Scenario Old CR New CR
RandomWalk latent 0.8 0.8
AR latent 1.0 1.0
MA latent 1.4 1.4
ARMA latent 2.3 2.3
ExpGrowthRate + Poisson 1.9 1.9
Renewal + NegativeBinomial 4.5 4.5
Renewal + LatentDelay 8.2 5.7
Renewal + UncertainGenInterval 1491.5 1064.4
Renewal + ImportedCases 181.2 173.3
Renewal + SusceptibleDepletion 138.0 129.5
Renewal + StratifiedRt 9.7 9.3
Renewal + FixedMixingK 9.9 9.7
Renewal + PairwiseGenInt 11.6 11.8
DirectInfections + Aggregate 4.5 4.9

The other backends were within noise (ratios 0.87 to 1.27 on runs of 0.2 to 10 µs, with other jobs running), and no gradient changed.

Modifier seam, Renewal + Poisson, n = 8 (seam.jl, new CR):

Modifiers ForwardDiff before → after Mooncake reverse before → after
none 1.1 → 1.2 3.8 → 3.5
SusceptibleDepletion 7.1 → 1.4 118.0 → 3.8
CR.Depletion passed directly 7.1 → 1.4 118.4 → 3.7
CR.Transform(+, 0.1) passed directly 6.9 → 1.3 113.0 → 3.6
ImportedCases 6.6 → 6.4 123.3 → 119.8
SusceptibleDepletion + ImportedCases 7.7 → 7.5 136.4 → 123.4

AD-fixture scenarios, original CTIDM vs this branch on new CR:

Scenario Backend Original This branch
Renewal + SusceptibleDepletion ForwardDiff 8.4 2.3
Renewal + SusceptibleDepletion Mooncake reverse 132.5 5.3
Renewal + SusceptibleDepletion Enzyme reverse 69.3 4.0
Renewal + ImportedCases (with SusceptibleDepletion) Mooncake reverse 146.5 143.3
Renewal + StratifiedImportedCases Mooncake reverse 260.9 210.1
Renewal + StratifiedRt Mooncake reverse 9.6 9.2
Renewal + FixedMixingK Mooncake reverse 10.0 9.6
DirectInfections + Aggregate Mooncake reverse 5.4 5.0
Renewal + NegativeBinomial (no modifiers, 2000 calls, two runs) ForwardDiff 1.4, 1.4 1.4, 1.4
Renewal + NegativeBinomial (no modifiers, 2000 calls, two runs) Mooncake reverse 4.4, 4.5 4.6, 4.3
Renewal + NegativeBinomial (no modifiers, 2000 calls, two runs) Enzyme reverse 3.0, 3.0 3.0, 3.0

ImportedCases still costs about 115 µs under Mooncake.
The CR operator with a drawn scalar Transform(+, ι) takes 0.6 µs under Mooncake, so the cost is in DynamicPPL's prefixed submodel path rather than CR.
That is a follow-up for CTIDM, not part of this PR.

expected_Rt is not on any gradient path. Its primal on a 200-day series with a 5-day interval went from 5.7 µs to 0.42 µs, with identical output.

Audit: what CTIDM already takes from CR, what changed, what stays

Already CR calls, no change: AR / random walk (Recurrence via _extend), MA (Convolution), ExpGrowthRate cumulative sum (Recurrence via _cumulate), LatentDelay (Convolution, TimeVarying), Aggregate (CR.window_sums), seeding (CR.exponential_history), susceptible depletion (Depletion(N, Floor())), imports (Transform(+, ι)), strata mixing (coupling, PerStratum, Pairwise).

Replaced:

  • expected_Rt denominator loop → Convolution.
  • Per-modifier prefixed submodel for modifiers that draw nothing → plain resolution (CTIDM glue, not a CR call).

Tried and reverted:

  • R_to_r (two Newton steps) → CR.growth_rate. The split NUTS test failed: during the initial step-size search R₁ reaches Inf, and growth_rate throws ArgumentError("growth_rate did not converge in 50 steps for R = Inf"). CTIDM's R_to_r returns NaN, and the sampler rejects the proposal. Kept CTIDM's R_to_r. Reproducer below.

Left, and why:

  • src/utils/recurrences.jl (_cumulate, _extend): two one-line wrappers that name the CR calls shared by four models. Inlining them repeats the keyword set four times.
  • DiffLatentModel: cumsum applied d times to [init; diff]. Base.cumsum is shorter than a Recurrence with a binomial kernel and has no history to set up.
  • neg_MGF, r_to_R: closed-form sums, not recurrences.
  • ReportTriangle, CombineInfections, Split loops: they loop over tilde statements or strata, not a recurrence.

Places where CR's API made CTIDM code awkward

For CR's API stabilisation (CR issue #916):

  1. No way to recognise a CR modifier. CTIDM hard-codes the built-in modifier types to accept a CR modifier as it is, so a user's own pure-step modifier must be wrapped in an AbstractRenewalModifier:
    const _RecurrenceModifier = Union{
        CR.Depletion, CR.Redistribute, CR.Allocate, CR.Transform,
    }
    A public trait (for example CR.ismodifier(::Type)) or abstract type would let Renewal accept any CR modifier.
  2. growth_rate throws on extreme values. R = Inf or 1e300 gives "did not converge" and R = 0 gives "R must be positive"; only NaN passes. Inside a sampler a throw aborts the run, where a NaN would reject the proposal. This blocks replacing CTIDM's R_to_r. growth_rate also takes one R and one g, so a per-stratum seed loops: [R_to_r(Rt₀[g], view(w, g, :)) for g in eachindex(Rt₀)].
  3. Lag conventions differ between operators. A Recurrence kernel is lag 1 first and a Convolution kernel is lag 0 first, so a renewal denominator from a generation interval needs a padded zero:
    Convolution(vcat(zero(eltype(g)), g))(infections; start = n + 1)
  4. A cumulative sum or AR path takes a unit-kernel recurrence and keywords:
    const _UNIT_LAG = [1.0]
    _cumulate(history, add) = Recurrence(_UNIT_LAG)(1.0; history = history, add = add)
    Recurrence(kernel)(gain; history = init, add = ϵ_t, include_history = true)
    A named scan or cumulative-sum constructor would remove CTIDM's wrappers.
  5. A one-lag per-stratum history must be a strata × 1 matrix:
    _strata_history(x::AbstractVector) = reshape(x, :, 1)

Generated by Claude Code

Pin ComposableRecurrences at ba05903, the head of its redesign branch.
CTIDM needed no source change to run on it.

Describe a custom renewal step as a pure ComposableRecurrences step
rather than a forward! method for the Step role.
Declare the tutorial ring coupling linear so its gradient takes the
dense coupling rule instead of plain AD of the whole operator.
Compute expected_Rt's denominator with a Convolution instead of a
hand-written loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WwC7iyq8PXsdfyhWyzdjES
The pre-scan seam put every modifier behind a prefixed submodel, even
a Depletion or Transform that samples nothing. That level cost about
115 µs of a Mooncake reverse gradient against 4 µs for the renewal
without modifiers. A modifier that draws nothing is now resolved by a
plain function, and a run of them ends the recursion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WwC7iyq8PXsdfyhWyzdjES
@seabbs-bot
seabbs-bot requested a review from seabbs as a code owner December 1, 2026 13:05
@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/cr-redesign-port")
using ComposableTuringIDModels

Option 2: Local Checkout

If you have the repo locally:

git checkout claude/cr-redesign-port
julia --project=. -e "using Pkg; Pkg.instantiate()"

Copy link
Copy Markdown
Collaborator Author

registrability fails here because the ComposableRecurrences compat 0.2 cannot be satisfied in General: CR 0.2 is not registered, which is why [sources] pins a commit.
It fails the same way on the base branch composable-recurrences (0bddf8a), so it is not caused by this PR.
It clears once CR 0.2 is registered and the [sources] pin is dropped.


Generated by Claude Code

Copy link
Copy Markdown
Collaborator Author

Two more failures that are not caused by this PR. Each fails with the same error on the base branch composable-recurrences (0bddf8a):

  • test (pre, *): resolving the workspace on pre-release Julia gives "Unsatisfiable requirements": ComposableRecurrences 0.2 and Mooncake together allow no version of Julia there.
  • downgrade-compat: "could not find manifest entry for package with uuid 4e7e49c6-…" (ComposableRecurrences). The downgrade resolver does not follow the [sources] commit pin of an unregistered package.

Generated by Claude Code

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
Add tests for modifiers that draw nothing, the empty tuple, a mixed
tuple keeping positional prefixes on draws, and expected_Rt against the
explicit generation-interval sum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WwC7iyq8PXsdfyhWyzdjES
@codecov

codecov Bot commented Dec 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.00000% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/infection_models/renewal/modifiers.jl 88.88% 1 Missing ⚠️
Flag Coverage Δ
ad-forwarddiff 61.60% <55.55%> (-0.12%) ⬇️
ad-mooncake-forward 61.60% <55.55%> (-0.12%) ⬇️
ad-mooncake-reverse 61.60% <55.55%> (-0.12%) ⬇️
ad-reversediff 61.65% <55.55%> (-0.12%) ⬇️
ad-reversediff-compiled 61.65% <55.55%> (-0.12%) ⬇️
unit 93.71% <90.00%> (-0.11%) ⬇️

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

Files with missing lines Coverage Δ
src/infection_models/utils.jl 97.14% <100.00%> (ø)
src/infection_models/renewal/modifiers.jl 88.00% <88.88%> (-7.24%) ⬇️
🚀 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 here with the same result as on the base branch composable-recurrences (run 46495803209): 925 passed, 2 errored, 1 broken.
Both errors are IllegalTypeAnalysisException in DynamicPPL's submodel tilde_assume!! on the Split scenarios.
ad / Enzyme reverse also fails on the base branch with the same exception.
Locally, Renewal+Split cascade posterior raises this error under Enzyme in three setups:

  • the old CR pin with the original CTIDM
  • the new CR with the original CTIDM
  • this branch

So the error comes from neither the CR repin nor the changes here.


Generated by Claude Code

@github-actions

github-actions Bot commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

📖 Documentation preview is ready!

View the docs for this PR at: https://EpiAware.github.io/ComposableTuringIDModels.jl/previews/PR453/

This preview will be updated automatically when you push new commits.

@seabbs
seabbs merged commit 3926c27 into composable-recurrences Dec 1, 2026
26 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