{"record":{"id":"fd2b1b946fe28f0f","repo":"deeplearning4j/deeplearning4j","slug":"mis-matched-lengths-x-y-array-1-shape","errorCode":null,"errorMessage":"Mis matched lengths: [X] != [Y] - Array 1 shape: [S1], array 2 shape: [S2]","messagePattern":"Mis matched lengths: \\[X\\] != \\[Y\\] - Array 1 shape: \\[S1\\], array 2 shape: \\[S2\\]","errorType":"exception","errorClass":"IllegalStateException","httpStatus":null,"severity":"error","filePath":"nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/LinAlgExceptions.java","lineNumber":53,"sourceCode":"     * Asserts that at least the number of arguments on the given op is\n     * met.\n     * @param op the op to validate\n     * @param numExpectedArgs the number of expected arguments\n     */\n    public static void assertAllConfigured(CustomOp op,int numExpectedArgs) {\n        Preconditions.checkArgument(op.numIArguments() >= numExpectedArgs,\"Unable to instantiate configuration, int arguments are incomplete. Please either specify a configuration or populate all fields in the int arguments.\");\n    }\n\n    /**\n     * Asserts both arrays be the same length\n     * @param x\n     * @param z\n     */\n    public static void assertSameLength(INDArray x, INDArray z) {\n        val lengthX = x.length();\n        val lengthZ = z.length();\n        if (lengthX != lengthZ && lengthX != 1 && lengthZ != 1)\n            throw new IllegalStateException(\"Mis matched lengths: [\" + x.length() + \"] != [\" + z.length() + \"] - \" +\n                    \"Array 1 shape: \" + Arrays.toString(x.shape()) + \", array 2 shape: \" + Arrays.toString(z.shape()));\n    }\n\n    public static void assertSameLength(INDArray x, INDArray y, INDArray z) {\n        val lengthX = x.length();\n        val lengthY = y.length();\n        val lengthZ = z != null ? z.length() : x.length();\n\n        if (lengthX != lengthY && lengthX != lengthZ && lengthX != 1 && lengthY != 1 && lengthZ != 1)\n            throw new IllegalStateException(\"Mis matched lengths: [\" + lengthX + \"] != [\" + lengthY + \"] != [\" + lengthZ + \"] - \" +\n                    \"Array 1 shape: \" + Arrays.toString(x.shape()) + \", array 2 shape: \" + Arrays.toString(y.shape()) + \", array 3 shape: \" + Arrays.toString(z.shape()));\n    }\n\n    public static void assertSameShape(INDArray x, INDArray y, INDArray z) {\n        //if (!Shape.isVector(x.shape()) && ! Shape.isVector(y.shape()) && !Shape.isVector(z.shape())) {\n            if (!Shape.shapeEquals(x.shape(), y.shape()))\n                throw new IllegalStateException(\"Mis matched shapes: \" + Arrays.toString(x.shape()) + \", \" + Arrays.toString(y.shape()));\n            if (!Shape.shapeEquals(x.shape(), z.shape()))","sourceCodeStart":35,"sourceCodeEnd":71,"githubUrl":"https://github.com/deeplearning4j/deeplearning4j/blob/4c22ac5fe4a8350d05d224e7f4499429f7f69c93/nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/LinAlgExceptions.java#L35-L71","documentation":"LinAlgExceptions.assertSameLength validates that two INDArrays have compatible element counts before element-wise operations. It throws IllegalStateException when x.length() != z.length() and neither is length 1 (a length-1 scalar is allowed and broadcast). The message embeds both lengths and full shapes to ease debugging of broadcasting mistakes.","triggerScenarios":"Calling assertSameLength(x, z) (directly or via ND4J ops like add/sub with two arrays) where x.length() != z.length() and both lengths > 1, e.g. shape [3,4] vs [2,5].","commonSituations":"Element-wise math on arrays built from different feature counts; applying a weight vector whose size doesn't match the batch element count; forgotten reshaping after preprocessing changes; comparing pre-flatten vs post-flatten arrays.","solutions":["Print x.shape() and z.shape() and reshape the smaller array to match the target length.","Use x.reshape(expectedShape) or broadcast helpers (e.g. x.addRowVector, x.addColumnVector) to align dimensions explicitly.","For scalar-ish operands, collapse the smaller to length 1 (e.g. sum/mean reduction) so the broadcast exception applies.","Wrap the op in a try/catch only when mismatch is expected to fall back to a broadcasting variant."],"exampleFix":"// before\nINDArray result = weights.mul(features); // weights [10], features [1000]\nLinAlgExceptions.assertSameLength(features, weights);\n// after\nINDArray w = weights.dup().repeat(1, features.length() / weights.length()).reshape(features.shape());\nINDArray result = w.mul(features);","handlingStrategy":"validation","validationCode":"static void requireSameLength(INDArray a, INDArray b) {\n    if (a.length() != b.length() && a.length() != 1 && b.length() != 1)\n        throw new IllegalStateException(\"length mismatch: \" + a.length() + \" vs \" + b.length()\n            + \" shapes \" + Arrays.toString(a.shape()) + \" vs \" + Arrays.toString(b.shape()));\n}","typeGuard":"static boolean sameLength(INDArray a, INDArray b) {\n    return a != null && b != null && (a.length() == b.length() || a.length() == 1 || b.length() == 1);\n}","tryCatchPattern":"try {\n    LinAlgExceptions.assertSameLength(x, z);\n    result = x.mul(z);\n} catch (IllegalStateException e) {\n    throw new IllegalArgumentException(\"elementwise op length mismatch; reshape/broadcast inputs\", e);\n}","preventionTips":["Check Shape.shapeEquals or length() before element-wise ops.","Reshape to matching shapes immediately after loading/preprocessing.","Use addRowVector/addColumnVector for intentional broadcasting.","Keep unit tests asserting shapes at pipeline boundaries."],"tags":["nd4j","shape-mismatch","elementwise","validation"],"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"}