huggingface/candle · error

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

Error message

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

What it means

When reshaping without (or beyond) a wildcard, the tensor's total element count must be divisible by the product of the requested dimensions. hole_size bails when el_count is not a multiple of prod_d, meaning the requested shape cannot tile the existing data evenly.

Source

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

            }
            .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. Use a wildcard for the unknown dimension: reshape ((,), 64) or ((), -1-equivalent) so candle infers it
  2. Compute the target dim from el_count / known_dims instead of hard-coding
  3. Check tensor.elem_count() and the product of the target dims before reshaping

Example fix

// before
let y = x.reshape((2, 499))?; // 1000 elems
// after
let y = x.reshape(((), 500))?; // hole inferred as 2
Defensive patterns

Strategy: validation

Validate before calling

let el = x.elem_count();
let prod: usize = dims.iter().product();
if !dims.contains(&HOLE) && el % prod != 0 {
    return Err(anyhow::anyhow!("cannot reshape {el} elements to {dims:?}"));
}

Try / catch

let y = x.reshape(dims).or_else(|_| {
    // retry with a hole in the first dim
    x.reshape(((), dims[1]))
})?;

Prevention

When it happens

Trigger: Calling tensor.reshape(...)/into_shape with concrete dims whose product does not divide the tensor's element count, e.g. reshaping a 1000-element tensor to (2, 499).

Common situations: Hard-coded reshape sizes that assume a different batch/sequence length; forgetting a channel dim; models with dynamic batch sizes where a constant target shape no longer divides evenly.

Related errors


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