Skip to content

Couplings ​

A coupling maps the kernel-weighted past of every stratum to the pressure on every stratum. A matrix is a coupling; a type with a forward! method for the role Pressure() is one that needs no matrix.

julia
using ComposableRecurrences
const CR = ComposableRecurrences
ComposableRecurrences

A coupling with a pullback ​

The forward! method for Pressure() writes the pressure q on each stratum from the kernel-weighted past p of each stratum. Its pullback! adds the cotangent of p into grads.p from that of q in grads.q, and the cotangents of the coupling's parameters into grads.piece. The example sends a share of the pressure of every stratum to the first,

where is the kernel-weighted past of stratum and the pressure on it. The indicator is 1 for the first stratum and 0 otherwise, and is the number of strata.

julia
struct ToFirst{A}
    share::A
end
function CR.forward!(C::ToFirst, ::CR.Pressure, q, p, t)
    q .= (1 - C.share) .* p
    q[1] += C.share * sum(p)
    return nothing
end
function CR.pullback!(grads, C::ToFirst, ::CR.Pressure, q, p, t)
    q̄, p̄ = grads.q, grads.p
    for i in eachindex(p, p̄)
        p̄[i] += (1 - C.share) * q̄[i] + C.share * q̄[1]
    end
    ā = q̄[1] * sum(p) - sum(i -> q̄[i] * p[i], eachindex(p))
    CR.add_cotangent!(CR.cotangent(grads.piece, :share), ā)
    return nothing
end

r = Recurrence([0.5, 0.5]; coupling = ToFirst(0.2))
r(1.0; history = ones(2, 2), stop = 4)
2×4 Matrix{Float64}:
 1.2  1.28  1.392  1.4688
 0.8  0.72  0.608  0.5312

A linear coupling ​

A coupling whose forward! is linear in p and does not depend on t is a matrix, which islinear declares. Each call then builds that matrix from forward! on the basis vectors,

where is the coupling's forward! and the -th basis vector. The call runs the built-in dense coupling in its place, and the gradient uses that coupling's pullback!. The same declaration on a whole-step modifier with no state of its own runs the matrix product as its step.

julia
using LinearAlgebra: mul!
struct Mixing{M}
    K::M
end
function CR.forward!(C::Mixing, ::CR.Pressure, q, p, t)
    mul!(q, C.K, p)
    return nothing
end
CR.islinear(::Mixing) = true

K = [0.9 0.2; 0.1 0.8]
r = Recurrence([0.5, 0.5]; coupling = Mixing(K))
r(1.0; history = ones(2, 2), stop = 4)
2×4 Matrix{Float64}:
 1.1  1.135  1.18225  1.21104
 0.9  0.865  0.81775  0.788963

The gradient of a declared linear coupling costs about as much as that of the built-in dense coupling. A coupling that is not linear, or that changes in time, takes the rule only with a pullback!.