{"record":{"id":"5124c5a2bc7f2956","repo":"huggingface/candle","slug":"reshape-invalid-dimension-v-in-target-shape","errorCode":null,"errorMessage":"Reshape: invalid dimension {v} in target shape","messagePattern":"Reshape: invalid dimension (.+?) in target shape","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"candle-onnx/src/eval.rs","lineNumber":417,"sourceCode":"                // A 0 in the target shape copies the corresponding input dimension, unless\n                // allowzero=1, where it means a literal zero-length dimension.\n                let allowzero = get_attr_opt::<i64>(node, \"allowzero\")?\n                    .copied()\n                    .unwrap_or(0)\n                    == 1;\n                if input1.iter().filter(|&&v| v == -1).count() > 1 {\n                    bail!(\"Reshape: at most one dimension of the target shape can be -1\")\n                }\n                // Resolve everything but -1 first: a copied 0 is part of the volume, so it\n                // has to be in the product that -1 is inferred against.\n                let mut resolved: Vec<Option<usize>> = Vec::with_capacity(input1.len());\n                for (idx, &v) in input1.iter().enumerate() {\n                    resolved.push(match v {\n                        -1 => None,\n                        0 if allowzero => Some(0),\n                        0 => Some(input0.dim(idx)?),\n                        v if v > 0 => Some(v as usize),\n                        v => bail!(\"Reshape: invalid dimension {v} in target shape\"),\n                    });\n                }\n                let known: usize = resolved.iter().flatten().product();\n                let input1 = resolved\n                    .into_iter()\n                    .map(|d| match d {\n                        Some(d) => Ok(d),\n                        // A -1 has no unique value when the rest of the volume is zero.\n                        None if known == 0 => {\n                            bail!(\"Reshape: -1 cannot be inferred when another dimension is zero\")\n                        }\n                        None => Ok(input0.elem_count() / known),\n                    })\n                    .collect::<Result<Vec<usize>>>()?;\n                let output = input0.reshape(input1)?;\n                values.insert(node.output[0].clone(), output);\n            }\n            \"LogSoftmax\" => {","sourceCodeStart":399,"sourceCodeEnd":435,"githubUrl":"https://github.com/huggingface/candle/blob/d5fee525bfde3273eb7c9b75fd2bc4937be867ca/candle-onnx/src/eval.rs#L399-L435","documentation":"The ONNX Reshape operator allows a target-shape element to be a positive dimension, 0 (copy input dim, when allowzero), or -1 (infer). Any other negative value is meaningless, so candle-onnx rejects it while resolving the target shape in simple_eval_.","triggerScenarios":"Calling Reshape (via simple_eval/simple_eval_) with a shape tensor input1 containing a negative value other than -1, e.g. -2, -5.","commonSituations":"Hand-written or generated ONNX models with a typo in the reshape shape constant; exporting from another framework that emitted a negative placeholder dim other than -1.","solutions":["Inspect the second input (shape tensor) of the Reshape node and replace any negative value other than -1 with the intended positive dimension or -1","If dimension is meant to be inferred, use -1 (only once) instead of an arbitrary negative number","If the model was exported, re-export with the exporter configured to emit concrete positive dimensions"],"exampleFix":"// before: shape tensor [-2, 128]\nlet shape = vec![-2i64, 128];\n// after: use -1 to infer, or the explicit positive dim\nlet shape = vec![-1i64, 128];","handlingStrategy":"validation","validationCode":"fn validate_reshape_shape(shape: &[i64]) -> Result<(), String> {\n    let negs: Vec<_> = shape.iter().filter(|&&v| v < 0 && v != -1).collect();\n    if !negs.is_empty() { return Err(format!(\"invalid dims {:?}; only -1 allowed\", negs)); }\n    Ok(())\n}","typeGuard":"fn is_valid_reshape_dim(v: i64) -> bool { v >= 0 || v == -1 }","tryCatchPattern":"match simple_eval(&model, inputs) {\n    Ok(out) => out,\n    Err(e) if e.to_string().contains(\"Reshape: invalid dimension\") => {\n        eprintln!(\"fix the shape tensor: {}\", e); Default::default()\n    }\n    Err(e) => return Err(e.into()),\n}","preventionTips":["Audit Reshape shape constants for negative values other than -1","Prefer explicit positive dimensions over inference where possible","Run onnx shape inference / checker before evaluation","Test every model with simple_eval before deploying"],"tags":["onnx","reshape","shape-mismatch"],"backgroundTag":"invalid-reshape-shape","analyzedSha":"d5fee525bfde3273eb7c9b75fd2bc4937be867ca","analyzedAt":"2026-09-02T00:15:47.023Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-09T06:17:21.866Z"}