Internal Documentation
Documentation for ComposableRecurrences's internal interface.
Contents
Index
ComposableRecurrences.TRACED_MIN_STRATAComposableRecurrences.AutoComposableRecurrences.ConvolutionMethodComposableRecurrences.ExecutorComposableRecurrences.RunComposableRecurrences.SecondaryComposableRecurrences.StateBase.transposeComposableRecurrences.contributionsComposableRecurrences.depthComposableRecurrences.each!ComposableRecurrences.forwardComposableRecurrences.ispointwiseComposableRecurrences.param_eltypeComposableRecurrences.test_adjointComposableRecurrences.uses_adjoint
Internal API
ComposableRecurrences.Auto Type
struct Auto <: ComposableRecurrences.ConvolutionMethodThe default method of a Convolution. A call with a fixed kernel (a vector or PerStratum) of Float64 arrays on the CPU, once the weak dependency of the FFT extension is loaded, takes
Any other call takes ComposableRecurrences.Direct. From these sizes the transform is faster than the direct method on typical series, forward and in reverse mode: by 1.02 to 1.14 times at 300 lags and 1000 outputs, and 1.5 to 2.1 times at 500 lags and 2000 outputs. Below them the direct method is faster, up to 2 times. So most models take the direct method, and Float32 models never take the transform. The kernel, eltype, arrays and loaded packages are resolved by dispatch, and the sizes by two integer comparisons per call.
Its accuracy, and its cost on a series spanning many orders of magnitude, are those of ComposableRecurrences.FFTMethod.
Examples
using ComposableRecurrences
k, x = [0.5, 0.5], [1.0, 2.0, 4.0]
Convolution(k)(x) == Convolution(k; method = ComposableRecurrences.Direct())(x)
# output
trueFields
sourceComposableRecurrences.ConvolutionMethod Type
abstract type ConvolutionMethodThe method a Convolution uses to compute its lag sum
The methods are ComposableRecurrences.Auto (the default), ComposableRecurrences.Direct and ComposableRecurrences.FFTMethod.
Examples
using ComposableRecurrences
ComposableRecurrences.Direct() isa ComposableRecurrences.ConvolutionMethod
# output
trueFields
sourceComposableRecurrences.Executor Type
abstract type ExecutorA strategy for how ComposableRecurrences.each! runs a loop over independent indices. Every executor e calls the same bodies, so the result does not depend on it:
Examples
using ComposableRecurrences
ComposableRecurrences.Serial() isa ComposableRecurrences.Executor
# output
trueFields
sourceComposableRecurrences.Run Type
struct RunThe role of an operator's whole call, forward(op, Run(), args...; kwargs...), which returns (y, cache); calling the operator lowers to it.
For inputs
with Recurrence or a Convolution; cache holds what the reverse pass needs, such as the ComposableRecurrences.State. It is the role an operator is asked about, as in uses_adjoint(op, Run()), PieceInterface with role = Run() and test_adjoint(backend, op, Run(), args...).
Examples
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5])
y, cache = CR.forward(r, CR.Run(), fill(1.1, 4); history = ones(2))
round.(y; digits = 3)
# output
4-element Vector{Float64}:
1.1
1.155
1.24
1.317Fields
sourceComposableRecurrences.Secondary Type
struct SecondaryThe default indexing of a TimeVarying coefficient: column t is read at time t.
For a kernel, the weight on lag
where
Examples
using ComposableRecurrences
typeof(TimeVarying([0.8 0.7; 0.2 0.3], ComposableRecurrences.Secondary()))
# output
TimeVarying{ComposableRecurrences.Secondary, Matrix{Float64}}Fields
sourceComposableRecurrences.State Type
struct State{H, M, T}The state a Recurrence call with record = (:state,) returns with its output, passed back as state to resume.
After a call that ended at absolute time
where history holds the last states each modifier's state and t the time of the next step, state continues exactly as one call over both ranges would.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
r = Recurrence([0.5, 0.5])
(; state) = r(fill(1.1, 6); history = ones(2), stop = 3, record = (:state,))
state.t, round.(r(fill(1.1, 6); state); digits = 3)
# output
(4, [1.317, 1.407, 1.498])Fields
history::Any: The last outputs, as many as the buffer depth, in the history's layout.states::Any: Each modifier's state.t::Any: The time of the next step.
ComposableRecurrences.TRACED_MIN_STRATA Constant
TRACED_MIN_STRATAThe fewest strata at which a loop of a traced call runs as one kernel.
A traced call runs each step's loop over S strata as one kernel when S is at least this, so its program does not grow with the strata. A shorter loop is written out, one block a stratum. Its program grows with S, but on the CPU its forward pass runs faster than a kernel launch each step. The default, 32, is measured on the CPU. From there a kernel runs gradients faster and compiles them faster, while a written-out loop still runs the forward pass faster. A model that mostly runs forward can raise it. On a GPU, where a launch costs less, a lower value may run faster. Set it with with, as for EXECUTOR.
Examples
using ComposableRecurrences
using Base.ScopedValues: with
const CR = ComposableRecurrences
with(CR.TRACED_MIN_STRATA => 8) do
CR.TRACED_MIN_STRATA[]
end
# output
8ComposableRecurrences.contributions Function
contributions(c::Convolution, x; kwargs...) -> AnyReturn the lag contributions of a Convolution: the terms of its sum over lags, before the sum,
in the notation of Convolution, so that ComposableRecurrences.Primary kernel reads TimeVarying(d, Primary()) with d a ComposableRecurrences.Derived or a ComposableRecurrences.Survival) is an ArgumentError: pass the dense kernel of its weights, TimeVarying(K, Primary()).
Takes the arguments of a call of c except add, which no lag carries. The output is L × T for a single series and S × L × T for S strata, with T = stop - start + 1 and lag 0 first, so summing over the lag axis gives c(x; gain, history, start, stop). A ComposableRecurrences.NoAdjoint convolution is differentiated by plain AD.
Arguments
c: the convolution, or itsNoAdjoint.x: the inputs, as in a call ofc.
Keyword Arguments
gain,history,start,stop: as in a call ofc.
Examples
using ComposableRecurrences
c = Convolution([0.5, 0.3, 0.2])
Y = ComposableRecurrences.contributions(c, [1.0, 2.0, 4.0, 8.0])
vec(sum(Y; dims = 1)) ≈ c([1.0, 2.0, 4.0, 8.0]), Y
# output
(true, [0.5 1.0 2.0 4.0; 0.0 0.3 0.6 1.2; 0.0 0.0 0.2 0.4])ComposableRecurrences.depth Function
depth(x) -> Int64Return the number of past outputs x reads from a recurrence's buffer, before the current step.
A Recurrence keeps
past outputs per stratum, where depth and ComposableRecurrences.State holds the last
Arguments
x: any object, such as a modifier, coupling or kernel.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
struct Window
w::Int
end
CR.depth(x::Window) = x.w
x = (Window(5), (; a = Window(9), b = 1.0))
CR.depth(x), CR.depth(CR.Transform(clamp, 0.0, 1.0))
# output
(9, 0)ComposableRecurrences.each! Function
each!(
body,
_::ComposableRecurrences.Serial,
n,
work,
args...
)each!(body, ex::Executor, n, work, args...)Call body(k, args...) for every k in 1:n with executor ex:
where each index k is one stratum or one output time.
body must write only the slots it owns for index k, so the indices can run in any order or at the same time. A new executor type adds a method of each!. Returns nothing.
Arguments
body: the per-index function, called asbody(k, args...).ex: the executor that runs the loop.n: the number of indices.work: an estimate of the loop's total cost in inner operations, which an executor may use to run small loops in order;Serialignores it.args: the arguments passed to every call ofbody.
Examples
using ComposableRecurrences
const CR = ComposableRecurrences
# Row sums of a matrix, one row per index.
rowsum!(k, y, A) = (y[k] = sum(view(A, k, :)); nothing)
A = [1.0 2.0; 3.0 4.0]
y = zeros(2)
CR.each!(rowsum!, CR.Serial(), 2, length(A), y, A)
y
# output
2-element Vector{Float64}:
3.0
7.0ComposableRecurrences.forward Function
Run operator op over a whole call, returning (y, cache).
This is the ComposableRecurrences.Run role: calling the operator lowers to forward(op, Run(), args...; kwargs...). For inputs
with cache holds what the reverse pass needs. Couplings, modifiers and depletion forms write their outputs in place through ComposableRecurrences.forward! instead.
Arguments
op: the operator.role:Run().args: the call's arguments.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
y, cache = CR.forward(Convolution([0.5, 0.5]), CR.Run(), [1.0, 2.0, 3.0])
y
# output
3-element Vector{Float64}:
0.5
1.5
2.5ComposableRecurrences.ispointwise Function
ispointwise(m) -> BoolReturn whether modifier m acts on each stratum separately: whether its ComposableRecurrences.blocks is (1, 1).
A pointwise modifier's step factorises over the
It follows from blocks, which is the trait to define.
Arguments
m: the modifier.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
CR.ispointwise(CR.Transform(clamp, 0.0, 1.0)), CR.ispointwise(nothing)
# output
(true, false)ComposableRecurrences.param_eltype Function
param_eltype(x) -> AnyReturn the element type the parameters of x contribute to an operator's buffer.
The buffer eltype is the float promotion of this over the kernel, coupling, modifiers, inputs and history,
where param_eltype, so a dual number or a Float32 anywhere sets it. The default recurses by value through fields, tuples and named tuples, so abstractly typed fields count; a Real gives its type and an array of reals its eltype. Add a method for a type whose parameters this does not reach.
Arguments
x: any object, such as a modifier, coupling or kernel.
Examples
using ComposableRecurrences
struct Scale
a
extra::NamedTuple
end
ComposableRecurrences.param_eltype(Scale(1.0f0, (; b = 2)))
# output
Float32ComposableRecurrences.test_adjoint Function
Test the rule of piece in role on the primal arguments args with the AD backend's own rule tester.
The tester checks the pullback against finite differences of the forward map
with
For an operator, role is ComposableRecurrences.Run and args are its positional arguments. Methods come from package extensions: AutoMooncake with Mooncake loaded (Mooncake.TestUtils.test_rule) and AutoEnzyme with EnzymeTestUtils loaded (test_reverse, with the operator active and constant).
Arguments
backend: anAutoMooncakeorAutoEnzymefrom ADTypes.piece: the operator.role:Run().args: the positional arguments.
Examples
using ComposableRecurrences
methods(ComposableRecurrences.test_adjoint)Base.transpose Method
transpose(
c::Convolution
) -> ComposableRecurrences._TransposedConvolutionReturn the transpose of the convolution c, also written c': a sum that reads the series forward from each time rather than back from it,
for a ComposableRecurrences.Primary or fixed kernel, in the notation of Convolution: if c without a gain or add input computes ComposableRecurrences.Secondary kernel (the default for a TimeVarying kernel) weights c' is the same operator, and the transpose of the transpose is c.
Called as transpose(c)(x; tail = nothing, start = 1, stop), it covers the absolute times start:stop:
x: the series, lengthnorS × n, read at absolute timet.tail: the series aftert = n, oldest first (any lengthm, orS × m); later values are zero. A series extended by its last value istail = fill(x[end], L - 1).start: the first time;1by default.stop: the last time;nby default. It may passn + m, where the series is zero, so an output that reads only those times is zero.
The output has the layout of x and length stop - start + 1. A Primary() kernel covers times up to stop, and any other TimeVarying kernel the last time it reads, min(stop + L - 1, n + m).
It takes the direct method whatever the method of c.
Examples
using ComposableRecurrences
c = Convolution([0.5, 0.25, 0.25])
c'([1.0, 2.0, 4.0, 8.0])
# output
4-element Vector{Float64}:
2.0
4.0
4.0
4.0ComposableRecurrences.uses_adjoint Function
uses_adjoint(piece, role) -> BoolReturn whether piece carries its own rule in role: a ComposableRecurrences.pullback! method for that role.
For outputs
directly, where
By default it is true when pullback! has a method for the type of piece and role whose other arguments are untyped, so writing the method is enough. The lookup is read from the types, so the route costs nothing per call. A method with a typed grads or typed arguments is not found, apart from a blockwise group step's with v::Tuple, s::Tuple; declare uses_adjoint(::T, role) = true for any other, which ComposableRecurrences.PieceInterface checks. A method of uses_adjoint also overrides the default, for example when the adjoint covers only some values of a type. If it is true but no pullback! method fits the arguments, the reverse pass throws a MethodError. An operator uses its adjoint in ComposableRecurrences.Run when it has one. A Recurrence does when every float it holds is a Float16, Float32 or Float64 and each component has a pullback! or a local step within its limits.
Arguments
piece: the operator, coupling, modifier or depletion form.role: the role.
Examples
using ComposableRecurrences
CR = ComposableRecurrences
CR.uses_adjoint(Recurrence([0.5, 0.5]), CR.Run())
# output
true