Writing new types
A modifier is a type with a step method: a pure function that maps the value and state of one stratum at one time to the new value and state. One modifier is defined below, run in a model, differentiated and checked. Steps on groups of strata, traces, depletion forms, couplings and parameters each have a page of their own.
The examples use CR for the package.
using ComposableRecurrences
const CR = ComposableRecurrencesA pointwise modifier
A pointwise modifier acts on each stratum separately. The example is exponential smoothing,
where
struct Smooth{A}
a::A
end
CR.init(::Smooth, θ, history) = last(history)
function CR.step(::Smooth, θ, v, s)
s′ = θ.a * s + (1 - θ.a) * v
return s′, s′
end
The method step takes the parameters θ, the value v and the state s, and returns the new value and state. The named tuple θ has one entry per field of the type, each read at the stratum and time, so θ.a is the smoothing weight there. A step reads its parameters from θ and not from the modifier, as the gradient is taken with respect to θ.
The method init returns the state before the first step from the stratum's history, here its last value. A modifier that keeps state has an init: there is no default, and a call without one is an ArgumentError. init(::Smooth, θ, history) = 0 starts the state at zero. A modifier that keeps no state declares isstateless in place of an init, and its step receives nothing as s.
A field may hold any parameter with the same step: a number, a PerStratum for one value per stratum, a TimeVarying for one per time, or TimeVarying(PerStratum(A)) for both. A field that is not a parameter, such as an integer or an index vector, reaches step unchanged.
The same method runs in every loop of the package: serially, under Threaded() and inside a kernel on a device array. It therefore takes its arguments untyped, allocates nothing and writes nothing. Rules for every type lists the full requirements.
In a model
A modifier is passed in the modifiers tuple of an operator, and the modifiers act in the order of the tuple. With Smooth before a Depletion, each step is
where
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
58The model is differentiable on every backend without further methods. In reverse mode the operator's rule differentiates step with one forward-mode pass over (v, s, θ) at each stratum and time. The example compares a reverse-mode gradient with a forward-mode one.
using DifferentiationInterface, ForwardDiff, Mooncake
loss(a) = sum(model(a[1])(fill(1.8, 80); history = seed))
gradient(loss, AutoMooncake(; config = nothing), [0.5]) ≈
gradient(loss, AutoForwardDiff(), [0.5])trueIts pullback
A step_pullback method returns the cotangents of the step's inputs in closed form, in place of the forward-mode pass. The method is optional. It is needed in two cases: where a benchmark shows it to be faster, and where the forward-mode pass multiplies zero by an infinite slope and returns NaN (A form at an empty pool). For the smoothing step the new value and the new state are both
where a bar marks a cotangent, the gradient of a scalar loss with respect to that quantity. The sum of the cotangents of the two outputs is
The method takes the arguments of step, then the cotangents of the new value and state. It returns the cotangents of the value and state before the step, and a named tuple of the cotangents of the parameters, named as in θ. A typed step_pullback is not called: the forward-mode pass is used in its place, so the gradient is unchanged and only the speed differs. gradient_routes and the :step check below report which of the two a modifier takes.
function CR.step_pullback(::Smooth, θ, v, s, v̄′, s̄′)
ḡ = v̄′ + s̄′
return (1 - θ.a) * ḡ, θ.a * ḡ, (; a = (s - v) * ḡ)
end
CR.step_pullback(Smooth(0.5), (; a = 0.5), 2.0, 1.0, 1.0, 0.5)(0.75, 0.75, (a = -1.5,))A step on a group of strata
A blockwise modifier acts on groups of a fixed number of strata. It declares the group shape with blocks as (nv, ns), the number of values and of state entries per group, and its step takes and returns them as tuples. The example moves a share
where
struct Shift{A}
a::A
end
CR.blocks(::Shift) = (2, 1)
CR.init(::Shift, θ, history) = 0
function CR.step(::Shift, θ, v, s)
x = θ.a * v[1]
return (v[1] - x, v[2] + x), (x,)
end
r = Recurrence([0.6, 0.4]; modifiers = (Shift(PerStratum([0.1, 0.3])),))
r(fill(1.1, 4, 3); history = ones(4, 2))4×3 Matrix{Float64}:
0.99 0.98406 0.976572
0.77 0.66374 0.543808
1.21 1.34794 1.53055
1.43 1.66826 1.96331With blocks (2, 1) the four strata form two groups: strata 1 and 2 hold the first value of each group, strata 3 and 4 the second, and each group keeps one state entry. A parameter is read at the group, so the PerStratum holds one entry per group. Steps across strata gives the layout in general.
Checking a new type
PieceInterface is the conformance test for a new type. It takes one Arguments per role, and the optional checks named in braces; Checking your type lists every check. The :step check requires that the result type of step is inferred and that step_pullback agrees with the forward-mode pass. It also requires that no method of step, init, step_pullback or trace types its arguments after the modifier. The check fails a step that reads a parameter from the modifier's fields and not from θ, as the gradient with respect to that parameter would be zero.
using Interfaces: Interfaces, Arguments
m = Smooth(PerStratum([0.3, 0.6]))
Interfaces.test(
CR.PieceInterface{(:nstate, :pullback, :step)}, 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)
),
]
)trueThe rule is checked against plain automatic differentiation (AD) of the operator's code, which NoAdjoint selects. The comparison uses a reverse-mode backend, Mooncake or Enzyme, as forward-mode backends do not take the rule, and a loss that depends on every parameter.
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])trueOn a device array
A call whose arrays are device arrays, such as GPU arrays, runs its loop over strata as a kernel on the device (Running on GPU arrays). The package calls step, init, trace and the local derivative or step_pullback inside that kernel, so the forward run, the rule's reverse pass and the trace need no method written for the device. The author of a modifier writes one method for it: Adapt.adapt_structure, which moves the arrays its parameters hold.
A device compiler accepts a step under these conditions.
Each field is a bits type, such as a number or a
Val, or a parameter that holds device arrays.The method allocates nothing and captures no host array.
The method raises no error whose message interpolates a value.
The number type of the result follows the arguments, so that
Float32inputs giveFloat32results.
The example runs Smooth with one weight per stratum in single precision on a JLArray, and compares the output with the host run.
using Adapt, JLArrays, KernelAbstractions
Adapt.adapt_structure(to, m::Smooth) = Smooth(adapt(to, m.a))
weights = PerStratum(Float32[0.3, 0.6])
host = Recurrence(Float32[0.5, 0.5]; modifiers = (Smooth(weights),))
x = Float32[1.1 1.2 1.3 1.2; 0.9 1.0 1.1 1.0]
h = ones(Float32, 2, 2)
device = adapt(JLArray, host)
y = device(JLArray(x); history = JLArray(h))
typeof(y), Array(y) ≈ host(x; history = h)(JLArrays.JLArray{Float32, 2}, true)gradient_routes with devices checks a modifier on a device. It runs the rule's forward and reverse pass on the host and on each device, and throws unless the cotangents agree. The rows with rule passes time those two passes.
devices = (; JLArray = a -> adapt(JLArray, a))
CR.gradient_routes(backend, host, x; history = h, devices)Test Summary: | Pass Total Time
Tuple{typeof(ComposableRecurrences._ad), Recurrence{Vector{Float32}, LinearAlgebra.UniformScaling{Int64}, Tuple{Main.Smooth{PerStratum{Vector{Float32}}}}, nothing}, Matrix{Float32}, Nothing, Matrix{Float32}, Nothing, Int64, Nothing} | 24 24 1.6s
route array via time (µs) allocs bytes
step_pullback Array AutoMooncake 1.4 49 2080
local derivative Array AutoMooncake 1.4 52 2144
plain AD Array AutoMooncake 3.7 47 2032
step_pullback Array rule passes 0.7 35 1664
local derivative Array rule passes 0.7 35 1664
step_pullback JLArray rule passes 97.1 1850 75808
local derivative JLArray rule passes 92.5 1850 75808The device support has these limits.
JLArrays runs each kernel as Julia code on the CPU, so it checks the kernel's result and not the four conditions above. The OpenCL workflow compiles the pure steps of
test/device/rules.jlas device code, on the CPU device of pocl. No user modifier has been run on a physical GPU.A user's whole-step modifier does not take the rule on a device: the operator takes plain AD there.
PieceInterfacechecks a modifier on host arrays.
Under Reactant
Reactant traces a call into one compiled program: each number in step is then a traced value, and a comparison of traced values is not a Bool. A step therefore has no branch on a value (Traced values). A branch written with if, &&, || or the ternary operator on a traced comparison raises a TypeError when the call is compiled. The same step written with ifelse, min, max or clamp compiles, with no method written for Reactant.
# Refused under Reactant: a branch on a value.
CR.step(::Cap, θ, v, s) = (v > θ.c ? θ.c : v, nothing)
# Compiles: both arms are computed and one is selected.
CR.step(::Cap, θ, v, s) = (ifelse(v > θ.c, θ.c, v), nothing)
CR.step(::Cap, θ, v, s) = (min(v, θ.c), nothing)A branch on a type, a size or an integer field is known when the model is built and is unaffected. Both arms of an ifelse are computed, so neither may throw, and for a gradient neither may be NaN or infinite where it is not selected. Reactant differentiates the traced program, so a step_pullback is not called. Reading one entry of a traced array in the code around a model needs Reactant.@allowscalar.
Smooth has no branch and compiles as written. The test "Reactant traces a user's pure step without a branch" in test/reactant/extension_check.jl compiles these steps and compares the forward run and the reverse-mode gradient with the host. At an exact tie, where both arguments of min are equal, the reverse-mode gradient under Reactant is that of the first argument and the gradient of the host run is that of the second. A user's trace method and a user's blockwise step have not been run under Reactant. The Reactant support matrix in test/reactant lists what else runs (Testing and benchmarking).
Steps that read every stratum
A whole-step modifier is one whose step reads every stratum at once, such as a mean over strata or a library call on the whole vector. It has no pure form and is written with the roles: a forward! method that updates the values v and the state s of every stratum in place. It runs on host arrays only, and takes the rule when it has a pullback! or is declared linear. Without either, the whole operator takes plain AD.
Where next
Steps across strata: blockwise steps and whole-step modifiers.
Traces: the series a modifier records at each step.
Depletion forms: the draw of a
Depletionas a pure step.Couplings: the mixing of strata.
Parameters and gradients: parameter forms, the gradient mirror and local rules for maps.
Rules for every type: untyped arguments, number types and threads.
Performance and trimming: timings, trimmed executables and specialised methods.
Extension API: every function, role and check.