From 4428bc249f178c16d46f497aece2cb359c760395 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:36:08 +0000 Subject: [PATCH 1/6] Take the value of a ReverseDiff tracked number where the package holds a quantity fixed growth found its root and Jacobian on tracked numbers under ReverseDiff, as _primal_value had no method for them, and ReverseDiff's hcat of a Matrix{TrackedReal} with a TrackedArray is ambiguous with SparseArrays loaded. A ReverseDiff extension gives _primal_value and _fixed their values, as for ForwardDiff's dual numbers. Fixes #1003. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwC7ixGWZNbRbSXXsSPbAs --- Project.toml | 3 +++ docs/pages.jl | 1 + docs/src/extensions/reverse-diff.md | 15 +++++++++++++++ docs/src/getting-started/index.md | 1 + ext/ComposableRecurrencesReverseDiffExt.jl | 16 ++++++++++++++++ 5 files changed, 36 insertions(+) create mode 100644 docs/src/extensions/reverse-diff.md create mode 100644 ext/ComposableRecurrencesReverseDiffExt.jl diff --git a/Project.toml b/Project.toml index 530cc1f0e..3c5c5aae3 100644 --- a/Project.toml +++ b/Project.toml @@ -31,6 +31,7 @@ LogExpFunctions = "2ab3a3ac-af41-5b50-aa03-7779005ae688" Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Reactant = "3c362404-f566-11ee-1572-e11a4b42c853" +ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" [extensions] ComposableRecurrencesCensoredDistributionsExt = ["CensoredDistributions", "Distributions"] @@ -46,6 +47,7 @@ ComposableRecurrencesLogExpFunctionsExt = "LogExpFunctions" ComposableRecurrencesMooncakeExt = ["ADTypes", "Mooncake", "Random"] ComposableRecurrencesReactantExt = "Reactant" ComposableRecurrencesReactantKernelAbstractionsExt = ["Adapt", "KernelAbstractions", "Reactant"] +ComposableRecurrencesReverseDiffExt = "ReverseDiff" [compat] ADTypes = "1" @@ -69,5 +71,6 @@ Mooncake = "0.5.61" PrecompileTools = "1" Random = "1" Reactant = "0.2.290" +ReverseDiff = "1.18.2" SparseArrays = "1" julia = "1.11, 1.12, 1.13" diff --git a/docs/pages.jl b/docs/pages.jl index afaa8d7ab..e567d639f 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -66,6 +66,7 @@ pages = [ "GPUArrays + KernelAbstractions" => "extensions/gpuarrays.md", "LogExpFunctions" => "extensions/log-exp-functions.md", "Reactant" => "extensions/reactant.md", + "ReverseDiff" => "extensions/reverse-diff.md", ], "Benchmarks" => [ "Performance over time" => "benchmarks/over-time.md", diff --git a/docs/src/extensions/reverse-diff.md b/docs/src/extensions/reverse-diff.md new file mode 100644 index 000000000..7a05e43db --- /dev/null +++ b/docs/src/extensions/reverse-diff.md @@ -0,0 +1,15 @@ +# [ReverseDiff](@id extension-reverse-diff) + +Loading ReverseDiff lets the package take the value of a tracked number where it holds a quantity fixed. +[`growth`](@ref ComposableRecurrences.growth) finds its root and Jacobian on these values and takes one Newton step from the root in tracked numbers, as it does with ForwardDiff's dual numbers. + +```julia +using ComposableRecurrences, ReverseDiff +K = [0.8 0.1 0.1; 0.2 0.7 0.1; 0.0 0.3 0.7] +g = [0.4, 0.3, 0.2, 0.1] +function loss(logR) + r = Recurrence(PerStratum(repeat(g', 3)); coupling = K) + return ComposableRecurrences.growth(r, PerStratum(exp.(logR))).rate +end +ReverseDiff.gradient(loss, log.([1.6, 0.9, 1.2])) +``` diff --git a/docs/src/getting-started/index.md b/docs/src/getting-started/index.md index 170eca0eb..c87262e26 100644 --- a/docs/src/getting-started/index.md +++ b/docs/src/getting-started/index.md @@ -41,6 +41,7 @@ No extension is needed to build or run a model. | `KernelAbstractions` and a GPU array package | Calls on GPU arrays | [GPUArrays](@ref extension-gpuarrays) | | `Reactant` | Compiled calls on traced arrays | [Reactant](@ref extension-reactant) | | `Reactant`, `KernelAbstractions` | Traced loops over strata as one kernel | [Reactant kernels](@ref extension-reactant-kernel-abstractions) | +| `ReverseDiff` | The values of tracked numbers where the package holds a quantity fixed | [ReverseDiff](@ref extension-reverse-diff) | ## Getting help diff --git a/ext/ComposableRecurrencesReverseDiffExt.jl b/ext/ComposableRecurrencesReverseDiffExt.jl new file mode 100644 index 000000000..796868b57 --- /dev/null +++ b/ext/ComposableRecurrencesReverseDiffExt.jl @@ -0,0 +1,16 @@ +module ComposableRecurrencesReverseDiffExt + +# The value of a ReverseDiff tracked number, so that what the package holds +# fixed, such as the growth rate's root and Jacobian, is computed on values +# and not recorded on the tape, as for ForwardDiff's dual numbers. +using ComposableRecurrences: ComposableRecurrences +using ReverseDiff: ReverseDiff, TrackedArray, TrackedReal + +function ComposableRecurrences._primal_value(x::TrackedReal) + return ComposableRecurrences._primal_value(ReverseDiff.value(x)) +end +function ComposableRecurrences._fixed(x::TrackedArray) + return map(ComposableRecurrences._primal_value, ReverseDiff.value(x)) +end + +end From 18d84c46e7cafe446fa10830a7105a8866dfd2c1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 14:49:47 +0000 Subject: [PATCH 2/6] Revert "Take the value of a ReverseDiff tracked number where the package holds a quantity fixed" This reverts commit 4428bc249f178c16d46f497aece2cb359c760395. --- Project.toml | 3 --- docs/pages.jl | 1 - docs/src/extensions/reverse-diff.md | 15 --------------- docs/src/getting-started/index.md | 1 - ext/ComposableRecurrencesReverseDiffExt.jl | 16 ---------------- 5 files changed, 36 deletions(-) delete mode 100644 docs/src/extensions/reverse-diff.md delete mode 100644 ext/ComposableRecurrencesReverseDiffExt.jl diff --git a/Project.toml b/Project.toml index 3c5c5aae3..530cc1f0e 100644 --- a/Project.toml +++ b/Project.toml @@ -31,7 +31,6 @@ LogExpFunctions = "2ab3a3ac-af41-5b50-aa03-7779005ae688" Mooncake = "da2b9cff-9c12-43a0-ae48-6db2b0edb7d6" Random = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c" Reactant = "3c362404-f566-11ee-1572-e11a4b42c853" -ReverseDiff = "37e2e3b7-166d-5795-8a7a-e32c996b4267" [extensions] ComposableRecurrencesCensoredDistributionsExt = ["CensoredDistributions", "Distributions"] @@ -47,7 +46,6 @@ ComposableRecurrencesLogExpFunctionsExt = "LogExpFunctions" ComposableRecurrencesMooncakeExt = ["ADTypes", "Mooncake", "Random"] ComposableRecurrencesReactantExt = "Reactant" ComposableRecurrencesReactantKernelAbstractionsExt = ["Adapt", "KernelAbstractions", "Reactant"] -ComposableRecurrencesReverseDiffExt = "ReverseDiff" [compat] ADTypes = "1" @@ -71,6 +69,5 @@ Mooncake = "0.5.61" PrecompileTools = "1" Random = "1" Reactant = "0.2.290" -ReverseDiff = "1.18.2" SparseArrays = "1" julia = "1.11, 1.12, 1.13" diff --git a/docs/pages.jl b/docs/pages.jl index e567d639f..afaa8d7ab 100644 --- a/docs/pages.jl +++ b/docs/pages.jl @@ -66,7 +66,6 @@ pages = [ "GPUArrays + KernelAbstractions" => "extensions/gpuarrays.md", "LogExpFunctions" => "extensions/log-exp-functions.md", "Reactant" => "extensions/reactant.md", - "ReverseDiff" => "extensions/reverse-diff.md", ], "Benchmarks" => [ "Performance over time" => "benchmarks/over-time.md", diff --git a/docs/src/extensions/reverse-diff.md b/docs/src/extensions/reverse-diff.md deleted file mode 100644 index 7a05e43db..000000000 --- a/docs/src/extensions/reverse-diff.md +++ /dev/null @@ -1,15 +0,0 @@ -# [ReverseDiff](@id extension-reverse-diff) - -Loading ReverseDiff lets the package take the value of a tracked number where it holds a quantity fixed. -[`growth`](@ref ComposableRecurrences.growth) finds its root and Jacobian on these values and takes one Newton step from the root in tracked numbers, as it does with ForwardDiff's dual numbers. - -```julia -using ComposableRecurrences, ReverseDiff -K = [0.8 0.1 0.1; 0.2 0.7 0.1; 0.0 0.3 0.7] -g = [0.4, 0.3, 0.2, 0.1] -function loss(logR) - r = Recurrence(PerStratum(repeat(g', 3)); coupling = K) - return ComposableRecurrences.growth(r, PerStratum(exp.(logR))).rate -end -ReverseDiff.gradient(loss, log.([1.6, 0.9, 1.2])) -``` diff --git a/docs/src/getting-started/index.md b/docs/src/getting-started/index.md index c87262e26..170eca0eb 100644 --- a/docs/src/getting-started/index.md +++ b/docs/src/getting-started/index.md @@ -41,7 +41,6 @@ No extension is needed to build or run a model. | `KernelAbstractions` and a GPU array package | Calls on GPU arrays | [GPUArrays](@ref extension-gpuarrays) | | `Reactant` | Compiled calls on traced arrays | [Reactant](@ref extension-reactant) | | `Reactant`, `KernelAbstractions` | Traced loops over strata as one kernel | [Reactant kernels](@ref extension-reactant-kernel-abstractions) | -| `ReverseDiff` | The values of tracked numbers where the package holds a quantity fixed | [ReverseDiff](@ref extension-reverse-diff) | ## Getting help diff --git a/ext/ComposableRecurrencesReverseDiffExt.jl b/ext/ComposableRecurrencesReverseDiffExt.jl deleted file mode 100644 index 796868b57..000000000 --- a/ext/ComposableRecurrencesReverseDiffExt.jl +++ /dev/null @@ -1,16 +0,0 @@ -module ComposableRecurrencesReverseDiffExt - -# The value of a ReverseDiff tracked number, so that what the package holds -# fixed, such as the growth rate's root and Jacobian, is computed on values -# and not recorded on the tape, as for ForwardDiff's dual numbers. -using ComposableRecurrences: ComposableRecurrences -using ReverseDiff: ReverseDiff, TrackedArray, TrackedReal - -function ComposableRecurrences._primal_value(x::TrackedReal) - return ComposableRecurrences._primal_value(ReverseDiff.value(x)) -end -function ComposableRecurrences._fixed(x::TrackedArray) - return map(ComposableRecurrences._primal_value, ReverseDiff.value(x)) -end - -end From 979337fc7327e38f52174f4bc243b875fab259ed Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:29:09 +0000 Subject: [PATCH 3/6] Build the growth Jacobian in an array like its blocks, and replay compiled tapes at a second point The Jacobian was joined with hcat and vcat, and ReverseDiff's hcat of a Matrix{TrackedReal} with a TrackedArray is ambiguous with SparseArrays loaded. It is now filled block by block in an array like M, which takes tracked numbers, and nothing is stripped for them: a compiled tape that takes the root as a constant gives a wrong gradient at another point. The compiled-tape check replays each registry scenario at a point about 1% from the one it was recorded at. Fixes #1003. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwC7ixGWZNbRbSXXsSPbAs --- src/operators/growth.jl | 12 ++++++++---- test/ad/checks.jl | 27 +++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/operators/growth.jl b/src/operators/growth.jl index 60d7d6391..58d55a044 100644 --- a/src/operators/growth.jl +++ b/src/operators/growth.jl @@ -472,10 +472,14 @@ function _eigen_jacobian( ) M = _primal_matrix(lin, gain, at, ρ, L, S) Dv = _fixed(_lagged(lin, gain, at, v, ρ, L)) - # Joined with `hcat` and `vcat`: Julia 1.11 does not infer the bracket - # form. - T = eltype(M) - J = vcat(hcat(M - I, -Dv), hcat(ones(T, 1, S), zeros(T, 1, 1))) + # Filled block by block in an array like `M`, so that it infers on + # Julia 1.11 and takes the number type of the entries, tracked or not. + T = promote_type(eltype(M), eltype(Dv)) + J = similar(M, T, S + 1, S + 1) + view(J, 1:S, 1:S) .= M - I + view(J, 1:S, S + 1) .= .-Dv + view(J, S + 1, 1:S) .= one(T) + view(J, S + 1, S + 1:S + 1) .= zero(T) return ρ, v, _inverse(J) end diff --git a/test/ad/checks.jl b/test/ad/checks.jl index 7410710ab..ab6e623bf 100644 --- a/test/ad/checks.jl +++ b/test/ad/checks.jl @@ -67,6 +67,33 @@ fired = ComposableRecurrences._PULLBACK_CALLS[] > calls rules_fire && test_rule_fires(s.name, fired, plain, s.name in broken) end + name == "ReverseDiff (compiled)" && + test_replay(scens, backend; rtol, broken) + end + return nothing + end + + # A compiled tape replays the operations it recorded, so a value taken + # as a constant when it was recorded gives a wrong gradient elsewhere. + # Each scenario of `scens` is recorded at its parameters and replayed at + # a point shifted by about 1% of each entry, or by 0.01 where an entry + # is zero, against the ForwardDiff gradient there. + function test_replay(scens, backend; rtol, broken) + forward = only( + b.backend for b in ADFixtures.backends() if b.name == "ForwardDiff" + ) + @testset "$(s.name), replayed at a second point" for s in scens + prep = DI.prepare_gradient(s.f, backend, copy(s.x)) + T = eltype(s.x) + scale = map(v -> iszero(v) ? one(v) : abs(v), s.x) + x = s.x .+ T(0.01) .* scale .* sin.(T.(eachindex(s.x))) + ref = DI.gradient(s.f, forward, x) + g = DI.gradient(s.f, prep, backend, x) + if s.name in broken + @test_broken entrywise(g, ref; rtol) + else + @test entrywise(g, ref; rtol) + end end return nothing end From af89ff8cb4c192e08dea351eae06bec21b637846 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 15:29:17 +0000 Subject: [PATCH 4/6] Format the growth Jacobian with Runic Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwC7ixGWZNbRbSXXsSPbAs --- src/operators/growth.jl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/operators/growth.jl b/src/operators/growth.jl index 58d55a044..b41dde942 100644 --- a/src/operators/growth.jl +++ b/src/operators/growth.jl @@ -479,7 +479,7 @@ function _eigen_jacobian( view(J, 1:S, 1:S) .= M - I view(J, 1:S, S + 1) .= .-Dv view(J, S + 1, 1:S) .= one(T) - view(J, S + 1, S + 1:S + 1) .= zero(T) + view(J, S + 1, (S + 1):(S + 1)) .= zero(T) return ρ, v, _inverse(J) end From b5d392248977f82da41765066e39aa0334f19aec Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:40:37 +0000 Subject: [PATCH 5/6] Mix strata at zero in the growth scenario, and replay every scenario The coupling of "Growth rate and profile of strata that mix" is `K0` scaled entry by entry by the exponential of its parameters, so it mixes the strata at the zero vector too. A tape recorded near the point it replays at runs the same steps of a loop, so the second-point replay check is `@test` for every scenario and no longer reads the broken list. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WwC7ixGWZNbRbSXXsSPbAs --- test/ADFixtures/src/registry.jl | 10 ++++++---- test/ad/checks.jl | 14 ++++++-------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/ADFixtures/src/registry.jl b/test/ADFixtures/src/registry.jl index e873e45cb..94179fb79 100644 --- a/test/ADFixtures/src/registry.jl +++ b/test/ADFixtures/src/registry.jl @@ -2540,11 +2540,13 @@ function _growth_rate(w, θ) return ComposableRecurrences.growth(r, exp(only(logR))).rate^2 end # The same for strata that mix: the rate and the profile over strata, from -# a Newton step on both. +# a Newton step on both. The coupling is `K0` scaled entry by entry by the +# exponential of its parameters, so that it mixes the strata at the zero +# vector too. const WG = [0.7, -0.4, 1.1] function _growth_strata(w, θ) - logR, logG, K = _unpack(θ, (S,), (S, L), (S, S)) - r = Recurrence(PerStratum(exp.(logG)); coupling = K) + logR, logG, logK = _unpack(θ, (S,), (S, L), (S, S)) + r = Recurrence(PerStratum(exp.(logG)); coupling = K0 .* exp.(logK)) out = ComposableRecurrences.growth(r, PerStratum(exp.(logR))) return out.rate^2 + sum(WG .* out.profile) end @@ -2558,7 +2560,7 @@ push!( ( "Growth rate and profile of strata that mix", _growth_strata, () -> _flat( - [log(1.6), log(0.9), log(1.2)], repeat(log.(G0)', S), K0 + [log(1.6), log(0.9), log(1.2)], repeat(log.(G0)', S), zeros(S, S) ), ), ) diff --git a/test/ad/checks.jl b/test/ad/checks.jl index ab6e623bf..164b7636c 100644 --- a/test/ad/checks.jl +++ b/test/ad/checks.jl @@ -68,7 +68,7 @@ rules_fire && test_rule_fires(s.name, fired, plain, s.name in broken) end name == "ReverseDiff (compiled)" && - test_replay(scens, backend; rtol, broken) + test_replay(scens, backend; rtol) end return nothing end @@ -77,8 +77,10 @@ # as a constant when it was recorded gives a wrong gradient elsewhere. # Each scenario of `scens` is recorded at its parameters and replayed at # a point shifted by about 1% of each entry, or by 0.01 where an entry - # is zero, against the ForwardDiff gradient there. - function test_replay(scens, backend; rtol, broken) + # is zero, against the ForwardDiff gradient there. A scenario whose + # loop runs as many steps at both points replays there, so the check + # holds for every scenario, those broken on the backend included. + function test_replay(scens, backend; rtol) forward = only( b.backend for b in ADFixtures.backends() if b.name == "ForwardDiff" ) @@ -89,11 +91,7 @@ x = s.x .+ T(0.01) .* scale .* sin.(T.(eachindex(s.x))) ref = DI.gradient(s.f, forward, x) g = DI.gradient(s.f, prep, backend, x) - if s.name in broken - @test_broken entrywise(g, ref; rtol) - else - @test entrywise(g, ref; rtol) - end + @test entrywise(g, ref; rtol) end return nothing end From 8cfb569609737d2ab40aaf1de90ebfe9b4325c78 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 2 Dec 2026 18:42:12 +0000 Subject: [PATCH 6/6] List the mixing growth scenario for compiled ReverseDiff tapes A compiled tape does not replay value-dependent iteration. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01WwC7iwncmH7NPsrzAxQM9s --- test/ADFixtures/src/registry.jl | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/test/ADFixtures/src/registry.jl b/test/ADFixtures/src/registry.jl index 94179fb79..9f0b42650 100644 --- a/test/ADFixtures/src/registry.jl +++ b/test/ADFixtures/src/registry.jl @@ -3589,7 +3589,14 @@ function backend_broken_scenarios() # does not. twin = "NoAdjoint Recurrence two draws on one pool with a flow between" _coverage() && VERSION >= v"1.13" && push!(enzyme, twin) + # The growth of strata that mix solves for its root by a Newton loop + # and a power iteration that run until they settle: value-dependent + # iteration, which a compiled tape does not replay. A tape recorded at + # the zero vector runs 6 power steps, where the scenario's parameters + # need 40. + mixed = "Growth rate and profile of strata that mix" return Dict( + "ReverseDiff (compiled)" => Set([mixed, "NoAdjoint " * mixed]), "Reactant" => Set(reduce(vcat, values(REACTANT_BROKEN))), "Reactant forward" => Set(reduce(vcat, values(REACTANT_BROKEN_FORWARD))), "Reactant reverse" => Set(reduce(vcat, values(REACTANT_BROKEN_REVERSE))),