Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
1 change: 0 additions & 1 deletion benchmark/parity.jl
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ end
function models(S; L = 20, T = 200, history = L)
g = exp.(-0.2 .* (1:L))
g ./= sum(g)
# A vector: a range here would send both models to plain AD.
N = [1.0e5 * (1 + 0.1 * k) for k in 1:S]
h = [10.0 + k + 0.1 * i for k in 1:S, i in 1:history]
pool = N .- vec(sum(h; dims = 2))
Expand Down
5 changes: 3 additions & 2 deletions docs/src/developer/extending-performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,9 @@ parity_table() # hide
parity_summary() # hide
```

A gradient through the trace costs a user's step more than the built-in, by the ratio in the table.
The reverse pass evaluates a user's `step` once more at each stratum and time, for the outputs that `trace` takes, where the built-in's trace has a closed-form derivative that does not need them.
A gradient through the trace is the row where a user's step differs most from the built-in, by the ratio in the table.
The reverse pass differentiates a user's `trace` by one pass of dual numbers, and adds the cotangent of each parameter whether or not the trace reads it.
The built-in's trace has a closed-form derivative.

The tests in `test/unit/parity.jl` hold the agreement, and the cases `renewal_depletion` and `user_depletion_pullback` of the benchmark matrix hold the times.
JLArrays runs each kernel on the CPU, so the two device rows compare the kernels' overhead and not times on a GPU.
Expand Down
11 changes: 10 additions & 1 deletion docs/src/explanation/adjoints-and-backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,16 @@ An operator whose kernel is a `Derived` with such a map takes plain AD for the s

The `Recurrence` constructor logs an `@info` when a component sends the operator to plain AD, naming the component and the reason.
It logs each message once per session, whatever the number types.
A call sent to plain AD by its float or array types logs nothing.

The rule also needs the call's numbers and arrays to be ones it can read and write.
It takes IEEE floats and integers, held in an `Array`, a sparse matrix, a `Diagonal`, or a view, reshape, transpose or adjoint of an `Array`.
A range, and a `PermutedDimsArray`, `Symmetric` or `Hermitian` of an `Array`, is copied to an `Array` on the way into the rule.
The backend differentiates that copy, so a range built from parameters keeps their gradients.
This holds for the kernel, the coupling, a modifier's parameters, the input and the history.
A call with any other array type, such as a static array or a symmetric wrapper of a sparse matrix, takes plain AD.
So does a call with a field of abstract type.
A reverse-mode backend that would have run the rule then logs the same `@info` once, naming the field or argument and its type.
A call on dual numbers or another number type that no rule runs takes plain AD by design and logs nothing.

### [The local derivative of a pure step](@id adjoint-local-step)

Expand Down
9 changes: 6 additions & 3 deletions ext/ComposableRecurrencesEnzymeExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ using ComposableRecurrences: PerStratum, Pressure, Serial, pullback!, _ADLeaves,
_growth_root, _check_parts, _check_secondary,
_convolve_masses!, _convolve_masses_back!, _current, _fft_convolve!,
_fft_convolve_back!, _fft_convolve_terms!, _flat_groups, _is_leaf,
_keep_inputs, _leaf_paths, _offset, _plain_hook, _rebuild_leaves,
_keep_inputs, _leaf_paths, _note_stopped, _offset, _plain_hook,
_rebuild_leaves,
_route_forward!, _run_forward, _run_pullback!, _scan!, _scan_back!,
_shared_shadow,
_spawn_blocks, _spawn_chunks, _start_times, _untraced
Expand Down Expand Up @@ -199,8 +200,9 @@ end
_active_operator(::Union{Const, Active}) = false
_active_operator(op) = _holds_float(typeof(op.val))

# The plain-AD hook does nothing in forward mode, and in reverse mode warns
# on Julia 1.11 when the operator has an active scalar float.
# The plain-AD hook does nothing in forward mode. In reverse mode it says once
# why the call takes plain AD, and warns on Julia 1.11 when the operator has
# an active scalar float.
function EnzymeRules.forward(
::EnzymeRules.FwdConfig, ::Const{typeof(_plain_hook)}, ::Type,
args::Vararg{Annotation, N}
Expand All @@ -212,6 +214,7 @@ function EnzymeRules.augmented_primal(
op::Annotation, args::Vararg{Annotation, N}
) where {N}
VERSION < v"1.12" && _warn_scalar_loss(typeof(op.val), op, _active_operator)
_note_stopped(op.val, map(a -> a.val, args)...)
return EnzymeRules.AugmentedReturn(nothing, nothing, nothing)
end
function EnzymeRules.reverse(
Expand Down
6 changes: 4 additions & 2 deletions ext/ComposableRecurrencesMooncakeExt.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ using ComposableRecurrences: ComposableRecurrences, Run, Serial, _Current, _ad,
_convolve_masses, _convolve_masses_back!, _current,
_fft_convolve!, _fft_convolve_back!, _flat_groups,
_join_history, _pad_front,
_movement, _movement_back!, _plain_hook, _run_forward,
_movement, _movement_back!, _note_stopped, _plain_hook, _run_forward,
_run_pullback!, _Scan, _scan_rule, _stack_values, _start_times, _untraced
using LinearAlgebra: Adjoint, Transpose, axpy!
using Mooncake: Mooncake, CoDual, NoFData, NoRData, primal, tangent
Expand Down Expand Up @@ -165,7 +165,8 @@ function Mooncake.rrule!!(
end
return CoDual(v, dv), stack_values_pb
end
# The plain-AD hook carries no derivative.
# The plain-AD hook carries no derivative. In reverse mode, where the rule
# would have run, it says once why the call takes plain AD.
Mooncake.@is_primitive Mooncake.DefaultCtx Tuple{typeof(_plain_hook), Vararg}
function Mooncake.frule!!(
::Mooncake.Dual{typeof(_plain_hook)}, args::Vararg{Mooncake.Dual, N}
Expand All @@ -175,6 +176,7 @@ end
function Mooncake.rrule!!(
f::CoDual{typeof(_plain_hook)}, op::CoDual, args::Vararg{CoDual, N}
) where {N}
_note_stopped(Mooncake.primal(op), map(Mooncake.primal, args)...)
return Mooncake.zero_fcodual(nothing), Mooncake.NoPullback(f, op, args...)
end

Expand Down
4 changes: 2 additions & 2 deletions src/ComposableRecurrences.jl
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ using DocStringExtensions: @template, DOCSTRING, EXPORTS, IMPORTS,
TYPEDEF, TYPEDFIELDS, TYPEDSIGNATURES
using ForwardDiff: ForwardDiff
using Interfaces: Interfaces, Arguments, @interface, @implements
using LinearAlgebra: Adjoint, Diagonal, I, Transpose, UniformScaling, dot,
mul!
using LinearAlgebra: Adjoint, Diagonal, Hermitian, I, Symmetric, Transpose,
UniformScaling, dot, mul!
using PrecompileTools: @compile_workload, @setup_workload
using SparseArrays: AbstractSparseMatrix, SparseMatrixCSC, nonzeros, nzrange,
rowvals
Expand Down
159 changes: 150 additions & 9 deletions src/adjoints/adjoints.jl
Original file line number Diff line number Diff line change
Expand Up @@ -157,12 +157,13 @@ end
# The hook gets the wrapper, so a backend tells it from the operator's own
# plain call.
function adjoint_call(n::NoAdjoint, args::Vararg{Any, N}) where {N}
_gate(n, args...) && _plain_hook(n, args...)
_hooked(n, args...) && _plain_hook(n, args...)
return _plain(n.op, args...)
end
function _route_val(op, args::Vararg{Any, N}) where {N}
ok = _gate(op, args...) || _device_gate(op, args...)
return Val(_type_adjoint(op) && ok ? :rule : :plain)
_type_adjoint(op) || return Val(:plain)
(_gate(op, args...) || _device_gate(op, args...)) && return Val(:rule)
return Val(_dense_gate(op, args...) ? :dense : :plain)
end

# The GPUArrays extension says which arrays live on a device
Expand All @@ -189,6 +190,11 @@ const _DeviceKernel = Union{
_type_adjoint(op) = uses_adjoint(op, Run())
_route(::Val{:plain}, op, args::Vararg{Any, N}) where {N} = _hooked_plain(op, args...)
_route(::Val{:rule}, op, args::Vararg{Any, N}) where {N} = _ad(op, args...)
# The rule reads a range or a lazy wrapper as the `Array` of its values. The
# copy is made here, outside the rule, so a backend differentiates it.
function _route(::Val{:dense}, op, args::Vararg{Any, N}) where {N}
return _ad(_dense(op, args...)...)
end

# An operator with a keyword `forward` adds methods for its positional form.
_run_forward(op, args...) = forward(op, Run(), args...)
Expand Down Expand Up @@ -253,12 +259,13 @@ end
# == Plain AD ==

_plain(op, args...) = _primal(op, args...)
# A no-op that the `Enzyme` extension's rule uses to warn of a gradient it
# can lose on Julia 1.11. The call boxes its arguments, so calls whose floats
# are not all IEEE, which no backend with a rule runs, skip it.
# A no-op that a backend with a rule replaces in reverse mode, to say why
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
# the call takes plain AD (`_note_stopped`). The call boxes its arguments, so
# calls that hold a real number no such backend runs, a dual number say,
# skip it.
@noinline _plain_hook(op, args...) = (Base.donotdelete(op, args...); nothing)
function _hooked_plain(op, args::Vararg{Any, N}) where {N}
_gate(op, args...) && _plain_hook(op, args...)
_hooked(op, args...) && _plain_hook(op, args...)
return _plain(op, args...)
end

Expand Down Expand Up @@ -288,6 +295,140 @@ end
# After its helpers: a generator sees only the methods defined before it.
@generated _gate(xs...) = all(_ok, xs)

# Whether a backend with a rule may run a value of type `T`: it holds no
# real number of a concrete type other than an IEEE float or an integer.
function _numbers_ok(::Type{T}) where {T}
T <: Union{_IEEEFloat, Integer} && return true
T <: Real && return !isconcretetype(T)
T <: AbstractArray && return _numbers_ok(eltype(T))
isconcretetype(T) && isstructtype(T) || return true
return all(_numbers_ok, fieldtypes(T))
end
@generated _hooked(xs...) = all(_numbers_ok, xs)

# == Lazy host arrays ==

# Host arrays the rule reads as the `Array` of their values: a range, and a
# wrapper of an `Array` or of one of these. A wrapper of a sparse or device
# array is not one, as the copy would be dense or leave the device.
const _LazyWrapper = Union{
SubArray, Base.ReshapedArray, Transpose, Adjoint, PermutedDimsArray,
Symmetric, Hermitian,
}
function _lazy(::Type{T}) where {T}
T <: AbstractRange && return true
T <: _LazyWrapper || return false
P = fieldtype(T, 1)
return P <: Array || _lazy(P)
end

# The type of `T` with each lazy host array as an `Array`, or `T` when it
# holds none or cannot be rebuilt with them: a mutable struct, or a struct
# whose field types do not follow from its type parameters.
function _dense_type(::Type{T}) where {T}
(T isa DataType && !_ok(T)) || return T
if T <: AbstractArray
_lazy(T) && return Array{eltype(T), ndims(T)}
T <: Diagonal || return T
return Diagonal{eltype(T), _dense_type(fieldtype(T, :diag))}
end
isconcretetype(T) && isstructtype(T) && !ismutabletype(T) || return T
isempty(T.parameters) && return T
D = try
T.name.wrapper{map(_dense_parameter, T.parameters)...}
catch
return T
end
same = isconcretetype(D) && fieldcount(D) == fieldcount(T) &&
all(i -> fieldtype(D, i) === _dense_type(fieldtype(T, i)), 1:fieldcount(T))
return same ? D : T
end
_dense_parameter(p) = p isa Type ? _dense_type(p) : p
# After its helpers: a generator sees only the methods defined before it.
@generated function _dense_gate(xs...)
X = Tuple{xs...}
D = _dense_type(X)
return D !== X && all(_ok, fieldtypes(D))
end

_dense_leaf(x::AbstractArray) = collect(x)
_dense_leaf(x::Diagonal) = Diagonal(_dense_leaf(x.diag))
_path_type(T, p) = isempty(p) ? T : _path_type(fieldtype(T, first(p)), Base.tail(p))
# The operator and arguments with each lazy leaf copied to an `Array`.
@generated function _dense(op, args::Vararg{Any, N}) where {N}
X = Tuple{op, args...}
roots = (:op, (:(args[$i]) for i in 1:N)...)
leaves = map(_leaf_paths(X)) do p
leaf = _path_expr(roots[first(p)], Base.tail(p))
L = _path_type(X, p)
_dense_type(L) === L ? leaf : :(_dense_leaf($leaf))
end
return :(_rebuild_leaves($(_dense_type(X)), ($(leaves...),)))
end

# == Why a call takes plain AD ==

# Says once per message why gradients take plain AD. Keyed on the message, so
# the same parts with other number types log nothing more.
const _PLAIN_NOTED = Set{String}()
const _PLAIN_SEEN = Base.IdSet{Any}()
const _PLAIN_LOCK = ReentrantLock()
function _note_plain(whys::Union{Tuple, AbstractVector}, what = "Recurrence")
isempty(whys) && return nothing
msg = string(
what, " gradients use plain AD of the whole operator: ",
join(unique(whys), "; ")
)
new = @lock _PLAIN_LOCK _first_time!(_PLAIN_NOTED, msg)
new && @info msg
return nothing
end
_first_time!(seen, x) = x in seen ? false : (push!(seen, x); 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.

Kept the set and recorded the cost in the comment. Keying on the message alone would rebuild the message, a walk over the types and a string, on every plain call; the set makes it one lookup. It holds one type per call signature, as the compiled methods for that signature already do.


Generated by Claude Code


# A backend with a rule calls this from its `_plain_hook` in reverse mode, so
# the reason is logged only when a rule was there to take. One lookup per
# call after the first of a signature.
function _note_stopped(op, args::Vararg{Any, N}) where {N}
X = Tuple{Core.Typeof(op), map(Core.Typeof, args)...}
new = @lock _PLAIN_LOCK _first_time!(_PLAIN_SEEN, X)
new && _note_plain(_stopped_whys(op, args...), _plain_what(op))
return nothing
end
# The user asked for plain AD.
_note_stopped(::NoAdjoint, args::Vararg{Any, N}) where {N} = nothing

function _stopped_whys(op, args...)
_type_adjoint(op) || return _plain_whys(op)
_any_on_gpu(args...) && !_device_ready(op) && return _device_whys(op)
out = String[]
_stopped!(out, typeof(op), string(_plain_what(op)))
foreach(i -> _stopped!(out, typeof(args[i]), "argument $i"), eachindex(args))
return out
end
# The operator each reason names, and why its types keep it from the rule;
# each operator file says so for its operators.
_plain_what(op) = nameof(typeof(op))
_plain_whys(op) = ("$(_plain_what(op)) has no pullback! for Run()",)
_device_whys(op) = ("$(_plain_what(op)) has no rule on device arrays",)

# The parts of a value of type `T` the gate stops at, each as its field path
# and why.
function _stopped!(out, ::Type{T}, label) where {T}
_ok(T) && return out
if !(isconcretetype(T) && isstructtype(T)) || T <: Union{Real, AbstractArray}
return push!(out, "$label is $(_stopped_why(T))")
end
for (name, F) in zip(fieldnames(T), fieldtypes(T))
_stopped!(out, F, "$label.$name")
end
return out
Comment thread
seabbs-bot marked this conversation as resolved.
Resolved
end
function _stopped_why(::Type{T}) where {T}
isconcretetype(T) || return "of type $T, which is not concrete"
T <: AbstractArray || return "a $T, not an IEEE float"
return "a $T, which the rule does not take: pass an Array"
end

# == Mirrors ==

@doc raw"""
Expand All @@ -307,8 +448,8 @@ and this returns ``\bar\theta_j`` for the field named `name`.
A mirror holds a struct's cotangents for a
[`ComposableRecurrences.pullback!`](@ref), one
[entry](@ref extending-mirror) per field: a `Ref` for a float scalar, an
array of the same shape for a float array, and `nothing` for an integer,
range or function.
array of the same shape for a float array or range, and `nothing` for an
integer, integer range or function.

# Arguments
- `x̄`: the mirror, a NamedTuple of field mirrors or `nothing`.
Expand Down
2 changes: 1 addition & 1 deletion src/depletion/pool.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1115,7 +1115,7 @@ Base.@propagate_inbounds function _unit_trace(
return _pool_trace(m, v, s, v′, s′, t, g)
end
Base.@propagate_inbounds function _unit_trace_back(
m̄, m::Depletion, r̄, v, s, t, g
m̄, m::Depletion, r̄, v, s, v′, s′, t, g
)
return _pool_trace_back((; piece = m̄, trace = r̄), m, v, s, t, g)
end
Expand Down
10 changes: 8 additions & 2 deletions src/interface/duals.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,14 @@ end

# `Σ ȳ ∂y/∂x_j` over the leaves of the output `y`, paired with those of its
# cotangent `ȳ`. A leaf that is not a dual number of the pass is constant.
@inline _contract(y::Dual{G}, ȳ, j, ::Type{G}) where {G} =
ȳ * @inbounds(ForwardDiff.partials(y, j))
# A partial that is zero adds nothing, whatever its cotangent: the output
# does not depend on that input, as a pullback written by hand would have
# it. The compiler then drops the terms of partials it knows to be zero,
# which it cannot do for a product with a cotangent that may be `NaN`.
@inline function _contract(y::Dual{G}, ȳ, j, ::Type{G}) where {G}
p = @inbounds ForwardDiff.partials(y, j)
return ifelse(iszero(p), zero(ȳ * p), ȳ * p)
end
@inline _contract(y, ȳ, j, ::Type{G}) where {G} = false
@inline _contract(::Tuple{}, ȳ, j, ::Type{G}) where {G} = false
@inline function _contract(y::Tuple, ȳ, j, ::Type{G}) where {G}
Expand Down
8 changes: 5 additions & 3 deletions src/interface/trace.jl
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,13 @@ end

# The cotangents `(v̄, s̄, v̄′, s̄′)` the trace's cotangent `r̄`, a tuple, adds
# to those of the step's inputs and outputs, with the parameters' added
# into the mirror `m̄`. The step runs again for its outputs.
Base.@propagate_inbounds function _unit_trace_back(m̄, m, r̄, v, s, t, k)
# into the mirror `m̄`. The step's outputs `v′` and `s′` come from the run's
# records, so the step does not run again.
Base.@propagate_inbounds function _unit_trace_back(
m̄, m, r̄, v, s, v′, s′, t, k
)
_has_trace(m) || _no_method(m, :trace)
θ = _theta(m, k, t)
v′, s′ = @inline 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̄′
Expand Down
24 changes: 7 additions & 17 deletions src/operators/recurrence.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1139,26 +1139,16 @@ _primary_adjoint(C) = _linear_coupling(C) ? :linear : _coupling_adjoint(C)
# Says once why a `Recurrence` whose types keep it from the rule takes plain
# AD.
function _check_parts(kernel, C, ms::Tuple)
_parts_adjoint(kernel, C, ms) && return nothing
C_why = _primary_adjoint(C) === :none ? (_part_why(C),) : ()
_note_plain((_no_adjoint_kernel(kernel)..., C_why..., _no_adjoint(ms...)...))
_parts_adjoint(kernel, C, ms) || _note_plain(_parts_whys(kernel, C, ms))
return nothing
end

# Keyed on the message, so the same parts with other number types, dual
# numbers included, log nothing more.
const _PLAIN_NOTED = Set{String}()
const _PLAIN_LOCK = ReentrantLock()
function _note_plain(whys::Union{Tuple, AbstractVector}, what = "Recurrence")
msg = string(
what, " gradients use plain AD of the whole operator: ",
join(unique(whys), "; ")
)
new = @lock _PLAIN_LOCK (msg in _PLAIN_NOTED ? false : (push!(_PLAIN_NOTED, msg); true))
new || return nothing
@info msg
return nothing
function _parts_whys(kernel, C, ms::Tuple)
C_why = _primary_adjoint(C) === :none ? (_part_why(C),) : ()
return (_no_adjoint_kernel(kernel)..., C_why..., _no_adjoint(ms...)...)
end
_plain_what(::Union{Recurrence, _WithState}) = :Recurrence
_plain_whys(r::Recurrence) = _parts_whys(r.kernel, r.coupling, r.modifiers)
_plain_whys(w::_WithState) = _plain_whys(w.r)
_no_adjoint() = ()
function _no_adjoint(m, ms...)
rest = _no_adjoint(ms...)
Expand Down
Loading
Loading