huggingface/candle · error
Reshape: invalid dimension {v} in target shape
Error message
Reshape: invalid dimension {v} in target shape What it means
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_.
Source
Thrown at candle-onnx/src/eval.rs:417
// A 0 in the target shape copies the corresponding input dimension, unless
// allowzero=1, where it means a literal zero-length dimension.
let allowzero = get_attr_opt::<i64>(node, "allowzero")?
.copied()
.unwrap_or(0)
== 1;
if input1.iter().filter(|&&v| v == -1).count() > 1 {
bail!("Reshape: at most one dimension of the target shape can be -1")
}
// Resolve everything but -1 first: a copied 0 is part of the volume, so it
// has to be in the product that -1 is inferred against.
let mut resolved: Vec<Option<usize>> = Vec::with_capacity(input1.len());
for (idx, &v) in input1.iter().enumerate() {
resolved.push(match v {
-1 => None,
0 if allowzero => Some(0),
0 => Some(input0.dim(idx)?),
v if v > 0 => Some(v as usize),
v => bail!("Reshape: invalid dimension {v} in target shape"),
});
}
let known: usize = resolved.iter().flatten().product();
let input1 = resolved
.into_iter()
.map(|d| match d {
Some(d) => Ok(d),
// A -1 has no unique value when the rest of the volume is zero.
None if known == 0 => {
bail!("Reshape: -1 cannot be inferred when another dimension is zero")
}
None => Ok(input0.elem_count() / known),
})
.collect::<Result<Vec<usize>>>()?;
let output = input0.reshape(input1)?;
values.insert(node.output[0].clone(), output);
}
"LogSoftmax" => {View on GitHub (pinned to d5fee525bf)
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
Example fix
// before: shape tensor [-2, 128] let shape = vec![-2i64, 128]; // after: use -1 to infer, or the explicit positive dim let shape = vec![-1i64, 128];
Defensive patterns
Strategy: validation
Validate before calling
fn validate_reshape_shape(shape: &[i64]) -> Result<(), String> {
let negs: Vec<_> = shape.iter().filter(|&&v| v < 0 && v != -1).collect();
if !negs.is_empty() { return Err(format!("invalid dims {:?}; only -1 allowed", negs)); }
Ok(())
} Type guard
fn is_valid_reshape_dim(v: i64) -> bool { v >= 0 || v == -1 } Try / catch
match simple_eval(&model, inputs) {
Ok(out) => out,
Err(e) if e.to_string().contains("Reshape: invalid dimension") => {
eprintln!("fix the shape tensor: {}", e); Default::default()
}
Err(e) => return Err(e.into()),
} Prevention
- 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
When it happens
Trigger: Calling Reshape (via simple_eval/simple_eval_) with a shape tensor input1 containing a negative value other than -1, e.g. -2, -5.
Common situations: 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.
Related errors
- Reshape: at most one dimension of the target shape can be -1
- unexpected rank for {}, got {:?}, expected {:?}
- unexpected dim {idx} for {}, got {:?}, expected {:?}
- Reshape: -1 cannot be inferred when another dimension is zer
- backward not supported for non uniform upscaling factors
AI-assisted analysis of huggingface/candle@d5fee525bf (2026-09-02).
Data as JSON: /api/errors/5124c5a2bc7f2956.
Report an issue: GitHub.