Repository navigation
No silent plain AD: the rule takes ranges and lazy wrappers, and names what it does not - #955
Conversation
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
|
On the review's point about Generated by Claude Code |
Try this Pull Request!Option 1: Julia Package ManagerOpen Julia and type: import Pkg
Pkg.activate(temp=true)
Pkg.add(url="https://github.com/EpiAware/ComposableRecurrences.jl", rev="claude/visible-plain-ad")
using ComposableRecurrencesOption 2: Local CheckoutIf you have the repo locally: git checkout claude/visible-plain-ad
julia --project=. -e "using Pkg; Pkg.instantiate()" |
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
|
Generated by Claude Code |
Benchmark comparison vs baseMinimum time per call. Buckets are PR time as a % of base, so lower is faster (🟢 faster, ⚪ within 5%, 🔴 slower). Counts of benchmarks per bucket:
Evaluation — 24 benchmarks (by time change)
AD gradients — 63 benchmarks (by time change)
|
|
Generated by Claude Code |
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ixMLmTv9ZNyQj17Pp8
Hand-over noteThis session stops here. The branch What each commit does
What was verifiedAll on Julia 1.13.4, on the tree at
What the AD runs still owe
Conflicts with
|
Take main's split of the AD fixtures and its Reactant results, and make the user copy of the hazard depletion valid at the zero vector in registry.jl. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ivYt11uRBnyJ1NF4ow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WwC7ivYt11uRBnyJ1NF4ow # Conflicts: # docs/src/explanation/adjoints-and-backends.md
Follow-up to #952: no call takes plain AD silently, the cause of the trace gap, two design proposals, and the runs #952 left out.
1. Silent routes to plain AD
The rule's gate is a test on types, and a call that failed it took plain AD with no message.
I listed every way a call can fail it and decided each on its merits.
StepRangeLen,LinRange) as a kernel, a modifier's parameter, an input, a history or aDiagonalcoupling's diagonalPermutedDimsArray,SymmetricorHermitianof anArrayFill, a user's array type, a symmetric wrapper of a sparse matrixpullback!BigFloat, any real number that is not an IEEE floatNoAdjointHow the rule takes a range.
The rule writes cotangents into arrays, and a backend's tangent of a range is not an array.
So a call with a range or one of the wrappers above takes a third route,
:dense: each such leaf is copied to anArrayoutside the rule, and the rule runs on the copy.The backend differentiates the copy, so a range built from parameters keeps their gradients (tested:
range(θ[1], θ[2]; length = n)as kernel, parameter, input, history and coupling, on Mooncake and Enzyme reverse, against ForwardDiff).The operator is rebuilt with the new field types from its type parameters, without its constructors.
A struct that cannot be rebuilt that way is left as it is and named.
The route is decided from the types, so a call that already took the rule compiles to what it did before.
Only Base and LinearAlgebra types whose values
collectgives are copied.Any other array type is not: it may be a device or traced array, or sparse, where a copy would be wrong or dense.
StaticArrays and FillArrays are in no test environment, so
SVectorandFillare covered by the rule for unknown types, tested with a stand-in.What the copy costs, on the model of the parity table (5 strata, 20 lags, 200 steps, Mooncake reverse, one process each, μs):
mainmainVectorPermutedDimsArrayA forward call with no AD pays the copy too: 8% for an input of 1,000 entries behind a
PermutedDimsArray.A range kernel is faster copied than read in place.
How the rest is named.
The plain route already calls a no-op hook that Mooncake and Enzyme replace.
In reverse mode the hook now logs the existing one-time
@info, with the field path or argument position and its type:It is logged from the backend's rule, so only when a rule was there to take: a forward call, forward mode and ForwardDiff log nothing.
The hook is skipped, as before, for a call that holds a number type no rule runs, so dual numbers pay nothing.
After the first call of a signature it costs one lookup under a lock, on a route that is already plain AD.
2. The trace gap
I had the cause wrong.
#952 said the gap was the generic trace pullback evaluating
stepagain.I made the change asked for: the pullback now reads the step's value from the next modifier's record or the output, and its state from the next step's record or the final state, which the traced record carries.
Calls that record no trace build no traced record, so they read nothing more.
It works on the host and on a device, and it did not move the time: 79.0 to 81.0 μs on
mainagainst 80.1 to 81.2 μs here, in alternating fresh processes, against 72 to 74 μs for the built-in.The cause, measured.
I swapped one part of the user's copy at a time, in one process, eight rounds:
Depletion, for referencemainSo about 6 μs of the 7.6 is the dual-number pass over
trace, 4 for the four step values and 2 for the parameters.tracehere is(s′, v′, v - v′): every partial is a constant 0, 1 or -1.The pass sums cotangent times partial, and the compiler cannot drop a product with a constant zero, because the cotangent may be
NaN.A fix I made and then dropped.
In the contraction I made a zero partial add nothing, whatever its cotangent, so the compiler could drop the terms it knows are zero.
It brought the ratio from 1.10 to 1.03 to 1.04, and
benchmark/ab.jlfound no cell outside noise over 36 cells.It also changed a result: zero times a
NaNor infinite cotangent became zero.The test was on the partial's value, as dual numbers cannot tell a partial that is zero by structure from one that is zero at the point.
So I compared the routes on a step with two inputs
(x, θ)and two outputs, with a non-finite cotangent on the first output.Each cell is the cotangent of
(x, θ).main)(2x, 3θ), cotangent(Inf, 1): the first output does not readθ(Inf, NaN)(Inf, 3)(Inf, 3)(Inf, 3)(Inf, 3)(Inf, NaN)(max(x, 0), θ)atx = -1, cotangent(Inf, 1)(NaN, NaN)(0, 1)(0, 1)(NaN, 1)(0, 1)(NaN, NaN)(x^2, θ)atx = 0, cotangent(Inf, 1)(NaN, NaN)(0, 1)(NaN, 1)(NaN, 1)(NaN, 1)(NaN, NaN)(θ x, θ)atx = 0, cotangent(NaN, 1)(NaN, NaN)(NaN, 1)(NaN, NaN)(NaN, NaN)(NaN, NaN)(NaN, NaN)(x (x/θ)^0.5, θ)atx = 0, the empty pool, cotangent(1, 1)(NaN, NaN)(NaN, NaN)(0, 1)(0, 1)(NaN, NaN)(NaN, NaN)What the table says:
maingives what ForwardDiff gives in every row. That is its contract: the local derivative is the step on dual numbers, and it never drops a non-finite cotangent.θwhere every other route returnsNaN. So it could hide aNaNthat marks a real fault upstream, which the IEEE pass cannot.NaNis made inside the dual arithmetic (zero times an infinite slope), before the contraction, soHazard's handstep_pullbackis needed either way and returns what it did.NaNlands (B and D split Mooncake from Enzyme). That holds onmainand is not new here; parity of the user's copy with the built-in is claimed for finite cotangents, and the page does not claim more.A few percent does not justify a result that no other route gives, so the contraction is as it was on
main, and a test now pins the IEEE behaviour.The commits are in the branch's history (
ba759a1, undone in69ba041) if the owner wants to look.Where that leaves the gap.
It stays at about 1.10.
Closing it without changing a result takes a
trace_pullbackbesidestep_pullback, with which the user's copy times as the closed-form row above.That is a design addition and I have not made it.
I also tried skipping a zero parameter cotangent before the store; in two alternating pairs of runs it was no faster, so it is not here either.
I kept the record change: it removes one evaluation of
stepper stratum and step from a traced reverse pass, which a costly step would pay for, though this step does not show it.3. Two design questions for the owner
Nothing below is implemented.
(a)
θdoes not reach nested partsWhat happens now.
θis the modifier's fields, each parameter read at the stratum and time.The read goes into tuples and named tuples and stops at any other struct, which reaches
stepas it is.The local derivative seeds the float leaves of
θ, so a float inside a nested struct is out of its reach, and a modifier that holds one takes plain AD ("holds floats in a field that is not a parameter").Depletionis a tuple of draws and flows, each a struct with its own form, population, weights or demand.So it cannot be a pure step: it has private
_step, pullback and trace methods, and a form gets its parameters through a private call that appendsNto the form's fields.Proposal.
Let a type declare that it is a part: a struct whose fields are read as a modifier's are.
θthen holds each part as a value of the same type with its parameters read, sostepcan still dispatch on the part's type (a form).The cotangent side follows the same shape: the mirror of a part is already the named tuple of its fields' mirrors.
What it would take.
ispart(::Type{<:MyDraw}) = true, false by default.Without it a nested struct would change meaning for existing user types, which is why it is not automatic.
_read_paramand_add_leaf!insrc/interface/canonical.jlgain a method for a part, rebuilt without its constructor as the rule's leaves are (_rebuild_leaves)._rule_fieldand the seeding insrc/interface/duals.jl(_flat,_unflat,_shaped) walk into a part.About 100 to 150 lines, with tests, and the device kernels need no change as the read stays per stratum.
test_step) and the developer pages gain the nested case.Depletionover it is a second, larger change:src/depletion/pool.jlandflows.jlare about 1,700 lines of private methods.The parity table is the guard: the one-pool hazard copy already matches the built-in through the public route.
What it would cost.
θfor the compiler: aDepletionwith three pools and four flows would read about a dozen parts per stratum and step.The risk is inference depth and compile time, not run time; it needs measuring on the largest registry scenario before the rewrite is committed to.
weights,into,overflow, a form inside aFlow, and a state record that is skipped when nothing reads it.Those are properties of
Depletion's pool layout, and would become public only whenDepletionitself is written through the route.Recommendation.
Do the declaration and the nested read first, on its own, with a user type of two nested parts as the test.
Decide on the
Depletionrewrite after its compile time is measured.(b) A user's coupling or whole-step modifier has no route to the device rule or the fused reverse
What happens now.
A recurrence takes the rule on device arrays when
_device_readyholds: its kernel, coupling and every modifier must each have a reverse step that runs on the device.A pure step always has one, as the package runs it inside its own kernels.
A coupling has one only if it is
I, aDiagonal, or a matrix on the device.A whole-step modifier has one only if it is built in.
A user's
forward!andpullback!are assumed to index their arrays one entry at a time, which a device array does not allow, so the whole recurrence takes plain AD.With this PR that call is named in the notice ("X has no rule on device arrays").
The fused reverse is narrower still: it is one kernel per step that does a dense matrix coupling's transposed product and the delay kernel's reverse together, and it exists for a device matrix and a device sparse matrix only.
Proposal, in two steps.
Say
ondevice(::MyCoupling) = true: a promise thatforward!andpullback!use whole-array operations (broadcasts, products, reductions) and no scalar indexing._device_couplingand_device_modifierthen return it for a user's type.The rule calls the user's methods once per step on device vectors, as it calls the built-in
Redistribute.A coupling declared
islinearalready runs as the matrix itsforward!gives, built once per call.On a device that matrix can be built on the host and moved, and it is then a device matrix: it takes the device rule and the fused reverse with no further code.
What it would take.
JLArray.I tried it with the two internal methods in place of the declaration: a broadcast-only whole-step modifier and a broadcast-only nonlinear coupling each took the rule on
JLArraywith scalar indexing off, and their outputs and cotangents matched the host's.So the reverse pass needs no change for step 1.
adaptto the input's array type.docs/src/developer/with a tested example of each, and theAdapt.adapt_structuremethod the user already writes for a pure step.What it would cost.
Each step makes one kernel launch per array operation in the user's method, where a fused step makes one.
That is the cost the built-in whole-step modifiers already pay, and it is far below plain AD of the whole recurrence on a device.
The check function for a new type should run it with scalar indexing off.
S × Sdense matrix on the device and builds it once per call.That is as the host does now, and it loses any sparsity the user's
forward!had.I would not design that until a model needs it: the fused path is worth most for dense matrices, which are linear.
Recommendation.
Step 1 and step 2 together are small and cover what the audit found.
The per-stratum coupling protocol is the open design question and can wait.
4. Runs
The branch is
mainmerged in at9f60eb1; it has no conflicts.All runs are local, on Julia 1.13.4.
On
9f60eb1:skip_quality): 41,452 passed, 1 broken (already marked), 0 failed.quality_only): 33 items passed.The held-out scenario hangs or segfaults in LLVM while Enzyme compiles it, on
mainas well; it is entry 10 of Enzyme.jl: upstream reports #931, and Carry one unit in registers and hold short-kernel caches strata × time #1008 makes it compile again.On the earlier merge
eabe769(mainas of #1005), bytest/adtag:All four errors are "Growth rate and profile of strata that mix", which fails the same way on
mainat that point (ReverseDiff: growth of a stratified recurrence stops at an ambiguous hcat #1003); Build the growth Jacobian without hcat, so ReverseDiff can take it, and replay compiled tapes at a second point #1006 and Growth under ReverseDiff: no hcat, a valid zero point, and a replay check #1022 fix it onmain.Not run: the AD tags on
9f60eb1(only slice 2 above), Enzyme forward on the full registry, the Reactant suite (this PR changes none of its rows), and a local docs build.https://claude.ai/code/session_01WwC7ivYt11uRBnyJ1NF4ow
Generated by Claude Code