Skip to content

Porting a patch model from hand-written loops ​

Introduction ​

The BVDOutbreakSize model covers an outbreak across 11 patches. It writes its renewal, movement between patches and reporting delay as loops with hand-written Mooncake rules. The inputs here are invented.

Packages used ​

julia
using ComposableRecurrences
using ComposableRecurrences: Depletion, Redistribute
using CairoMakie, AlgebraOfGraphics, DataFramesMeta
using ADTypes: AutoEnzyme, AutoForwardDiff, AutoMooncake
import DifferentiationInterface as DI
import Enzyme, ForwardDiff, Mooncake

CairoMakie.activate!(type = "png", px_per_unit = 2)

The source model ​

Each patch runs a renewal process seeded by days of infections. Its value on day is  . A share of what origin generates is realised in patch instead. Each patch then draws its infections from its own pool by the hazard form of depletion. Reports follow a delay over lags, lag 0 first:

Here is patch 's population, and its pool starts at   . The model runs at the source model's size: 11 patches, 200 days, a 20-day generation interval and a 30-day delay.

julia
S, T, L, L_w = 11, 200, 20, 30
gi = let w = [l^2 * exp(-l / 2.5) for l in 1:L]
    w ./ sum(w)
end
delay = let w = [exp(-l / 6) for l in 0:(L_w - 1)]
    w ./ sum(w)
end
N = [2.0e4 + 4.0e3 * p for p in 1:S]
# Importation falls with the distance between patches on a line.
K = [p == q ? 0.0 : 0.1 / abs(p - q) for p in 1:S, q in 1:S]
ε = [0.02 + 0.01 * sin((t + 9 * p) / 15) for p in 1:S, t in 1:T]
R = [1.6 - 0.6 * t / T + 0.1 * cos(p) for p in 1:S, t in 1:T]
# The outbreak is seeded in patch 1, with a few cases elsewhere.
seeds = [p == 1 ? 1.0 : 0.02 for p in 1:S, l in 1:L]
inputs = (; gi, delay, K, seeds);

The model is two modifiers on one Recurrence, then a Convolution. Redistribute moves each origin's share, and Depletion draws from each patch's pool. The seeds are the history, so the run starts on the day after them. The fixed inputs come in as one named tuple, so the function reads no globals.

julia
function backend_model(R, ε, N, inputs)
    (; gi, delay, K, seeds) = inputs
    S = PerStratum(max.(N .- vec(sum(seeds; dims = 2)), 0))
    modifiers = (
        Redistribute(K, ε),
        Depletion(PerStratum(N); pools = (; S)),
    )
    infections = Recurrence(gi; modifiers)(R; history = seeds)
    return (; infections, reports = Convolution(delay)(infections))
end
y = backend_model(R, ε, N, inputs)

long(x, name) = DataFrame(
    patch = repeat(1:S, outer = T), day = repeat(1:T, inner = S),
    count = vec(x), series = name
)
@chain vcat(long(y.infections, "Infections"), long(y.reports, "Reports")) begin
    @subset(in.(:patch, Ref([1, 4, 7, 11])))
    @transform(:patch = "Patch " .* string.(:patch))
    data(_) * mapping(:day, :count, color = :series => "", layout = :patch) *
        visual(Lines, linewidth = 2)
    draw(_; axis = (xlabel = "Day", ylabel = "Daily count"))
end

The outbreak grows first in patch 1 and reaches the far patches through importation.

Checking against the source loops ​

The benchmark keeps loops in the style of BVDOutbreakSize, each with a hand-written Mooncake rule. They read and on the seed days too and return those days first, so the check pads and trims them.

