Repository navigation
No silent plain AD: the rule takes ranges and lazy wrappers, and names what it does not #955
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 4 commits
585d550
0684fc1
ba759a1
680f026
69ba041
7e6061d
7e230a7
695a6fc
47038d3
42b1532
22d907a
eabe769
9f60eb1
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 |
|---|---|---|
|
|
@@ -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 | ||
|
|
@@ -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...) | ||
|
|
@@ -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 | ||
| # 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 | ||
|
|
||
|
|
@@ -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.
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 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 | ||
|
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""" | ||
|
|
@@ -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`. | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.