{"record":{"id":"58cbd3a37007c9b2","repo":"tracel-ai/burn","slug":"matrix-multiplication-requires-an-array-with-at-le","errorCode":null,"errorMessage":"Matrix multiplication requires an array with at least 2 dimensions. Got Rank {}","messagePattern":"Matrix multiplication requires an array with at least 2 dimensions\\. Got Rank (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/burn-ndarray/src/ops/matmul.rs","lineNumber":115,"sourceCode":"    }\n}\n\n/// Compute the (broadcasted) output shape of matrix multiplication, along with strides for\n/// the non-matrix dimensions of all arrays.\n///\n/// # Arguments\n/// * `lsh`: Shape of the first (left-hand) matrix multiplication argument.\n/// * `rsh`: Shape of the second (right-hand) matrix multiplication argument.\n///\n/// # Panics\n/// * If `D` is not at least 2.\n/// * If the matrix multiplication dimensions (last 2) are incompatible.\n/// * If any other dimension is not the same for both tensors, or equal to 1. (Any dimension where\n///   one dim is equal to 1 is broadcast.)\nfn output_shape(lsh: &[usize], rsh: &[usize]) -> (Shape, Strides, Strides, Strides) {\n    let ndims = lsh.num_dims();\n    if ndims < 2 {\n        panic!(\n            \"Matrix multiplication requires an array with at least 2 dimensions. Got Rank {}\",\n            ndims\n        );\n    }\n\n    // Fetch matrix dimensions and check compatibility.\n    let l_rows = lsh[ndims - 2];\n    let l_cols = lsh[ndims - 1];\n    let r_rows = rsh[ndims - 2];\n    let r_cols = rsh[ndims - 1];\n    if l_cols != r_rows {\n        panic!(\n            \"Dimensions are incompatible for matrix multiplication: LHS columns ({}) != ({})\",\n            l_cols, r_rows\n        );\n    }\n    // Set matrix dimensions of the output shape.\n    let mut osh = vec![0; ndims];","sourceCodeStart":97,"sourceCodeEnd":133,"githubUrl":"https://github.com/tracel-ai/burn/blob/d16f7ba2ed0d41408189384044cc886fb4c8f957/crates/burn-ndarray/src/ops/matmul.rs#L97-L133","documentation":"output_shape computes the result shape for matmul and requires at least 2 dimensions because matrix multiplication operates on the last two axes. If the left-hand shape has rank < 2 the op cannot proceed and panics.","triggerScenarios":"Calling tensor.matmul(other) with a rank-0 (scalar) or rank-1 (vector) LHS tensor. burn requires explicit unsqueeze/reshape to 2D+ before matmul.","commonSituations":"Passing a 1-D bias or flattened vector directly into matmul; a reshape/squeeze earlier in the pipeline accidentally dropped a batch dimension.","solutions":["Unsqueeze the 1-D tensor to 2-D before matmul: vector.unsqueeze::<2>(0) for row-vector or unsqueeze::<2>(1) for column-vector.","Use reshape to give the tensor at least 2 dimensions with compatible matrix dims.","Verify the LHS rank before matmul with tensor.shape().num_dims() >= 2.","If multiplying matrix by vector, use matmul with the vector expanded, or a dedicated mul/add instead."],"exampleFix":"// before\nlet v = Tensor::<NdArray<f32>, 1>::from_floats([1.0, 2.0]);\nlet y = m.matmul(v); // panic: rank 1\n// after\nlet v2 = v.unsqueeze::<2>(); // shape [1, 2]\nlet y = m.matmul(v2).squeeze::<1>(0);","handlingStrategy":"validation","validationCode":"fn ensure_rank_at_least2<D: burn::tensor::Dimension>(t: &burn::tensor::Tensor<burn::backend::NdArray, D>) {\n    assert!(D::NUM_DIMS >= 2, \"matmul requires rank >= 2, got {}\", D::NUM_DIMS);\n}","typeGuard":null,"tryCatchPattern":"// burn panics rather than returning Result; run risky ops behind catch_unwind if needed\nlet result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| lhs.matmul(rhs.clone())));","preventionTips":["Keep vectors as rank-2 tensors ([1,n] or [n,1]) throughout pipelines.","Check shapes before matmul in debug builds.","Use unsqueeze/reshape explicitly instead of relying on implicit rank promotion.","Add rank assertions at pipeline boundaries."],"tags":["rust","burn-ndarray","matmul","shape"],"backgroundTag":"matmul-dimension-mismatch","analyzedSha":"d16f7ba2ed0d41408189384044cc886fb4c8f957","analyzedAt":"2026-09-05T13:19:14.260Z","contentChangedAt":"2026-09-05T13:19:14.260Z","schemaVersion":2},"datasetVersion":"2026-09-12T17:17:11.597Z"}