Skip to content
Merged
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
8 changes: 4 additions & 4 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ ComposableTuringIDModelsCatalystExt = ["Catalyst", "ModelingToolkit"]
ComposableTuringIDModelsEnzymeExt = "Enzyme"

[compat]
Catalyst = "16"
Catalyst = "16, 17.0"
CensoredDistributions = "0.2.22"
ConstructionBase = "1.6.0"
Distributions = "0.25.128"
DocStringExtensions = "0.9.5"
DocStringExtensions = "0.9.5, 0.10"
DynamicPPL = "0.42.1"
Enzyme = "0.13"
FlexiChains = "0.6.13"
FlexiChains = "0.6.13, 0.7"
KernelFunctions = "0.10.65, 0.11"
LinearAlgebra = "1.11, 1.12"
LogExpFunctions = "0.3.29, 1.0"
Expand All @@ -46,7 +46,7 @@ OrdinaryDiffEq = "7.1.0"
Random = "1.11, 1.12"
Statistics = "1.11, 1.12"
Tables = "1.13.0"
Turing = "0.46, 0.47"
Turing = "0.46, 0.47, 0.49"
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
julia = "1.11, 1.12"

[workspace]
Expand Down
10 changes: 6 additions & 4 deletions docs/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,16 @@ ADFixtures = {path = "../test/ADFixtures"}
ComposableTuringIDModels = {path = ".."}

[compat]
Dates = "1.11"
Enzyme = "0.13.199"
EpiAwarePackageTools = "0.3, 0.4"
ADTypes = "1"
AbstractGPs = "0.5"
Accessors = "0.1"
AlgebraOfGraphics = "0.12, 0.13"
CSV = "0.10"
CSV = "0.10, 1.3"
CairoMakie = "0.15"
Catalyst = "16"
Catalyst = "16, 17.0"
Chairmarks = "1"
DataFrames = "1"
DataFramesMeta = "0.15"
Expand All @@ -64,14 +65,15 @@ Literate = "2"
DynamicPPL = "0.42"
LogDensityProblems = "2"
LogExpFunctions = "0.3, 1"
MCMCChains = "7"
MCMCChains = "7, 8.0"
Markdown = "1"
ModelingToolkit = "11"
Mooncake = "0.5"
OrdinaryDiffEq = "7"
PairPlots = "3"
Plots = "1"
Random = "1.11"
ReverseDiff = "1.17.0"
Statistics = "1"
StatsBase = "0.34, 0.35"
Turing = "0.46, 0.47"
Turing = "0.46, 0.47, 0.49"
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"@mathjax/src": "^4.0.0",
"@mdit/plugin-mathjax": "^0.25.0",
"@mdit/plugin-tex": "^0.23.1",
"@nolebase/vitepress-plugin-enhanced-readabilities": "^2.14.0",
"@nolebase/vitepress-plugin-enhanced-readabilities": "~2.18.2",
"d3-format": "^3.1.0",
"markdown-it": "^14.1.0",
"markdown-it-footnote": "^4.0.0",
Expand Down
32 changes: 29 additions & 3 deletions ext/ComposableTuringIDModelsCatalystExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ using Catalyst: Catalyst, ReactionSystem
# public and owner-correct for ExplicitImports).
using ModelingToolkit: ModelingToolkit
using OrdinaryDiffEq: ODEProblem, remake
using DynamicPPL: DynamicPPL, @model, NamedDist
using DynamicPPL: DynamicPPL, @model
using Distributions: Distribution

