Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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 docs/src/developer/extending-rules.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ A pure step is called at every stratum, or group, and time, in every loop of the

- It allocates nothing and writes nothing, and returns the new value and state.
The `:step` check asks that its result type is inferred from its arguments.
- It reads its parameters from `θ`, not from the modifier's fields, as the gradient is taken in `θ`.
- It reads its parameters from `θ`, as the gradient is taken in `θ`; a float parameter read from the modifier's fields is an `ArgumentError`.
The `:step` check fails a step whose result changes with the modifier's fields when `θ` is held.
- It has no time argument.
A field read at each time is a parameter, such as [`TimeVarying`](@ref), so that it reaches `θ` read at the time.
Expand Down
3 changes: 2 additions & 1 deletion docs/src/developer/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ show_snippet("smooth.jl") # hide

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 `θ`.
A step reads its parameters from `θ`, as the gradient is taken with respect to `θ`.
Inside the step a float parameter field of the modifier holds no value, so `m.a * v` is an `ArgumentError`; fields that are not floats, such as a `Bool` or a function, are read from the modifier.

The method [`init`](@ref ComposableRecurrences.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`.
Expand Down
5 changes: 3 additions & 2 deletions src/adjoints/local.jl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ end

# A draw from pool `s` of population `N`: the form's pure step.
@inline function _draw(form, v, s, N)
return @inline step(form, _form_theta(form, N), v, s)
return @inline step(_in_step(form), _form_theta(form, N), v, s)
end
_form_adjoint(form) = _step_rule(form)
# The cotangents `(v̄, s̄, N̄)` of a draw, with the form's own parameters'
Expand Down Expand Up @@ -175,7 +175,7 @@ function _init_pass!(
xd = ntuple(i -> D(convert(T, xs[i]), _unit(T, i - o, Val(W))), Val(Q))
θd = Q == 0 ? θ : first(_unflat(θ, xd))
hd = _seeded_rows(h̄, D, rows, Q - o, L)
y = _init_value(m, init(m, θd, _only_row(m, hd)))
y = _init_value(m, init(_in_step(m), θd, _only_row(m, hd)))
_has_partials(y, G) || return ḡ, false
ḡ′ = _init_grads(ḡ, y, s̄, o, Val(W), G)
h̄ === nothing && return ḡ′, true
Expand Down Expand Up @@ -384,6 +384,7 @@ end
@inline function trace(w::_LocalRoute, θ, v, s, v′, s′)
return @inline trace(w.m, θ, v, s, v′, s′)
end
_in_step(w::_LocalRoute) = _LocalRoute(_in_step(w.m))
_has_init(w::_LocalRoute) = _has_init(w.m)
_has_trace(w::_LocalRoute) = _has_trace(w.m)
_no_method(w::_LocalRoute, f::Symbol) = _no_method(w.m, f)
Expand Down
120 changes: 112 additions & 8 deletions src/interface/canonical.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ modifier's parameters there.
[parameter](@ref ComposableRecurrences.param) is read at the stratum and
time, a tuple or NamedTuple of parameters entry by entry, and any other
field is passed as it is.
Read parameters from `θ`, not from `m`, as the derivative is taken in `θ`.
Read parameters from `θ`, where the derivative is taken: inside the step a
float parameter field of `m` holds no value, and arithmetic on it is an
`ArgumentError`.
The method takes `θ`, `v` and `s` untyped, allocates nothing and writes
nothing, so the same method runs in the host loops, under
[`ComposableRecurrences.Threaded`](@ref) and inside a device kernel.
Expand Down Expand Up @@ -267,15 +269,112 @@ Base.@propagate_inbounds function _add_read!(x̄, x, g, k, t)
return nothing
end

# == The modifier a step is given ==

# What a float parameter of a modifier holds inside its `step`, `init`,
# `step_pullback` and `trace`: no value, as the value is in `θ`, where the

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 394de5c: a test runs each listed binary and unary operator on the marker and checks the error.

# derivative is taken. Arithmetic on it is an error that says so.
struct _InTheta <: Real end
@noinline function _read_from_modifier()
throw(
ArgumentError(
"a float parameter was read from the modifier inside its step; " *
"read it from θ, as θ.a for a field a: the derivative is " *
"taken in θ"
)
)
end
Base.promote_rule(::Type{_InTheta}, ::Type{<:Real}) = _read_from_modifier()
function Base.promote_rule(
::Type{_InTheta}, ::Type{Dual{T, V, N}}
) where {T, V, N}
return _read_from_modifier()
end
Base.AbstractFloat(::_InTheta) = _read_from_modifier()
for f in (:+, :-, :*, :/, :^, :<, :<=)
@eval Base.$f(::_InTheta, ::_InTheta) = _read_from_modifier()
end
for f in (:+, :-, :zero, :one, :inv, :abs)
@eval Base.$f(::_InTheta) = _read_from_modifier()
end

# A field as a step sees it: a float parameter, alone or in a tuple, is
# `_InTheta()`, and any other field is as it is. Where the modifier's type
# cannot hold `_InTheta()`, a float is `NaN` in its own type.
@inline _in_theta(x) = x

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 394de5c: the comments above _in_theta and _in_step are cut to the mutable pass-through, the _nan fallback and the generator ordering.

@inline _in_theta(::Real) = _InTheta()
@inline _in_theta(x::Integer) = x
@inline _in_theta(x::Union{Tuple, NamedTuple}) = map(_in_theta, x)
@inline _nan(x) = x
@inline _nan(x::AbstractFloat) = oftype(x, NaN)
@inline _nan(x::Union{Tuple, NamedTuple}) = map(_nan, x)
_in_theta_type(::Type{T}) where {T} = T
_in_theta_type(::Type{<:Real}) = _InTheta
_in_theta_type(::Type{T}) where {T <: Integer} = T
function _in_theta_type(::Type{T}) where {T <: Tuple}
return Tuple{map(_in_theta_type, fieldtypes(T))...}
end
function _in_theta_type(::Type{NamedTuple{K, V}}) where {K, V}
return NamedTuple{K, _in_theta_type(V)}
end

# The type of `M` whose fields are those of `_in_theta`: each such field's
# type is a type parameter of `M`, replaced here. `nothing` when a field is
# declared with a concrete type or a bound `_InTheta` does not meet.
function _in_theta_struct(::Type{M}) where {M}
new = map(_in_theta_type, fieldtypes(M))
W = Base.typename(M).wrapper
body = Base.unwrap_unionall(W)
params = Any[M.parameters...]
for (declared, T) in zip(fieldtypes(body), new)
j = findfirst(v -> v === declared, body.parameters)
j === nothing || (params[j] = T)
end
N = try
W{params...}
catch
return nothing
end
return fieldtypes(N) == new ? N : nothing
end

# The modifier its `step`, `init`, `step_pullback` and `trace` are given:
# `m` with each float parameter field replaced, so a method that reads one
# from `m` fails where it would otherwise lose that parameter's derivative.
# Non-float fields, such as a `Bool` or a function, are those of `m`. A
# mutable modifier is passed as it is. After its helpers: a generator sees

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Kept the NaN and documented it in the step docstring in 394de5c. Throwing in _in_step or at construction would refuse every modifier with a concrete float field, including ones that read θ correctly. Whether to refuse such types when the operator is built is left to the owner in the PR description.

# only the methods defined before it.
@generated function _in_step(m)
n = fieldcount(m)
(isstructtype(m) && !ismutabletype(m) && n > 0) || return :m

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 394de5c: the step docstring says a mutable modifier is passed as it is, and a test checks the pass-through.

N = _in_theta_struct(m)
f, T = N === nothing ? (:_nan, m) : (:_in_theta, N)
return Expr(:new, T, (:($f(getfield(m, $i))) for i in 1:n)...)
end

# == The step and its pullback on scalars ==

# A step returns the pair `(v′, s′)`; any other result is said at the call.
@inline _step_pair(m, r::Tuple{Any, Any}) = r
@noinline function _step_pair(m, r)
throw(
ArgumentError(
"step(::$(nameof(typeof(m))), θ, v, s) returned a $(typeof(r)); " *
"a step returns the new value and state, (v′, s′), with " *
"nothing as the state of a stateless modifier"
)
)
end

# A stateless modifier's step gets no state and keeps the one it is given.
# The choice is a dispatch, so the step is compiled for the modifier's own
# type on either arm.
@inline _pure_step(m, θ, v, s) = _pure_step(Val(isstateless(m)), m, θ, v, s)
@inline _pure_step(::Val{false}, m, θ, v, s) = @inline step(m, θ, v, s)
@inline function _pure_step(::Val{false}, m, θ, v, s)
return _step_pair(m, @inline step(_in_step(m), θ, v, s))
end
@inline function _pure_step(::Val{true}, m, θ, v, s)
v′, _ = @inline step(m, θ, v, nothing)
v′, _ = _step_pair(m, @inline step(_in_step(m), θ, v, nothing))
return v′, s
end

Expand All @@ -292,15 +391,18 @@ end
return v̄0, s̄, θ̄
end
@inline function _pure_grads(m, θ, v, s, v̄, s̄, active::Val)
_has_step_pullback(m) && return @inline step_pullback(m, θ, v, s, v̄, s̄)
_has_step_pullback(m) &&
return @inline step_pullback(_in_step(m), θ, v, s, v̄, s̄)
return _local_grads(m, θ, v, s, v̄, s̄, active)
end
@inline function _local_grads(m, θ, v, s, v̄, s̄, ::Val{true})
f = @inline z -> @inline step(m, z[3], z[1], z[2])
ms = _in_step(m)
f = @inline z -> @inline step(ms, z[3], z[1], z[2])
return _dual_back(f, (v, s, θ), (v̄, s̄))
end
@inline function _local_grads(m, θ, v, s, v̄, s̄, ::Val{false})
f = @inline z -> @inline step(m, θ, z[1], z[2])
ms = _in_step(m)
f = @inline z -> @inline step(ms, θ, z[1], z[2])
v̄0, s̄0 = _dual_back(f, (v, s), (v̄, s̄))
return v̄0, s̄0, (;)
end
Expand Down Expand Up @@ -345,7 +447,8 @@ function _init_states!(::Nothing, m, s, history, t0)
return nothing
end
function _init_body!(k, s, m, history, t0)
@inbounds s[k] = init(m, _theta(m, k, t0), _history_row(history, k))
θ = @inbounds _theta(m, k, t0)
@inbounds s[k] = init(_in_step(m), θ, _history_row(history, k))
return nothing
end
function _init_states!(::Val{B}, m, s, history, t0) where {B}
Expand All @@ -357,7 +460,8 @@ function _init_states!(::Val{B}, m, s, history, t0) where {B}
end
function _init_group_body!(g, s, m, history, ::Val{B}, G, t0) where {B}
nv, ns = B
x = init(m, _theta(m, g, t0), _history_rows(history, Val(nv), G, g))
rows = _history_rows(history, Val(nv), G, g)
x = init(_in_step(m), _theta(m, g, t0), rows)
_scatter!(s, _init_entries(x, Val(ns)), G, g)
return nothing
end
Expand Down
10 changes: 6 additions & 4 deletions src/interface/trace.jl
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ trace(::_NoModifier, θ, v, s, v′, s′) = ()
# its fields has its own methods.
Base.@propagate_inbounds function _unit_trace(m, v, s, v′, s′, t, k)
_has_trace(m) || _no_method(m, :trace)
return @inline trace(m, _theta(m, k, t), v, s, v′, s′)
return @inline trace(_in_step(m), _theta(m, k, t), v, s, v′, s′)
end

# The cotangents `(v̄, s̄, v̄′, s̄′)` the trace's cotangent `r̄`, a tuple, adds
Expand All @@ -215,17 +215,19 @@ end
Base.@propagate_inbounds function _unit_trace_back(m̄, m, r̄, v, s, t, k)
_has_trace(m) || _no_method(m, :trace)
θ = _theta(m, k, t)
v′, s′ = @inline step(m, θ, v, s)
v′, s′ = @inline step(_in_step(m), θ, v, s)
v̄, s̄, v̄′, s̄′, θ̄ = _trace_grads(m, θ, v, s, v′, s′, r̄, _active(m̄, m))
_add_theta!(m̄, m, θ̄, k, t)
return v̄, s̄, v̄′, s̄′
end
@inline function _trace_grads(m, θ, v, s, v′, s′, r̄, ::Val{true})
f = @inline z -> @inline trace(m, z[5], z[1], z[2], z[3], z[4])
ms = _in_step(m)
f = @inline z -> @inline trace(ms, z[5], z[1], z[2], z[3], z[4])
return _dual_back(f, (v, s, v′, s′, θ), r̄)
end
@inline function _trace_grads(m, θ, v, s, v′, s′, r̄, ::Val{false})
f = @inline z -> @inline trace(m, θ, z[1], z[2], z[3], z[4])
ms = _in_step(m)
f = @inline z -> @inline trace(ms, θ, z[1], z[2], z[3], z[4])
v̄, s̄, v̄′, s̄′ = _dual_back(f, (v, s, v′, s′), r̄)
return v̄, s̄, v̄′, s̄′, (;)
end
Expand Down
88 changes: 88 additions & 0 deletions test/unit/pure_step.jl
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,86 @@ end
@test !step_ok(Unstable(), ([2.0], [1.0], 1))
end

@testitem "Pure step: a float read from the modifier is an error" begin
using ComposableRecurrences
const CR = ComposableRecurrences
g, R, h = [0.2, 0.3, 0.5], fill(1.1, 6), ones(3)
run(m; kw...) = Recurrence(g; modifiers = (m,))(R; history = h, kw...)
misread = r"read from the modifier"
# The step, the init, the pullback and the trace each get the modifier
# with its float parameters replaced.
struct StepReads{A}
a::A
end
CR.isstateless(::StepReads) = true
CR.step(m::StepReads, θ, v, s) = (m.a * v, nothing)
@test_throws misread run(StepReads(0.9))
struct TupleReads{A}
a::A
end
CR.isstateless(::TupleReads) = true
CR.step(m::TupleReads, θ, v, s) = (exp(-m.a[1]) * v, nothing)
@test_throws misread run(TupleReads((0.9, 0.1)))
struct InitReads{A}
a::A
end
CR.init(m::InitReads, θ, history) = m.a + last(history)
CR.step(::InitReads, θ, v, s) = (θ.a * v + s, s)
@test_throws misread run(InitReads(0.9))
struct TraceReads{A}
a::A
end
CR.init(::TraceReads, θ, history) = 0
CR.step(::TraceReads, θ, v, s) = (θ.a * v, s)
CR.trace(m::TraceReads, θ, v, s, v′, s′) = (1 - m.a,)
@test run(TraceReads(0.9)) isa Vector{Float64}
@test_throws misread run(TraceReads(0.9); record = (CR.Trace(),))
struct BackReads{A}
a::A
end
CR.isstateless(::BackReads) = true
CR.step(::BackReads, θ, v, s) = (θ.a * v, nothing)
function CR.step_pullback(m::BackReads, θ, v, s, v̄′, s̄′)
return m.a * v̄′, nothing, (; a = v * v̄′)
end
grads = (; piece = (; a = Ref(0.0)), v = 1.0, s = nothing)
back() = CR._step_pullback(grads, BackReads(0.9), 2.0, nothing, 1, 1)
@test_throws misread back()
# A field declared with a concrete float type cannot hold the marker,
# so it reads as NaN.
struct FixedReads
a::Float64
end
CR.isstateless(::FixedReads) = true
CR.step(m::FixedReads, θ, v, s) = (m.a * v, nothing)
@test all(isnan, run(FixedReads(0.9)))
# Fields that are not floats are those of the modifier, and the
# replaced copy costs nothing.
struct StepKeeps end
CR.isstateless(::StepKeeps) = true
CR.step(::StepKeeps, θ, v, s) = (v, nothing)
struct Mixed{A, F}
a::A
flag::Bool
n::Int
f::F
end
CR.isstateless(::Mixed) = true

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 394de5c: the warm-up line has a comment.

function CR.step(m::Mixed, θ, v, s)
return (m.flag ? m.n * m.f(θ.a * v) : v, nothing)
end
twice = Mixed(0.9, true, 1, v -> 2sqrt(v))
@test run(Mixed(0.9, true, 2, sqrt)) ≈ run(twice)
@test run(Mixed(0.9, false, 2, sqrt)) == run(StepKeeps())
m = Mixed(0.9, true, 2, sqrt)
seen = @inferred CR._in_step(m)
@test seen.a isa CR._InTheta
@test (seen.flag, seen.n, seen.f) === (true, 2, sqrt)
allocated(m) = @allocated CR._in_step(m)

This comment was marked as resolved.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 394de5c: tests for a stateful misreading step (the Val{false} arm), a misread through _local_route (_LocalRoute) and a depletion form misreading in _draw. _init_pass! is not tested apart: its init is the one the forward run calls first, so a misread fails there before the pass.

allocated(m)
@test allocated(m) == 0
end

@testitem "Pure step: ties take the branch of the values" setup = [AdjointCheck] begin
using ComposableRecurrences
# At `v == θ.c` the step takes the second branch, and so does its
Expand Down Expand Up @@ -401,6 +481,14 @@ end
@test_throws "types its arguments after the modifier" r(
1.0; history = [1.0], stop = 2
)
# A step that returns the value alone is said at the call too.
struct OnlyValue end
CR.isstateless(::OnlyValue) = true
CR.step(::OnlyValue, θ, v, s) = v / 2
r = Recurrence([0.5]; modifiers = (OnlyValue(),))
@test_throws "returns the new value and state" r(
1.0; history = [1.0], stop = 2
)
end

@testitem "Pure step: a state needs an init the call can see" begin
Expand Down
Loading