deeplearning4j/deeplearning4j · error · IllegalStateException

Output shape and input shape do not match

Error message

Output shape${output.shape()} and input shape${targetShape} do not match

What it means

After passing the shape equality check, ReshapePreprocessor.backprop also requires that the output gradient's element count equals the product of the recomputed inputShape before reshaping back; otherwise it throws IllegalStateException with this message. Note the message confusingly prints targetShape while the semantic requirement is a product match with inputShape. It guards against gradients that cannot be losslessly reshaped to the original input layout.

Solutions

  1. Ensure the constructor's inputShape and targetShape have equal element counts (prodLong equal).
  2. Rebuild the network configuration after changing layer sizes so the preprocessor's recorded shapes match the actual activations.
  3. Recompute the preprocessor shapes from InputType via NeuralNetConfiguration listeners rather than hard-coding stale dimensions.

Example fix

// before
new ReshapePreprocessor(new long[]{10, 20}, new long[]{10, 30}); // products 200 vs 300
// after
new ReshapePreprocessor(new long[]{10, 20}, new long[]{4, 50}); // both products 200
Defensive patterns

Strategy: validation

Validate before calling

long pin = 1, tprod = 1;
for (long d : inputShape) pin *= d;
for (long d : targetShape) tprod *= d;
if (pin != tprod) throw new IllegalArgumentException("inputShape and targetShape must have equal element counts");

Try / catch

try { preproc.backprop(output, miniBatchSize, workspaceMgr); } catch (IllegalStateException e) { log.error("Reshape preprocessor config inconsistent", e); }

Prevention

When it happens

Trigger: Calling backprop where output shape equals targetShape but prod(output) != prod(inputShape) — typically caused by inconsistent inputShape/targetShape constructor arguments.

Common situations: Constructing ReshapePreprocessor with input/target shapes of different total sizes; dimension changes (e.g. channel count) between train and inference; misconfigured graph where upstream gradient size differs from the recorded input shape.

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/1b0a650676232ce7. Report an issue: GitHub.

Appendix: source

Thrown at deeplearning4j/deeplearning4j-nn/src/main/java/org/deeplearning4j/preprocessors/ReshapePreprocessor.java:130

        }
    }

    @Override
    public INDArray backprop(INDArray output, int miniBatchSize, LayerWorkspaceMgr workspaceMgr) {
        long[] targetShape = getShape(this.targetShape, miniBatchSize);
        long[] inputShape = getShape(this.inputShape, miniBatchSize);

        if (!Arrays.equals(targetShape, output.shape())) {
            throw new IllegalStateException("Unexpected output shape" + Arrays.toString(output.shape())
                    + " (expected to be " + Arrays.toString(targetShape) + ")");
        }
        if (prodLong(output.shape()) == prodLong((targetShape))) {
            if (output.ordering() != 'c' || !Shape.hasDefaultStridesForShape(output)) {
                output = workspaceMgr.dup(ArrayType.ACTIVATIONS, output, 'c');
            }
            return workspaceMgr.leverageTo(ArrayType.ACTIVATION_GRAD, output.reshape(inputShape));
        } else {
            throw new IllegalStateException("Output shape" + Arrays.toString(output.shape())
                    + " and input shape" + Arrays.toString(targetShape) + " do not match");
        }
    }

    @Override
    public InputType getOutputType(InputType inputType) throws InvalidInputTypeException {
        long[] shape = getShape(this.targetShape, 0);
        InputType ret;
        switch (shape.length) {
            case 2:
                ret = InputType.feedForward(shape[1]);
                break;
            case 3:
                RNNFormat format = RNNFormat.NWC;
                if(this.format != null && this.format instanceof RNNFormat)
                    format = (RNNFormat) this.format;

                ret = InputType.recurrent(shape[2], shape[1], format);

View on GitHub (pinned to 4c22ac5fe4)