Skip to content
Open
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
92 changes: 62 additions & 30 deletions approaches/composable-recurrences.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ page-layout: full

```{.julia .code-overflow-scroll}
using ComposableRecurrences
using ComposableRecurrences: Depletion, Floor, Add, with_state
using ComposableRecurrences: Depletion, Floor, Transform, Resume

# Generation interval, lag 1 first: weights on y[t-1], y[t-2], y[t-3]
g = [0.6, 0.3, 0.1]
Expand All @@ -85,7 +85,7 @@ K = [0.9 0.1; 0.2 0.8]
# Modifiers are structs in a tuple, applied in order after each step
N = PerStratum([1_000.0, 500.0])
infections = Recurrence(g; coupling = K,
modifiers = (Depletion(N, Floor()), Add(0.5)))
modifiers = (Depletion(N, Floor()), Transform(+, 0.5)))

# Reporting delay, lag 0 first: P(delay = 0, 1, 2, 3)
reports = Convolution([0.0, 0.5, 0.3, 0.2])
Expand All @@ -96,7 +96,7 @@ y = infections(R; history = ones(2, 3))
cases = reports(y)

# Keep the state after day 5, then resume for a forecast
y1, st = with_state(infections, R; history = ones(2, 3), stop = 5)
y1, st = infections(R; history = ones(2, 3), stop = 5, record = Resume())
y2 = infections(R; state = st)
y ≈ hcat(y1, y2)
```
Expand All @@ -106,8 +106,8 @@ y ≈ hcat(y1, y2)

:::

