deeplearning4j/deeplearning4j · error · IllegalStateException
Mis matched lengths: [X] != [Y] - Array 1 shape: [S1]…
Error message
Mis matched lengths: [X] != [Y] - Array 1 shape: [S1], array 2 shape: [S2]
What it means
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.
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.
Example fix
// before INDArray result = weights.mul(features); // weights [10], features [1000] LinAlgExceptions.assertSameLength(features, weights); // after INDArray w = weights.dup().repeat(1, features.length() / weights.length()).reshape(features.shape()); INDArray result = w.mul(features);
Defensive patterns
Strategy: validation
Validate before calling
static void requireSameLength(INDArray a, INDArray b) {
if (a.length() != b.length() && a.length() != 1 && b.length() != 1)
throw new IllegalStateException("length mismatch: " + a.length() + " vs " + b.length()
+ " shapes " + Arrays.toString(a.shape()) + " vs " + Arrays.toString(b.shape()));
} Type guard
static boolean sameLength(INDArray a, INDArray b) {
return a != null && b != null && (a.length() == b.length() || a.length() == 1 || b.length() == 1);
} Try / catch
try {
LinAlgExceptions.assertSameLength(x, z);
result = x.mul(z);
} catch (IllegalStateException e) {
throw new IllegalArgumentException("elementwise op length mismatch; reshape/broadcast inputs", e);
} Prevention
- 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.
When it happens
Trigger: 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].
Common situations: 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.
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
- Both arrays must have the same length
- Length of probabilities array [" + prob.length() + "]…
- Mis matched lengths: [X] != [Y] != [Z] - Array 1 shape…
- Mis matched shapes: " + Arrays.toString(n.shape()) + ", " +…
- Mis matched shapes: " + Arrays.toString(x.shape()) + ", " +…
AI-assisted analysis of deeplearning4j/deeplearning4j@4c22ac5fe4 (2026-09-07).
Data as JSON: /api/errors/fd2b1b946fe28f0f.
Report an issue: GitHub.
Appendix: source
Thrown at nd4j/nd4j-backends/nd4j-api-parent/nd4j-api/src/main/java/org/nd4j/linalg/util/LinAlgExceptions.java:53
* Asserts that at least the number of arguments on the given op is
* met.
* @param op the op to validate
* @param numExpectedArgs the number of expected arguments
*/
public static void assertAllConfigured(CustomOp op,int numExpectedArgs) {
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.");
}
/**
* Asserts both arrays be the same length
* @param x
* @param z
*/
public static void assertSameLength(INDArray x, INDArray z) {
val lengthX = x.length();
val lengthZ = z.length();
if (lengthX != lengthZ && lengthX != 1 && lengthZ != 1)
throw new IllegalStateException("Mis matched lengths: [" + x.length() + "] != [" + z.length() + "] - " +
"Array 1 shape: " + Arrays.toString(x.shape()) + ", array 2 shape: " + Arrays.toString(z.shape()));
}
public static void assertSameLength(INDArray x, INDArray y, INDArray z) {
val lengthX = x.length();
val lengthY = y.length();
val lengthZ = z != null ? z.length() : x.length();
if (lengthX != lengthY && lengthX != lengthZ && lengthX != 1 && lengthY != 1 && lengthZ != 1)
throw new IllegalStateException("Mis matched lengths: [" + lengthX + "] != [" + lengthY + "] != [" + lengthZ + "] - " +
"Array 1 shape: " + Arrays.toString(x.shape()) + ", array 2 shape: " + Arrays.toString(y.shape()) + ", array 3 shape: " + Arrays.toString(z.shape()));
}
public static void assertSameShape(INDArray x, INDArray y, INDArray z) {
//if (!Shape.isVector(x.shape()) && ! Shape.isVector(y.shape()) && !Shape.isVector(z.shape())) {
if (!Shape.shapeEquals(x.shape(), y.shape()))
throw new IllegalStateException("Mis matched shapes: " + Arrays.toString(x.shape()) + ", " + Arrays.toString(y.shape()));
if (!Shape.shapeEquals(x.shape(), z.shape()))View on GitHub (pinned to 4c22ac5fe4)