tracel-ai/burn · error

Index out of bounds for SelectionDataset: {index} >= {}

Error message

Index out of bounds for SelectionDataset: {index} >= {}

What it means

`SelectionDataset`'s `Dataset::get` first looks up `self.indices[index]` to translate the selection position into a wrapped-dataset index; if the position is not present in the indices vector (i.e. `index >= indices.len()`), it panics. Note the bound checked is the length of the indices list, not the wrapped dataset.

Source

Thrown at crates/burn-dataset/src/transform/selection.rs:231

            let dataset = self.slice(start, end);

            current += batch_size;
            datasets.push(dataset);
        }

        datasets
    }
}

impl<D, I> Dataset<I> for SelectionDataset<D, I>
where
    D: Dataset<I>,
    I: Clone + Send + Sync,
{
    fn get(&self, index: usize) -> Result<I, DatasetError> {
        let Some(&index) = self.indices.get(index) else {
            panic!(
                "Index out of bounds for SelectionDataset: {index} >= {}",
                self.indices.len()
            );
        };
        self.wrapped.get(index)
    }

    fn get_many(&self, indexes: Vec<usize>) -> Result<Vec<I>, DatasetError> {
        let translated: Vec<usize> = indexes
            .into_iter()
            .map(|i| {
                self.indices.get(i).copied().unwrap_or_else(|| {
                    panic!(
                        "Index out of bounds for SelectionDataset: {i} >= {}",
                        self.indices.len()
                    )
                })
            })

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Bound loops by `selection.len()`, not the wrapped dataset's length.
  2. Guard each access: `if index < selection.len() { selection.get(index) }`.
  3. Use `selection.iter()` / sampler APIs that respect the selection size.
  4. Verify the selection was constructed with the intended index list (log its len).

Example fix

// before
for i in 0..wrapped.len() {
    let item = selection.get(i).unwrap(); // panics once i >= selection.len()
}

// after
for i in 0..selection.len() {
    let item = selection.get(i)?;
}
Defensive patterns

Strategy: validation

Validate before calling

if index < selection.len() {
    let item = selection.get(index)?;
} else {
    // handle out-of-range position

Prevention

When it happens

Trigger: Calling `selection.get(position)` with `position >= selection.len()` (== `self.indices.len()`); iterating past the selection length; batch code using the wrapped dataset's length instead of the selection's length.

Common situations: Using `wrapped.len()` for loop bounds while the selection is a subset (e.g. a validation subset of train); stale cached lengths after reshuffling; off-by-one `0..=len` loops.

Related errors


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