From 585d5507202cb2bd1cf5891033e39bda43b41f3a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 05:57:55 +0000 Subject: [PATCH 01/10] Take ranges and lazy wrappers in the rule; name every other stopped call A call whose kernel, coupling, parameter, input or history is a range, or a PermutedDimsArray, Symmetric or Hermitian of an Array, took plain AD with no message. Such a call now takes a third route that copies those leaves to Arrays outside the rule, so the backend differentiates the copy. A call the gate still stops (another array type, a field of abstract type, a part with no rule on device arrays) is named by the one-time notice, logged from the plain-AD hook that reverse-mode backends replace. Calls on number types no rule runs skip the hook as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- docs/src/explanation/adjoints-and-backends.md | 11 +- ext/ComposableRecurrencesEnzymeExt.jl | 9 +- ext/ComposableRecurrencesMooncakeExt.jl | 6 +- src/ComposableRecurrences.jl | 4 +- src/adjoints/adjoints.jl | 159 +++++++++++++++++- src/operators/recurrence.jl | 24 +-- src/operators/recurrence_adjoint.jl | 15 ++ src/operators/trace_run.jl | 3 + test/ad/adjoints.jl | 84 +++++++++ test/unit/adjoints.jl | 98 +++++++++++ test/unit/device_rules.jl | 3 + 11 files changed, 382 insertions(+), 34 deletions(-) diff --git a/docs/src/explanation/adjoints-and-backends.md b/docs/src/explanation/adjoints-and-backends.md index 07e8c490f..ce9f2d759 100644 --- a/docs/src/explanation/adjoints-and-backends.md +++ b/docs/src/explanation/adjoints-and-backends.md @@ -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) diff --git a/ext/ComposableRecurrencesEnzymeExt.jl b/ext/ComposableRecurrencesEnzymeExt.jl index d76a127ce..ab93d7d67 100644 --- a/ext/ComposableRecurrencesEnzymeExt.jl +++ b/ext/ComposableRecurrencesEnzymeExt.jl @@ -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 @@ -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} @@ -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( diff --git a/ext/ComposableRecurrencesMooncakeExt.jl b/ext/ComposableRecurrencesMooncakeExt.jl index fad10e955..a4161f076 100644 --- a/ext/ComposableRecurrencesMooncakeExt.jl +++ b/ext/ComposableRecurrencesMooncakeExt.jl @@ -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 @@ -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} @@ -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 diff --git a/src/ComposableRecurrences.jl b/src/ComposableRecurrences.jl index 5cee66b21..89e72a1a2 100644 --- a/src/ComposableRecurrences.jl +++ b/src/ComposableRecurrences.jl @@ -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 diff --git a/src/adjoints/adjoints.jl b/src/adjoints/adjoints.jl index bd39edfbc..769d42f78 100644 --- a/src/adjoints/adjoints.jl +++ b/src/adjoints/adjoints.jl @@ -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) + +# 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 +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`. diff --git a/src/operators/recurrence.jl b/src/operators/recurrence.jl index d16efaa69..a4cb3311d 100644 --- a/src/operators/recurrence.jl +++ b/src/operators/recurrence.jl @@ -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...) diff --git a/src/operators/recurrence_adjoint.jl b/src/operators/recurrence_adjoint.jl index 3b177ddde..93f08758f 100644 --- a/src/operators/recurrence_adjoint.jl +++ b/src/operators/recurrence_adjoint.jl @@ -177,6 +177,21 @@ end function _device_ready(r::Recurrence{<:Union{Pairwise, TimeVarying{<:Any, <:Pairwise}}}) return _device_coupling(r.coupling) && _device_modifiers(r.modifiers) end +# Names the parts that keep a recurrence from the rule on device arrays. +function _device_whys(r::Recurrence) + C = r.coupling + out = String[] + _device_coupling(C) || + push!(out, "the coupling, a $(typeof(C)), has no rule on device arrays") + foreach(r.modifiers) do m + _device_modifier(m) || + push!(out, "$(nameof(typeof(m))) has no rule on device arrays") + end + isempty(out) || return out + K = nameof(typeof(r.kernel)) + return ["the kernel, a $K, has no rule on device arrays"] +end +_device_whys(w::_WithState) = _device_whys(w.r) _device_coupling(C) = false _device_coupling(::Union{UniformScaling, Diagonal}) = true _device_coupling(C::AbstractMatrix) = _on_gpu(C) diff --git a/src/operators/trace_run.jl b/src/operators/trace_run.jl index bed15076f..1596706e4 100644 --- a/src/operators/trace_run.jl +++ b/src/operators/trace_run.jl @@ -20,6 +20,9 @@ _nmodifiers(w::_WithState) = _nmodifiers(w.r) uses_adjoint(w::_WithTrace, ::Run) = uses_adjoint(w.op, Run()) _type_adjoint(w::_WithTrace) = _type_adjoint(w.op) _device_ready(w::_WithTrace) = _device_ready(w.op) +_plain_what(w::_WithTrace) = _plain_what(w.op) +_plain_whys(w::_WithTrace) = _plain_whys(w.op) +_device_whys(w::_WithTrace) = _device_whys(w.op) function _run_forward(w::_WithTrace, gain, add, h, s0, τ0, stop) y, cache = _run_forward(w.op, gain, add, h, s0, τ0, stop, Val(:traced)) diff --git a/test/ad/adjoints.jl b/test/ad/adjoints.jl index 3a81ecaeb..ad45bccad 100644 --- a/test/ad/adjoints.jl +++ b/test/ad/adjoints.jl @@ -2823,3 +2823,87 @@ end @test _PULLBACK_CALLS[] > n0 end end + +@testitem "Lazy host arrays take the rule; other containers are named once" tags = [:ad, :mooncake, :mooncake_reverse, :enzyme, :enzyme_reverse] setup = [JobBackends] begin + using ComposableRecurrences, LinearAlgebra, SparseArrays + using ComposableRecurrences: ComposableRecurrences as CR + using ADTypes: AutoMooncake, AutoEnzyme + using DifferentiationInterface: gradient + import Enzyme, Mooncake, ForwardDiff + # An array type the rule does not know; one per backend, as the note is + # logged once per message. + struct WrappedM{T} <: AbstractVector{T} + x::Vector{T} + end + struct WrappedE{T} <: AbstractVector{T} + x::Vector{T} + end + for W in (WrappedM, WrappedE) + @eval Base.size(v::$W) = size(v.x) + @eval Base.getindex(v::$W, i::Int) = v.x[i] + end + struct Loss{F} + model::F + end + function (l::Loss)(θ) + r, x, h = l.model(θ) + return sum(abs2, r(x; history = h)) + end + g, R, h = [0.5, 0.3, 0.2], fill(1.1, 2, 6), ones(2, 3) + span(θ, n) = range(θ[1], θ[2]; length = n) + depletion(N) = CR.Depletion(PerStratum(N)) + # Each model holds θ in a range or a lazy wrapper, as a kernel, a + # parameter, an input, a history or a coupling. + lazy = ( + θ -> (Recurrence(span(θ, 3)), R, h), + θ -> (Recurrence(LinRange(θ[1], θ[2], 3)), R, h), + θ -> (Recurrence(g; modifiers = (depletion(span(80 .* θ, 2)),)), R, h), + θ -> (Recurrence(g), span(θ, 6), ones(3)), + θ -> (Recurrence(g), reshape(span(θ, 12), 2, 6), h), + θ -> (Recurrence(g), PermutedDimsArray(θ[1] .* fill(θ[2], 6, 2), (2, 1)), h), + θ -> (Recurrence(g), fill(1.1, 6), span(θ, 3)), + θ -> (Recurrence(g; coupling = Diagonal(span(θ, 2))), R, h), + θ -> (Recurrence(g; coupling = Symmetric([θ[1] 0.1; 0.3 θ[2]])), R, h), + ) + θ = [0.4, 0.7] + for (W, backend) in job_backends( + :mooncake_reverse => (WrappedM, AutoMooncake(; config = nothing)), + :enzyme_reverse => ( + WrappedE, + AutoEnzyme(; + mode = Enzyme.set_runtime_activity(Enzyme.Reverse), + function_annotation = Enzyme.Const + ), + ), + ) + @testset "lazy model $i" for (i, model) in enumerate(lazy) + l = Loss(model) + calls = CR._PULLBACK_CALLS[] + got = @test_logs gradient(l, backend, θ) + @test got ≈ ForwardDiff.gradient(l, θ) rtol = 1.0e-8 + @test CR._PULLBACK_CALLS[] > calls + end + # A container the rule does not take: plain AD, with its field and + # type named once. + told = ( + θ -> (Recurrence(W([θ[1], θ[2], 0.1])), R, h), + θ -> ( + Recurrence(g; coupling = Symmetric(sparse([θ[1] 0.1; 0.1 θ[2]]))), + R, h, + ), + ) + names = (Regex("kernel is a .*$(nameof(W))"), r"coupling is a .*Symmetric") + empty!(CR._PLAIN_NOTED) + empty!(CR._PLAIN_SEEN) + @testset "named container $i" for (i, model) in enumerate(told) + l = Loss(model) + calls = CR._PULLBACK_CALLS[] + got = @test_logs (:info, names[i]) match_mode = :any gradient(l, backend, θ) + @test got ≈ ForwardDiff.gradient(l, θ) rtol = 1.0e-8 + @test CR._PULLBACK_CALLS[] == calls + @test_logs gradient(l, backend, θ) + end + end + # Dual numbers take plain AD by design, with nothing logged. + @test_logs ForwardDiff.gradient(Loss(first(lazy)), θ) +end diff --git a/test/unit/adjoints.jl b/test/unit/adjoints.jl index 51adbe123..dcbb6164f 100644 --- a/test/unit/adjoints.jl +++ b/test/unit/adjoints.jl @@ -1865,3 +1865,101 @@ end @test all(iszero, H[1:2, :]) end end + +@testitem "Adjoint: lazy host arrays reach the rule as arrays" setup = [AdjointCheck] begin + using ComposableRecurrences, ForwardDiff, LinearAlgebra, SparseArrays + V, M = Vector{Float64}, Matrix{Float64} + span = typeof(range(0.1, 0.3; length = 3)) + # A range or a wrapper of an array becomes the `Array` of its values; + # a struct follows its type parameters. + for (T, D) in ( + (span, V), (typeof(LinRange(0.1, 0.3, 3)), V), + (typeof(reshape(range(0.0, 1.0; length = 4), 2, 2)), M), + (typeof(PermutedDimsArray(ones(2, 3), (2, 1))), M), + (typeof(Symmetric(ones(2, 2))), M), (typeof(Hermitian(ones(2, 2))), M), + (typeof(view(range(0.0, 1.0; length = 4), 2:3)), V), + (Diagonal{Float64, span}, Diagonal{Float64, V}), + (PerStratum{span}, PerStratum{V}), (Tuple{span, Int}, Tuple{V, Int}), + ) + @test CR._dense_type(T) === D + end + # Unchanged: what the gate takes as it is, sparse storage and an abstract + # type. + D1 = ForwardDiff.Dual{Nothing, Float64, 1} + for T in ( + V, typeof(view(ones(4), 2:3)), typeof(Symmetric(sparse(ones(2, 2)))), + BitVector, AbstractVector, + ) + @test CR._dense_type(T) === T + end + # A struct that fixes its field's type cannot hold the array. + struct FixedSpan + x::typeof(range(0.1, 0.3; length = 3)) + end + @test CR._dense_type(FixedSpan) === FixedSpan + g, R, h = [0.5, 0.3, 0.2], fill(1.1, 2, 6), ones(2, 3) + depletion(N) = CR.Depletion(PerStratum(N)) + dense = Recurrence(g; coupling = [0.9 0.1; 0.1 0.9], modifiers = (depletion([80.0, 90.0]),)) + lazy = Recurrence( + range(0.5, 0.2; length = 3); + coupling = Symmetric([0.9 0.1; 0.3 0.9]), + modifiers = (depletion(80.0:10.0:90.0),) + ) + args = recargs(PermutedDimsArray(permutedims(R), (2, 1)), nothing, h) + @test (@inferred CR._route_val(lazy, args...)) === Val(:dense) + @test (@inferred CR._route_val(dense, recargs(R, nothing, h)...)) === Val(:rule) + op, rest... = @inferred CR._dense(lazy, args...) + @test op.kernel isa V && op.coupling isa M && first(rest) isa M + @test only(op.modifiers) isa typeof(only(dense.modifiers)) + @test CR._gate(op, rest...) + @test CR.adjoint_call(lazy, args...) == CR.adjoint_call(op, rest...) + # Dual numbers in a range stay plain, with no copy. + dual = Recurrence(range(D1(0.5), D1(0.2); length = 3)) + @test CR._route_val(dual, recargs(R, nothing, h)...) === Val(:plain) + @test !CR._hooked(dual, recargs(R, nothing, h)...) +end + +@testitem "Adjoint: a call the gate stops names what stopped it" setup = [AdjointCheck] begin + using ComposableRecurrences, ForwardDiff, LinearAlgebra, SparseArrays + struct Wrapped{T} <: AbstractVector{T} + x::Vector{T} + end + Base.size(v::Wrapped) = size(v.x) + Base.getindex(v::Wrapped, i::Int) = v.x[i] + g, R, h = [0.5, 0.3, 0.2], fill(1.1, 2, 6), ones(2, 3) + args = recargs(R, nothing, h) + r = Recurrence(Wrapped(g)) + @test CR._route_val(r, args...) === Val(:plain) + @test CR._hooked(r, args...) + @test only(CR._stopped_whys(r, args...)) == + "Recurrence.kernel is a $(Wrapped{Float64}), which the rule does not " * + "take: pass an Array" + # Once per signature, and once per message. + empty!(CR._PLAIN_NOTED) + empty!(CR._PLAIN_SEEN) + @test_logs (:info, r"plain AD of the whole operator: Recurrence.kernel") CR._note_stopped(r, args...) + @test_logs CR._note_stopped(r, args...) + @test_logs CR._note_stopped(CR.NoAdjoint(r), args...) + # An argument is named by its position, a nested field by its path. + lazy = recargs(Wrapped(fill(1.1, 6)), nothing, ones(3)) + @test occursin("argument 1 is a", only(CR._stopped_whys(Recurrence(g), lazy...))) + sparse_c = Recurrence(g; coupling = Symmetric(sparse([0.9 0.1; 0.1 0.9]))) + @test occursin(r"Recurrence\.coupling is a .*Symmetric", only(CR._stopped_whys(sparse_c, args...))) + nested = Recurrence(g; modifiers = (CR.Depletion(PerStratum(Wrapped([80.0, 90.0]))),)) + @test occursin(r"Recurrence\.modifiers\.1\..*is a ", only(CR._stopped_whys(nested, args...))) + # A field of abstract type is named as such. + struct Loose + x::AbstractVector{Float64} + end + out = CR._stopped!(String[], Loose, "Loose") + @test only(out) == "Loose.x is of type AbstractVector{Float64}, which is not concrete" + # A recurrence without a rule gives its construction-time reasons, and + # nothing is logged for a number type no rule runs. + struct Scaled + a::Float64 + end + CR.forward!(m::Scaled, ::CR.Step, v, s, t) = (v .*= m.a; nothing) + plain = Recurrence(g; modifiers = (Scaled(0.9),)) + @test CR._stopped_whys(plain, args...) == CR._plain_whys(plain) + @test !CR._hooked(Recurrence(g), recargs(big.(R), nothing, h)...) +end diff --git a/test/unit/device_rules.jl b/test/unit/device_rules.jl index 96b9230c9..e6727e90c 100644 --- a/test/unit/device_rules.jl +++ b/test/unit/device_rules.jl @@ -982,6 +982,9 @@ end ) op, args = modified_case((DevVectorPairs(0.9),), 4, true) @test inferred_route(op, args...) === Val(:plain) + # The notice names the modifier that has no rule on the device. + @test CR._stopped_whys(op, args...) == + ["DevVectorPairs has no rule on device arrays"] @testset "$name, $S strata" for (name, (ms, how)) in cases, S in (4, many) op, args = modified_case(ms(S), S, true) @test CR._route_val(CR._WithTrace(op), args...) === Val(how) From 0684fc1c91905140d95337285527755d918776d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:13:20 +0000 Subject: [PATCH 02/10] Read a step's outputs from the records in the generic trace pullback The pullback of a user's trace evaluated step once more at each stratum and time to get the step's outputs. The reverse pass already holds them: the value is the next modifier's record or the output, and the state is the next step's record or the final state, which the traced record now carries. Calls that record no trace build no traced record and read nothing more. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- benchmark/parity.jl | 1 - src/depletion/pool.jl | 2 +- src/interface/trace.jl | 8 ++-- src/operators/recurrence_adjoint.jl | 9 ++-- src/operators/trace_run.jl | 68 +++++++++++++++++++---------- test/unit/method_lookups.jl | 5 ++- test/unit/trace.jl | 3 +- 7 files changed, 62 insertions(+), 34 deletions(-) diff --git a/benchmark/parity.jl b/benchmark/parity.jl index 55f9b7fb4..002e84ec7 100644 --- a/benchmark/parity.jl +++ b/benchmark/parity.jl @@ -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)) diff --git a/src/depletion/pool.jl b/src/depletion/pool.jl index cc664a323..554984395 100644 --- a/src/depletion/pool.jl +++ b/src/depletion/pool.jl @@ -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 diff --git a/src/interface/trace.jl b/src/interface/trace.jl index c6433f082..129383de6 100644 --- a/src/interface/trace.jl +++ b/src/interface/trace.jl @@ -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̄′ diff --git a/src/operators/recurrence_adjoint.jl b/src/operators/recurrence_adjoint.jl index 93f08758f..065cbb002 100644 --- a/src/operators/recurrence_adjoint.jl +++ b/src/operators/recurrence_adjoint.jl @@ -47,7 +47,8 @@ function pullback!(grads, w::_WithTrace, ::Run, c) inner = (; piece = cotangent(grads.piece, :op), y = ȳ, args = grads.args) quiet = _zero_trace(Q̄) _zero_trace(T̄s) && quiet && return pullback!(inner, w.op, Run(), c) - rec = _zero_trace(T̄s) ? c.rec : _traced_records(c.rec, T̄s, c.S) + rec = _zero_trace(T̄s) ? c.rec : + _traced_records(c.rec, T̄s, c.states, c.S) pr = quiet ? c.pr : merge(c.pr, (; Q̄ = _strata_rows(Q̄))) return pullback!(inner, w.op, Run(), _with_fields(c, (; rec, pr))) end @@ -457,7 +458,9 @@ end function _series_stage_back!(::Val{true}, m, m̄, rec, s̄, v̄, τ, t, k, y) R = first(rec) vk, sk = R.V[k, t], _state_at(R.S, k, t) - v̄, s̄k, a, b = _trace_out(R, m, m̄, v̄, s̄[k], vk, sk, τ, t, k) + v̄, s̄k, a, b = _trace_out( + R, m, m̄, v̄, s̄[k], vk, sk, τ, t, k, Base.tail(rec), y + ) g = _with_output( Val(_wants_output(m)), (; piece = m̄, v = v̄, s = s̄k), Base.tail(rec), y, t, k @@ -747,7 +750,7 @@ function _stages_back!(ms::Tuple, m̄s, rec, s̄s, bufs, v̄, τ, t, y) ) R, m, m̄, s̄ = first(rec), first(ms), first(m̄s), first(s̄s) v, s = view(R.V, :, t), _states_at(R.S, t) - _trace_out!(R, m, m̄, v̄, s̄, v, s, τ, t) + _trace_out!(R, m, m̄, v̄, s̄, v, s, τ, t, Base.tail(rec), y) g = _with_output( Val(_wants_output(m)), _step_grads(m̄, v̄, s̄, R.A, first(bufs), t), Base.tail(rec), y, t, : diff --git a/src/operators/trace_run.jl b/src/operators/trace_run.jl index 1596706e4..2a6492836 100644 --- a/src/operators/trace_run.jl +++ b/src/operators/trace_run.jl @@ -205,38 +205,51 @@ _outputs_at(rec::Tuple, H, D, t) = view(first(rec).V, :, t) # == Reverse pass == # A modifier's records with its trace cotangent `T̄` and the buffers for the -# cotangents its trace sends to the step's inputs. `live` is false for an +# cotangents its trace sends to the step's inputs. `F` is the state after +# the last step, which no later step records. `live` is false for an # all-zero `T̄`, as a loss that reads another modifier's trace gives. -const _TracedRecord = NamedTuple{(:V, :S, :A, :T̄, :V̄, :S̄, :live)} -_traced_records(rec, ::Nothing, S) = rec -function _traced_records(rec, T̄s::Tuple, S) - return map((R, T̄) -> _traced_record(R, T̄, S), rec, T̄s) +const _TracedRecord = NamedTuple{(:V, :S, :A, :T̄, :V̄, :S̄, :F, :live)} +_traced_records(rec, ::Nothing, finals, S) = rec +function _traced_records(rec, T̄s::Tuple, finals, S) + return map((R, T̄, F) -> _traced_record(R, T̄, F, S), rec, T̄s, finals) end -_traced_record(R, ::Nothing, S) = R -function _traced_record(R, T̄, S) +_traced_record(R, ::Nothing, F, S) = R +function _traced_record(R, T̄, F, S) return (; R..., T̄, V̄ = _zeros(R.V, eltype(R.V), S), - S̄ = zero(_states_at(R.S, 1)), live = !iszero(T̄), + S̄ = zero(_states_at(R.S, 1)), F, live = !iszero(T̄), ) end +# The state after step `t`: the next step's recorded state, or the final +# one. A step's value after it is the next modifier's record (`_output_at`). +Base.@propagate_inbounds function _state_after(R, k, t) + return t < size(R.V, 2) ? _state_at(R.S, k, t + 1) : R.F[k] +end # `_trace_out` adds the trace's share of the step's output cotangents and # returns its share of the inputs', which `_trace_in` adds after the pullback. -_trace_out(R, m, m̄, v̄, s̄, v, s, τ, t, k) = v̄, s̄, nothing, nothing +# `rest` and `y` give the step's value after it; only a traced record reads +# them. +function _trace_out(R, m, m̄, v̄, s̄, v, s, τ, t, k, rest, y) + return v̄, s̄, nothing, nothing +end function _trace_out(R::_TracedRecord, m, args...) return _trace_out(Val(isstateless(m)), R, m, args...) end # A modifier whose state never changes has no trace, so no cotangent. -function _trace_out(::Val{true}, R, m, m̄, v̄, s̄, v, s, τ, t, k) +function _trace_out(::Val{true}, R, m, m̄, v̄, s̄, v, s, τ, t, k, rest, y) return v̄, s̄, nothing, nothing end # At stratum `k`, from its entries of the trace's cotangent. -@inline function _trace_out(::Val{false}, R, m, m̄, v̄, s̄, v, s, τ, t, k) +@inline function _trace_out( + ::Val{false}, R, m, m̄, v̄, s̄, v, s, τ, t, k, rest, y + ) z = zero(v̄) R.live || return v̄ + z, s̄ + z, z, z S = length(R.V̄) r̄ = _gather(view(R.T̄, :, t), Val(ntrace(m, 1)), S, k) - a, b, c, d = @inline _unit_trace_back(m̄, m, r̄, v, s, τ, k) + v′, s′ = _output_at(rest, y, t, k), _state_after(R, k, t) + a, b, c, d = @inline _unit_trace_back(m̄, m, r̄, v, s, v′, s′, τ, k) return v̄ + c, s̄ + d, z + a, z + b end _trace_in(::Nothing, x̄) = x̄ @@ -245,12 +258,19 @@ _trace_in(a, x̄) = x̄ + a # The same for a vector-level step, with the inputs' share in the record's # buffers. A trace that is the state after the step (`_trace_is_state`) is # added into `s̄` alone. -_trace_out!(R, m, m̄, v̄, s̄, v, s, τ, t) = nothing +_trace_out!(R, m, m̄, v̄, s̄, v, s, τ, t, rest, y) = nothing _trace_is_state(m) = _whole_step(m) && !_has_whole_trace(m) -function _trace_out!(R::_TracedRecord, m, m̄, v̄, s̄, v, s, τ, t) +function _trace_out!(R::_TracedRecord, m, m̄, v̄, s̄, v, s, τ, t, rest, y) (isstateless(m) || !R.live) && return nothing _trace_is_state(m) && return _add_trace_column!(s̄, R.T̄, t) - _trace_back!(R, m, m̄, v̄, s̄, view(R.T̄, :, t), v, s, τ) + r̄, v′ = view(R.T̄, :, t), _output_at(rest, y, t, :) + # The final state on its own, so each call sees one type. + if t < size(R.V, 2) + s′ = _states_at(R.S, t + 1) + _trace_back!(R, m, m̄, v̄, s̄, r̄, v, s, v′, s′, τ) + else + _trace_back!(R, m, m̄, v̄, s̄, r̄, v, s, v′, R.F, τ) + end return nothing end # An `Allocate` with imports records its state, then the imports. While a @@ -258,7 +278,7 @@ end # cotangent, as a state trace does, and its buffers stay zero for # `_trace_in!`. function _trace_out!( - R::_TracedRecord, m::_TracedImports, m̄, v̄, s̄, v, s, τ, t + R::_TracedRecord, m::_TracedImports, m̄, v̄, s̄, v, s, τ, t, rest, y ) R.live || return nothing n, col = length(s̄), view(R.T̄, :, t) @@ -268,7 +288,7 @@ function _trace_out!( R.S̄ .= zero(eltype(R.S̄)) return nothing end - _trace_back!(R, m, m̄, v̄, s̄, col, v, s, τ, _column(R.A, t)) + _trace_back!(R, m, m̄, v̄, s̄, col, v, s, nothing, nothing, τ, _column(R.A, t)) return nothing end _trace_in!(R, m, v̄, s̄) = nothing @@ -298,8 +318,9 @@ end # cotangents. Those that share a parameter add into stacked copies of its # cotangent, as their step pullbacks do. `after` is the state after the step # where the run kept it (`_keeps_after`), so a whole-step pullback need not -# compute it again. -function _trace_back!(R, m, m̄, v̄, s̄, r̄, v, s, τ, after = nothing) +# compute it again. `v′` and `s′` are the step's outputs from the records, +# which a stratum's or group's pullback reads. +function _trace_back!(R, m, m̄, v̄, s̄, r̄, v, s, v′, s′, τ, after = nothing) R.V̄ .= zero(eltype(R.V̄)) R.S̄ .= zero(eltype(R.S̄)) if _whole_step(m) @@ -314,19 +335,22 @@ function _trace_back!(R, m, m̄, v̄, s̄, r̄, v, s, τ, after = nothing) accs = _accumulators(Serial(), v, G, G, _param_slots(m̄, m)) R̄ = (; V̄ = R.V̄, S̄ = R.S̄) _reduce_blocks!( - _trace_back_blocks!, accs, G, R̄, v̄, s̄, r̄, v, s, τ, m, B, G + _trace_back_blocks!, accs, G, R̄, v̄, s̄, r̄, v, s, v′, s′, τ, m, B, G ) _reduce!(accs) return nothing end -function _trace_back_blocks!(gs, acc, R̄, v̄, s̄, r̄, v, s, τ, m, B, G) +function _trace_back_blocks!( + gs, acc, R̄, v̄, s̄, r̄, v, s, v′, s′, τ, m, B, G + ) m̄ = _unown(acc) nv, ns = _trace_shape(B) V, Σ = Val(nv), Val(ns) for g in gs r̄g = _gather(r̄, Val(ntrace(m, nv)), G, g) a, b, c, d = @inline _unit_trace_back( - m̄, m, r̄g, _unit_of(B, v, V, G, g), _unit_of(B, s, Σ, G, g), τ, g + m̄, m, r̄g, _unit_of(B, v, V, G, g), _unit_of(B, s, Σ, G, g), + _unit_of(B, v′, V, G, g), _unit_of(B, s′, Σ, G, g), τ, g ) _add_unit!(B, R̄.V̄, a, V, G, g) _add_unit!(B, R̄.S̄, b, Σ, G, g) diff --git a/test/unit/method_lookups.jl b/test/unit/method_lookups.jl index 0d83b4984..e8599a5e0 100644 --- a/test/unit/method_lookups.jl +++ b/test/unit/method_lookups.jl @@ -76,8 +76,9 @@ end CR.trace(::Moved, θ, v, s, v′, s′) = s′ m = Moved(0.3) r̄ = (0.7,) + v, s = (1.0, 2.0), (0.5,) v̄, s̄, v̄′, s̄′ = CR._unit_trace_back( - nothing, m, r̄, (1.0, 2.0), (0.5,), 1, 1 + nothing, m, r̄, v, s, CR.step(m, (; a = 0.3), v, s)..., 1, 1 ) @test v̄ == (0.0, 0.0) @test s̄ == (0.0,) @@ -90,7 +91,7 @@ end CR.step(::Kept, θ, v, s) = (θ.a * v, s + v) CR.init(::Kept, θ, history) = 0 CR.trace(::Kept, θ, v, s, v′, s′) = (s′,) - @test CR._unit_trace_back(nothing, Kept(0.3), r̄, 1.0, 0.5, 1, 1) == + @test CR._unit_trace_back(nothing, Kept(0.3), r̄, 1.0, 0.5, 0.3, 1.5, 1, 1) == (0.0, 0.0, 0.0, 0.7) # Through a call: the gradient of a loss on the trace. function loss(a) diff --git a/test/unit/trace.jl b/test/unit/trace.jl index a037ab04f..2c8e22893 100644 --- a/test/unit/trace.jl +++ b/test/unit/trace.jl @@ -344,8 +344,7 @@ end piece = (; pieces = (map(_ -> (; demand = Ref(0.0), form = nothing), only(m.pieces)),), ) - v, s = parts(z) - x̄ = CR._unit_trace_back(piece, m, Tuple(r̄), v, s, 1, 1) + x̄ = CR._unit_trace_back(piece, m, Tuple(r̄), parts(z)..., 1, 1) d̄ = [f̄.demand[] for f̄ in only(piece.pieces)] @test [reduce(vcat, map(collect, x̄)); d̄] ≈ ref end From ba759a12e89ba2cc7e5dda53da9970bbf29ff42a Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:38:16 +0000 Subject: [PATCH 03/10] Skip zero partials in the dual pass's contraction The local derivative of a step or trace is a sum of cotangents times partials. A partial the compiler knows to be zero still cost a product, as the cotangent may be NaN. A zero partial now adds nothing, as in a pullback written by hand, so those terms fold away. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- src/interface/duals.jl | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/src/interface/duals.jl b/src/interface/duals.jl index a4a14248c..a6fdbf189 100644 --- a/src/interface/duals.jl +++ b/src/interface/duals.jl @@ -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} From 680f0266d0e73e6eb6e775771d1fea3a45666cb7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 06:39:43 +0000 Subject: [PATCH 04/10] Test the zero-partial rule; correct the page's account of the trace row Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- docs/src/developer/extending-performance.md | 5 +++-- test/unit/pure_step.jl | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/docs/src/developer/extending-performance.md b/docs/src/developer/extending-performance.md index a6c771dad..32f0f5f3b 100644 --- a/docs/src/developer/extending-performance.md +++ b/docs/src/developer/extending-performance.md @@ -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. diff --git a/test/unit/pure_step.jl b/test/unit/pure_step.jl index 52e97a826..142581bcd 100644 --- a/test/unit/pure_step.jl +++ b/test/unit/pure_step.jl @@ -665,3 +665,21 @@ end @test agree(p̄1, p̄0) end end + +@testitem "Pure step: a zero partial adds nothing to a cotangent" begin + using ComposableRecurrences + CR = ComposableRecurrences + # Each output reads one input, so each input's cotangent is that of its + # own output, whatever the other's: a `NaN` or `Inf` cotangent does not + # reach an input its output does not read. + f(z) = (2 * z[1], 3 * z[2]) + @test CR._dual_back(f, (1.0, 1.0), (NaN, 1.0)) === (NaN, 3.0) + @test CR._dual_back(f, (1.0, 1.0), (1.0, Inf)) === (2.0, Inf) + # A partial that is zero at the point, not by structure, adds nothing + # either. + g(z) = (z[1] * z[2],) + @test CR._dual_back(g, (0.0, 2.0), (Inf,)) === (Inf, 0.0) + # A `NaN` partial still shows. + h(z) = (NaN * z[1], z[2]) + @test isnan(first(CR._dual_back(h, (1.0, 1.0), (1.0, 1.0)))) +end From 69ba041e01d35c13f31894d51416ae4f7a5266b7 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:30:53 +0000 Subject: [PATCH 05/10] Keep the dual pass's IEEE contraction; pin it with a test Skipping zero partials made a zero partial times a NaN or infinite cotangent zero. Where the partial is zero by value, as for x^2 at zero, every other route gives NaN there, so the change could hide a NaN that a hand pullback, Mooncake, Enzyme and ForwardDiff all show. The contraction is as it was: the local derivative is the step on dual numbers and follows forward mode. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- src/interface/duals.jl | 10 ++-------- test/unit/pure_step.jl | 24 +++++++++++------------- 2 files changed, 13 insertions(+), 21 deletions(-) diff --git a/src/interface/duals.jl b/src/interface/duals.jl index a6fdbf189..a4a14248c 100644 --- a/src/interface/duals.jl +++ b/src/interface/duals.jl @@ -107,14 +107,8 @@ 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. -# 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::Dual{G}, ȳ, j, ::Type{G}) where {G} = + ȳ * @inbounds(ForwardDiff.partials(y, j)) @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} diff --git a/test/unit/pure_step.jl b/test/unit/pure_step.jl index 142581bcd..46b4026cd 100644 --- a/test/unit/pure_step.jl +++ b/test/unit/pure_step.jl @@ -666,20 +666,18 @@ end end end -@testitem "Pure step: a zero partial adds nothing to a cotangent" begin +@testitem "Pure step: a non-finite cotangent reaches every input" begin using ComposableRecurrences CR = ComposableRecurrences - # Each output reads one input, so each input's cotangent is that of its - # own output, whatever the other's: a `NaN` or `Inf` cotangent does not - # reach an input its output does not read. + # The local derivative is the step on dual numbers, so it follows IEEE + # arithmetic as forward mode does: a zero partial times a `NaN` or + # infinite cotangent is `NaN`, and no such cotangent is dropped. A + # pullback written by hand, or a reverse-mode backend, leaves an input + # the output does not read untouched. f(z) = (2 * z[1], 3 * z[2]) - @test CR._dual_back(f, (1.0, 1.0), (NaN, 1.0)) === (NaN, 3.0) - @test CR._dual_back(f, (1.0, 1.0), (1.0, Inf)) === (2.0, Inf) - # A partial that is zero at the point, not by structure, adds nothing - # either. - g(z) = (z[1] * z[2],) - @test CR._dual_back(g, (0.0, 2.0), (Inf,)) === (Inf, 0.0) - # A `NaN` partial still shows. - h(z) = (NaN * z[1], z[2]) - @test isnan(first(CR._dual_back(h, (1.0, 1.0), (1.0, 1.0)))) + g = CR._dual_back(f, (1.0, 1.0), (Inf, 1.0)) + @test first(g) == Inf + @test isnan(last(g)) + # A partial that is zero at the point is the same. + @test all(isnan, CR._dual_back(z -> (z[1]^2, z[2]), (0.0, 1.0), (Inf, 1.0))) end From 7e6061ddbb99c35f09350ea698d4de869da46f23 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:33:11 +0000 Subject: [PATCH 06/10] Do not name a lazy array the rule would copy as what stops a call Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- src/adjoints/adjoints.jl | 15 +++++++++------ test/unit/adjoints.jl | 4 ++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/src/adjoints/adjoints.jl b/src/adjoints/adjoints.jl index 769d42f78..b2836a5b6 100644 --- a/src/adjoints/adjoints.jl +++ b/src/adjoints/adjoints.jl @@ -260,9 +260,9 @@ end _plain(op, args...) = _primal(op, args...) # 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. +# the call takes plain AD (`_note_stopped`). Calls holding a number type no +# backend with a rule runs (a dual number, say) skip it, as the call boxes +# its arguments. @noinline _plain_hook(op, args...) = (Base.donotdelete(op, args...); nothing) function _hooked_plain(op, args::Vararg{Any, N}) where {N} _hooked(op, args...) && _plain_hook(op, args...) @@ -296,7 +296,8 @@ end @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. +# real number of a concrete type other than an IEEE float or an integer. A +# real number of abstract type may be either, so it passes. function _numbers_ok(::Type{T}) where {T} T <: Union{_IEEEFloat, Integer} && return true T <: Real && return !isconcretetype(T) @@ -387,7 +388,8 @@ _first_time!(seen, x) = x in seen ? false : (push!(seen, x); true) # 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. +# call after the first of a signature, whose type is kept for the session, +# as its compiled methods are. 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) @@ -414,7 +416,8 @@ _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 + # A lazy array the rule would copy is not what stops the call. + _ok(_dense_type(T)) && return out if !(isconcretetype(T) && isstructtype(T)) || T <: Union{Real, AbstractArray} return push!(out, "$label is $(_stopped_why(T))") end diff --git a/test/unit/adjoints.jl b/test/unit/adjoints.jl index dcbb6164f..24dab7906 100644 --- a/test/unit/adjoints.jl +++ b/test/unit/adjoints.jl @@ -1947,6 +1947,10 @@ end @test occursin(r"Recurrence\.coupling is a .*Symmetric", only(CR._stopped_whys(sparse_c, args...))) nested = Recurrence(g; modifiers = (CR.Depletion(PerStratum(Wrapped([80.0, 90.0]))),)) @test occursin(r"Recurrence\.modifiers\.1\..*is a ", only(CR._stopped_whys(nested, args...))) + # A range beside it, which the rule would copy, is not named. + both = Recurrence(range(0.5, 0.2; length = 3); coupling = sparse_c.coupling) + @test CR._route_val(both, args...) === Val(:plain) + @test occursin("coupling", only(CR._stopped_whys(both, args...))) # A field of abstract type is named as such. struct Loose x::AbstractVector{Float64} From 7e230a78b85381badbff73ca53d9508038d9e056 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 08:38:39 +0000 Subject: [PATCH 07/10] Regenerate the parity table Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- benchmark/results/parity.csv | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/benchmark/results/parity.csv b/benchmark/results/parity.csv index 85c1bfab6..ec2faac3a 100644 --- a/benchmark/results/parity.csv +++ b/benchmark/results/parity.csv @@ -1,16 +1,16 @@ dimension,agree,builtin_us,user_us,ratio,band,revision,julia,cpu,threads -forward run; 1 strata,true,7.34,7.33,1.00,1.00,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; 5 strata,true,19.05,19.75,1.04,1.04,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; 50 strata,true,179.92,179.63,1.00,1.01,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; Threaded; 50 strata,true,184.03,179.07,0.97,1.00,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; record = Trace(),true,23.19,23.95,1.03,1.02,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; resumed at half,true,19.85,20.79,1.05,1.04,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient; ForwardDiff,true,7168.87,6944.74,0.97,1.06,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient; Mooncake reverse,true,91.14,91.65,1.01,1.01,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient; Mooncake forward,true,71464.04,69065.35,0.97,1.07,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient; Enzyme reverse,true,76.23,74.23,0.97,1.01,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient; Enzyme forward,true,22130.08,21375.53,0.97,1.08,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient through Trace(); Mooncake reverse,true,101.83,113.95,1.12,1.06,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -gradient in a history of 400; Mooncake reverse,true,94.22,89.85,0.95,1.01,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -forward run; JLArray,true,1858.28,1852.82,1.00,1.55,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 -rule passes; JLArray,true,7098.88,7095.21,1.00,1.08,880c6024,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; 1 strata,true,7.35,7.32,1.00,1.00,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; 5 strata,true,18.93,19.43,1.03,1.02,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; 50 strata,true,179.66,180.74,1.01,1.00,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; Threaded; 50 strata,true,184.50,179.22,0.97,1.01,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; record = Trace(),true,23.58,24.11,1.02,1.02,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; resumed at half,true,20.45,20.57,1.01,1.03,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient; ForwardDiff,true,7103.10,6979.01,0.98,1.04,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient; Mooncake reverse,true,91.96,90.90,0.99,1.01,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient; Mooncake forward,true,71174.39,68766.02,0.97,1.17,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient; Enzyme reverse,true,77.43,75.22,0.97,1.02,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient; Enzyme forward,true,22307.05,21174.51,0.95,1.11,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient through Trace(); Mooncake reverse,true,108.10,114.61,1.06,1.01,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +gradient in a history of 400; Mooncake reverse,true,94.60,94.78,1.00,1.01,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +forward run; JLArray,true,1727.47,1803.77,1.04,1.09,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 +rule passes; JLArray,true,7352.25,7067.18,0.96,1.08,7e6061dd,1.13.4,Intel(R) Xeon(R) Processor @ 2.10GHz,4 From 695a6fce78e9e68404d0f252d25fa42dbb836bd3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 09:50:00 +0000 Subject: [PATCH 08/10] Add the Reactant results of the user copy of the hazard depletion The registry scenario had no rows in the results file, so the registry check of the smoke and reactant jobs failed. Both modes work. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- test/reactant/results.tsv | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/reactant/results.tsv b/test/reactant/results.tsv index cf6acba18..422d078b7 100644 --- a/test/reactant/results.tsv +++ b/test/reactant/results.tsv @@ -266,6 +266,8 @@ error NaN NaN NaN NaN MethodError - MethodError: no method matching SparseArrays error NaN NaN NaN NaN MethodError - MethodError: no method matching SparseArrays.SparseMatrixCSC(::Int64, ::Int64, ::Vector{Int64}, ::Vector{Int64}, ::Reactant.TracedRArray{Float64, 1}) The type `SparseArrays.SparseMatrixCSC` exists, but no method is defined for this combination of argument types when trying to construct it. Closest c Recurrence sparse user coupling declared linear reverse registry cpu 12 0.0 works 2.4e-15 2.6 11.7 2.9 Recurrence whole-step modifier declared linear forward registry cpu 12 0.0 works 5.0e-15 1.5 11.8 35.0 Recurrence whole-step modifier declared linear reverse registry cpu 12 0.0 +works 4.0e-16 55.5 38.9 3.3 Recurrence user copy of the hazard depletion forward registry cpu 12 0.0 +works 8.2e-15 4.1 84.2 93.8 Recurrence user copy of the hazard depletion reverse registry cpu 12 0.0 works 0.0e+00 8.8 4.0 0.1 control forward cases cpu 20 0.0 works 0.0e+00 5.0 4.2 0.6 control reverse cases cpu 20 0.0 works 2.0e-16 20.3 10.4 0.2 rec_single forward cases cpu 20 0.0 From 47038d3c834e38aaa0d82ebfbcbabc9d72fe1a0e Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 10:02:14 +0000 Subject: [PATCH 09/10] Rebuild the Reactant report with the new scenario's rows Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- test/reactant/RESULTS.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/reactant/RESULTS.md b/test/reactant/RESULTS.md index 34937b5a3..3bc345e18 100644 --- a/test/reactant/RESULTS.md +++ b/test/reactant/RESULTS.md @@ -86,6 +86,7 @@ Total run time 34.8 min, timeout 600 s a case. | Recurrence trace of a protected pool | works (2.9 s / 13.5 µs) | works (1.7 s / 101.2 µs) | | Recurrence trace of pointwise modifiers | works (4.0 s / 20.0 µs) | works (1.7 s / 16.8 µs) | | Recurrence default traces of user modifiers | works (5.3 s / 18.6 µs) | works (2.1 s / 79.6 µs) | +| Recurrence user copy of the hazard depletion | works (55.5 s / 38.9 µs) | works (4.1 s / 84.2 µs) | | Recurrence user traces on groups and over the whole step | works (5.1 s / 54.3 µs) | works (3.8 s / 68.1 µs) | | Recurrence trace of a ward's flows | works (5.1 s / 83.1 µs) | works (2.0 s / 109.2 µs) | | Recurrence trace of a weekly budget with a queue | works (3.5 s / 50.6 µs) | works (1.7 s / 91.8 µs) | @@ -441,6 +442,8 @@ Plain Julia is the call (forward) or `ForwardDiff.gradient` (reverse), on the CP | registry | Recurrence sparse user coupling declared linear | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | MethodError: no method matching SparseArrays.SparseMatrixCSC(::Int64, ::Int64, ::Vector{Int64}, ::Vector{Int64}, ::Reactant.TracedRArray{Float64, 1}) The type ` | | registry | Recurrence whole-step modifier declared linear | forward | cpu | 12 | works | 2.4e-15 | 2.6 | 11.7 | 2.9 | | | | registry | Recurrence whole-step modifier declared linear | reverse | cpu | 12 | works | 5.0e-15 | 1.5 | 11.8 | 35.0 | | | +| registry | Recurrence user copy of the hazard depletion | forward | cpu | 12 | works | 4.0e-16 | 55.5 | 38.9 | 3.3 | | | +| registry | Recurrence user copy of the hazard depletion | reverse | cpu | 12 | works | 8.2e-15 | 4.1 | 84.2 | 93.8 | | | | cases | control | forward | cpu | 20 | works | 0.0e+00 | 8.8 | 4.0 | 0.1 | | | | cases | control | reverse | cpu | 20 | works | 0.0e+00 | 5.0 | 4.2 | 0.6 | | | | cases | rec_single | forward | cpu | 20 | works | 2.0e-16 | 20.3 | 10.4 | 0.2 | | | From 42b153282a8d5ba8ccdb47fcdee05457ea1790a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 12:11:56 +0000 Subject: [PATCH 10/10] Make the user-copy registry scenario valid at every parameter value Its pool was the population less the seed, negative at the zero vector where Mooncake prepares its rule, so the loss took the log of a negative number. The pool is now the parameter and the population is the pool plus the seed. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8 --- test/ADFixtures/src/ADFixtures.jl | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/test/ADFixtures/src/ADFixtures.jl b/test/ADFixtures/src/ADFixtures.jl index 378faba0f..a3ee1c97c 100644 --- a/test/ADFixtures/src/ADFixtures.jl +++ b/test/ADFixtures/src/ADFixtures.jl @@ -1679,11 +1679,12 @@ end # A user's copy of the hazard depletion, with its pullback and its trace, # and the populations as parameters: what the built-in gives, through the -# public route alone. +# public route alone. The pool is positive at every `θ`, zero included, +# where a backend may prepare: the population is the pool plus the seed. function _hazard_copy(w, θ) - logh, logR, logN = _unpack(θ, (S4, L), (S4, T), (S4,)) - seed, N = exp.(logh), exp.(logN) - pool = N .- vec(sum(seed; dims = 2)) + logh, logR, logpool = _unpack(θ, (S4, L), (S4, T), (S4,)) + seed, pool = exp.(logh), exp.(logpool) + N = pool .+ vec(sum(seed; dims = 2)) m = HazardCopy(PerStratum(N), PerStratum(pool)) r = Recurrence(G0; modifiers = (m,)) y, tr = returning_trace(w(r), exp.(logR); history = seed)