huggingface/candle · error
Reshape: at most one dimension of the target shape can be -1
Error message
Reshape: at most one dimension of the target shape can be -1
What it means
The Reshape op implementation enforces the ONNX rule that the target shape tensor may contain at most one -1 (a dimension whose size is inferred from the remaining volume). If more than one -1 appears, the shape is mathematically ambiguous and the evaluator bails with this message.
Source
Thrown at candle-onnx/src/eval.rs:406
values.insert(node.output[0].clone(), xs);
}
"MatMul" => {
let input0 = get(&node.input[0])?;
let input1 = get(&node.input[1])?;
let output = input0.broadcast_matmul(input1)?;
values.insert(node.output[0].clone(), output);
}
"Reshape" => {
let input0 = get(&node.input[0])?;
let input1 = get(&node.input[1])?.to_vec1::<i64>()?;
// 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),View on GitHub (pinned to d5fee525bf)
Solutions
- Fix the shape input so only one dimension is -1; replace the others with concrete sizes or 0 (copy from input, respecting allowzero semantics).
- If the shape is computed at runtime, debug the shape-producing nodes and ensure exactly one inferred dim.
- Validate the model with onnx.checker to catch the malformed Reshape constant.
- If the -1s are intentional for a dynamic axis, restructure the reshape (e.g. use Squeeze/Unsqueeze or Split) so at most one dim is inferred.
Example fix
// before # shape constant: [-1, -1, 768] (invalid) // after # shape constant: [-1, seq, 768] or [batch, seq, 768] with only one -1
Defensive patterns
Strategy: try-catch
Validate before calling
fn check_reshape_shapes(model: &onnx::ModelProto) -> Vec<String> {
let mut bad = vec![];
if let Some(g) = &model.graph {
for n in &g.node {
if n.op_type == "Reshape" {
for init in &g.initializer {
if n.input.contains(&init.name) {
// count -1 entries in i64 raw data when applicable
if init.data_type == 7 && init.raw_data.len() % 8 == 0 {
let negs = init.raw_data.chunks_exact(8)
.filter(|c| i64::from_le_bytes(c.try_into().unwrap()) == -1).count();
if negs > 1 { bad.push(n.name.clone()); }
}
}
}
}
}
}
bad
} Try / catch
match simple_eval(&model, inputs) {
Err(e) if e.to_string().contains("at most one dimension") => {
anyhow::bail!("model contains an invalid Reshape target shape with multiple -1s; fix or re-export the model")
}
r => r?,
} Prevention
- Ensure Reshape shape tensors contain at most one -1
- Debug runtime-computed shape tensors for duplicated inferred dims
- Run onnx.checker to catch malformed reshape constants
- Restructure dynamic reshapes with Unsqueeze/Squeeze instead of multiple -1s
When it happens
Trigger: simple_eval on a model whose Reshape node receives a shape input containing two or more -1 entries — from an invalid constant, a wrongly computed dynamic shape, or a hand-edited shape tensor.
Common situations: Dynamic shape computation bugs where the shape tensor is built at runtime (e.g. concatenating [-1] twice); exporters or scripts generating reshape constants incorrectly; manual model surgery.
Related errors
- unexpected rank for {}, got {:?}, expected {:?}
- unexpected dim {idx} for {}, got {:?}, expected {:?}
- Reshape: invalid dimension {v} in target shape
- missing input {}
- unsupported 'value' data-type {dt:?} for {}
AI-assisted analysis of huggingface/candle@d5fee525bf (2026-09-02).
Data as JSON: /api/errors/d916579c35ee3a9b.
Report an issue: GitHub.