Depletion forms
This page is for a reader whose pool gives up its value by a rule the built-in forms lack. It assumes Writing new types. A depletion form is the function by which a pool of a Depletion meets the value a step asks of it: it returns the value drawn and the pool after the draw. Depletion forms lists the built-in forms.
using ComposableRecurrences
const CR = ComposableRecurrencesComposableRecurrencesThe methods of a form
A form is a pure step, with the value asked for as v and the pool as s.
| Part | Method | Needed |
|---|---|---|
| the draw | step(form, θ, v, s) returns the value drawn and the pool after it | yes |
| its derivative | step_pullback(form, θ, v, s, v̄′, s̄′) | no |
θ holds the form's own fields, such as the exponent of Hazard, and the population the Depletion reads for the step as θ.N. A form passed to Depletion as its draw takes from the first pool. The Depletion starts the pool and records the trace, so a form has no init and no trace.
A form
The example draws a share of the value asked for, bounded by the pool,
where
struct Capped{C}
c::C
end
function CR.step(::Capped, θ, v, s)
y = min(θ.c * v, s)
return y, s - y
end
d = CR.Depletion(10.0, Capped(0.9))
Recurrence([0.5, 0.5]; modifiers = (d,))(2.0; history = [1.0, 2.0], stop = 8)8-element Vector{Float64}:
2.7
4.23
3.0699999999999994
0.0
0.0
0.0
0.0
0.0The draws fall to zero once the pool of 10 is spent.
The gradient with respect to the share and to every input of the recurrence needs no further method.
using DifferentiationInterface, ForwardDiff, Mooncake
loss(c) = sum(
Recurrence(
[0.5, 0.5]; modifiers = (CR.Depletion(10.0, Capped(c[1])),)
)(2.0; history = [1.0, 2.0], stop = 8)
)
gradient(loss, AutoMooncake(; config = nothing), [0.9]) ≈
gradient(loss, AutoForwardDiff(), [0.9])trueA step_pullback returns the cotangents of v and s and a named tuple of those of the parameters, with the population's under N. PieceInterface checks a form with role = Step() and args = (v, s, N), vectors of values and pools and a float N in place of a modifier's time.
using Interfaces: Interfaces, Arguments
Interfaces.test(
CR.PieceInterface{(:pullback, :step)}, Capped,
[
Arguments(;
piece = Capped(0.9), role = CR.Step(),
args = ([2.0, 9.0], [5.0, 4.0], 10.0)
),
]
)trueA form at an empty pool
Without a step_pullback, the derivative of a form is taken with dual numbers, which carry the derivative through each operation of the step. A product of the pool with a power of the pool, such as NaN. A branch on the value avoids the power at the empty pool: s > 0 || return zero(s), s returns before it is taken. The built-in Hazard has a step_pullback for the same reason.