Repository navigation
Description
With registered Enzyme (0.13.220), a prepared reverse gradient over a NonAllocatingKernel can return NaN at every later point after one call whose gradient is not finite. RKPPL's prepare_sampler uses such a kernel by default, so one extreme point can leave a sampler with NaN gradients for the rest of the run.
Cause (in Enzyme)
- The reverse rules of BLAS
gemv,gemm,symv,symmandsyrkwithbeta == 0multiply the output's adjoint bybetainstead of clearing it.0 * NaNand0 * InfareNaN, so a non-finite adjoint stays in the output's shadow. - The reverse rule of
BLAS.blascopy!never clears its destination's adjoint. - A non-allocating gradient passes its reused buffers to DifferentiationInterface as a
Cachecontext. DifferentiationInterface creates that shadow once, when it prepares the gradient, and reuses it on every call without zeroing it. A matrix product step writes its result withmul!, so theNaNin the product buffer's shadow reaches every later gradient.
The ordinary PreparedKernel gradient is not affected, because it allocates a fresh product on each call.
Which Julia builds show it: the matrix routines (gemm, symm, syrk) keep the NaN with every build. For gemv and symv it depends on OpenBLAS: 0.3.29 and later (Julia 1.12, 1.13) keep it, and 0.3.23 (the official Julia 1.10 build) does not.
Reproduction
using ReactiveKernels, MutatingFunctions, Enzyme
using DifferentiationInterface: AutoEnzyme
spec = @kernel product_target(B, X, Y) = begin
eta = X * B
r = exp.(eta) # overflows past 709.78
p = r ./ (1 .+ r) # Inf / Inf is NaN there
lp = -sum(abs2, Y .- p)
return lp
end
X = [1.0 0.5; 0.2 1.0; -0.3 0.4]
Y = [0.2 0.6; 0.7 0.1; 0.5 0.4]
good = [0.3 0.1; -0.2 0.4]
bad = [900.0 0.0; 0.0 0.0]
ordinary = prepare(spec; have = (:B, :X, :Y), want = :lp, bound = (; X, Y))
ad = prepare_ad(prepare_nonallocating(ordinary, good),
AutoEnzyme(mode = Enzyme.Reverse), good; active = :B)
g = similar(good)
ad_value_and_gradient!(ad, g, good); first_gradient = copy(g)
ad_value_and_gradient!(ad, g, bad) # NaN value and gradient, as expected
ad_value_and_gradient!(ad, g, good)
g == first_gradient # false with registered Enzyme: g has NaN entriesStatus
The Enzyme.jl dogfood branch of nsiccha/Enzyme.jl repairs the rules from commit cb2b2b1e (Enzyme.has_dogfood_repair(:blas_overwritten_output)): after a reverse pass through a BLAS call that overwrote its output, that output's shadow is exactly zero.
test/test_nonallocating_nonfinite_ad.jl (run by test/run_nonallocating_integration.jl) requires the first gradient back bit for bit when the repair is present. Without it, the matrix-matrix case is marked @test_broken and the matrix-vector case is not asserted, because its outcome depends on the OpenBLAS build. test/test_ppl_nonallocating_sampler.jl checks the same for an RKPPL sampler.
Close this issue once registered Enzyme carries an equivalent fix, and then make those checks unconditional.
Activity