Skip to content

Writing new types ​

A new modifier, coupling or depletion form is a type with a forward! method for each of its roles. One modifier built end to end shows each step, and the pages after this one cover the other cases.

julia
using ComposableRecurrences
const CR = ComposableRecurrences
ComposableRecurrences

A first modifier ​

This modifier smooths each stratum exponentially:

where is the value it receives, the value it passes on and its state.

julia
struct Smooth{A}
    a::A
end
CR.blocks(::Smooth) = (1, 1)
function CR.forward!(m::Smooth, ::CR.Init, s, history)
    H = reshape(history, length(s), :)
    s .= view(H, :, size(H, 2))
    return nothing
end
function CR.forward!(m::Smooth, ::CR.Step, v, s, t)
    for k in eachindex(v, s)
        s[k] = m.a * s[k] + (1 - m.a) * v[k]
        v[k] = s[k]
    end
    return nothing
end

The second argument of forward! is the role, a type with no fields that selects the method by dispatch. The role Step() computes one step from the values v, one per stratum, the state s and the time t. The role Init() sets the starting state from the call's history, here its last value. Both write in place and return nothing.

The modifier acts on each stratum alone, so it is pointwise. It says so with blocks(::Smooth) = (1, 1): one value and one state entry per stratum. Rules for every type lists what else a forward! must respect, such as taking dual numbers.

In a model ​

The modifier goes in the modifier tuple beside the built-in ones. Placed before Depletion, it smooths the infections drawn from the pool. With the smoothing and the depletion draw, each step gives

where is the kernel, the gain and the output. More smoothing delays the peak.

julia
seed = [1.0, 2.0, 3.0]
N = 10_000.0
pool = CR.Depletion(N; pools = (S = N - sum(seed),))
model(a) = Recurrence(
    [0.1, 0.3, 0.3, 0.2, 0.1]; modifiers = (Smooth(a), pool)
)
[argmax(model(a)(fill(1.8, 80); history = seed)) for a in (0.0, 0.5, 0.8)]
3-element Vector{Int64}:
 31
 39
 58

Without a pullback!, the model is still differentiable: the operator's rule differentiates the modifier's step locally with dual numbers.

julia
using ForwardDiff

loss(a) = sum(model(a)(fill(1.8, 80); history = seed))
ForwardDiff.derivative(loss, 0.5)
-59.695054865984936

Its pullback ​

A pullback! gives the derivative in closed form instead. The new value and state are both , so their cotangents add:

where a bar marks a cotangent, is the summed cotangent and is the state before the step.

A pullback! takes the named tuple grads first, then the same arguments as forward!. Its entries grads.v and grads.s hold the cotangents of the new value and state, and the method overwrites them with those of the old. The entry grads.piece holds the cotangents of the type's own fields. The function cotangent reads the entry of the field a, and add_cotangent! adds to it. The Init pullback adds the state's cotangent into the last column of the history.

julia
function CR.pullback!(grads, m::Smooth, ::CR.Step, v, s, t)
    v̄, s̄ = grads.v, grads.s
    for k in eachindex(v, s)
        ḡ = v̄[k] + s̄[k]
        ā = (s[k] - v[k]) * ḡ
        CR.add_cotangent!(CR.cotangent(grads.piece, :a), ā)
        v̄[k], s̄[k] = (1 - m.a) * ḡ, m.a * ḡ
    end
    return nothing
end
function CR.pullback!(grads, m::Smooth, ::CR.Init, s, history)
    grads.history === nothing && return nothing
    H̄ = reshape(grads.history, length(s), :)
    view(H̄, :, size(H̄, 2)) .+= grads.s
    return nothing
end

grads = (; piece = (; a = Ref(0.0)), v = [1.0], s = [0.5])
CR.pullback!(grads, Smooth(0.5), CR.Step(), [2.0], [1.0], 1)
(grads.v, grads.s, grads.piece.a[])
([0.75], [0.75], -1.5)

Parameters and gradients gives the layout of grads.piece for every kind of field.

Checking a new type ​

The test PieceInterface checks forward! with one Arguments per role, and here also the optional checks in braces; Checking your type lists them all.

julia
using Interfaces: Interfaces, Arguments

m = Smooth(0.3)
Interfaces.test(
    CR.PieceInterface{(:pointwise, :nstate, :pullback)}, Smooth,
    [
        Arguments(; piece = m, role = CR.Init(), args = (zeros(2), ones(2, 3))),
        Arguments(;
            piece = m, role = CR.Step(), args = ([1.0, 2.0], [0.5, 0.5], 1)
        ),
    ]
)
true

Last, compare a reverse-mode gradient through the operator with its NoAdjoint twin, which takes plain automatic differentiation (AD) of the operator's code. Use Mooncake or Enzyme, and a loss that changes with every parameter, as forward-mode backends never take the rule.

julia
using DifferentiationInterface, Mooncake

smooth(a) = Recurrence([0.5, 0.5]; modifiers = (Smooth(a[1]),))
abs2_loss(op) = a -> sum(abs2, op(a)(fill(1.2, 30); history = [1.0, 2.0]))
backend = AutoMooncake(; config = nothing)
gradient(abs2_loss(smooth), backend, [0.3]) ≈
    gradient(abs2_loss(CR.NoAdjoint ∘ smooth), backend, [0.3])
true

Where next ​