tracel-ai/burn · error

Cannot substitute -1 for a non-existing dimension! Got {:?}

Error message

Cannot substitute -1 for a non-existing dimension! Got {:?}

What it means

After resolving broadcast args, a resulting dimension of 0 means a -1 could not be substituted — i.e. the code path that replaces -1 with the existing dimension found no valid dimension to take the size from. Burn panics with the resolved new_shape for diagnosis. In practice this indicates the -1 inference produced an invalid shape: the -1s could not be mapped onto the tensor's existing dims (e.g. more -1s than original dims, or the resolved shape collapsed to 0).

Source

Thrown at crates/burn-tensor/src/tensor/api/base.rs:3404

            .map(|x| {
                let primitive = x.as_index();
                if primitive < -1 || primitive == 0 {
                    panic!(
                        "Broadcast arguments must be positive or -1! Got {}",
                        primitive
                    );
                }
                primitive
            })
            .zip(shape.iter().rev().chain(repeat(&0)).take(self.len())) // Pad the original shape with 0s
            .map(|(x, &y)| if x == -1 { y } else { x as usize })
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();

        if new_shape.contains(&0) {
            panic!(
                "Cannot substitute -1 for a non-existing dimension! Got {:?}",
                new_shape
            );
        }

        let new_shape: [usize; D2] = new_shape.try_into().unwrap();

        Shape::from(new_shape)
    }
}

impl<const D: usize, K> Serialize for Tensor<D, K>
where
    K: Basic,
{
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let data = self.to_data();
        data.serialize(serializer)

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Use at most one -1 per broadcast/reshape call and give every other dimension an explicit positive size
  2. Ensure the argument array's rank matches the tensor's rank so each -1 maps to an existing dimension
  3. Print/inspect x.dims() and the target shape, then replace ambiguous -1s with concrete sizes (e.g. 1 for broadcast-expanded dims)
  4. Use tensor.to_dtype-free helpers like reshape with an explicit Shape built from known dims instead of -1 inference

Example fix

// before, x is [B, C]
let y = x.reshape([-1, -1, 64]); // -1s cannot all be resolved -> resolved shape contains 0 -> panic
// after
let y = x.reshape([-1, 1, 64]); // only one -1; other dims explicit
Defensive patterns

Strategy: validation

Validate before calling

// Ensure at most one -1 and that the arg rank matches the tensor rank
let minus_ones = args.iter().filter(|d| d.as_index() == -1).count();
assert!(minus_ones <= 1, "at most one -1 can be inferred");
assert!(args.len() >= x.shape().num_dims());

Try / catch

// Panic API; build the shape explicitly instead of relying on -1 inference:
let mut target = x.dims(); target[0] = 1; // construct concrete dims, then reshape(target)

Prevention

When it happens

Trigger: Using multiple -1 entries in a broadcast/reshape argument where at most one can be inferred, so the resolution yields a 0 entry; broadcasting a higher-rank argument array against a lower-rank tensor so some -1s have no source dimension; a -1 landing on a dimension the original tensor doesn't have.

Common situations: Copy-pasted numpy/torch reshape code that uses -1 freely, run against Burn's stricter broadcast semantics; dynamically built shape vectors where the number of -1 placeholders outgrew the tensor rank; refactors that changed tensor rank without updating the -1 placeholders.

Related errors


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