From 84bf1bb5a78b0f6da88b0a2dd02bc078e3633fc4 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Fri, 2 Oct 2026 19:17:09 -0400 Subject: [PATCH 1/4] Attach implicit-function sensitivities to continuous callback roots MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reverse-mode Enzyme gradients through parameter-dependent event times were wrong because they differentiated the ITP bracketing iterations, which do not carry the derivative of the mathematical root. gpu_find_root now returns the converged root with the implicit-function-theorem tangent -f_θ/f_t attached through a correction term that is identically zero in the primal, so the forward root and its rootfind side are unchanged. Fixes #533 Co-Authored-By: Chris Rackauckas Co-Authored-By: Claude Agent-Harness: Claude Code 2.1.287 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-DiffEqGPU.jl-533/log.txt on amdci2.julia.csail.mit.edu --- src/DiffEqGPU.jl | 2 +- .../integrators/integrator_utils.jl | 24 +++++++++--- test/enzyme/gradients.jl | 39 +++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/DiffEqGPU.jl b/src/DiffEqGPU.jl index 401a5103..ec1da6f7 100644 --- a/src/DiffEqGPU.jl +++ b/src/DiffEqGPU.jl @@ -5,7 +5,7 @@ module DiffEqGPU using DocStringExtensions: DocStringExtensions using SciMLPublic: @public -using EnzymeCore: within_autodiff +using EnzymeCore: ignore_derivatives, within_autodiff using KernelAbstractions: KernelAbstractions, @Const, @index, @kernel, CPU import KernelAbstractions: get_backend, allocate using SciMLBase: SciMLBase, CallbackSet, CheckInit, ContinuousCallback, diff --git a/src/ensemblegpukernel/integrators/integrator_utils.jl b/src/ensemblegpukernel/integrators/integrator_utils.jl index fc3b31c8..b8943830 100644 --- a/src/ensemblegpukernel/integrators/integrator_utils.jl +++ b/src/ensemblegpukernel/integrators/integrator_utils.jl @@ -404,11 +404,25 @@ end end end - if rootfind == SciMLBase.LeftRootFind - return left - else - return right - end + root = rootfind == SciMLBase.LeftRootFind ? left : right + return _implicit_root(f, root, tup) +end + +# The bracketing iterations above carry no derivative information about the root, so +# reattach the implicit-function-theorem sensitivity dt = -∂f/∂θ / ∂f/∂t. The correction +# term is identically zero in the primal, which keeps the returned root bit-for-bit equal +# to `root` and preserves the side of the event chosen by `rootfind`. +@inline function _implicit_root(f, root, tup) + left, right = tup + t = ignore_derivatives(root) + h = cbrt(eps(typeof(t))) * max(abs(t), right - left) + tl = max(left, t - h) + tr = min(right, t + h) + slope = ignore_derivatives((f(tr) - f(tl)) / (tr - tl)) + valid = !iszero(slope) & isfinite(slope) + ft = f(t) + correction = (ft - ignore_derivatives(ft)) / ifelse(valid, slope, one(slope)) + return t - convert(typeof(t), ifelse(valid, correction, zero(correction))) end @inline function DiffEqBase.find_callback_time( diff --git a/test/enzyme/gradients.jl b/test/enzyme/gradients.jl index d9c4ec2f..b8eec838 100644 --- a/test/enzyme/gradients.jl +++ b/test/enzyme/gradients.jl @@ -120,3 +120,42 @@ end Enzyme.autodiff(Reverse, initial_state_loss, Active, Duplicated(u0, du0), Const(backend)) @test du0 ≈ fill(exp(0.2), length(u0)) rtol = 1.0e-7 end + +event_condition(u, t, integrator) = u[1] - integrator.p[1] +reset_half!(integrator) = (integrator.u = SVector(0.5)) + +function event_time_loss(p, rhs, u0, backend) + prob = ODEProblem{false}(rhs, SVector(u0), (0.0, 1.0), SVector(p[1])) + prob_func = (prob, ctx) -> remake(prob; p = SVector(p[ctx.sim_id])) + cb = ContinuousCallback(event_condition, reset_half!; save_positions = (false, false)) + sol = solve( + EnsembleProblem(prob; prob_func, safetycopy = false), GPUTsit5(), + EnsembleGPUKernel(backend, 0.0); trajectories = length(p), adaptive = false, + dt = 0.05, callback = cb, merge_callbacks = true, save_everystep = false + ) + return sum(s -> only(s.u[end]), sol.u) +end + +@testset "Parameter-dependent continuous event time gradients" begin + # u′ = 1 from 0 hits u = p > 0.75 once, at t = p, so u(1) = 1.5 - p. + p = [0.78, 0.84, 0.93] + rhs = (u, p, t) -> SVector(1.0) + @test event_time_loss(p, rhs, 0.0, backend) ≈ sum(1.5 .- p) rtol = 1.0e-10 + dp = zero(p) + Enzyme.autodiff( + Reverse, event_time_loss, Active, Duplicated(p, dp), + Const(rhs), Const(0.0), Const(backend) + ) + @test dp ≈ -ones(3) rtol = 1.0e-8 + + # u′ = u from 1 hits u = p at t = log(p), so u(1) = 0.5e / p. + p = [1.3, 1.7, 2.2] + rhs = (u, p, t) -> u + @test event_time_loss(p, rhs, 1.0, backend) ≈ sum(0.5 * ℯ ./ p) rtol = 1.0e-7 + dp = zero(p) + Enzyme.autodiff( + Reverse, event_time_loss, Active, Duplicated(p, dp), + Const(rhs), Const(1.0), Const(backend) + ) + @test dp ≈ -0.5 * ℯ ./ p .^ 2 rtol = 1.0e-6 +end From 36cc2f88b85721f44f0ecff884c743f45d4e5e17 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Fri, 2 Oct 2026 23:33:24 -0400 Subject: [PATCH 2/4] Use exact dual-number time derivatives for event-root sensitivities MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The implicit-function correction now takes the condition's time derivative from a ForwardDiff dual at the converged root instead of a finite difference, which was inaccurate for curved Float32 conditions and large time origins. The correction runs only under Enzyme (`within_autodiff()`), so the ordinary forward root-finding path is identical to master. Tangential or singular crossings (zero or non-finite time derivative) raise an error instead of returning a zero gradient. Event-time duals use a private tag so they always interpolate the state, and the Tsit5 interpolant gets a local coefficient evaluation for them because SimpleDiffEq.bθs requires matching element types. Co-Authored-By: Chris Rackauckas Co-Authored-By: Claude Agent-Harness: Claude Code 2.1.287 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-DiffEqGPU.jl-533/log.txt on amdci2.julia.csail.mit.edu --- .../integrators/integrator_utils.jl | 47 +++++++---- .../integrators/nonstiff/interpolants.jl | 18 ++++- test/enzyme/gradients.jl | 77 ++++++++++++++----- 3 files changed, 109 insertions(+), 33 deletions(-) diff --git a/src/ensemblegpukernel/integrators/integrator_utils.jl b/src/ensemblegpukernel/integrators/integrator_utils.jl index b8943830..0ab9ff8c 100644 --- a/src/ensemblegpukernel/integrators/integrator_utils.jl +++ b/src/ensemblegpukernel/integrators/integrator_utils.jl @@ -405,24 +405,27 @@ end end root = rootfind == SciMLBase.LeftRootFind ? left : right - return _implicit_root(f, root, tup) + return within_autodiff() ? _implicit_root(f, root) : root end -# The bracketing iterations above carry no derivative information about the root, so -# reattach the implicit-function-theorem sensitivity dt = -∂f/∂θ / ∂f/∂t. The correction -# term is identically zero in the primal, which keeps the returned root bit-for-bit equal -# to `root` and preserves the side of the event chosen by `rootfind`. -@inline function _implicit_root(f, root, tup) - left, right = tup +struct EventTimeTag end + +@inline _event_time_derivative(y::ForwardDiff.Dual{EventTimeTag}) = ForwardDiff.partials(y, 1) +@inline _event_time_derivative(y) = zero(y) + +# The bracketing iterations carry no derivative information about the root, so attach +# the implicit-function-theorem sensitivity dt = -∂f/∂θ / ∂f/∂t at the converged root. +# The correction term is identically zero in the primal, so the root is unchanged. +@inline function _implicit_root(f, root) t = ignore_derivatives(root) - h = cbrt(eps(typeof(t))) * max(abs(t), right - left) - tl = max(left, t - h) - tr = min(right, t + h) - slope = ignore_derivatives((f(tr) - f(tl)) / (tr - tl)) - valid = !iszero(slope) & isfinite(slope) + slope = ignore_derivatives( + _event_time_derivative(f(ForwardDiff.Dual{EventTimeTag}(t, one(t)))) + ) + if iszero(slope) || !isfinite(slope) + error("Cannot differentiate a continuous callback event time: the condition's time derivative at the event is zero or non-finite (tangential or singular crossing).") + end ft = f(t) - correction = (ft - ignore_derivatives(ft)) / ifelse(valid, slope, one(slope)) - return t - convert(typeof(t), ifelse(valid, correction, zero(correction))) + return t - convert(typeof(t), (ft - ignore_derivatives(ft)) / slope) end @inline function DiffEqBase.find_callback_time( @@ -519,3 +522,19 @@ end end return callback.condition(tmp, abst, integrator) end + +# Event-time derivatives must include the interpolated state's dependence on time, so +# they always interpolate instead of reusing the stored endpoint states. +@inline function DiffEqBase.get_condition( + integrator::SciMLBase.AbstractODEIntegrator{ + AlgType, + IIP, + S, T, + }, + callback, + abst::ForwardDiff.Dual{EventTimeTag} + ) where { + AlgType <: GPUODEAlgorithm, IIP, S, T, + } + return callback.condition(integrator(abst), abst, integrator) +end diff --git a/src/ensemblegpukernel/integrators/nonstiff/interpolants.jl b/src/ensemblegpukernel/integrators/nonstiff/interpolants.jl index a72811cb..6819e860 100644 --- a/src/ensemblegpukernel/integrators/nonstiff/interpolants.jl +++ b/src/ensemblegpukernel/integrators/nonstiff/interpolants.jl @@ -369,6 +369,22 @@ end ) end +@inline _tsit5_bθs(rs, θ) = SimpleDiffEq.bθs(rs, θ) + +# `SimpleDiffEq.bθs` requires θ to share the coefficients' element type, which excludes +# the dual times used to differentiate event conditions. +@inline function _tsit5_bθs(rs::SVector{22}, θ::ForwardDiff.Dual{EventTimeTag}) + r11, r12, r13, r14, r22, r23, r24, r32, r33, r34, r42, r43, r44, r52, r53, + r54, r62, r63, r64, r72, r73, r74 = rs + z = zero(eltype(rs)) + return ( + @evalpoly(θ, z, r11, r12, r13, r14), @evalpoly(θ, z, z, r22, r23, r24), + @evalpoly(θ, z, z, r32, r33, r34), @evalpoly(θ, z, z, r42, r43, r44), + @evalpoly(θ, z, z, r52, r53, r54), @evalpoly(θ, z, z, r62, r63, r64), + @evalpoly(θ, z, z, r72, r73, r74), + ) +end + @inline @muladd function _ode_interpolant( Θ, dt, y₀, integ::T @@ -376,7 +392,7 @@ end T <: Union{GPUT5I, GPUAT5I}, } - b1θ, b2θ, b3θ, b4θ, b5θ, b6θ, b7θ = SimpleDiffEq.bθs(integ.rs, Θ) + b1θ, b2θ, b3θ, b4θ, b5θ, b6θ, b7θ = _tsit5_bθs(integ.rs, Θ) return y₀ + dt * ( diff --git a/test/enzyme/gradients.jl b/test/enzyme/gradients.jl index b8eec838..c3c8813f 100644 --- a/test/enzyme/gradients.jl +++ b/test/enzyme/gradients.jl @@ -121,41 +121,82 @@ end @test du0 ≈ fill(exp(0.2), length(u0)) rtol = 1.0e-7 end -event_condition(u, t, integrator) = u[1] - integrator.p[1] -reset_half!(integrator) = (integrator.u = SVector(0.5)) +linear_event(u, t, integrator) = u[1] - integrator.p[1] +function curved_event(u, t, integrator) + d = u[1] - integrator.p[1] + return d + eltype(u)(1.0e4) * d^3 +end +reset_half!(integrator) = (integrator.u = SVector(oftype(integrator.u[1], 0.5))) -function event_time_loss(p, rhs, u0, backend) - prob = ODEProblem{false}(rhs, SVector(u0), (0.0, 1.0), SVector(p[1])) +function event_time_loss(p::Vector{T}, rhs, condition, u0, backend) where {T} + prob = ODEProblem{false}(rhs, SVector(T(u0)), (zero(T), one(T)), SVector(p[1])) prob_func = (prob, ctx) -> remake(prob; p = SVector(p[ctx.sim_id])) - cb = ContinuousCallback(event_condition, reset_half!; save_positions = (false, false)) + cb = ContinuousCallback(condition, reset_half!; save_positions = (false, false)) sol = solve( EnsembleProblem(prob; prob_func, safetycopy = false), GPUTsit5(), EnsembleGPUKernel(backend, 0.0); trajectories = length(p), adaptive = false, - dt = 0.05, callback = cb, merge_callbacks = true, save_everystep = false + dt = T(0.05), callback = cb, merge_callbacks = true, save_everystep = false ) return sum(s -> only(s.u[end]), sol.u) end -@testset "Parameter-dependent continuous event time gradients" begin - # u′ = 1 from 0 hits u = p > 0.75 once, at t = p, so u(1) = 1.5 - p. - p = [0.78, 0.84, 0.93] - rhs = (u, p, t) -> SVector(1.0) - @test event_time_loss(p, rhs, 0.0, backend) ≈ sum(1.5 .- p) rtol = 1.0e-10 - dp = zero(p) - Enzyme.autodiff( - Reverse, event_time_loss, Active, Duplicated(p, dp), - Const(rhs), Const(0.0), Const(backend) +function event_root(p::T, g, bracket, rootfind) where {T} + return DiffEqGPU.gpu_find_root(t -> g(t, p), T.(bracket), rootfind) +end + +@testset "Continuous event root sensitivities ($T, p = $p, $rootfind)" for (T, g, p, bracket) in ( + (Float32, (t, p) -> (t - p) + 1.0f4 * (t - p)^3, 0.71f0, (0.7, 0.75)), + (Float64, (t, p) -> (t - p) + 1.0e4 * (t - p)^3, 0.71, (0.7, 0.75)), + (Float64, (t, p) -> (t - p) + (t - p)^3, 1.0e9, (1.0e9 - 1, 1.0e9 + 1)), + (Float32, (t, p) -> expm1(25000.0f0 * (t - p)), 0.71f0, (0.7065, 0.7135)), + ), rootfind in (SciMLBase.LeftRootFind, SciMLBase.RightRootFind) + # Each condition crosses zero transversally at t = p, so dt/dp = 1 exactly. + dp, root = Enzyme.autodiff( + ReverseWithPrimal, event_root, Active, Active(p), Const(g), Const(bracket), + Const(rootfind) ) - @test dp ≈ -ones(3) rtol = 1.0e-8 + @test root === event_root(p, g, bracket, rootfind) + @test first(dp) ≈ 1 rtol = 10 * eps(T) +end + +@testset "Event root sensitivities reject degenerate crossings" begin + # Zero time derivative at the exact root t = 0, and a slope that overflows Float32. + for (p, g, bracket) in ( + (0.0, (t, p) -> t^3 - p, (-1.0, 1.0)), + (0.71f0, (t, p) -> ((t - p) * 1.0f38) * 10.0f0, (0.7, 0.75)), + ) + @test_throws ErrorException Enzyme.autodiff( + Reverse, event_root, Active, Active(p), Const(g), Const(bracket), + Const(SciMLBase.LeftRootFind) + ) + end +end + +@testset "Parameter-dependent continuous event time gradients ($T)" for T in (Float32, Float64) + rtol = T === Float32 ? 2.0e-5 : 1.0e-8 + # u′ = 1 from 0 hits u = p > 0.75 once, at t = p, so u(1) = 1.5 - p. + p = T[0.78, 0.84, 0.93] + rhs = (u, p, t) -> SVector(one(eltype(u))) + for condition in (linear_event, curved_event) + @test event_time_loss(p, rhs, condition, 0, backend) ≈ sum(T(1.5) .- p) rtol = rtol + dp = zero(p) + Enzyme.autodiff( + Reverse, event_time_loss, Active, Duplicated(p, dp), + Const(rhs), Const(condition), Const(0), Const(backend) + ) + @test dp ≈ -ones(T, 3) rtol = rtol + end +end +@testset "Nonlinear continuous event time gradients" begin # u′ = u from 1 hits u = p at t = log(p), so u(1) = 0.5e / p. p = [1.3, 1.7, 2.2] rhs = (u, p, t) -> u - @test event_time_loss(p, rhs, 1.0, backend) ≈ sum(0.5 * ℯ ./ p) rtol = 1.0e-7 + @test event_time_loss(p, rhs, linear_event, 1, backend) ≈ sum(0.5 * ℯ ./ p) rtol = 1.0e-7 dp = zero(p) Enzyme.autodiff( Reverse, event_time_loss, Active, Duplicated(p, dp), - Const(rhs), Const(1.0), Const(backend) + Const(rhs), Const(linear_event), Const(1), Const(backend) ) @test dp ≈ -0.5 * ℯ ./ p .^ 2 rtol = 1.0e-6 end From 2eabab5189008eacde32f5b9ff8408efa03f6c83 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 3 Oct 2026 04:11:45 -0400 Subject: [PATCH 3/4] Carry event-time sensitivities through exact step-endpoint events MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An event whose condition is exactly zero at the step end bypassed root finding and returned `top_t` with no sensitivity, and both the time change and the final save skip interpolation when the times are equal, so the gradient was silently zero (e.g. `u′ = 1`, event at `t = p = 0.75`, `dt = 0.25`). Under Enzyme only, that branch now applies the implicit-function correction, and the equal-time paths add `u - (I(t_step) - I(t_event))`, which is exactly `u` in the primal but carries the event time's sensitivity relative to the step end. The non-AD forward path is unchanged. The slope of the implicit correction is no longer wrapped in `ignore_derivatives`: the correction's numerator is exactly zero, so the slope's own sensitivity drops out, and Enzyme cannot apply `ignore_derivatives` to the constant zero slope of a time-independent condition. Co-Authored-By: Chris Rackauckas Co-Authored-By: Claude Agent-Harness: Claude Code 2.1.287 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-DiffEqGPU.jl-533/log.txt on amdci2.julia.csail.mit.edu --- .../integrators/integrator_utils.jl | 20 ++++++--- src/ensemblegpukernel/kernels.jl | 6 +++ test/enzyme/gradients.jl | 42 +++++++++++++++++-- 3 files changed, 59 insertions(+), 9 deletions(-) diff --git a/src/ensemblegpukernel/integrators/integrator_utils.jl b/src/ensemblegpukernel/integrators/integrator_utils.jl index 0ab9ff8c..32d5f68c 100644 --- a/src/ensemblegpukernel/integrators/integrator_utils.jl +++ b/src/ensemblegpukernel/integrators/integrator_utils.jl @@ -230,6 +230,12 @@ end integrator.step_idx -= Int(round((integrator.t - t) / integrator.dt)) integrator.t = t #integrator.dt = integrator.t - integrator.tprev + elseif within_autodiff() + # An event exactly at the step end leaves the values unchanged, but its time may + # carry a different sensitivity than the step end, which must reach the state. + # The difference of equal interpolated values is +0.0, so `u` is unchanged. + integrator.u = integrator.u - (integrator(integrator.t) - integrator(t)) + integrator.t = t end end @inline function DiffEqBase.change_t_via_interpolation!( @@ -415,12 +421,11 @@ struct EventTimeTag end # The bracketing iterations carry no derivative information about the root, so attach # the implicit-function-theorem sensitivity dt = -∂f/∂θ / ∂f/∂t at the converged root. -# The correction term is identically zero in the primal, so the root is unchanged. +# The correction term is identically zero in the primal, so the root is unchanged, and +# its numerator being zero also makes the slope's own sensitivity drop out. @inline function _implicit_root(f, root) t = ignore_derivatives(root) - slope = ignore_derivatives( - _event_time_derivative(f(ForwardDiff.Dual{EventTimeTag}(t, one(t)))) - ) + slope = _event_time_derivative(f(ForwardDiff.Dual{EventTimeTag}(t, one(t)))) if iszero(slope) || !isfinite(slope) error("Cannot differentiate a continuous callback event time: the condition's time derivative at the event is zero or non-finite (tangential or singular crossing).") end @@ -470,15 +475,18 @@ end bottom_sign * top_sign <= 0 event_idx = 1 + zero_func(abst, p = nothing) = DiffEqBase.get_condition(integrator, callback, abst) if !event_occurred callback_t = integrator.t residual = zero(bottom_condition) - elseif callback.rootfind == SciMLBase.NoRootFind || iszero(top_sign) + elseif callback.rootfind == SciMLBase.NoRootFind callback_t = top_t residual = zero(bottom_condition) + elseif iszero(top_sign) + callback_t = within_autodiff() ? _implicit_root(zero_func, top_t) : top_t + residual = zero(bottom_condition) else - zero_func(abst, p = nothing) = DiffEqBase.get_condition(integrator, callback, abst) callback_t = gpu_find_root(zero_func, (bottom_t, top_t), callback.rootfind) residual = zero_func(callback_t) end diff --git a/src/ensemblegpukernel/kernels.jl b/src/ensemblegpukernel/kernels.jl index 448d46f0..18185ffa 100644 --- a/src/ensemblegpukernel/kernels.jl +++ b/src/ensemblegpukernel/kernels.jl @@ -58,6 +58,12 @@ if integ.t > tspan[2] && saveat === nothing @inbounds us[end] = integ(tspan[2]) @inbounds ts[end] = tspan[2] + elseif within_autodiff() && integ.t == tspan[2] && saveat === nothing + # A grid ending exactly at tspan[2] can still carry a different time + # sensitivity (e.g. after an event on a step endpoint). The difference of + # equal interpolated values is +0.0, so the saved state is unchanged. + @inbounds us[end] = integ.u - (integ(integ.t) - integ(tspan[2])) + @inbounds ts[end] = tspan[2] end else @inbounds us[1] = prob.u0 diff --git a/test/enzyme/gradients.jl b/test/enzyme/gradients.jl index c3c8813f..038bb8b8 100644 --- a/test/enzyme/gradients.jl +++ b/test/enzyme/gradients.jl @@ -160,12 +160,15 @@ end end @testset "Event root sensitivities reject degenerate crossings" begin - # Zero time derivative at the exact root t = 0, and a slope that overflows Float32. + # Zero time derivative at the exact root t = 0, a slope that overflows Float32, and + # a condition whose time derivative cancels. The slopes depend on `p` at run time, + # as kernel conditions always do through the integrator state. for (p, g, bracket) in ( (0.0, (t, p) -> t^3 - p, (-1.0, 1.0)), - (0.71f0, (t, p) -> ((t - p) * 1.0f38) * 10.0f0, (0.7, 0.75)), + (0.71f0, (t, p) -> ((t - p) * p * 1.0f38) * 10.0f0, (0.7, 0.75)), + (0.5, (t, p) -> p * t - p * t + (one(t) - p), (-1.0, 1.0)), ) - @test_throws ErrorException Enzyme.autodiff( + @test_throws r"time derivative at the event is zero or non-finite" Enzyme.autodiff( Reverse, event_root, Active, Active(p), Const(g), Const(bracket), Const(SciMLBase.LeftRootFind) ) @@ -200,3 +203,36 @@ end ) @test dp ≈ -0.5 * ℯ ./ p .^ 2 rtol = 1.0e-6 end + +time_event(u, t, integrator) = t - integrator.p[1] +reset_zero!(integrator) = (integrator.u = zero(integrator.u)) +double_state!(integrator) = (integrator.u = 2 * integrator.u) + +function endpoint_event_loss(p, affect!, backend) + prob = ODEProblem{false}( + (u, p, t) -> SVector(1.0), SVector(0.0), (0.0, 1.0), SVector(p[1]) + ) + cb = ContinuousCallback(time_event, affect!; save_positions = (false, false)) + sol = solve( + EnsembleProblem(prob; safetycopy = false), GPUTsit5(), + EnsembleGPUKernel(backend, 0.0); trajectories = 3, adaptive = false, + dt = 0.25, callback = cb, merge_callbacks = true, save_everystep = false + ) + return sum(s -> only(s.u[end]), sol.u) / 3 +end + +@testset "Event time gradients at step endpoints ($(nameof(affect!)))" for (affect!, sign) in ( + (reset_zero!, -1), (double_state!, 1), + ) + # u′ = 1 from 0 with the event at t = p: resetting gives u(1) = 1 - p and doubling + # gives u(1) = 2p + (1 - p) = 1 + p. p = 0.5 and 0.75 land exactly on step endpoints. + for p in (0.5, 0.74, 0.75, 0.76) + @test endpoint_event_loss([p], affect!, backend) ≈ 1 + sign * p rtol = 1.0e-12 + dp = [0.0] + Enzyme.autodiff( + Reverse, endpoint_event_loss, Active, Duplicated([p], dp), + Const(affect!), Const(backend) + ) + @test only(dp) ≈ sign rtol = 1.0e-10 + end +end From 561cad4af45140c35454ee056ae04ac5a0244c51 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas-Claude Date: Sat, 3 Oct 2026 06:10:47 -0400 Subject: [PATCH 4/4] Hold the event time fixed in the implicit correction's parameter partial MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The numerator of the implicit-function correction evaluated the condition through `get_condition`'s endpoint shortcut, so for an event exactly on a step endpoint it used the stored step-end state, whose sensitivity follows the moving endpoint (`u′(T)·∂T/∂θ`). That dropped the initial-time sensitivity and introduced a spurious step-size sensitivity for state-dependent conditions. The value and the time partial now both come from the single dual evaluation at the detached root, which always interpolates, so ∂g/∂θ holds the evaluation time fixed. A non-finite condition value at the root is reported as degenerate. Co-Authored-By: Chris Rackauckas Co-Authored-By: Claude Agent-Harness: Claude Code 2.1.287 Agent-Model: claude-opus-5-5 Agent-Session: local session, transcript at /home/crackauc/sandbox/goals/issue-backlog/jobs/fix-DiffEqGPU.jl-533/log.txt on amdci2.julia.csail.mit.edu --- .../integrators/integrator_utils.jl | 17 ++++--- test/enzyme/gradients.jl | 44 +++++++++++++++++++ 2 files changed, 55 insertions(+), 6 deletions(-) diff --git a/src/ensemblegpukernel/integrators/integrator_utils.jl b/src/ensemblegpukernel/integrators/integrator_utils.jl index 32d5f68c..82b74402 100644 --- a/src/ensemblegpukernel/integrators/integrator_utils.jl +++ b/src/ensemblegpukernel/integrators/integrator_utils.jl @@ -418,18 +418,23 @@ struct EventTimeTag end @inline _event_time_derivative(y::ForwardDiff.Dual{EventTimeTag}) = ForwardDiff.partials(y, 1) @inline _event_time_derivative(y) = zero(y) +@inline _event_value(y::ForwardDiff.Dual{EventTimeTag}) = ForwardDiff.value(y) +@inline _event_value(y) = y # The bracketing iterations carry no derivative information about the root, so attach -# the implicit-function-theorem sensitivity dt = -∂f/∂θ / ∂f/∂t at the converged root. -# The correction term is identically zero in the primal, so the root is unchanged, and -# its numerator being zero also makes the slope's own sensitivity drop out. +# the implicit-function-theorem sensitivity dτ = -∂f/∂θ / ∂f/∂t at the converged root. +# Both partials come from one dual evaluation at the detached root, which interpolates +# the state even at a step endpoint, so ∂f/∂θ holds the evaluation time fixed instead of +# following a moving endpoint. The correction is identically zero in the primal, so the +# root is unchanged, and its zero numerator makes the slope's own sensitivity drop out. @inline function _implicit_root(f, root) t = ignore_derivatives(root) - slope = _event_time_derivative(f(ForwardDiff.Dual{EventTimeTag}(t, one(t)))) - if iszero(slope) || !isfinite(slope) + y = f(ForwardDiff.Dual{EventTimeTag}(t, one(t))) + slope = _event_time_derivative(y) + ft = _event_value(y) + if iszero(slope) || !isfinite(slope) || !isfinite(ft) error("Cannot differentiate a continuous callback event time: the condition's time derivative at the event is zero or non-finite (tangential or singular crossing).") end - ft = f(t) return t - convert(typeof(t), (ft - ignore_derivatives(ft)) / slope) end diff --git a/test/enzyme/gradients.jl b/test/enzyme/gradients.jl index 038bb8b8..2c977b40 100644 --- a/test/enzyme/gradients.jl +++ b/test/enzyme/gradients.jl @@ -236,3 +236,47 @@ end @test only(dp) ≈ sign rtol = 1.0e-10 end end + +function event_fields_loss(x, condition, adaptive, backend) + a, b, t0, tf, c, r, dt = x + prob = ODEProblem{false}( + (u, p, t) -> SVector(p[1]), SVector(b), (t0, tf), SVector(a, c, r) + ) + affect!(integrator) = (integrator.u = SVector(integrator.p[3])) + cb = ContinuousCallback(condition, affect!; save_positions = (false, false)) + sol = solve( + EnsembleProblem(prob; safetycopy = false), GPUTsit5(), + EnsembleGPUKernel(backend, 0.0); trajectories = 3, adaptive, dt, + callback = cb, merge_callbacks = true, save_everystep = false + ) + return sum(s -> only(s.u[end]), sol.u) / 3 +end + +mixed_event(u, t, integrator) = u[1] + 10 * t - integrator.p[2] +state_event(u, t, integrator) = u[1] - integrator.p[2] + +@testset "Event time gradients for all problem fields (adaptive = $adaptive)" for adaptive in (false, true) + # x = [a, b, t0, tf, c, r, dt] for u′ = a, u(t0) = b, reset to r, dt = 0.25. + # u + 10t = c fires once at τ = (c - b + a t0) / (a + 10), so L = r + a (tf - τ). + # c = 8.25 puts τ = 0.75 exactly on a step endpoint. + for c in (8.14, 8.25, 8.36) + x = [1.0, 0.0, 0.0, 1.0, c, 2.0, 0.25] + dx = zero(x) + @test event_fields_loss(x, mixed_event, adaptive, backend) ≈ 3 - c / 11 atol = 1.0e-12 + Enzyme.autodiff( + Reverse, event_fields_loss, Active, Duplicated(x, dx), + Const(mixed_event), Const(adaptive), Const(backend) + ) + @test dx ≈ [1 - 10c / 121, 1 / 11, -1 / 11, 1, -1 / 11, 1, 0] atol = 1.0e-10 + end + # u = c fires at τ₁ = t0 + (c - b) / a and, after each reset to r = 0, every c / a, + # giving six events per solve, several within one original step: L = a (tf - τ₆). + x = [1.0, 0.0, 0.0, 1.0, 0.15, 0.0, 0.25] + dx = zero(x) + @test event_fields_loss(x, state_event, adaptive, backend) ≈ 0.1 atol = 1.0e-12 + Enzyme.autodiff( + Reverse, event_fields_loss, Active, Duplicated(x, dx), + Const(state_event), Const(adaptive), Const(backend) + ) + @test dx ≈ [1, 1, -1, 1, -6, 6, 0] atol = 1.0e-10 +end