agentleFS
90184479018447/julia-pro-p/skills/differentiation/SKILL.md

differentiation

Skill0 starsChanged 3 days agoMITView on GitHub

Differentiation in Julia: pick Zygote, Enzyme, ForwardDiff, or DifferentiationInterface, write ChainRules rules, and prove a gradient against finite differences. Use when a gradient is wrong, missing, or slow.

1 other project uses a version of this.

Adopted by

Most recently taken up by

The file

Files
SKILL.md

Differentiation

Two questions decide the backend, and they are independent:

  • Mode — forward (cost grows with inputs) or reverse (cost grows with outputs).
  • Mechanism — source-to-source (Zygote), LLVM-level (Enzyme), operator overloading (ForwardDiff), or a rule you write.

The third question is the one that produces the bug reports: does the code mutate, branch on values, or call out to C?

Choosing

SituationBackendWhy
n parameters, m outputs, n \ll mForwardDiffone pass, no tape
n \gg m (a loss, a scalar objective)Zygote or Enzymereverse mode
mutation, setindex!, push!EnzymeZygote cannot
a C or Fortran call in the pathEnzyme (or an rrule)LLVM sees through ccall
Hessian, or a Jacobian of a gradientForwardDiff over Zygote, or Enzyme Hessianmixed mode
a library that must accept any of themDifferentiationInterfacethe seam
an expression, not a programsymbolic-mathSymbolics, then build_function

Parameter count is the pivot, not taste: at 5 parameters forward mode wins outright; at 5 million it cannot be afforded.

Zygote

using Zygote
g = Zygote.gradient(f, x)[1]              # reverse mode, scalar output
val, g = Zygote.withgradient(f, x)        # value and gradient in one pass
y, pb = Zygote.pullback(f, x); g = pb(1.0)[1]   # manual VJP

Its limits are hard errors, and each names the fix:

Error or limitFix
Mutating arrays is not supportedZygote.Buffer, or restructure to allocate a new array
Can't differentiate foreigncall expressionwrite an rrule, or switch to Enzyme
try/catch in the pathmove the rescue outside the differentiated function
Dict mutationNamedTuple, or a buffer indexed by an integer
a branch on a differentiated valueifelse keeps both sides live; a branch is fine when the predicate is not differentiated

Enzyme

using Enzyme
f!(y, x) = (y[1] = x[1]^2 + x[2]^2; nothing)
dx = zeros(2)
Enzyme.autodiff(Reverse, f!, Duplicated([1.0], [1.0]), Duplicated([3.0, 4.0], dx))
AnnotationMeaningUse
Active(x)differentiated scalarthe objective's output
Duplicated(x, dx)primal and shadowarrays, mutating code
Const(x)not differentiatedparameters, indices
DuplicatedNoNeed(x, dx)shadow onlywhen the primal is not needed downstream

A shadow array must be zeroed before the call; Enzyme accumulates into it. Enzyme.setabstol! sets the activity of an abstractly typed argument when the type is only known at runtime.

ForwardDiff

using ForwardDiff
ForwardDiff.gradient(f, x)
ForwardDiff.jacobian(x -> [x[1]^2, x[1]*x[2]], [3.0, 4.0])
ForwardDiff.hessian(f, x)
ForwardDiff.gradient(f, x, ForwardDiff.GradientConfig(f, x, ForwardDiff.Chunk{4}()))

Chunk size is the SIMD width: too small wastes passes, too large wastes lanes. Chunk{4}() is a reasonable default for Float64 without AVX-512.

Dual numbers must fit the container type. A preallocated Vector{Float64} cannot hold a Dual, so an in-place function called under ForwardDiff allocates a new array per call or fails: preallocate through PreallocationTools.DiffCache and pass the cache.

Rules you write

using ChainRulesCore
function ChainRulesCore.rrule(::typeof(myfunc), x)
    y = myfunc(x)
    myfunc_pullback(dy) = (NoTangent(), dy .* dmyfunc(x))
    return y, myfunc_pullback
end
function ChainRulesCore.frule((_, dx), ::typeof(myfunc), x)
    y = myfunc(x)
    return y, dmyfunc(x) .* dx
end
@non_differentiable sortdigits(::Any)

Both directions when both are cheap; only the one your backends use otherwise. NoTangent() for the function itself, ZeroTangent() for an argument whose derivative is a structural zero.

Proving a gradient

using FiniteDifferences
ad = Zygote.gradient(f, x)[1]
fd = FiniteDifferences.grad(central_fdm(5, 1), f, x)[1]
@test maximum(abs.(ad .- fd)) < 1e-6

A gradient test belongs in the suite, not in a notebook: it is the only thing that catches a silently wrong rrule after a refactor. Check a second point — a rule that is right at the origin and wrong elsewhere passes a single-point test.

proof-list applies: the gradient is proven by the comparison, and the comparison is committed.

Symbolic differentiation

For a derivative you want as an expression — to simplify, to inline, to emit C — differentiate symbolically and then compile the result: see ../symbolic-math/SKILL.md, which is the Symbolics.gradient / build_function path.

The split: symbolic for a formula you inspect or ship, AD for a program you run.

Done when

The gradient is proven against central finite differences on a random input (FiniteDifferences.central_fdm(5, 1)) at the precision you run in, and the backend's restrictions are respected: no mutation or try/catch under Zygote, explicit Active/Duplicated annotations under Enzyme, and a hand-written rrule only where the generic rule is wrong rather than slow.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.