huggingface/candle · error

two elements have different shapes {shape:?} {shape0:?}

Error message

two elements have different shapes {shape:?} {shape0:?}

What it means

When building a 3-D tensor from Vec<Vec<Vec<S>>>, every element's inner 2-D shape must match the first element's. NdArray::shape recursively computes each sub-shape and bails on the first mismatch, since the result must be rectangular.

Source

Thrown at candle-core/src/device.rs:172

        let mut dst = Vec::with_capacity(len);
        for v in self.iter() {
            dst.extend(v.iter().copied());
        }
        S::to_cpu_storage_owned(dst)
    }
}

impl<S: WithDType> NdArray for Vec<Vec<Vec<S>>> {
    fn shape(&self) -> Result<Shape> {
        if self.is_empty() {
            crate::bail!("empty array")
        }
        let shape0 = self[0].shape()?;
        let n = self.len();
        for v in self.iter() {
            let shape = v.shape()?;
            if shape != shape0 {
                crate::bail!("two elements have different shapes {shape:?} {shape0:?}")
            }
        }
        Ok(Shape::from([[n].as_slice(), shape0.dims()].concat()))
    }

    fn to_cpu_storage(&self) -> CpuStorage {
        if self.is_empty() {
            return S::to_cpu_storage_owned(vec![]);
        }
        let len: usize = self
            .iter()
            .map(|v| v.iter().map(|v| v.len()).sum::<usize>())
            .sum();
        let mut dst = Vec::with_capacity(len);
        for v1 in self.iter() {
            for v2 in v1.iter() {
                dst.extend(v2.iter().copied());
            }

View on GitHub (pinned to d5fee525bf)

Solutions

  1. Resize/pad all sub-elements to a common 2-D shape before construction.
  2. Validate each element's shape equals the first before calling Tensor::new.
  3. Group samples by shape and build one tensor per shape group.

Example fix

// before
let t = Tensor::new(vec![vec![vec![1.0]], vec![vec![1.0, 2.0]]], &dev)?;
// after
let t = Tensor::new(vec![vec![vec![1.0, 0.0]], vec![vec![1.0, 2.0]]], &dev)?;
Defensive patterns

Strategy: validation

Validate before calling

let shape0 = (samples[0].len(), samples[0][0].len());
if samples.iter().any(|s| (s.len(), s[0].len()) != shape0) {
    return Err(anyhow::anyhow!("all samples must share the same 2d shape"));
}

Prevention

When it happens

Trigger: Tensor::new with Vec<Vec<Vec<_>>> where any sample has a different (rows, cols) shape than sample 0.

Common situations: Batches of images with differing resolutions stacked without resizing; mixed-size nested samples.

Related errors


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