{"record":{"id":"0ebb003ed0477850","repo":"deeplearning4j/deeplearning4j","slug":"gradient-shape-does-not-match-variable-shape-for-v","errorCode":null,"errorMessage":"Gradient shape does not match variable shape for variable \"${v.name()}\": shape ${Arrays.toString(v.getArr().shape())} vs. gradient shape ${Arrays.toString(ga.shape())}","messagePattern":"Gradient shape does not match variable shape for variable \"(.+?)\": shape (.+?) vs\\. gradient shape (.+?)","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/GradCheckUtil.java","lineNumber":165,"sourceCode":"        for(SDVariable v : sd.variables()) {\n            if (fnOutputs.contains(v.name())) {\n                //This is not an input to the graph\n                continue;\n            }\n            if(!v.hasGradient()) {\n                //Skip non-fp variables, or variables that don't impact loss function value\n                continue;\n            }\n            SDVariable g = sd.grad(v.name());\n            if(g == null){\n                throw new IllegalStateException(\"Null gradient variable for \\\"\" + v.name() + \"\\\"\");\n            }\n            INDArray ga = gm.get(v.name());\n            if(ga == null) {\n                throw new IllegalStateException(\"Null gradient array encountered for variable: \" + v.name());\n            }\n            if(!Arrays.equals(v.getArr().shape(), ga.shape())) {\n                throw new IllegalStateException(\"Gradient shape does not match variable shape for variable \\\"\" +\n                        v.name() + \"\\\": shape \" + Arrays.toString(v.getArr().shape()) + \" vs. gradient shape \" +\n                        Arrays.toString(ga.shape()));\n            }\n            grad.put(v.name(), ga.dup());\n        }\n\n        //Validate gradients for each variable:\n        int totalNFailures = 0;\n        int totalCount = 0;\n        double maxError = 0.0;\n        Random r = new Random(12345);\n        for(SDVariable s : sd.variables()) {\n            if (fnOutputs.contains(s.name()) || !s.dataType().isFPType()) {\n                //This is not an input to the graph, or is not a floating point input (so can't be gradient checked)\n                continue;\n            }\n\n            if(skipVariables != null && skipVariables.contains(s.name())){","sourceCodeStart":147,"sourceCodeEnd":183,"githubUrl":"https://github.com/deeplearning4j/deeplearning4j/blob/4c22ac5fe4a8350d05d224e7f4499429f7f69c93/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/autodiff/validation/GradCheckUtil.java#L147-L183","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Inspect the op producing that variable and fix its doDiff to output the same shape as the forward output","Add shape assertions in the custom op's doDiff implementation","Check for accidental reshapes/transposes in the graph around the offending variable","Update ND4J if using a built-in op (shape bugs are fixed in newer releases)","Reduce the graph to a minimal repro and validate op-by-op"],"exampleFix":"// before: doDiff returns wrong-shaped gradient\npublic List<SDVariable> doDiff(List<SDVariable> grads) {\n    return Collections.singletonList(f().square(grads.get(0)).mul(2));\n}\n// after: ensure output shape matches input variable shape\npublic List<SDVariable> doDiff(List<SDVariable> grads) {\n    INDArray g = grads.get(0).getArr();\n    Preconditions.checkState(Arrays.equals(g.shape(), arg().getArr().shape()), \"Grad shape mismatch\");\n    return Collections.singletonList(grads.get(0));\n}","handlingStrategy":"validation","validationCode":"for (SDVariable v : sd.variables()) {\n    INDArray ga = grads.get(v.name());\n    if (ga != null && !Arrays.equals(v.getArr().shape(), ga.shape()))\n        throw new IllegalStateException(\"Shape mismatch for \" + v.name());\n}","typeGuard":null,"tryCatchPattern":"try { GradCheckUtil.checkGradients(sd, cfg, ...); }\ncatch (IllegalStateException e) {\n    if (e.getMessage().contains(\"shape does not match\")) inspectOpDoDiff(sd, e.getMessage());\n    else throw e;\n}","preventionTips":["Assert output shape equals input shape in every custom doDiff","Avoid manual reshapes around checked variables","Test each op's backward shapes independently","Pin ND4J versions and review op change notes when upgrading"],"tags":["java","nd4j","samediff","gradient-check","shape-mismatch"],"backgroundTag":"tensor-shape-mismatch","analyzedSha":"4c22ac5fe4a8350d05d224e7f4499429f7f69c93","analyzedAt":"2026-09-07T05:27:04.714Z","contentChangedAt":"2026-09-07T05:27:04.714Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}