Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion benchmark/matrix.jl
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ const REACTANT_PROJECT = normpath(joinpath(@__DIR__, "..", "test", "reactant"))
# Targets not run yet, with what they wait for. CPU threaded runs are not
# listed: every target runs under `Threaded()` with `--executor=threaded`.
const PENDING_TARGETS = [
("KA CPU primal", "a `--executor=device` option for `Device`"),
("KA CPU primal", "a `--executor=device` option for `Parallel`"),
("CUDA primal", "GPU array path"),
("CUDA gradient", "GPU array path and rules"),
("Reactant GPU primal", "a GPU runner"),
Expand Down
11 changes: 5 additions & 6 deletions docs/src/developer/extending-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ A modifier that acts on each stratum, or each group of strata, is defined by up

A modifier keeps state unless it is declared [`isstateless`](@ref ComposableRecurrences.isstateless) or its [`blocks`](@ref ComposableRecurrences.blocks) has no state entries.
A call that needs a missing `init` or `trace` is an `ArgumentError`.
[`ismodifier(m)`](@ref ComposableRecurrences.ismodifier) is `true` for a built-in modifier and for any type with a `step`, so code that takes modifiers accepts a new type without listing types.

The parameters `θ` are a named tuple of the modifier's fields, each parameter read at the stratum, or group, and time.
The method `init` gets `θ` read at the call's first time, its `start`, and the stratum's history as a vector.
Expand All @@ -36,7 +37,6 @@ The type does its work in a [`forward!`](@ref ComposableRecurrences.forward!) me
| [`Init()`](@ref ComposableRecurrences.Init) | a whole-step modifier's starting state | [The roles](@ref extending-roles) |
| [`Trace()`](@ref ComposableRecurrences.Trace) | a whole-step modifier's record | [The roles](@ref extending-roles) |
| [`Pressure()`](@ref ComposableRecurrences.Pressure) | a coupling's mixing, `forward!(C, Pressure(), q, p, t)`, and `pullback!(grads, C, Pressure(), nothing, p, t)` | [Couplings](@ref extending-coupling) |
| [`Local()`](@ref ComposableRecurrences.Local) | a map's own derivative rule | [Local rules for maps](@ref extending-local-rules) |

`Pressure()` and `Trace()` are also markers a call's `record` takes, for the pressure of each step and the modifiers' records, beside [`Resume()`](@ref ComposableRecurrences.Resume) for the [`State`](@ref ComposableRecurrences.State) to resume from.

Expand Down Expand Up @@ -78,13 +78,12 @@ It also requires that the step's result type is inferred and that the step reads
[`NoAdjoint(op)`](@ref ComposableRecurrences.NoAdjoint) is the same operator differentiated by plain automatic differentiation and not by its [rule](@ref adjoints-backends).
Its gradient is the reference for the rule's gradient, and the ratio of the two times is the gain from the rule.

The names below are internal and may change without notice.
The names below check a rule and say which route a call takes.

| Name | What it does | Returns |
|:--|:--|:--|
| [`ComposableRecurrences.uses_adjoint(m, role)`](@ref ComposableRecurrences.uses_adjoint) | whether the rule calls `m`'s `pullback!` for `role` | `Bool` |
| [`ComposableRecurrences.Run()`](@ref ComposableRecurrences.Run) | the role of an operator's whole call | a type with no fields |
| [`ComposableRecurrences.test_adjoint(backend, op, ComposableRecurrences.Run(), args...)`](@ref ComposableRecurrences.test_adjoint) | runs the rule tester of an automatic differentiation package on an operator's rule | a test result |
| [`ComposableRecurrences.gradient_routes(backend, r, x; history)`](@ref ComposableRecurrences.gradient_routes) | times the gradient by each route a recurrence can take, after checking that the routes agree | a vector of rows |
| [`ComposableRecurrences.test_adjoint(backend, op, args...)`](@ref ComposableRecurrences.test_adjoint) | runs the rule tester of an automatic differentiation package on an operator's rule at its positional arguments | a test result |

For an operator, pass `Run()` as the role to `uses_adjoint`, `PieceInterface` and `test_adjoint`.
`gradient_routes` needs ADTypes and DifferentiationInterface loaded.
`test_adjoint` needs Mooncake, or Enzyme with EnzymeTestUtils, loaded.
49 changes: 30 additions & 19 deletions docs/src/developer/extending-parameters.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# [Parameters and gradients](@id extending-parameters)

A parameter is a field of a modifier or coupling that a step reads through [`param`](@ref ComposableRecurrences.param): a number, a [`PerStratum`](@ref), a [`TimeVarying`](@ref) or a derived form.
The gradient with respect to a parameter is accumulated in the mirror of the type that holds it, and a map can declare its own derivative.
The gradient with respect to a parameter is accumulated in the mirror of the type that holds it.

```@example extending-parameters
using ComposableRecurrences
Expand Down Expand Up @@ -113,30 +113,41 @@ CR.pullback!(grads, m, CR.Step(), [2.0, 1.0], zeros(2), 1)
grads.piece.b.x
```

## [Local rules for maps](@id extending-local-rules)
## [Closed-form derivatives of maps](@id extending-map-derivatives)

The map of a [`Derived`](@ref ComposableRecurrences.Derived) parameter or a [`Transform`](@ref ComposableRecurrences.Transform) is differentiated one entry at a time.
Without a rule of its own, each entry takes a local forward-mode derivative, which evaluates the map on dual numbers.
A map whose derivative has a closed form declares it with a [`pullback!`](@ref ComposableRecurrences.pullback!) method in the [`Local`](@ref ComposableRecurrences.Local) role.
It receives the map's value at the entry, as the forward pass computed it, before the map's arguments, and returns the partial derivatives, one per argument.
Each entry takes a local forward-mode derivative, which evaluates the map on dual numbers.
The functions `identity`, `+`, `-`, `*`, `/`, `exp`, `log`, `min` and `max` have closed-form derivatives already, and [LogExpFunctions](@ref extension-log-exp-functions) adds `logistic`, `log1pexp` and `logit`.
A modifier whose map has a closed-form derivative of its own is written as a pure [`step`](@ref ComposableRecurrences.step) with a [`step_pullback`](@ref ComposableRecurrences.step_pullback), in place of a `Transform`.

The map is a callable struct or a named function, so that the method is defined for a type the author owns.
A reporting-delay hazard on the logit scale, ``h = \operatorname{logistic}(a + \gamma)``, has ``\partial h / \partial a = \partial h / \partial \gamma = h (1 - h)``:
The example scales each value by a logistic share,

```math
v' = h v, \qquad h = \operatorname{logistic}(a), \qquad
\frac{\partial v'}{\partial v} = h, \qquad
\frac{\partial v'}{\partial a} = v h (1 - h),
```

where ``v`` is the value of a stratum, ``v'`` the value passed on and ``a`` the parameter.

```@example extending-parameters
struct LogisticSum end
(::LogisticSum)(a, γ) = inv(1 + exp(-(a + γ)))
function CR.pullback!(grads, ::LogisticSum, ::CR.Local, y, a, γ)
d = y * (1 - y)
return d, d
struct LogisticScale{A}
a::A
end
CR.isstateless(::LogisticScale) = true
CR.step(::LogisticScale, θ, v, s) = (v * inv(1 + exp(-θ.a)), s)
function CR.step_pullback(::LogisticScale, θ, v, s, v̄′, s̄′)
h = inv(1 + exp(-θ.a))
return h * v̄′, s̄′, (; a = v * h * (1 - h) * v̄′)
end

hazard = CR.Derived(LogisticSum(), [-2.0, -1.5, -1.0], TimeVarying(zeros(6)))
delay = TimeVarying(CR.Increments(1 - CR.Survival(hazard)), CR.Primary())
round.(CR.kernel_weights(delay, 2); digits = 3)
scaled_loss(a) = sum(
Recurrence([0.5, 0.5]; modifiers = (LogisticScale(PerStratum(a)),))(
fill(1.0, 2, 4); history = ones(2, 2)
)
)
gradient(scaled_loss, AutoMooncake(; config = nothing), [0.0, 1.0]) ≈
gradient(scaled_loss, AutoForwardDiff(), [0.0, 1.0])
```

The operators find the method from the types at compile time, so a map without one adds no cost per call.
`identity`, `+`, `-`, `*`, `/`, `exp`, `log`, `min` and `max` have rules already, and [LogExpFunctions](@ref extension-log-exp-functions) adds `logistic`, `log1pexp` and `logit`.
A `Transform` map `f(v, θ)` returns `(∂f/∂v, ∂f/∂θ)`, the second shaped as `θ`.
A map with float fields of its own keeps taking plain AD, as the rule gives no gradient for those fields; pass them in `θ`.
A map with float fields of its own takes plain AD, as the rule gives no gradient for those fields; pass them in `θ`.
7 changes: 4 additions & 3 deletions docs/src/explanation/adjoints-and-backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Each operator call is differentiated in one of two ways.
- The rule is a reverse pass written for the operator, which the [Mooncake](@ref extension-mooncake) and [Enzyme](@ref extension-enzyme) extensions register.
- Under plain AD the backend differentiates the operator's forward loop.

A call takes the rule when [`uses_adjoint(op, Run())`](@ref ComposableRecurrences.uses_adjoint) is `true` and every float it holds is a `Float16`, `Float32` or `Float64`.
A call takes the rule when each of its components takes it, as in the table below, and every float it holds is a `Float16`, `Float32` or `Float64`.
These floats may sit in an `Array`, a view or reshape of one, a sparse matrix or a `Diagonal`.
Dual numbers, tracked values, `BigFloat`, abstractly typed fields and other array types take plain AD.
The choice depends only on these types.
Expand Down Expand Up @@ -42,7 +42,8 @@ A user-written coupling, modifier or depletion form takes the rule in one of two
| modifier or depletion form written as a pure [`step`](@ref ComposableRecurrences.step) | always, by its [local derivative](@ref adjoint-local-step) or its [`step_pullback`](@ref ComposableRecurrences.step_pullback) |
| coupling or modifier written with [`forward!`](@ref ComposableRecurrences.forward!) | with a `pullback!`, or declared [`islinear`](@ref ComposableRecurrences.islinear); otherwise plain AD |

`uses_adjoint` finds a component's `pullback!` from its methods, so writing the method is enough.
The package finds a component's `pullback!` from its methods, so writing the method is enough.
[`gradient_routes`](@ref ComposableRecurrences.gradient_routes) gives the routes a recurrence can take, with the gradient time of each.
A component declared linear runs as the matrix its `forward!` gives, built once per call outside the rule.
A modifier that sets its starting state with `forward!` for [`Init()`](@ref ComposableRecurrences.Init) needs a `pullback!` for it too.
A [`Derived`](@ref ComposableRecurrences.Derived) parameter or kernel whose map holds floats sends the operator to plain AD, as no pullback reaches those floats.
Expand Down Expand Up @@ -74,7 +75,7 @@ Wrap an array in [`PerStratum`](@ref) or [`TimeVarying`](@ref) to make it a para
The dual numbers compare by value only, as plain floats do.
So at a tie, such as `x > 0 ? y / x : zero(x)` at `x = 0`, the derivative is that of the branch the step takes.
A backend's own rule for a function with a kink can pick the other side, as for `abs` at zero and, on Mooncake, `clamp` at a bound.
The same holds for a [`Transform`](@ref ComposableRecurrences.Transform) whose map has no [local rule](@ref extending-local-rules).
The same holds for a [`Transform`](@ref ComposableRecurrences.Transform) whose map has no [closed-form derivative](@ref extending-map-derivatives).

## [Backends](@id adjoint-backends)

Expand Down
2 changes: 1 addition & 1 deletion docs/src/explanation/modifiers.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ total(depleted)
- [`Transform(f, θ)`](@ref ComposableRecurrences.Transform) maps each value through ``f(v, \theta)``, such as `Transform(+, b)` or `Transform(clamp, lo, hi)`.

Each modifier here has its own [hand-written gradient](@ref adjoint-routing).
A `Transform` has one when `f` holds no numbers of its own: from `f`'s [local rule](@ref extending-local-rules) when it has one, or else from a local forward-mode derivative.
A `Transform` has one when `f` holds no numbers of its own: from `f`'s [closed-form derivative](@ref extending-map-derivatives) when it has one, or else from a local forward-mode derivative.
The gradient of `Transform(clamp, lo, hi)` goes to the active bound, or to the value when neither bound is active.
A plain number `γ` in `Transform(*, γ)` is fixed and has no gradient.

Expand Down
4 changes: 2 additions & 2 deletions docs/src/explanation/operators.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ The seed is passed as history when the reports cover the run only, and joined in

## [Output number type](@id explanation-eltype)

The buffer eltype promotes [`ComposableRecurrences.param_eltype`](@ref) of every input and field.
`Float32` inputs give a `Float32` output, and dual numbers pass through any slot.
The output's number type is the promotion of the number types of every input and field.
So Float32 inputs give a Float32 output, and dual numbers pass through any slot.
With integer and `Bool` inputs and fields alone and no modifiers, the output keeps that integer type promoted with `Int`.
A signed or `Bool` running total then has the eltype that `cumsum` gives.
Otherwise it is the float type.
Expand Down
4 changes: 2 additions & 2 deletions docs/src/extensions/enzyme-test-utils.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ It runs `EnzymeTestUtils.test_reverse` on the rule of an operator at its positio

```jldoctest; filter = r"Test Summary:.*\n.*\n"
using ComposableRecurrences, ADTypes, Enzyme, EnzymeTestUtils
using ComposableRecurrences: Run, test_adjoint
using ComposableRecurrences: test_adjoint
c = Convolution([0.5, 0.3, 0.2])
# The input, gain, add, history, start time and trace of a run.
args = (abs.(sin.(1:20)), true, nothing, [1.0, 1.0], 1, nothing)
test_adjoint(AutoEnzyme(), c, Run(), args...; rtol = 1.0e-7, atol = 1.0e-7)
test_adjoint(AutoEnzyme(), c, args...; rtol = 1.0e-7, atol = 1.0e-7)
true

# output
Expand Down
16 changes: 10 additions & 6 deletions docs/src/extensions/log-exp-functions.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
# [Link-function rules with LogExpFunctions](@id extension-log-exp-functions)

Loading LogExpFunctions gives `logistic`, `log1pexp` and `logit` their own [local rules](@ref extending-local-rules).
Loading LogExpFunctions gives `logistic`, `log1pexp` and `logit` [closed-form derivatives](@ref extending-map-derivatives).
A [`Derived`](@ref ComposableRecurrences.Derived) parameter or a [`Transform`](@ref ComposableRecurrences.Transform) whose map is one of them then takes its closed-form derivative rather than dual numbers.
The rule for `logistic` reads the forward value ``y`` and returns ``y (1 - y)``:
The derivative of `logistic` at value ``y`` is ``y (1 - y)``.
Here a delay's hazard is the logistic of a parameter:

```jldoctest
using ComposableRecurrences, LogExpFunctions
using ComposableRecurrences: Local, pullback!
y = logistic(0.5)
pullback!((;), logistic, Local(), y, 0.5)
CR = ComposableRecurrences
h = CR.Derived(logistic, [-1.5, -0.5])
cdf = TimeVarying(1 - CR.Survival(h), CR.Primary())
round.(CR.kernel_weights(cdf, 1); digits = 3)

# output

(0.23500371220159452,)
2×1 Matrix{Float64}:
0.182
0.491
```
4 changes: 2 additions & 2 deletions docs/src/extensions/reactant-kernel-abstractions.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# [Reactant kernels with KernelAbstractions](@id extension-reactant-kernel-abstractions)

Loading KernelAbstractions with Reactant gives a traced array a kernel backend.
A traced loop over at least [`TRACED_MIN_STRATA`](@ref ComposableRecurrences.TRACED_MIN_STRATA) strata then runs as one kernel, so the compiled program does not grow with strata.
Without KernelAbstractions such a loop is written out, one block a stratum.
A traced loop over few strata is written out, one block a stratum; a loop over more strata then runs as one kernel, so the compiled program does not grow with strata.
Without KernelAbstractions every traced loop is written out.
[Compiling with Reactant](@ref extension-reactant) covers the rest of a traced call.
2 changes: 1 addition & 1 deletion docs/src/extensions/reactant.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ grad(R) = Enzyme.gradient(Enzyme.Reverse, loss, R)[1]
dR = (Reactant.@compile raise = true raise_first = true grad(R))(R)
```

A loop over at least [`TRACED_MIN_STRATA`](@ref ComposableRecurrences.TRACED_MIN_STRATA) strata compiles its kernel through CUDA.jl, so load CUDA, on the CPU too.
A loop over many strata runs as one kernel, which compiles through CUDA.jl, so load CUDA, on the CPU too.
An Enzyme gradient through the loop's kernels compiles once Reactant raises them to array operations, so pass `raise = true raise_first = true` to `@compile`, as above.
A user modifier follows the rules for [traced values](@ref extending-traced).

Expand Down
35 changes: 20 additions & 15 deletions docs/src/getting-started/tutorials/transform.jl
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
# ## Packages used

using ComposableRecurrences
using ComposableRecurrences: Transform
using CairoMakie, AlgebraOfGraphics, DataFramesMeta
using ForwardDiff
using LinearAlgebra
Expand Down Expand Up @@ -198,10 +197,10 @@ plot_mean_cases(1:60, traced...; xlabel = "Day", legend = "Traced share")
#
# where ``G`` is the probability generating function of the offspring distribution.
# The recurrence has the kernel `[1.0]` and no gain, so the value that enters the modifiers is ``q_{n-1}``.
# Its one modifier is a [`Transform`](@ref ComposableRecurrences.Transform) that applies ``G`` with parameters ``\theta = (R, \kappa)``.
# Its one modifier applies ``G`` with parameters ``R`` and ``\kappa``.
# Here ``R = 1.5``, and the history is ``q_0 = 0``.
#
# ``G`` is written as a callable struct, so it can carry its partial derivatives in ``s`` and in ``\theta`` as a local rule: a [`pullback!`](@ref ComposableRecurrences.pullback!) method in the [`Local`](@ref ComposableRecurrences.Local) role.
# The modifier is written as a pure [`step`](@ref ComposableRecurrences.step), so it can carry its partial derivatives in ``s``, ``R`` and ``\kappa`` as a [`step_pullback`](@ref ComposableRecurrences.step_pullback).
# With ``u = 1 + R (1 - s) / \kappa``, they are
#
# ```math
Expand All @@ -211,23 +210,29 @@ plot_mean_cases(1:60, traced...; xlabel = "Day", legend = "Traced share")
# ```
#
# The reverse pass of a gradient evaluates these closed forms in place of ``G`` on dual numbers.
# Each partial derivative contains ``G``, so the rule takes the output ``y = G(s)`` of the step as an argument, and the reverse pass passes the value from the forward pass.
# Each partial derivative contains ``G``, so the `step_pullback` computes ``G`` once and reuses it.
# The step receives ``s`` as `q`, and `step_pullback` returns the cotangents of `q`, the state and the parameters, each a partial derivative times the cotangent ``\bar y`` of the output.

struct OffspringPGF end
(::OffspringPGF)(s, θ) = (1 + θ.R / θ.κ * (1 - s))^(-θ.κ)
function ComposableRecurrences.pullback!(
grads, ::OffspringPGF, ::ComposableRecurrences.Local, y, s, θ
)
u = 1 + θ.R / θ.κ * (1 - s)
∂R = -(1 - s) * y / u
∂κ = y * (θ.R * (1 - s) / (θ.κ * u) - log(u))
return θ.R * y / u, (; R = ∂R, κ = ∂κ)
struct OffspringPGF{R, K}
R::R
κ::K
end
ComposableRecurrences.isstateless(::OffspringPGF) = true
function ComposableRecurrences.step(::OffspringPGF, θ, q, s)
return (1 + θ.R / θ.κ * (1 - q))^(-θ.κ), s
end
function ComposableRecurrences.step_pullback(::OffspringPGF, θ, q, s, ȳ, s̄)
u = 1 + θ.R / θ.κ * (1 - q)
y = u^(-θ.κ)
∂R = -(1 - q) * y / u
∂κ = y * (θ.R * (1 - q) / (θ.κ * u) - log(u))
return θ.R * y / u * ȳ, s̄, (; R = ∂R * ȳ, κ = ∂κ * ȳ)
end

## The probability of extinction by each of generations 1 to `n`, for
## offspring parameters `θ = (; R, κ)`.
function extinction(θ, n)
m = Transform(OffspringPGF(), θ)
m = OffspringPGF(θ.R, θ.κ)
return Recurrence([1.0]; modifiers = (m,))(; history = [0.0], stop = n)
end

Expand Down Expand Up @@ -275,5 +280,5 @@ performance_plot("transform")
#
# ## Learning more
#
# - [Local rules for maps](@ref extending-local-rules) describes the `Local` role that the rule of `OffspringPGF` uses.
# - [Closed-form derivatives of maps](@ref extending-map-derivatives) describes the `step_pullback` that `OffspringPGF` uses.
# - [Time-varying delays and kernels](@ref tutorial-time-varying-kernels) models isolation that starts on a set day.
6 changes: 3 additions & 3 deletions ext/ComposableRecurrencesDifferentiationInterfaceExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ module ComposableRecurrencesDifferentiationInterfaceExt

using ADTypes: AbstractADType
using ComposableRecurrences: ComposableRecurrences as CR, NoAdjoint,
PieceInterface, Recurrence, Run, Step
PieceInterface, Recurrence, Step
import DifferentiationInterface as DI
using Interfaces: Interfaces
using LinearAlgebra: dot, norm
Expand Down Expand Up @@ -120,9 +120,9 @@ _gap(a, b) = length(a) == length(b) ? _inf(a .- b) : "its length"

# The backend's own rule tester, where it has a method.
function _test_adjoint(backend, r, x, history)
sig = Tuple{typeof(backend), Any, Run, Vararg}
sig = Tuple{typeof(backend), Any, Vararg}
hasmethod(CR.test_adjoint, sig) || return nothing
CR.test_adjoint(backend, r, Run(), _rule_args(r, x, history)...)
CR.test_adjoint(backend, r, _rule_args(r, x, history)...)
return nothing
end

Expand Down
Loading
Loading