Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 48 additions & 5 deletions ext/ComposableRecurrencesReactantExt.jl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module ComposableRecurrencesReactantExt

using ComposableRecurrences: ComposableRecurrences, Executor, Parallel, PerStratum, Primary,
using ComposableRecurrences: ComposableRecurrences, Depletion, Executor, Parallel,
PerStratum, Primary, Recurrence,
Secondary, Serial, TimeVarying, _BoundRecent, _CPUArray, _OldestFirstPiecewise, _Piecewise,
_ComputedKernel, _PointwiseCoupling, _Ragged, _array, _lagweight, _nlags,
_seg_weights, _steps!, _weight
Expand All @@ -16,12 +17,17 @@ using Reactant: Reactant, @allowscalar, @trace, AnyTracedRArray, AnyTracedRMatri
# loop is written out, one block a stratum, whose forward pass runs faster
# on the CPU than a kernel launch each step. The threshold is
# `TRACED_MIN_STRATA`. Without KernelAbstractions loaded every strata loop
# is written out.
# is written out. With `kernels_only` a loop that would be written out
# throws instead (see `_kernels_only` below).
struct Traced <: Executor
min_strata::Int
kernels_only::Bool
end
function Traced(; min_strata::Integer = ComposableRecurrences.TRACED_MIN_STRATA[])
return Traced(Int(min_strata))
function Traced(;
min_strata::Integer = ComposableRecurrences.TRACED_MIN_STRATA[],
kernels_only::Bool = false
)
return Traced(Int(min_strata), kernels_only)
end

# Reactant compiles a KernelAbstractions kernel through CUDA.jl, on every
Expand Down Expand Up @@ -61,6 +67,7 @@ ComposableRecurrences._kernel_arg(::Traced) = Serial()
@debug "traced loop written out" body n exception = e
end
end
ex.kernels_only && n > 0 && _written_out_gradient(backend)
for k in 1:n
@inline body(k, args...)
end
Expand Down Expand Up @@ -514,8 +521,44 @@ function ComposableRecurrences._run(
::Type{Tp}, r, gain, add, h, s0, τ0, L, D, S, T, cache::Val;
kwargs...
) where {Tp <: TracedRNumber}
ex = _kernels_only(r) ? Traced(; min_strata = 1, kernels_only = true) :
Traced()
return @allowscalar ComposableRecurrences._run(
Tp, Traced(), r, gain, add, h, s0, τ0, L, D, S, T, cache; kwargs...
Tp, ex, r, gain, add, h, s0, τ0, L, D, S, T, cache; kwargs...
)
end

# Under Reactant's AD, a recurrence with a kernel per stratum and a
# `Depletion` among its modifiers gets a wrong gradient, or one that does
# not compile, when its strata loops are written out one block a stratum;
# run as kernels, they give the right one (#983). Such a call runs every
# strata loop as a kernel, and a loop that cannot run as one throws rather
# than give a wrong gradient. The primal call is right either way, so it
# keeps the usual executor.
function _kernels_only(r)
return Reactant.Enzyme.within_autodiff() && _per_stratum_depletion(r)
end
_per_stratum_depletion(r) = false
function _per_stratum_depletion(r::Recurrence)
return r.kernel isa PerStratum && _any_depletion(r.modifiers)
end
_any_depletion(::Tuple{}) = false
function _any_depletion(ms::Tuple)
return first(ms) isa Depletion || _any_depletion(Base.tail(ms))
end
@noinline function _written_out_gradient(backend)
why = backend === nothing ?
"load `KernelAbstractions` and `CUDA` with " *
"`using KernelAbstractions, CUDA`, so its strata loops run as kernels" :
"this loop could not run as a kernel"
throw(
ArgumentError(
"Reactant's AD gives a wrong gradient for a Recurrence with a " *
"kernel per stratum (PerStratum) and a Depletion modifier " *
"when its strata loops are written out: $why. A kernel " *
"shared by the strata, or a gradient taken outside " *
"Reactant, does not need them"
)
)
end

