Repository navigation
Fail at the call when a step reads a float parameter from the modifier #981
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
9ee653b
cacce6a
19fb726
394de5c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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. | ||
|
|
@@ -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 | ||
| # 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.
Sorry, something went wrong.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 394de5c: the comments above |
||
| @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.
Sorry, something went wrong.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Kept the NaN and documented it in the |
||
| # 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.
Sorry, something went wrong.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 394de5c: the |
||
| 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 | ||
|
|
||
|
|
@@ -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 | ||
|
|
@@ -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} | ||
|
|
@@ -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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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.
Sorry, something went wrong.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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.
Sorry, something went wrong.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fixed in 394de5c: tests for a stateful misreading step (the |
||
| 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 | ||
|
|
@@ -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 | ||
|
|
||
This comment was marked as resolved.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
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.