Skip to content

Parameters and gradients ​

A parameter is a field of a modifier or coupling that a step reads through param: a number, a PerStratum, a TimeVarying or a derived form. The gradient with respect to a parameter is accumulated in the mirror of the type that holds it.

julia
using ComposableRecurrences
const CR = ComposableRecurrences
ComposableRecurrences

The gradient mirror ​

The mirror of a type is the object that holds the cotangents of its fields, with one entry per field. A pullback! receives it as grads.piece. The entry depends on the type of the field:

FieldMirror entry
float scalarRef, add with x̄[] += g
float arrayan array of the same shape
PerStratum, TimeVarying or another structa NamedTuple of its own fields' mirrors, such as (; x = zeros(S))
integer, range, nothing, functionnothing
struct with no fields(;)

The whole mirror, or any entry, is nothing when the backend holds it constant.

A pure step never sees the mirror. The package reads each parameter into θ, and adds the cotangents in θ̄ into the mirror with add_param!: those a step_pullback returns, or those of the forward-mode pass without one. A whole-step modifier's pullback! gets the mirror as grads.piece and adds into it itself.

A per-stratum parameter ​

The example adds to the value of stratum ,

where is the value of stratum at time . It keeps no state, so it declares isstateless and receives nothing as s. Its step_pullback returns the cotangent of b under the name b, as in θ.

julia
struct Shift{B}
    b::B
end
CR.isstateless(::Shift) = true
CR.step(::Shift, θ, v, s) = (v + θ.b, s)
CR.step_pullback(::Shift, θ, v, s, v̄′, s̄′) = (v̄′, s̄′, (; b = v̄′))

CR.step_pullback(Shift(0.1), (; b = 0.1), 2.0, nothing, 1.5, nothing)
(1.5, nothing, (b = 1.5,))

b may be one value or any other parameter form, and step reads it the same way. For a PerStratum b the mirror entry is (; x), and the package adds the cotangent at stratum k into x[k].

julia
using DifferentiationInterface, ForwardDiff, Mooncake

loss(b) = sum(
    Recurrence([0.5, 0.5]; modifiers = (Shift(PerStratum(b)),))(
        fill(1.0, 2, 4); history = ones(2, 2)
    )
)
gradient(loss, AutoMooncake(; config = nothing), [0.1, 0.2]) ≈
    gradient(loss, AutoForwardDiff(), [0.1, 0.2])
true

A pure step reads each parameter at its own stratum, or group, and time, and init reads it at the call's first time, its start. A call checks the PerStratum parameters of a pointwise or blockwise modifier against the number of strata, or of groups.

A parameter of your own ​

A parameter of your own is a subtype of AbstractParameter with a method of param and, for its gradient, of add_param!. It then goes wherever a modifier takes a parameter, and arithmetic with it builds a Derived. The example interpolates a value linearly between values at knot times,

where is the value at knot time and   .

julia
struct Knots{V} <: CR.AbstractParameter
    times::Vector{Int}
    values::V
end
function knot_weight(x::Knots, t)
    i = clamp(searchsortedlast(x.times, t), 1, length(x.times) - 1)
    return i, clamp((t - x.times[i]) / (x.times[i + 1] - x.times[i]), 0, 1)
end
function CR.param(x::Knots, k, t)
    i, w = knot_weight(x, t)
    return (1 - w) * x.values[i] + w * x.values[i + 1]
end
function CR.add_param!(x̄, x::Knots, v, k, t)
    i, w = knot_weight(x, t)
    CR.add_cotangent!(CR.cotangent(x̄, :values), (1 - w) * v, i)
    CR.add_cotangent!(CR.cotangent(x̄, :values), w * v, i + 1)
    return nothing
end

scaled(a) = CR.Transform(*, 0.9 * Knots([1, 4, 8], a))
simulate(a) = Recurrence([0.5, 0.3]; modifiers = (scaled(a),))(
    fill(1.2, 8); history = ones(2)
)
a = [0.9, 1.3, 0.7]
gradient(a -> sum(simulate(a)), AutoMooncake(; config = nothing), a)
3-element Vector{Float64}:
 7.83303824135217
 7.266095327384515
 2.335763860848061

In a whole-step pullback ​

A whole-step modifier, written with the roles, reads a parameter with param and adds its cotangent with add_param!, which accept every parameter form, including Derived, Gather and Recent. Read a mirror entry with cotangent, which returns nothing for a field the backend holds constant, and add to a field that is not a parameter with add_cotangent!, which skips nothing. Call add_param! for every parameter, even with a nothing mirror, as a Recent parameter still sends its cotangent to the outputs it read.

The example adds to each stratum a share of the total over strata,

where is the number of strata. Its pullback adds to the cotangent of , and to the cotangent of every value.

julia
struct AddShare{B}
    b::B
end
CR.param_rows(::AddShare, S) = S
function CR.forward!(m::AddShare, ::CR.Step, v, s, t)
    total = sum(v)
    for k in eachindex(v)
        v[k] += CR.param(m.b, k, t) * total
    end
    return nothing
end
function CR.pullback!(grads, m::AddShare, ::CR.Step, v, s, t)
    v̄, b̄ = grads.v, CR.cotangent(grads.piece, :b)
    total = sum(v)
    c = sum(k -> CR.param(m.b, k, t) * v̄[k], eachindex(v̄))
    for k in eachindex(v̄)
        CR.add_param!(b̄, m.b, v̄[k] * total, k, t)
        v̄[k] += c
    end
    return nothing
end

m = AddShare(PerStratum([0.1, 0.2]))
grads = (; piece = (; b = (; x = zeros(2))), v = [1.5, 0.5], s = zeros(2))
CR.pullback!(grads, m, CR.Step(), [2.0, 1.0], zeros(2), 1)
grads.piece.b.x
2-element Vector{Float64}:
 4.5
 1.5

Closed-form derivatives of maps ​

The map of a Derived parameter or a Transform is differentiated one entry at a time. Each entry takes a local forward-mode derivative, which evaluates the map on dual numbers. The functions identity, +, -, *, /, exp, log, min and max have closed-form derivatives already, and LogExpFunctions adds logistic, log1pexp and logit. A modifier whose map has a closed-form derivative of its own is written as a pure step with a step_pullback, in place of a Transform.

The example scales each value by a logistic share,

where is the value of a stratum, the value passed on and the parameter.

julia
struct LogisticScale{A}
    a::A
end
CR.isstateless(::LogisticScale) = true
CR.step(::LogisticScale, θ, v, s) = (v * inv(1 + exp(-θ.a)), s)
function CR.step_pullback(::LogisticScale, θ, v, s, v̄′, s̄′)
    h = inv(1 + exp(-θ.a))
    return h * v̄′, s̄′, (; a = v * h * (1 - h) * v̄′)
end

scaled_loss(a) = sum(
    Recurrence([0.5, 0.5]; modifiers = (LogisticScale(PerStratum(a)),))(
        fill(1.0, 2, 4); history = ones(2, 2)
    )
)
gradient(scaled_loss, AutoMooncake(; config = nothing), [0.0, 1.0]) ≈
    gradient(scaled_loss, AutoForwardDiff(), [0.0, 1.0])
true

A map with float fields of its own takes plain AD, as the rule gives no gradient for those fields; pass them in θ.