Couplings
A new coupling mixes strata where a matrix is wasteful, building on Writing new types.
using ComposableRecurrences
const CR = ComposableRecurrencesComposableRecurrencesA coupling with a pullback
A coupling's role is Pressure(): it writes the pressure q on each stratum from each stratum's kernel-weighted past p, and its pullback adds grads.q back into grads.p. This one 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.5312A linear coupling
A coupling whose forward! is linear in p and does not read t is a matrix, and can say so with islinear. 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.788963A forward! written as a matrix product then has a gradient close to the built-in coupling's. One written as scalar loops, or a coupling that is not linear or changes in time, needs a pullback! to be fast.