huggingface/candle · error

cannot reshape tensor of {el_count} elements to {s:?}

Error message

cannot reshape tensor of {el_count} elements to {s:?}

What it means

into_shape supports one wildcard dimension (a hole) in the target shape. hole_size computes the hole's size by dividing the tensor's element count by the product of the concrete dims. If that product is 0 (the target shape contains a 0-sized dimension alongside the hole), the hole cannot be resolved and this error fires.

Source

Thrown at candle-core/src/shape.rs:496

            return Err(Error::ShapeMismatch {
                buffer_size: el_count,
                shape,
            }
            .bt());
        }
        Ok(shape)
    }
}

impl ShapeWithOneHole for ((),) {
    fn into_shape(self, el_count: usize) -> Result<Shape> {
        Ok(el_count.into())
    }
}

fn hole_size(el_count: usize, prod_d: usize, s: &dyn std::fmt::Debug) -> Result<usize> {
    if prod_d == 0 {
        crate::bail!("cannot reshape tensor of {el_count} elements to {s:?}")
    }
    if !el_count.is_multiple_of(prod_d) {
        crate::bail!("cannot reshape tensor with {el_count} elements to {s:?}")
    }
    Ok(el_count / prod_d)
}

impl ShapeWithOneHole for ((), usize) {
    fn into_shape(self, el_count: usize) -> Result<Shape> {
        let ((), d1) = self;
        Ok((hole_size(el_count, d1, &self)?, d1).into())
    }
}

impl ShapeWithOneHole for (usize, ()) {
    fn into_shape(self, el_count: usize) -> Result<Shape> {
        let (d1, ()) = self;
        Ok((d1, hole_size(el_count, d1, &self)?).into())

View on GitHub (pinned to d5fee525bf)

Solutions

  1. Remove the 0-sized dimension from the target shape or fix the upstream dim that is 0
  2. If you intended a wildcard, use () (or -1 in user-facing APIs) for the unknown dim, not 0
  3. Compute the target shape explicitly with element counts you control

Example fix

// before
t.into_shape((0, 64))? // prod includes 0
// after
t.into_shape(((), 64))? // hole infers the 0-th dim
Defensive patterns

Strategy: validation

Validate before calling

let target = (0usize, 64usize); // built programmatically
if target.0 == 0 && uses_hole(target) {
    return Err(anyhow::anyhow!("0 dim alongside a reshape hole is invalid"));
}

Prevention

When it happens

Trigger: Calling tensor.into_shape(...) / reshape with a shape containing both a hole (e.g. ((), 64)) and a 0 dimension, so prod_d == 0 while the tensor is non-empty.

Common situations: Constructing shapes from runtime dims where a batch/seq dim was 0; passing shape tuples built programmatically with a 0 entry; misunderstanding that a 0 dim is itself a valid wildcard-free dim.

Related errors


AI-assisted analysis of huggingface/candle@d5fee525bf (2026-09-02). Data as JSON: /api/errors/c5fbf00b129a70df. Report an issue: GitHub.