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 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
4 changes: 3 additions & 1 deletion docs/src/developer/extending.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@ 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 @@ -378,6 +378,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
106 changes: 98 additions & 8 deletions src/interface/canonical.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,13 @@ 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`.
Two kinds of modifier cannot hold that marker.
A float field declared with a concrete type, such as `a::Float64`, reads
as `NaN`, so a misread gives `NaN` output.
A mutable modifier is passed as it is, and a misread there is not caught.
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,6 +273,85 @@ 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. `_nan` is for a type that cannot hold
# `_InTheta()`.
@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.
# A mutable modifier is passed as it is. After its helpers: a generator sees
# 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.
Expand All @@ -286,10 +371,10 @@ end
# type on either arm.
@inline _pure_step(m, θ, v, s) = _pure_step(Val(isstateless(m)), m, θ, v, s)
@inline function _pure_step(::Val{false}, m, θ, v, s)
return _step_pair(m, @inline step(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′, _ = _step_pair(m, @inline step(m, θ, v, nothing))
v′, _ = _step_pair(m, @inline step(_in_step(m), θ, v, nothing))
return v′, s
end

Expand All @@ -306,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 @@ -359,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 @@ -371,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
8 changes: 5 additions & 3 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 @@ -223,11 +223,13 @@ Base.@propagate_inbounds function _unit_trace_back(
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
118 changes: 118 additions & 0 deletions test/unit/pure_step.jl
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,124 @@ 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 KeptReads{A}
a::A
end
CR.init(::KeptReads, θ, history) = 0.0
CR.step(m::KeptReads, θ, v, s) = (m.a * v, s)
@test_throws misread run(KeptReads(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()
# The local-derivative route and a depletion form's draw too.
struct RouteReads{A}
a::A
end
CR.isstateless(::RouteReads) = true
CR.step(m::RouteReads, θ, v, s) = (m.a * v, nothing)
function CR.step_pullback(::RouteReads, θ, v, s, v̄′, s̄′)
return θ.a * v̄′, nothing, (; a = v * v̄′)
end
route = CR._local_route(Recurrence(g; modifiers = (RouteReads(0.9),)))
@test first(route.modifiers) isa CR._LocalRoute
@test_throws misread route(R; history = h)
struct FormReads{P}
p::P
end
function CR.step(m::FormReads, θ, v, s)
y = min(m.p * v * s / θ.N, s)
return y, s - y
end
@test_throws misread run(CR.Depletion(100.0, FormReads(0.5)))
# Each operation on the marker says so.
for op in (+, -, *, /, ^, <, <=)
@test_throws misread op(CR._InTheta(), CR._InTheta())
end
for op in (+, -, zero, one, inv, abs)
@test_throws misread op(CR._InTheta())
end
# A mutable modifier is passed as it is.
mutable struct MutableReads{A}
a::A
end
@test CR._in_step(MutableReads(0.9)).a === 0.9
# 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) # compiles it first
@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
Loading