julia
include(joinpath(pkgdir(ComposableRecurrences), "benchmark", "bvd_handrule.jl"))
pad(X, m) = hcat(zeros(eltype(X), size(X, 1), m), X)
function loop_model(R, ε, N, inputs)
    (; gi, delay, K, seeds) = inputs
    m = size(seeds, 2)
    infections = BVDHandRule.patch_infections(
        pad(R, m), gi, seeds, K, pad(ε, m), N
    )[:, (m + 1):end]
    reports = reduce(
        vcat,
        [BVDHandRule.convolve_delay(collect(x), delay)' for x in eachrow(infections)]
    )
    return (; infections, reports)
end
z = loop_model(R, ε, N, inputs)
report_error = maximum(abs, y.reports .- z.reports) / maximum(z.reports)

The two agree to rounding: the largest difference in reports is   of the largest report. The use-case tests check each kernel against the code of BVDOutbreakSize, one test per row of the porting tables.

Gradients ​

The loss is a Poisson log-likelihood of fixed counts given the reports. Its parameters are the log reproduction numbers, the importation shares and the populations:

julia
counts = round.(y.reports .* (1 .+ 0.2 .* sin.(reshape(1:(S * T), S, T))))
function unpack(θ, S, T)
    n = S * T
    logR = reshape(θ[1:n], S, T)
    return exp.(logR), reshape(θ[(n + 1):(2n)], S, T), θ[(2n + 1):end]
end
poisson(C, counts) = sum(counts .* log.(C) .- C)
function make_loss(model, inputs, counts)
    S, T = size(counts)
    return θ -> poisson(model(unpack(θ, S, T)..., inputs).reports, counts)
end
loss = make_loss(backend_model, inputs, counts)
loop_loss = make_loss(loop_model, inputs, counts)
θ0 = vcat(vec(log.(R)), vec(ε), N)

The parameter vector has 4411 entries: 2200 log reproduction numbers, 2200 importation shares and 11 populations. Mooncake and Enzyme differentiate the model in reverse mode, ForwardDiff in forward mode as the reference. Mooncake also differentiates the loops through their hand-written rules.

julia
backends = [
    "ForwardDiff" => AutoForwardDiff(),
    "Mooncake" => AutoMooncake(; config = nothing),
    "Enzyme" => AutoEnzyme(;
        mode = Enzyme.set_runtime_activity(Enzyme.Reverse),
        function_annotation = Enzyme.Const,
    ),
]
grads = Dict(name => DI.gradient(loss, b, θ0) for (name, b) in backends)
grads["Mooncake, hand rules"] = DI.gradient(loop_loss, last(backends[2]), θ0)
relerr(a, b) = maximum(abs, a .- b) / maximum(abs, b)
@chain DataFrame(gradient = ["Mooncake", "Enzyme", "Mooncake, hand rules"]) begin
    @transform(:relative_error = relerr.(getindex.(Ref(grads), :gradient), Ref(grads["ForwardDiff"])))
    data(_) * mapping(:gradient => "", :relative_error) * visual(Scatter, markersize = 14)
    draw(_; axis = (ylabel = "Relative error against ForwardDiff", yscale = log10, limits = (nothing, (1.0e-16, 1.0e-10))))
end

Each reverse-mode gradient matches the ForwardDiff reference to rounding, with relative errors below . The package's gradient needs no rule written for the model: each operator call takes its own rule or plain AD.

Performance ​

The benchmark matrix times the gradient of each BVDOutbreakSize kernel in four arms:

  • the package as written here, ComposableRecurrences;

  • the package with its rules turned off, plain AD;

  • the BVDOutbreakSize loop differentiated by the AD package, hand loop;

  • the same loop with its hand-written Mooncake rules, hand rules.

The bars are the minimum times in microseconds, read from benchmark/results/docs.csv, so this page times nothing itself. Each case names the kernel and its size: the days T, the kernel length L and the patches S. The hand rules are Mooncake rules, so Enzyme has no time for them.

julia
results = joinpath(pkgdir(ComposableRecurrences), "benchmark", "results", "docs.csv")
timings = if isfile(results)
    lines = readlines(results)
    header = Symbol.(split(first(lines), ','))
    rows = split.(lines[2:end], ',')
    @chain DataFrame([h => String.(getindex.(rows, i)) for (i, h) in enumerate(header)]) begin
        @subset(
            startswith.(:block, "backend "), :status .== "ok",
            in.(:target, Ref(["Mooncake reverse", "Enzyme reverse"]))
        )
        @transform(:case = chopprefix.(:block, "backend ") .* ", " .* :size, :min_us = parse.(Float64, :min_us))
        data(_) * mapping(
            :case => "", :min_us => "Minimum time (μs)",
            color = :method => "", dodge = :method, row = :target
        ) * visual(BarPlot, fillto = 1)
        draw(_; axis = (yscale = log10, xticklabelrotation = π / 4), figure = (size = (800, 700),))
    end
end

Porting from a hand-written loop ​

A hand-written loop maps to one operator call per kernel. Each use-case test in the tables matches values and ForwardDiff gradients against a verbatim copy of the loop in test/usecases/references/.

The model BVDOutbreakSize writes its kernels as functions over the whole series:

LoopPackageTest
renewal_infections(Rt, g, seed, N)Recurrence(g; modifiers = (Depletion(N; pools = (S = max(N - sum(seed), 0),)),)), called as vcat(seed, r(Rt; history = seed, start = length(seed) + 1))BVD renewal_infections
patch_infections(Rt, g, seeds, K, ε, N)Recurrence(g; modifiers = (Redistribute(K, ε), Depletion(PerStratum(N); pools = (; S)))), with S = PerStratum(max.(N .- vec(sum(seeds; dims = 2)), 0)), called as hcat(seeds, r(Rt; history = seeds, start = size(seeds, 2) + 1))BVD patch model
convolve_delay(x, delay)Convolution(delay)(x)BVD convolve_delay

The package ComposableTuringIDModels writes each step for an accumulate_scan:

StepPackageTest
RenewalStep with UniformScaling mixingRecurrence(g), one vector or one row per stratumrenewal, strata with identity mixing
RenewalStep with matrix mixing KRecurrence(g; coupling = K)strata with a mixing matrix
RenewalStep with SusceptibleDepletion(N)Depletion(N, Floor()) in modifiersrenewal with susceptible depletion
LDStep in LatentDelayConvolution(pmf)(Y)[d:end]fixed reporting delay (LatentDelay)
TimeVaryingLDStep in LatentDelayConvolution(TimeVarying(P))(Y)[d:end], one pmf per columntime-varying reporting delay

Four conventions differ between the loops and the package:

  • Generation interval: ComposableTuringIDModels stores it reversed, and the package takes it lag 1 first, as a recurrence's first weight is on the previous value.

  • Seed days: BVDOutbreakSize reads Rt on them and returns them first, and start skips them and vcat joins them in front.

  • Seeding: ComposableTuringIDModels seeds on a growth path, and exponential_history builds the same window.

  • Reporting window: ComposableTuringIDModels reports only the days with a full delay window, d:n, so the call keeps those days.

Learning more ​