Expand Down
12 changes: 3 additions & 9 deletions test/ADFixtures/src/registry.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3722,19 +3722,13 @@ const REACTANT_BROKEN_FORWARD = Dict(
)

# The scenarios whose traced call compiles and is right under Reactant while
# its gradient is wrong or does not compile, by cause. Each is a recurrence
# with a capacity, and each gradient is right with ReactantCore 0.1.26.
# its gradient does not compile, by cause. The capacity scenarios, a kernel
# per stratum with a depletion, take the right gradient by running their
# strata loops as kernels under Reactant's AD (#983).
const REACTANT_BROKEN_REVERSE = Dict(
# The gradient compiles and runs, and its values are wrong.
"the gradient is wrong, with no error" => [
"Recurrence capacity, dropped overflow after a truncated draw",
],
# Reactant's optimisation passes turn the gradient's program into one
# that does not verify: a product of arrays of two shapes.
"an optimisation pass gives an invalid program for the gradient" => [
"Recurrence capacity, beds with overflow",
"Recurrence capacity, weekly budget with a queue",
"Recurrence trace of a weekly budget with a queue",
"Recurrence with a value for each stratum as its history",
],
)
Expand Down
19 changes: 10 additions & 9 deletions test/reactant/RESULTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

Generated by `test/reactant/runtests.jl`; do not edit by hand.
Run on 2026-12-02, Julia 1.12.7, Reactant 0.2.310, ReactantCore 0.1.28, Enzyme 0.13.220.
Later rows run on 2026-12-05, Julia 1.12.7, Reactant 0.2.311, ReactantCore 0.1.28, Enzyme 0.13.220.
Total run time 49.9 min, timeout 600 s a case.