The example uses API v0.1 of [ComposableRecurrences.jl](https://github.com/EpiAware/ComposableRecurrences.jl), which is landing on the main branch now.
The package is not registered yet, so install it from the repository to try it.
The example uses [ComposableRecurrences.jl](https://github.com/EpiAware/ComposableRecurrences.jl) v0.2.0.
Install it with `Pkg.add("ComposableRecurrences")`.

## The approach

Expand All @@ -134,7 +134,8 @@ Every kernel is written lag first, the way a generation interval or AR coefficie
A `Recurrence` kernel starts at lag 1 and a `Convolution` kernel at lag 0, so nothing is ever reversed by hand.
Operators are built once, outside the model, and called with the per-day inputs that are usually sampled.
Chaining is function composition, as in `reports(infections(R; history))`.
Every time-indexed input is read at absolute time, so `with_state` returns the output with its state and a later call resumes from `state`.
Every time-indexed input is read at absolute time, so a call with `record = Resume()` returns the output with its state and a later call resumes from `state`.
`record = Pressure()` adds the weighted sum of each step before the gain, and `record = Trace()` adds what each modifier recorded.

### Strata, time variation and coupling

Expand All @@ -144,25 +145,42 @@ Wrappers name the extra axis of a coefficient or parameter.
`Pairwise` is a kernel that gives each pair of strata its own lags, so it replaces the coupling.
Otherwise the coupling mixes strata before the gain, as a contact or mobility matrix does.
Couplings can be dense, sparse or diagonal matrices, and any real element type is accepted, so `Float32` and dual numbers pass through.
A time-varying input can also be given as `start => value` change points.

Gains, `add` inputs and modifier parameters can be parameters as well as arrays.
`Derived` computes a parameter from others, and `Recent` reads one from the recurrence's own recent outputs.
`Gather` reads a parameter at another row, so strata can share values.
Kernels can be computed too.
`Survival`, `Increments` and `Normalised` build a kernel from coefficients, and with Distributions or CensoredDistributions loaded a delay distribution can be passed as a kernel.

### Modifiers

Modifiers are structs composed in a tuple.
They are applied in order after each step and carry their own state.
They handle what the linear core cannot.
`Depletion(N)` depletes susceptibles by a hazard, and `Depletion(N, Floor())` by a floored fraction.
`Add(b)` adds an input at that point in the tuple, such as imports after depletion.
`Redistribute` moves cases between strata and `Clamp` bounds them.
Variants such as `Floor()` are structs too.
A new modifier or variant is a struct with a `forward` method for its step, so a modelling package can add its own.
A `Depletion` can hold several named pools through `pools`, with flows between them, as vaccination moves people out of the susceptible pool.
Its depletion forms, `Hazard`, `Floor` and `Truncate`, are structs too.
`Transform` applies a function at that point in the tuple, such as `Transform(+, b)` for imports after depletion or `Transform(clamp, lo, hi)` for bounds.
`Redistribute` moves cases between strata and `Allocate` rescales groups of strata to given totals.
A new modifier or depletion form is a struct with a pure `step` method, so a modelling package can add its own.

### Plug-in adjoints
### Gradient rules and backends

Reverse-mode AD is slow when each step copies its lag window into a new state.
The operators own a history buffer instead, which avoids that copy.
Native adjoints will plug in per operator, modifier or coupling by adding a `pullback!` method, with no AD declarations from the user.
`NoAdjoint(op)` turns an adjoint off, so its gain can be timed and the adjoint dropped if a backend catches up.
A [benchmark script](https://github.com/EpiAware/ComposableRecurrences.jl/blob/main/benchmark/gradients.jl) in the repository times plain AD gradients of the operators under Mooncake and Enzyme.
Every call runs under ForwardDiff, ReverseDiff, Mooncake, Enzyme and Reactant.
The Mooncake and Enzyme extensions add a reverse rule for each operator, with no AD declarations from the user.
A modifier written as a pure `step` takes the rule too.
`NoAdjoint(op)` turns a rule off, so its gain can be timed, and `test_adjoint` checks a rule against plain AD.
The [performance page](https://composablerecurrences.epiaware.org/stable/performance/index) compares the operators and their gradients with hand-written loops.

### Executors and GPUs

An executor sets where the loops of a call run.
`Serial()` is the default, `Threaded()` splits the loops across CPU threads and `Parallel(backend)` runs them as kernels on a device.
With KernelAbstractions loaded, calls run on GPU arrays, forward and in reverse.
Reactant compiles calls on traced arrays.

### How it fits with the other approaches

Expand All @@ -171,13 +189,14 @@ The operators are a foundation for the other approaches.
Its renewal, delay and latent process steps become calls to `Recurrence` and `Convolution`, with the priors and observation models staying in the Turing layer.
The [composed distributions](composed-distributions.qmd) stack will use them inside its packages.
ComposedDistributions can run a renewal across a distribution tree, taking each step's kernel from the tree ([#82](https://github.com/EpiAware/ComposedDistributions.jl/issues/82)).
CensoredDistributions may build on them in the same way.
The operators depend on none of these packages, so they can also be used in other models.
CensoredDistributions already supplies kernels to them through an optional extension, which turns a continuous delay distribution into the masses on each lag.
It may also build on the operators in the same way.
The operators need none of these packages, so they can also be used in other models.

## Package map

Arrows point from a package to the packages that use it.
The dashed grey arrow is a test and documentation dependency, and it is the only link in place today.
The dashed grey arrows are a test and documentation dependency and an optional extension, and they are the only links in place today.
The dashed teal arrows are planned and not yet implemented.

```{=html}
Expand All @@ -198,8 +217,8 @@ The dashed teal arrows are planned and not yet implemented.
<rect class="cr-node cr-focus" x="300" y="42" width="360" height="88" rx="6"/>
<text x="316" y="68" font-size="15" font-weight="700">ComposableRecurrences</text>
<text class="cr-sub" x="316" y="88">Recurrence · Convolution · TimeVarying · PerStratum · Pairwise</text>
<text class="cr-sub" x="316" y="104">Depletion · Add · Redistribute · Clamp</text>
<text class="cr-sub" x="316" y="120">no runtime EpiAware dependency</text>
<text class="cr-sub" x="316" y="104">Depletion · Redistribute · Allocate · Transform</text>
<text class="cr-sub" x="316" y="120">no required EpiAware dependency</text>

<rect class="cr-node" x="36" y="42" width="200" height="88" rx="6"/>
<text x="50" y="68" font-size="14" font-weight="600">EpiAwarePackageTools</text>
Expand All @@ -222,8 +241,9 @@ The dashed teal arrows are planned and not yet implemented.

<rect class="cr-node" x="644" y="270" width="280" height="96" rx="6"/>
<text x="658" y="294" font-size="14" font-weight="600">CensoredDistributions</text>
<text class="cr-sub" x="658" y="314">may build on the operators</text>
<text class="cr-sub" x="658" y="330">in the same way</text>
<text class="cr-sub" x="658" y="314">delay distributions as kernels</text>
<text class="cr-sub" x="658" y="330">through an optional extension</text>
<text class="cr-sub" x="658" y="346">may build on the operators</text>

<!-- edges -->
<path class="cr-e cr-dash" d="M238,86 L298,86" marker-end="url(#cr-map-am)"/>
Expand All @@ -232,6 +252,8 @@ The dashed teal arrows are planned and not yet implemented.
<path class="cr-e cr-plan" d="M480,132 L480,268" marker-end="url(#cr-map-a)"/>
<path class="cr-e cr-plan" d="M540,132 L760,268" marker-end="url(#cr-map-a)"/>
<text class="cr-lbl" x="490" y="196">planned</text>
<path class="cr-e cr-dash" d="M860,268 L662,110" marker-end="url(#cr-map-am)"/>
<text class="cr-lbl" x="790" y="176">extension</text>
</svg>
</figure>
```
Expand All @@ -243,21 +265,31 @@ Moving them onto one set of operators gives one forward kernel and one adjoint t
## Status

This approach is under development.
The core operators and the built-in modifiers are merged on the main branch of ComposableRecurrences.jl.
These are `Recurrence`, `Convolution`, the `TimeVarying`, `PerStratum` and `Pairwise` wrappers, the coupling and modifier interfaces, and `Depletion`, `Imports`, `Redistribute` and `Clamp`.
The test suite differentiates them with ForwardDiff, ReverseDiff, Mooncake and Enzyme through plain AD.
ComposableRecurrences.jl v0.2.0 is the current registered release.
It needs Julia 1.12 or later, and it also supports Julia 1.13.
It holds `Recurrence`, `Convolution`, the `TimeVarying`, `PerStratum` and `Pairwise` wrappers, parameters, computed kernels, and the `Depletion`, `Redistribute`, `Allocate` and `Transform` modifiers.
It also holds the Mooncake and Enzyme rules, the executors, and an FFT method for long convolution kernels.
The test suite differentiates the operators with ForwardDiff, ReverseDiff, Mooncake, Enzyme and Reactant.
Use-case tests check them against copies of the ComposableTuringIDModels and other model steps they will replace.

The API v0.1 consolidation is in progress.
It makes every option a struct, renames `Imports` to `Add`, makes `Pairwise` a kernel, and replaces `return_state` with `with_state`.
The native Mooncake and Enzyme adjoints are also in progress.
A first registered release follows them, and then the port of ComposableTuringIDModels onto the operators.
An FFT method for long fixed kernels is a later extension.
v0.2.0 renames or removes parts of v0.1.
`Add` and `Clamp` become `Transform`, `with_state` becomes `record = Resume()`, and `seeded` becomes `include_history = true`.
`Depletion` takes its starting pools through `pools`, and its heterogeneity exponent through its form, as in `Hazard(α)`.
The [release notes](https://github.com/EpiAware/ComposableRecurrences.jl/releases/tag/v0.2.0) list every change.
The port of ComposableTuringIDModels onto the operators follows the release.

## Where next

- The [ComposableRecurrences.jl documentation](https://composablerecurrences.epiaware.org/stable/)
covers the full API, with an
[API overview](https://composablerecurrences.epiaware.org/stable/explanation/api-overview)
that defines each concept once.
- Run it: the
[tutorials](https://composablerecurrences.epiaware.org/stable/getting-started/index)
each build one model, starting with
[three towns, step by step](https://composablerecurrences.epiaware.org/stable/getting-started/three-towns).
- The [ComposableRecurrences.jl repository](https://github.com/EpiAware/ComposableRecurrences.jl)
tracks development, and its documentation will follow the first release.
tracks development.
- Building a full model with priors and observations? See the
[composable Turing models approach](composable-turing-models.qmd).
- Composing delay distributions? See the
Expand Down
4 changes: 2 additions & 2 deletions packages/index.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,9 @@ Status reflects where a package sits in its release cycle rather than a judgemen
<td class="data-name">
<a href="https://github.com/EpiAware/ComposableRecurrences.jl">ComposableRecurrences.jl</a>
<a class="data-gh" href="https://github.com/EpiAware/ComposableRecurrences.jl" aria-label="ComposableRecurrences.jl on GitHub"><i class="bi bi-github"></i></a>
<span class="status-pill status-experimental">experimental</span>
<span class="status-pill status-maturing">maturing</span>
</td>
<td>Fast, differentiable recurrences and causal convolutions, the renewal, autoregressive and delay steps inside a model. The core operators are on the main branch but not yet registered, and native adjoints are in progress.</td>
<td>Fast, differentiable recurrences and causal convolutions, the renewal, autoregressive and delay steps inside a model. Registered at v0.2.0, with Mooncake and Enzyme gradient rules.</td>
</tr>
<tr data-category="distributions">
<td class="data-name">
Expand Down
Loading