# A specification for one species or parameter: its symbolic handle (used to build
Expand Down Expand Up @@ -93,6 +93,28 @@ function ComposableTuringIDModels.CatalystODEParams(
return CatalystODEParams(prob, u0_specs, p_specs)
end

# DynamicPPL names a sampled variable after the literal left-hand side of `~`,
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
# so a name held at run time takes the calls `~` itself makes: a fixed value is
# returned unrecorded, as `~` returns it, a conditioned one is scored, and
# anything else is drawn.
# These are DynamicPPL internals, matching its 0.42 compiler; `y ~ dist`, the
# documented replacement for `NamedDist`, needs the name when it is written.
function _named_tilde!!(model, varinfo, dist, vn)
context = model.context
full_vn = DynamicPPL.prefix(context, vn)
template = DynamicPPL.VarNamedTuples.NoTemplate()
rhs = DynamicPPL.check_tilde_rhs(dist)
if DynamicPPL.contextual_isfixed(context, full_vn)
return DynamicPPL.getfixed_nested(context, full_vn), varinfo
elseif DynamicPPL.contextual_isassumption(context, full_vn)
return DynamicPPL.tilde_assume!!(context, rhs, vn, template, varinfo)
end
value = DynamicPPL.getconditioned_nested(context, full_vn)
return DynamicPPL.tilde_observe!!(
context, rhs, value, vn, template, varinfo
)
end

# Sample every distribution-valued spec into a flat, symbol-named Turing variable
# (`β`, `S`, ...) — fixed `Real` specs are used as constants, NOT sampled — and
# return the initial state and parameters as SYMBOLIC `symbol => value` maps. The
Expand All @@ -106,15 +128,19 @@ end
p = Vector{Pair}(undef, length(params.p_specs))
for (k, s) in enumerate(params.u0_specs)
if s.spec isa Distribution
x ~ NamedDist(s.spec, DynamicPPL.VarName{s.name}())
x, __varinfo__ = _named_tilde!!(
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
__model__, __varinfo__, s.spec, DynamicPPL.VarName{s.name}()
)
u0[k] = s.symbol => x
else
u0[k] = s.symbol => s.spec
end
end
for (k, s) in enumerate(params.p_specs)
if s.spec isa Distribution
x ~ NamedDist(s.spec, DynamicPPL.VarName{s.name}())
x, __varinfo__ = _named_tilde!!(
__model__, __varinfo__, s.spec, DynamicPPL.VarName{s.name}()
)
p[k] = s.symbol => x
else
p[k] = s.symbol => s.spec
Expand Down
13 changes: 12 additions & 1 deletion ext/ComposableTuringIDModelsEnzymeExt.jl
Original file line number Diff line number Diff line change
@@ -1,13 +1,24 @@
# Enzyme AD-safety machinery: `deepcopy` of missing-bearing conditioning data
# is marked inactive, and forward-mode `dot` gets a rule BLAS does not provide.
# and the rebuild of a partially missing series are marked inactive, and
# forward-mode `dot` gets a rule BLAS does not provide.
# Both are generic DynamicPPL/Enzyme fixes, so they belong in
# `EpiAwareADTools.jl`.
module ComposableTuringIDModelsEnzymeExt

using ComposableTuringIDModels: ComposableTuringIDModels, MissingObservations
using Enzyme: Enzyme
using Enzyme.EnzymeRules: EnzymeRules
using LinearAlgebra: dot

# Rebuilding a partially missing series is data only, and its
# `Union{Missing, T}` vector fails Enzyme's type analysis, so it is inactive.
function EnzymeRules.inactive(
::typeof(ComposableTuringIDModels._restore_missing),
::MissingObservations
)
return nothing
end

# Keep the `T <: Real` bound. `Union{Missing, Any}` collapses to `Any`, so a
# wider signature would also match `deepcopy(::Vector{Any})` and silently zero a
# real tangent.
Expand Down
23 changes: 4 additions & 19 deletions src/observation_models/ObservationErrorModels/methods.jl
Original file line number Diff line number Diff line change
Expand Up @@ -94,30 +94,17 @@ end
function _score_missing_observations!!(
context, varinfo, y::MissingObservations, diff_t, Y_t, dist
)
n = length(y.value)
# `scored` is untyped until every entry is in.
# The final `identity.()` narrowing runs after every tilde call has
# accumulated its log-probability, so it is not part of what Enzyme
# differentiates.
scored = Vector{Any}(undef, n)
for i in _scored_steps(diff_t, Y_t)
idx = i + diff_t
y.present[idx] || continue
vn = DynamicPPL.VarName{:y_t}(DynamicPPL.Index((idx,), NamedTuple()))
val = y.value[idx]
_, varinfo = DynamicPPL.tilde_observe!!(
context, dist(i), val, vn, y.value, varinfo
context, dist(i), y.value[idx], vn, y.value, varinfo
)
scored[idx] = val
end
# Left unassigned above are the marginalised gaps and any entry outside the
# scored window, reached when `Y_t` is shorter than `y_t`.
# Keep both as given.
for idx in 1:n
isassigned(scored, idx) && continue
scored[idx] = y.present[idx] ? y.value[idx] : missing
end
return identity.(scored), varinfo
# The series returned is the data as given, gaps and all, so it carries no
# derivative; the Enzyme extension marks its rebuild inactive.
return _restore_missing(y), varinfo
end

@doc raw"
Expand Down Expand Up @@ -158,8 +145,6 @@ end

# Rebuild the ragged `Vector{Union{Missing,T}}` a `MissingObservations` carrier
# stands in for.
# Only standalone `define_y_t` calls reach this.
# The hot loop goes through `_score_missing_observations!!` instead.
_restore_missing(y) = y
_restore_missing(y::MissingObservations) = map((v, p) -> p ? v : missing, y.value, y.present)

Expand Down
22 changes: 15 additions & 7 deletions src/steps/RenewalStep.jl
Original file line number Diff line number Diff line change
Expand Up @@ -259,25 +259,33 @@ end
# directly, so a drawn coupling operator is named the same way whether or not
# the step carries modifiers.
core ~ as_turing_submodel(step.core, n)
modifiers ~ to_submodel(_resolve_modifiers(step.modifiers, n, 1), false)
modifiers ~ to_submodel(
_resolve_modifiers(step.modifiers, n, 1, ()), false
)
return RenewalStep(core, modifiers)
end

# The recursion is structural, over the tuple rather than an index into it, so
# each level has a concrete tuple type.
# Each modifier is prefixed by its position, so two modifiers of the same kind
# cannot collide on a variable name.
@model function _resolve_modifiers(mods::Tuple{}, n, index)
return ()
# The resolved modifiers are passed down and returned from the last level, not
# splatted back up: Enzyme rejects the splat when the levels mix a modifier
# that draws parameters with one that draws none.
@model function _resolve_modifiers(mods::Tuple{}, n, index, resolved)
return resolved
end

@model function _resolve_modifiers(mods::Tuple, n, index)
@model function _resolve_modifiers(mods::Tuple, n, index, resolved)
modifier ~ to_submodel(
prefix(as_turing_model(first(mods), n), Symbol(:modifier_, index)),
false
)
rest ~ to_submodel(
_resolve_modifiers(Base.tail(mods), n, index + 1), false
complete ~ to_submodel(
_resolve_modifiers(
Base.tail(mods), n, index + 1, (resolved..., modifier)
),
false
)
return (modifier, rest...)
return complete
end
4 changes: 3 additions & 1 deletion src/steps/RenewalSteps.jl
Original file line number Diff line number Diff line change
Expand Up @@ -178,8 +178,10 @@ _series(v::AbstractVector{<:AbstractVector}) = reduce(hcat, v)

# Drop the oldest entry and commit the new incidence.
_advance(window::AbstractVector, new) = vcat(window[2:end], new)
# `cat` rather than `hcat`: ReverseDiff's `hcat` method for a tracked vector is
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
# ambiguous with SparseArrays' once both are loaded.
function _advance(window::AbstractMatrix, new)
return hcat(collect(view(window, :, 2:size(window, 2))), new)
return cat(collect(view(window, :, 2:size(window, 2))), new; dims = 2)
end

# The number of lags a generation interval covers.
Expand Down
12 changes: 2 additions & 10 deletions test/ADFixtures/src/ADFixtures.jl
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,7 @@ function _models()
Aggregate(PoissonError(), [0, 0, 0, 0, 0, 0, 7])
)
# Partially-missing observations: the blank entries are marginalised out,
# so the gradient covers the carrier's scoring loop skipping them. The
# scored series it returns is ragged, so Enzyme reverse cannot compile it
# and the scenario is listed broken for that backend below.
# so the gradient covers the carrier's scoring loop skipping them.
partialmiss = IDModel(
DirectInfections(; Z = RandomWalk(), initialisation = Normal()),
NormalError()
Expand Down Expand Up @@ -760,13 +758,7 @@ function backend_broken_scenarios()
"ReverseDiff (compiled)" => reverse_only,
"Mooncake reverse" => reverse_only,
"Mooncake forward" => reverse_only,
# A partially-missing series is marginalised, so the scored series
# comes back as `Vector{Union{Missing,T}}`. Enzyme's reverse-mode type
# analysis fails on the `similar(::Broadcasted, ::Type{Union{Missing,
# Float64}})` that rebuilds it.
"Enzyme reverse" => union(
reverse_only, Set(["DirectInfections+PartiallyMissing posterior"])
),
"Enzyme reverse" => reverse_only,
# Enzyme forward returns a finite but wrong gradient here, every entry
# offset by the same constant. Every other backend agrees with the
# reference, so the fault is in the backend rather than the model.
Expand Down
12 changes: 10 additions & 2 deletions test/Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,29 @@ ComposableTuringIDModels = {path = ".."}

[compat]
ADTypes = "1.23.0"
Accessors = "0.1.46"
Aqua = "0.8.16"
BenchmarkTools = "1.8.0"
Catalyst = "16.2.3"
Catalyst = "16.2.3, 17.0"
DifferentiationInterface = "0.7.20"
Distributions = "0.25.130"
Documenter = "1.17.0"
DynamicPPL = "0.42.4"
EpiAwarePackageTools = "0.4.1"
ExplicitImports = "1.15.0"
ForwardDiff = "1.4.5"
InteractiveUtils = "1.11"
KernelFunctions = "0.11.1"
LinearAlgebra = "1.11"
LogDensityProblems = "2.2.0"
LogExpFunctions = "0.3.29, 1.0"
ModelingToolkit = "11.39.0"
OrdinaryDiffEq = "7.6.0"
Pkg = "1.11"
Random = "1.11"
Runic = "=1.9.0"
Statistics = "1.11"
Test = "1.11"
TestItemRunner = "1.1.5"
TestItems = "1.0.0"
Turing = "0.46, 0.47"
Turing = "0.46, 0.47, 0.49"
40 changes: 40 additions & 0 deletions test/unit/ode/catalyst_ext.jl
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,46 @@ end
@test !("R" in nms)
end

@testitem "CatalystODEParams names can be conditioned, fixed and prefixed" begin
using ComposableTuringIDModels, Catalyst, ModelingToolkit, OrdinaryDiffEq,
Distributions
using DynamicPPL: DynamicPPL, condition, fix, prefix, logprior
sir = @reaction_network begin
β, S + I --> 2I
γ, I --> R
end
β_prior = LogNormal(log(0.3), 0.05)
params = CatalystODEParams(
sir;
tspan = (0.0, 30.0),
u0_priors = [sir.S => 0.99, sir.I => 0.01, sir.R => 0.0],
p_priors = [sir.β => β_prior, sir.γ => LogNormal(log(0.1), 0.05)]
)
model = as_turing_model(params, nothing)
rate(pairs, value) = any(pr -> pr.second == value, pairs)

# Conditioned: β is no longer drawn, its value reaches the rates and it is
# scored against its prior.
conditioned = condition(model, (β = 0.25,))
_, p = conditioned()
@test rate(p, 0.25)
@test !("β" in string.(keys(rand(conditioned))))
vi = DynamicPPL.VarInfo(conditioned)
@test DynamicPPL.getlogp(vi).loglikelihood ≈ logpdf(β_prior, 0.25)

# Fixed: β takes the value and is neither drawn nor scored.
fixed = fix(model, (β = 0.25,))
_, p = fixed()
@test rate(p, 0.25)
@test !("β" in string.(keys(rand(fixed))))

# Inside a prefixed submodel the names take the prefix.
@test all(
n -> n in string.(keys(rand(prefix(model, :ode)))),
["ode.β", "ode.γ"]
)
end

@testitem "CatalystODEParams enforces a prior for every species and parameter" begin
using ComposableTuringIDModels, Catalyst, ModelingToolkit, OrdinaryDiffEq, Distributions
sir = @reaction_network begin
Expand Down
Loading