- `forward`: `Reactant.@compile` of the call against plain Julia.
Expand Down Expand Up @@ -81,9 +82,9 @@ Total run time 49.9 min, timeout 600 s a case.
| Recurrence empty pool with a differentiated heterogeneity | works (7.3 s / 12.5 µs) | works (1.6 s / 10.6 µs) |
| Recurrence Derived modifier parameters | works (5.2 s / 10.8 µs) | works (1.8 s / 53.9 µs) |
| Recurrence Redistribute, Transform(+) and Transform(clamp) | works (4.2 s / 60.1 µs) | works (2.4 s / 88.2 µs) |
| Recurrence capacity, beds with overflow | works (5.5 s / 9.2 µs) | error: CompilationError |
| Recurrence capacity, beds with overflow | works (5.5 s / 9.2 µs) | works (3.3 s / 33.8 µs) |
| Recurrence bed cap with a stay that is not geometric | works (10.6 s / 10.2 µs) | works (1.8 s / 89.8 µs) |
| Recurrence capacity, weekly budget with a queue | works (5.3 s / 10.1 µs) | error: CompilationError |
| Recurrence capacity, weekly budget with a queue | works (5.3 s / 10.1 µs) | works (2.6 s / 67.1 µs) |
| Recurrence trace of the importation (Redistribute) | works (7.6 s / 11.9 µs) | works (2.1 s / 40.1 µs) |
| Recurrence trace through a sparse coupling | error: MethodError | error: MethodError |
| Recurrence trace of a protected pool | works (3.7 s / 11.4 µs) | works (2.7 s / 87.6 µs) |
Expand All @@ -92,12 +93,12 @@ Total run time 49.9 min, timeout 600 s a case.
| Recurrence user copy of the hazard depletion | works (6.0 s / 19.8 µs) | works (2.1 s / 12.9 µs) |
| Recurrence user traces on groups and over the whole step | works (5.9 s / 52.0 µs) | works (2.3 s / 51.3 µs) |
| Recurrence trace of a ward's flows | works (4.7 s / 67.5 µs) | works (3.1 s / 110.4 µs) |
| Recurrence trace of a weekly budget with a queue | works (4.0 s / 42.5 µs) | error: CompilationError |
| Recurrence trace of a weekly budget with a queue | works (4.0 s / 42.5 µs) | works (5.2 s / 115.5 µs) |
| Recurrence effective reproduction number from its pressure | works (4.6 s / 17.1 µs) | works (3.3 s / 158.9 µs) |
| Recurrence effective reproduction number from its trace | works (2.5 s / 10.9 µs) | works (1.9 s / 16.2 µs) |
| Recurrence pressure from its trace, by coupling and with no input | works (12.7 s / 57.6 µs) | works (2.9 s / 125.5 µs) |
| Recurrence pressure and a named trace read from one record | works (7.4 s / 19.1 µs) | works (2.5 s / 20.3 µs) |
| Recurrence capacity, dropped overflow after a truncated draw | works (5.7 s / 13.4 µs) | wrong (relerr 1.7e+02) |
| Recurrence capacity, dropped overflow after a truncated draw | works (5.7 s / 13.4 µs) | works (35.5 s / 81.6 µs) |
| Recurrence depletion with truncated draws | works (3.7 s / 10.1 µs) | works (1.6 s / 23.6 µs) |
| Recurrence depletion with smoothly truncated draws | works (3.5 s / 12.9 µs) | works (1.9 s / 88.1 µs) |
| Recurrence in Float32 | works (4.4 s / 10.3 µs) | works (1.5 s / 13.2 µs) |
Expand Down Expand Up @@ -190,7 +191,7 @@ Plain Julia is the call (forward) or `ForwardDiff.gradient` (reverse), on the CP
| registry | Convolution with a number as its history | forward | cpu | 12 | works | 0.0e+00 | 9.1 | 8.6 | 0.6 | | |
| registry | Convolution with a number as its history | reverse | cpu | 12 | works | 1.4e-16 | 1.2 | 7.6 | 3.5 | | |
| registry | Recurrence with a value for each stratum as its history | forward | cpu | 12 | works | 1.1e-15 | 50.1 | 12.7 | 2.2 | | |
| registry | Recurrence with a value for each stratum as its history | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | CompilationError: MLIR pass pipeline "post_op_transpose_reshape" failed error: 'stablehlo.multiply' op requires compatible types for all operands and results |
| registry | Recurrence with a value for each stratum as its history | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | CompilationError: MLIR pass pipeline "post_op_transpose_reshape" failed error: 'stablehlo.multiply' op requires compatible types for all operands and results |
| registry | Convolution with a value for each stratum as its history | forward | cpu | 12 | works | 1.2e-16 | 46.9 | 10.8 | 0.5 | | |
| registry | Convolution with a value for each stratum as its history | reverse | cpu | 12 | works | 7.9e-16 | 3.8 | 9.7 | 24.1 | | |
| registry | Recurrence gain per stratum and add read per group (Gather) | forward | cpu | 12 | works | 2.8e-16 | 12.9 | 9.3 | 1.6 | | |
Expand Down Expand Up @@ -310,11 +311,11 @@ Plain Julia is the call (forward) or `ForwardDiff.gradient` (reverse), on the CP
| registry | Recurrence Redistribute, Transform(+) and Transform(clamp) | forward | cpu | 12 | works | 6.3e-16 | 4.2 | 60.1 | 3.0 | | |
| registry | Recurrence Redistribute, Transform(+) and Transform(clamp) | reverse | cpu | 12 | works | 7.9e-06 | 2.4 | 88.2 | 113.2 | | |
| registry | Recurrence capacity, beds with overflow | forward | cpu | 12 | works | 3.4e-16 | 5.5 | 9.2 | 2.0 | | |
| registry | Recurrence capacity, beds with overflow | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | CompilationError: MLIR pass pipeline "post_op_transpose_reshape" failed error: 'stablehlo.multiply' op requires compatible types for all operands and results |
| registry | Recurrence capacity, beds with overflow | reverse | cpu | 12 | works | 2.9e-14 | 3.3 | 33.8 | 31.3 | | |
| registry | Recurrence bed cap with a stay that is not geometric | forward | cpu | 12 | works | 0.0e+00 | 10.6 | 10.2 | 1.0 | | |
| registry | Recurrence bed cap with a stay that is not geometric | reverse | cpu | 12 | works | 1.5e-16 | 1.8 | 89.8 | 6.0 | | |
| registry | Recurrence capacity, weekly budget with a queue | forward | cpu | 12 | works | 1.9e-16 | 5.3 | 10.1 | 1.9 | | |
| registry | Recurrence capacity, weekly budget with a queue | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | CompilationError: MLIR pass pipeline "post_op_transpose_reshape" failed error: 'stablehlo.multiply' op requires compatible types for all operands and results |
| registry | Recurrence capacity, weekly budget with a queue | reverse | cpu | 12 | works | 1.4e-14 | 2.6 | 67.1 | 116.3 | | |
| registry | Recurrence trace of the importation (Redistribute) | forward | cpu | 12 | works | 6.8e-16 | 7.6 | 11.9 | 3.9 | | |
| registry | Recurrence trace of the importation (Redistribute) | reverse | cpu | 12 | works | 1.0e-14 | 2.1 | 40.1 | 71.7 | | |
| registry | Recurrence trace through a sparse coupling | forward | 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 ` |
Expand All @@ -332,7 +333,7 @@ Plain Julia is the call (forward) or `ForwardDiff.gradient` (reverse), on the CP
| registry | Recurrence trace of a ward's flows | forward | cpu | 12 | works | 3.9e-16 | 4.7 | 67.5 | 8.0 | | |
| registry | Recurrence trace of a ward's flows | reverse | cpu | 12 | works | 1.4e-14 | 3.1 | 110.4 | 304.3 | | |
| registry | Recurrence trace of a weekly budget with a queue | forward | cpu | 12 | works | 4.2e-16 | 4.0 | 42.5 | 3.5 | | |
| registry | Recurrence trace of a weekly budget with a queue | reverse | cpu | 12 | error | NaN | NaN | NaN | NaN | - | CompilationError: MLIR pass pipeline "post_op_transpose_reshape" failed error: 'stablehlo.multiply' op requires compatible types for all operands and results |
| registry | Recurrence trace of a weekly budget with a queue | reverse | cpu | 12 | works | 5.8e-15 | 5.2 | 115.5 | 162.1 | | |
| registry | Recurrence effective reproduction number from its pressure | forward | cpu | 12 | works | 8.0e-16 | 4.6 | 17.1 | 2.8 | | |
| registry | Recurrence effective reproduction number from its pressure | reverse | cpu | 12 | works | 1.5e-14 | 3.3 | 158.9 | 47.4 | | |
| registry | Recurrence effective reproduction number from its trace | forward | cpu | 12 | works | 1.9e-16 | 2.5 | 10.9 | 3.5 | | |
Expand All @@ -342,7 +343,7 @@ Plain Julia is the call (forward) or `ForwardDiff.gradient` (reverse), on the CP
| registry | Recurrence pressure and a named trace read from one record | forward | cpu | 12 | works | 4.6e-16 | 7.4 | 19.1 | 10.4 | | |
| registry | Recurrence pressure and a named trace read from one record | reverse | cpu | 12 | works | 9.1e-14 | 2.5 | 20.3 | 184.1 | | |
| registry | Recurrence capacity, dropped overflow after a truncated draw | forward | cpu | 12 | works | 3.0e-16 | 5.7 | 13.4 | 5.4 | | |
| registry | Recurrence capacity, dropped overflow after a truncated draw | reverse | cpu | 12 | wrong | 1.7e+02 | 2.9 | 146.0 | 81.1 | | |
| registry | Recurrence capacity, dropped overflow after a truncated draw | reverse | cpu | 12 | works | 1.6e-06 | 35.5 | 81.6 | 105.5 | | |
| registry | Recurrence depletion with truncated draws | forward | cpu | 12 | works | 4.0e-16 | 3.7 | 10.1 | 1.8 | | |
| registry | Recurrence depletion with truncated draws | reverse | cpu | 12 | works | 1.8e-14 | 1.6 | 23.6 | 42.2 | | |
| registry | Recurrence depletion with smoothly truncated draws | forward | cpu | 12 | works | 1.0e-15 | 3.5 | 12.9 | 3.0 | | |
Expand Down
56 changes: 55 additions & 1 deletion test/reactant/extension_check.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
# the package's Reactant extension, that it adds no method ambiguities, and
# that it still checks a traced coefficient's shape, says CUDA.jl is needed
# when it is not loaded, compiles a program that does not grow with the
# number of strata, and launches kernels from `TRACED_MIN_STRATA` strata.
# number of strata, launches kernels from `TRACED_MIN_STRATA` strata, and
# takes a right gradient, or says why it cannot, of a kernel per stratum
# with a depletion.
# Run by `runtests.jl` in its own process, as the probes are, so the runner
# does not load Reactant.
using ComposableRecurrences, Reactant, KernelAbstractions, CUDA, Enzyme, Test
Expand Down Expand Up @@ -269,3 +271,55 @@ ComposableRecurrences.step(::CapMin, θ, v, s) = (min(v, θ.c), nothing)
f = loss(CapBranch)
@test_throws TypeError Reactant.@compile f(x)
end

# Under Reactant's AD, the strata loops of a recurrence with a kernel per
# stratum and a depletion, written out one block a stratum, give a wrong
# gradient (#983); they run as kernels instead, which give the right one,
# while the primal call keeps the usual executor.
@testset "Reactant gradient of a kernel per stratum with a depletion" begin
G = [0.3 0.2 0.1; 0.5 0.1 0.1; 0.4 0.3 0.1]
h = [1.0 + k + 0.1 * i for k in 1:3, i in 1:3]
d = ComposableRecurrences.Depletion(PerStratum([40.0, 60.0, 80.0]))
r = Recurrence(PerStratum(G); modifiers = (d,))
f(θ) = sum(log.(r(exp.(θ); history = h)))
θ = [0.5 + 0.1 * k + 0.02 * t for k in 1:3, t in 1:8]
x = Reactant.to_rarray(θ)
grad(θ) = Enzyme.gradient(Enzyme.Reverse, f, θ)[1]
@test Reactant.@compile(f(x))(x) ≈ f(θ)
c = Reactant.@compile raise = true raise_first = true grad(x)
@test Array(c(x)) ≈ Enzyme.gradient(Enzyme.Reverse, Enzyme.Const(f), θ)[1]
end

# Without KernelAbstractions the strata loops cannot run as kernels, so the
# gradient of such a call says what it needs rather than give a wrong one;
# the primal call compiles as before.
@testset "Reactant gradient of a kernel per stratum without kernels" begin
code = """
using ComposableRecurrences, Reactant, Enzyme
name = :ComposableRecurrencesReactantKernelAbstractionsExt
Base.get_extension(ComposableRecurrences, name) === nothing ||
error("KernelAbstractions is loaded")
G = [0.3 0.2 0.1; 0.5 0.1 0.1; 0.4 0.3 0.1]
h = [1.0 + k + 0.1 * i for k in 1:3, i in 1:3]
d = ComposableRecurrences.Depletion(PerStratum([40.0, 60.0, 80.0]))
r = Recurrence(PerStratum(G); modifiers = (d,))
f(θ) = sum(log.(r(exp.(θ); history = h)))
θ = [0.5 + 0.1 * k + 0.02 * t for k in 1:3, t in 1:8]
x = Reactant.to_rarray(θ)
isapprox(Reactant.@compile(f(x))(x), f(θ)) || error("wrong primal")
grad(θ) = Enzyme.gradient(Enzyme.Reverse, f, θ)[1]
err = try
Reactant.@compile raise = true raise_first = true grad(x)
nothing
catch e
e
end
msg = err === nothing ? "" : sprint(showerror, err)
occursin("PerStratum", msg) && occursin("Depletion", msg) &&
occursin("using KernelAbstractions, CUDA", msg) ||
error("the gradient did not name what it needs: \$msg")
"""
project = dirname(Base.active_project())
cmd = `$(Base.julia_cmd()) --project=$project --startup-file=no -e $code`
@test success(pipeline(cmd; stdout = devnull, stderr = stderr))
end
Loading
Loading