Couplings
This page is for a reader whose mixing of strata has structure that a matrix wastes or cannot hold. It assumes Writing new types. 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.
using ComposableRecurrences
const CR = ComposableRecurrencesComposableRecurrencesA 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
where
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.5312The first stratum receives the share of pressure that the second gives up, so its values are the larger.
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 forward! and pullback!. The same declaration on a whole-step modifier with no state of its own runs the matrix product as its step.
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.788963The call runs as if the matrix K were passed as the coupling.
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!.