huggingface/candle · error

empty array

Error message

empty array

What it means

When building a tensor from Vec<&[S]> (2-D slice rows), NdArray::shape returns an error if the outer vector is empty, since no shape can be derived. This check runs when converting the nested array into a Shape.

Source

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

        }
        S::to_cpu_storage_owned(vec)
    }
}

impl<S: WithDType> NdArray for Vec<S> {
    fn shape(&self) -> Result<Shape> {
        Ok(Shape::from(self.len()))
    }

    fn to_cpu_storage(&self) -> CpuStorage {
        S::to_cpu_storage(self.as_slice())
    }
}

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

    fn to_cpu_storage(&self) -> CpuStorage {
        let data = self.iter().copied().flatten().copied().collect::<Vec<_>>();
        S::to_cpu_storage_owned(data)
    }
}

impl<S: WithDType> NdArray for Vec<Vec<S>> {

View on GitHub (pinned to d5fee525bf)

Solutions

  1. Check the collection is non-empty before constructing the tensor.
  2. Return a meaningful application-level error for empty input instead of constructing a tensor.
  3. Construct with an explicit shape/dtype if a placeholder tensor is needed.

Example fix

// before
let t = Tensor::new(rows, &Device::Cpu)?;
// after
anyhow::ensure!(!rows.is_empty(), "need at least one row");
let t = Tensor::new(rows, &Device::Cpu)?;
Defensive patterns

Strategy: validation

Validate before calling

if rows.is_empty() {
    return Err(anyhow::anyhow!("cannot build tensor from empty rows"));
}

Prevention

When it happens

Trigger: Calling Tensor::new(vec![]), Tensor::from_slice of an empty slice-of-slices, or Tensor::from_vecs with an empty Vec<&[S]> on CPU.

Common situations: Building tensors from dynamically collected data that ended up empty (no rows loaded, empty batch).

Related errors


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