Skip to content

Internal Documentation ​

Documentation for ComposableRecurrences's internal interface.

Contents ​

Index ​

Internal API ​

ComposableRecurrences.Auto Type
julia
struct Auto <: ComposableRecurrences.ConvolutionMethod

The default method of a Convolution. A call with a fixed kernel (a vector or PerStratum) of lags, outputs and 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

julia
using ComposableRecurrences
k, x = [0.5, 0.5], [1.0, 2.0, 4.0]
Convolution(k)(x) == Convolution(k; method = ComposableRecurrences.Direct())(x)

# output

true

Fields

source
ComposableRecurrences.ConvolutionMethod Type
julia
abstract type ConvolutionMethod

The method a Convolution uses to compute its lag sum

The methods are ComposableRecurrences.Auto (the default), ComposableRecurrences.Direct and ComposableRecurrences.FFTMethod.

Examples

julia
using ComposableRecurrences
ComposableRecurrences.Direct() isa ComposableRecurrences.ConvolutionMethod

# output

true

Fields

source
ComposableRecurrences.Executor Type
julia
abstract type Executor

A 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

julia
using ComposableRecurrences
ComposableRecurrences.Serial() isa ComposableRecurrences.Executor

# output

true

Fields

source
ComposableRecurrences.Run Type
julia
struct Run

The role of an operator's whole call, forward(op, Run(), args...; kwargs...), which returns (y, cache); calling the operator lowers to it.

For inputs (the call's arguments and the operator's fields) it computes the output over the call's times  ,

with the maths of the operator, a 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

julia
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.317

Fields

source
ComposableRecurrences.Secondary Type
julia
struct Secondary

The default indexing of a TimeVarying coefficient: column t is read at time t.

For a kernel, the weight on lag of the output at time is

where is the kernel's weight on lag in column and is the absolute time of the output, counted from 1. A time-varying coupling or modifier parameter is likewise read as . This is the only indexing outside a kernel.

Examples

julia
using ComposableRecurrences
typeof(TimeVarying([0.8 0.7; 0.2 0.3], ComposableRecurrences.Secondary()))

# output

TimeVarying{ComposableRecurrences.Secondary, Matrix{Float64}}

Fields

source
ComposableRecurrences.State Type
julia
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 it carries

where is the output at time (one entry per stratum), the number of kernel weights and the state of the -th of modifiers after the last step. history holds the last outputs, states each modifier's state and t the time of the next step,  . A call with state continues exactly as one call over both ranges would.

Examples

julia
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.

source
ComposableRecurrences.TRACED_MIN_STRATA Constant
julia
TRACED_MIN_STRATA

The 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

julia
using ComposableRecurrences
using Base.ScopedValues: with
const CR = ComposableRecurrences
with(CR.TRACED_MIN_STRATA => 8) do
    CR.TRACED_MIN_STRATA[]
end

# output

8
source
ComposableRecurrences.contributions Function
julia
contributions(c::Convolution, x; kwargs...) -> Any

Return the lag contributions of a Convolution: the terms of its sum over lags, before the sum,

in the notation of Convolution, so that   . A ComposableRecurrences.Primary kernel reads  , so is the share of the input at time   that arrives at : a reporting triangle by arrival time. Terms whose input is before the history, or past a ragged column's end, are zero. A kernel computed from coefficients (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 its NoAdjoint.

  • x: the inputs, as in a call of c.

Keyword Arguments

  • gain, history, start, stop: as in a call of c.

Examples

julia
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])
source
ComposableRecurrences.depth Function
julia
depth(x) -> Int64

Return the number of past outputs x reads from a recurrence's buffer, before the current step.

A Recurrence keeps

past outputs per stratum, where is the kernel length, is depth and are the modifiers. The kernel reads the last of them; the deeper rows are kept for objects that read further back than the kernel. A ComposableRecurrences.State holds the last outputs, so a resumed call reads the same past. The default recurses by value through the fields of immutable structs, tuples and named tuples and takes the largest. Numbers, arrays, functions, mutable objects and operators (which keep their own buffers) read nothing,  , so an object held inside an array or a mutable struct is not counted. Add a method for a type that reads the buffer.

Arguments

  • x: any object, such as a modifier, coupling or kernel.

Examples

julia
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)
source
ComposableRecurrences.each! Function
julia
each!(
    body,
    _::ComposableRecurrences.Serial,
    n,
    work,
    args...
)
julia
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 as body(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; Serial ignores it.

  • args: the arguments passed to every call of body.

Examples

julia
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.0
source
ComposableRecurrences.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 it computes

with the operator's own maths, and 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

julia
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.5
source
ComposableRecurrences.ispointwise Function
julia
ispointwise(m) -> Bool

Return whether modifier m acts on each stratum separately: whether its ComposableRecurrences.blocks is (1, 1).

A pointwise modifier's step factorises over the strata: at absolute time , stratum 's new value and state depend only on its own,

It follows from blocks, which is the trait to define.

Arguments

  • m: the modifier.

Examples

julia
using ComposableRecurrences
CR = ComposableRecurrences
CR.ispointwise(CR.Transform(clamp, 0.0, 1.0)), CR.ispointwise(nothing)

# output

(true, false)
source
ComposableRecurrences.param_eltype Function
julia
param_eltype(x) -> Any

Return 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 is 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

julia
using ComposableRecurrences
struct Scale
    a
    extra::NamedTuple
end
ComposableRecurrences.param_eltype(Scale(1.0f0, (; b = 2)))

# output

Float32
source
ComposableRecurrences.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  : for random directions and cotangents ,

with from finite differences and from the pullback.

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: an AutoMooncake or AutoEnzyme from ADTypes.

  • piece: the operator.

  • role: Run().

  • args: the positional arguments.

Examples

julia
using ComposableRecurrences
methods(ComposableRecurrences.test_adjoint)
source
Base.transpose Method
julia
transpose(
    c::Convolution
) -> ComposableRecurrences._TransposedConvolution

Return 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  , the transpose computes  . A ComposableRecurrences.Secondary kernel (the default for a TimeVarying kernel) weights by  , the column of the time it reads. 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, length n or S × n, read at absolute time t.

  • tail: the series after t = n, oldest first (any length m, or S × m); later values are zero. A series extended by its last value is tail = fill(x[end], L - 1).

  • start: the first time; 1 by default.

  • stop: the last time; n by default. It may pass n + 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

julia
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.0
source
ComposableRecurrences.uses_adjoint Function
julia
uses_adjoint(piece, role) -> Bool

Return whether piece carries its own rule in role: a ComposableRecurrences.pullback! method for that role.

For outputs   of the role, with inputs and parameters , the adjoint computes the cotangents

directly, where is the gradient of a scalar loss with respect to .

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

julia
using ComposableRecurrences
CR = ComposableRecurrences
CR.uses_adjoint(Recurrence([0.5, 0.5]), CR.Run())

# output

true
source