drannarosen/research-workflow/gradient-validation
Claude Code and agent skill by drannarosen/research-workflow
- community
Checking that the SKILL.md file is still in the repository.
Validate gradients of a differentiable model, not just its forward value. Use for finite-difference grad-checks with a relative step, NaN/Inf under jax.grad, and silently zero gradients from stop_gradient, argmax, a where() with a singular dead branch, or clip saturation. Don't use for forward convergence (→ numerical-method-validation) or JAX tracing mechanics (→ jax-code-validator).
Install
npx vskill@latest install drannarosen/research-workflow/gradient-validationSKILL.md
The same SKILL.md was published earlier as drannarosen/research-workflow/gradient-validation.
A correct forward value does not imply a correct gradient. In differentiable astrophysics codes, every gradient-based fit, inference, or optimization rides on jax.grad being right, and it can be wrong while the loss looks perfect. Grad-check before trusting any gradient-based result. The step sizes, number of directions and seeds, and the surrogate for a needed hard operation are yours to choose and state.
1. Finite-difference grad-check (the anchor)
Compare the autodiff gradient against a central finite difference, component by component:
g_fd ≈ [f(x + h·eᵢ) − f(x − h·eᵢ)] / (2h), with a relative step h = h_rel · max(|xᵢ|, x_scale)
- Use float64 (
jax.config.update("jax_enable_x64", True)); float32 noise swamps the check. - Pass criterion: relative error
|g_ad − g_fd| / (|g_ad| + |g_fd| + ε)below ~1e-5. - Sweep the relative step
h_rel ∈ {1e-4 … 1e-8}and take the best — too large = truncation error, too small = round-off. There is a sweet spot; onehcan falsely fail. - Don't use an absolute step on dimensional inputs. In CGS a mass is ~2e33 g;
x + 1e-6 == xon the float grid, the FD gradient is exactly 0, and a correct gradient fails the check. Scalehto|x|, or better, grad-check in nondimensional code units (which is also where autodiff and float32 are least fragile). - Check on a random direction for high-dim
x(full Jacobian is expensive); test several seeds.
Runnable demo of the check + the fix below: see example.py.
2. NaN-gradient traps (forward finite, grad = nan / inf)
sqrt, log, pow, 1/x, norm have infinite or undefined derivatives at their domain edge. The forward value can be clamped and finite while the backward pass propagates nan or inf.
Real bug (King-model `K`-function): f(x) = sqrt(max(x, 0)). Forward f(0)=0 is fine, but grad(f)(0.0) is non-finite (inf/nan) — the derivative 0.5/sqrt(x) blows up and autodiff still differentiates the dead max branch at the kink. (Run example.py: the buggy form's gradient at 0 prints inf — it becomes nan as soon as that cotangent is multiplied by a zero downstream — while the safe form gives 0.0.)
Canonical fix — the double-`where` / safe-primitive pattern: clamp the input to a safe value, evaluate the primitive there, then where the result. Both branches must be finite so the cotangent is finite:
A single where(x>0, sqrt(x), 0.0) is NOT enough — sqrt(x) is still evaluated (and differentiated) at x=0, so 0 · inf = nan reaches the cotangent. Clamp before the primitive.
3. Zero / blocked-gradient traps (grad = 0 silently)
A wrong but finite gradient is worse than a crash. Watch for:
- `argmax` / `argsort` / `round` / `floor` — piecewise-constant, gradient is zero almost everywhere. Use a softmax/soft-rank surrogate if you need to differentiate the selection.
- Hard thresholds / step functions — zero gradient in the flat region; the optimizer gets no signal.
- `clip` / floor saturation — once pinned at the bound,
∂out/∂x = 0. A "floor as a fix" silently kills the gradient there. - `jax.lax.stop_gradient` — verify every use is intended; an accidental one blocks learning on that path.
Checklist
- [ ] float64 on; FD vs
jax.gradrel-err < 1e-5, with a relative-hsweep (or nondimensionalized inputs). - [ ] gradient finite (no
nan/inf) at domain edges and special points (0, boundaries, equal masses, r=0). - [ ] every
sqrt/log/pow/normnear its edge uses the double-wheresafe pattern. - [ ] no unintended
stop_gradient,argmax/argsort, hard threshold, or saturatedclip/floor on the differentiated path. - [ ] checked at ≥2 seeds / points, not one lucky spot.
Related
numerical-method-validation— the forward-method analogue (order/conservation); pair them for a differentiable solver.adversarial-result-check— its gradient/autodiff attack lane invokes this protocol.jax-code-validator— reviews JAX tracing/PRNG/JIT mechanics in source; this skill validates the gradient's numerical correctness.
Security
- Security scanPassed, 90 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/gradient-validation/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/drannarosen/research-workflow/gradient-validation)