deeplearning4j/deeplearning4j · error · IllegalStateException

Gradient shape does not match variable shape for variable

Error message

Gradient shape does not match variable shape for variable "${v.name()}": shape ${Arrays.toString(v.getArr().shape())} vs. gradient shape ${Arrays.toString(ga.shape())}

What it means

During gradient validation, GradCheckUtil compares the shape of each variable's array with the shape of its computed gradient. If they differ, backprop produced a gradient with an unexpected shape, and this IllegalStateException is thrown before the numerical/analytic comparison can proceed.

Solutions

  1. Inspect the op producing that variable and fix its doDiff to output the same shape as the forward output
  2. Add shape assertions in the custom op's doDiff implementation
  3. Check for accidental reshapes/transposes in the graph around the offending variable
  4. Update ND4J if using a built-in op (shape bugs are fixed in newer releases)
  5. Reduce the graph to a minimal repro and validate op-by-op

Example fix

// before: doDiff returns wrong-shaped gradient
public List<SDVariable> doDiff(List<SDVariable> grads) {
    return Collections.singletonList(f().square(grads.get(0)).mul(2));
}
// after: ensure output shape matches input variable shape
public List<SDVariable> doDiff(List<SDVariable> grads) {
    INDArray g = grads.get(0).getArr();
    Preconditions.checkState(Arrays.equals(g.shape(), arg().getArr().shape()), "Grad shape mismatch");
    return Collections.singletonList(grads.get(0));
}
Defensive patterns

Strategy: validation

Validate before calling

for (SDVariable v : sd.variables()) {
    INDArray ga = grads.get(v.name());
    if (ga != null && !Arrays.equals(v.getArr().shape(), ga.shape()))
        throw new IllegalStateException("Shape mismatch for " + v.name());
}

Try / catch

try { GradCheckUtil.checkGradients(sd, cfg, ...); }
catch (IllegalStateException e) {
    if (e.getMessage().contains("shape does not match")) inspectOpDoDiff(sd, e.getMessage());
    else throw e;
}

Prevention

When it happens

Trigger: checkGradients on a SameDiff where an op's backward function outputs an INDArray whose shape differs from its input variable's shape — usually due to a buggy custom differential function or a reshape/broadcast mismatch in the forward graph.

Common situations: Custom ops with hand-written doDiff that return wrongly-shaped arrays; ops with dynamic shapes where grad shapes drift; broadcasting errors in the graph; migrating graphs across ND4J versions where an op's backward behavior changed.

Understand the failure class

Background: Tensor shape mismatch errors ("must have shape", "expected shape ... got ..."): when tensor dimensions disagree with what an op or layer was told to expect — this error's family across 6 libraries.

Related errors


AI-assisted analysis of deeplearning4j/deeplearning4j@4c22ac5fe4 (2026-09-07). Data as JSON: /api/errors/0ebb003ed0477850. 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:165

        for(SDVariable v : sd.variables()) {
            if (fnOutputs.contains(v.name())) {
                //This is not an input to the graph
                continue;
            }
            if(!v.hasGradient()) {
                //Skip non-fp variables, or variables that don't impact loss function value
                continue;
            }
            SDVariable g = sd.grad(v.name());
            if(g == null){
                throw new IllegalStateException("Null gradient variable for \"" + v.name() + "\"");
            }
            INDArray ga = gm.get(v.name());
            if(ga == null) {
                throw new IllegalStateException("Null gradient array encountered for variable: " + v.name());
            }
            if(!Arrays.equals(v.getArr().shape(), ga.shape())) {
                throw new IllegalStateException("Gradient shape does not match variable shape for variable \"" +
                        v.name() + "\": shape " + Arrays.toString(v.getArr().shape()) + " vs. gradient shape " +
                        Arrays.toString(ga.shape()));
            }
            grad.put(v.name(), ga.dup());
        }

        //Validate gradients for each variable:
        int totalNFailures = 0;
        int totalCount = 0;
        double maxError = 0.0;
        Random r = new Random(12345);
        for(SDVariable s : sd.variables()) {
            if (fnOutputs.contains(s.name()) || !s.dataType().isFPType()) {
                //This is not an input to the graph, or is not a floating point input (so can't be gradient checked)
                continue;
            }

            if(skipVariables != null && skipVariables.contains(s.name())){

View on GitHub (pinned to 4c22ac5fe4)