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
- retospect/precis-mcptheir own version, first seen Nov 22, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 1
- retospect/precis-mcp★ 13same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository55 other files it gives its agents.
- advanced-optimizationSkill
- bayesian-inferenceSkill
- bayesian-pinnSkill
- bayesian-ude-workflowSkill
- catalyst-reactionsSkill
- continuum-mechanics-and-rheologySkill
- control-theorySkill
- creating-julia-appSkill
- debugging-toolkitSkill
- differential-equationsSkill
- equation-discoverySkill
- experiment-trackingSkill
- fem-feaSkill
- julia-graph-neural-networksSkill
- julia-languageSkill
- julia-ml-and-dlSkill
- julia-model-deploymentSkill
- julia-paper-implementationSkill
- julia-pro-helpSkill
- julia-pro-modeSkill
- julia-reinforcement-learningSkill
- modeling-toolkitSkill
- neural-pdeSkill
- nonlinear-dynamicsSkill
- numerical-methods-implementationSkill
- package-development-workflowSkill
- performance-tuningSkill
- physical-learning-systemsSkill
- playbook-debugSkill
- playbook-model-validateSkill
- playbook-package-releaseSkill
- playbook-paper-implementSkill
- playbook-perfSkill
- playbook-test-specSkill
- principle-both-sidesSkill
- principle-breakingSkill
- principle-file-is-truthSkill
- principle-gateSkill
- principle-limitsSkill
- principle-loud-failureSkill
- principle-one-stepSkill
- principle-proof-listSkill
- principle-rebuttalSkill
- principle-runtime-surfaceSkill
- principle-three-boundsSkill
- principle-three-clocksSkill
- scientific-visualizationSkill
- sciml-and-diffeqSkill
- setup-julia-proSkill
- signal-processingSkill
- simulation-and-hpcSkill
- statistical-physicsSkill
- symbolic-mathSkill
- web-development-juliaSkill
- zarr-cloud-arraysSkill
The file
Files
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
| Situation | Backend | Why |
n parameters, m outputs, n \ll m | ForwardDiff | one pass, no tape |
n \gg m (a loss, a scalar objective) | Zygote or Enzyme | reverse mode |
mutation, setindex!, push! | Enzyme | Zygote cannot |
| a C or Fortran call in the path | Enzyme (or an rrule) | LLVM sees through ccall |
| Hessian, or a Jacobian of a gradient | ForwardDiff over Zygote, or Enzyme Hessian | mixed mode |
| a library that must accept any of them | DifferentiationInterface | the seam |
| an expression, not a program | symbolic-math | Symbolics, 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 VJPIts limits are hard errors, and each names the fix:
| Error or limit | Fix |
Mutating arrays is not supported | Zygote.Buffer, or restructure to allocate a new array |
Can't differentiate foreigncall expression | write an rrule, or switch to Enzyme |
try/catch in the path | move the rescue outside the differentiated function |
Dict mutation | NamedTuple, or a buffer indexed by an integer |
| a branch on a differentiated value | ifelse 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))| Annotation | Meaning | Use |
Active(x) | differentiated scalar | the objective's output |
Duplicated(x, dx) | primal and shadow | arrays, mutating code |
Const(x) | not differentiated | parameters, indices |
DuplicatedNoNeed(x, dx) | shadow only | when 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-6A 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.
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
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.

