tracel-ai/burn · error

Cannot compute max of empty tensor

Error message

Cannot compute max of empty tensor

What it means

max_view reduces a (zero-copy) view of the tensor to its maximum element using reduce(), which returns None when the iterator is empty. The expect() then panics, because there is no defined max of zero elements. Applies to the max_dim reduction (full reduction) on the ndarray backend.

Source

Thrown at crates/burn-ndarray/src/ops/base.rs:1267

                        false => -one,
                    }
                }
            })
            .into_shared()
    }
}

impl<E> NdArrayMathOps<E>
where
    E: Copy + NdArrayElement + PartialOrd,
{
    /// Max of all elements - zero-copy for borrowed storage.
    pub fn max_view(view: ArrayView<'_, E, IxDyn>) -> SharedArray<E> {
        let max = view
            .iter()
            .copied()
            .reduce(|a, b| if a > b { a } else { b })
            .expect("Cannot compute max of empty tensor");
        ArrayD::from_elem(IxDyn(&[1]), max).into_shared()
    }

    /// Max of all floating-point elements with NaN propagation.
    pub fn max_float_view(view: ArrayView<'_, E, IxDyn>) -> SharedArray<E>
    where
        E: FloatNdArrayElement,
    {
        let max = view
            .iter()
            .copied()
            .reduce(|a, b| {
                if a.partial_cmp(&a).is_none() || a > b {
                    a
                } else {
                    b
                }
            })

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Guard: if tensor.num_elements() == 0, skip the reduction or return a sentinel value instead of calling max
  2. Fix upstream slicing/shape logic so dimensions are never 0 at the reduction point
  3. Filter empty batches before running the model

Example fix

// before
let m = empty_batch.max(); // panics
// after
if empty_batch.num_elements() > 0 {
    let m = empty_batch.max();
} else {
    // handle empty case: skip or default value
}
Defensive patterns

Strategy: validation

Validate before calling

fn safe_max<E: burn_ndarray::FloatElement, const D: usize>(t: &Tensor<NdArray<E>, D>) -> Option<Tensor<NdArray<E>, 1>> {
    if t.num_elements() == 0 { None } else { Some(t.max()) }
}

Prevention

When it happens

Trigger: Calling Tensor::max_dim / max reduction on a tensor with zero elements (any dimension of size 0), e.g. after slicing an empty range or a batch dimension of size 0.

Common situations: Empty batches in a data loader with drop logic that lets an empty batch reach max pooling; slicing with an empty range (0..0); dynamic shapes that collapse to 0 under certain inputs.

Related errors


AI-assisted analysis of tracel-ai/burn@d16f7ba2ed (2026-09-05). Data as JSON: /api/errors/7dd6195bc3412960. Report an issue: GitHub.