deeplearning4j/deeplearning4j · error · IllegalStateException

Analytic (SameDiff) gradient was

Error message

Analytic (SameDiff) gradient was ${analyticGrad} for variable "${name}", parameter ${i} of ${n} (position: ${strIdx})

What it means

After computing the analytic (SameDiff backprop) gradient at a parameter position, GradCheckUtil validates it is finite. If the analytic gradient is Infinity or NaN, backprop itself produced an invalid value, and this IllegalStateException is thrown — unlike the numerical variant, this points at the backward pass, not the finite-difference evaluation.

Solutions

  1. Inspect the op at the reported position and add epsilon guards in its backward math
  2. Validate placeholder inputs are within the valid domain before running the check
  3. Clamp forward outputs (e.g. logits) to avoid zero/negative values in log-type backward paths
  4. Enable gradient explosion mitigations (normalize loss, smaller network for the check)
  5. Bisect the graph: check subgraphs to find which op first yields NaN/Inf

Example fix

// before: backward of log divides by x which can be 0
doDiff: grad / x
// after: guard the denominator
INDArray safe = x.add(1e-8);
INDArray g = grad.div(safe);
Defensive patterns

Strategy: validation

Validate before calling

INDArray a = sd.execBackEndPlaceholders(...); // then per-element:
for (int i = 0; i < aGrad.length(); i++)
    if (!Double.isFinite(aGrad.getDouble(i))) throw new IllegalStateException("Non-finite analytic grad at " + i);

Type guard

boolean finite(INDArray a){ return !a.isNaN().any() && !a.isInfinite().any(); }

Try / catch

try { GradCheckUtil.checkGradients(sd, cfg, ...); }
catch (IllegalStateException e) {
    if (e.getMessage().contains("Analytic (SameDiff) gradient was")) bisectBackwardOps(sd);
    else throw e;
}

Prevention

When it happens

Trigger: checkGradients where backprop through some op produces NaN/Inf: division by zero in backward, log-gradient of non-positive forward output, gradient explosion through many layers, or uninitialized/poisoned activation arrays feeding the backward pass.

Common situations: Graphs containing log, sqrt, division, or reciprocal of values that can hit zero; deep graphs with exploding gradients; placeholders fed values outside the valid domain; custom ops whose backward divides by the forward output.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of deeplearning4j/deeplearning4j@4c22ac5fe4 (2026-09-07). Data as JSON: /api/errors/31d6ab02b660c336. Report an issue: GitHub.

Appendix: source

Thrown at nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/GradCheckUtil.java:283

                for(INDArray arr : m.values()) {
                    scoreMinus += arr.sumNumber().doubleValue();
                }
                a.putScalar(idx, orig);

                double numericalGrad = (scorePlus - scoreMinus) / (2 * eps);
                INDArray aGrad = grad.get(s.name());
                if(aGrad == null) {
                    log.warn("No gradient array for variable \"{}\" was found, skipping variable...", s.name());
                    continue;
                }
                double analyticGrad = aGrad.getDouble(idx);

                if (Double.isInfinite(numericalGrad) || Double.isNaN(numericalGrad)) {
                    throw new IllegalStateException("Numerical gradient was " + numericalGrad + " for variable \"" + name
                            + "\", parameter " + i + " of " + n + " (position: " + strIdx + ")");
                }
                if (Double.isInfinite(analyticGrad) || Double.isNaN(analyticGrad)) {
                    throw new IllegalStateException("Analytic (SameDiff) gradient was " + analyticGrad + " for variable \"" + name
                            + "\", parameter " + i + " of " + n + " (position: " + strIdx + ")");
                }


                double relError;
                if(numericalGrad == 0.0 || analyticGrad == 0.0) {
                    relError = 0.0;
                } else {
                    relError = Math.abs(analyticGrad - numericalGrad) / (Math.abs(Math.abs(analyticGrad) + Math.abs(numericalGrad)));
                }

                if (relError > maxError)
                    maxError = relError;

                if (relError > maxRelError || Double.isNaN(relError)) {
                    double absError = Math.abs(analyticGrad - numericalGrad);
                    if (absError < minAbsError) {
                        if(print) {

View on GitHub (pinned to 4c22ac5fe4)