tracel-ai/burn · error

D2 must equal D + 1 for Tensor::cartesian_grid

Error message

D2 must equal D + 1 for Tensor::cartesian_grid

What it means

Compile-time-vs-runtime rank check in `Tensor::cartesian_grid`: given a D-dimensional input shape, the output grid tensor must have rank D+1 (one coordinate plane per axis); if the caller annotates the result with a D2 that isn't D+1, the function panics. The failing input is the mismatched const generic D2 on the call site.

Source

Thrown at crates/burn-tensor/src/tensor/api/cartesian_grid.rs:30

/// # Panics
///
/// Panics if `D2` is not equal to `D+1`.
///
/// # Examples
///
/// ```rust
///    use burn_tensor::Int;
///    use burn_tensor::{Shape, Tensor};
/// let device = Default::default();
/// let result: Tensor<3, _> = Tensor::<2, Int>::cartesian_grid([2, 3], &device);
/// println!("{}", result);
/// ```
pub fn cartesian_grid<S: Into<Shape>, const D: usize, const D2: usize>(
    shape: S,
    device: &Device,
) -> Tensor<D2, Int> {
    if D2 != D + 1 {
        panic!("D2 must equal D + 1 for Tensor::cartesian_grid")
    }

    let dims = shape.into();
    let mut indices: Vec<Tensor<D, Int>> = Vec::new();

    for dim in 0..D {
        let dim_range: Tensor<1, Int> = Tensor::arange(0..dims[dim] as i64, device);

        let mut shape = [1; D];
        shape[dim] = dims[dim];
        let mut dim_range = dim_range.reshape(shape);

        for (i, &item) in dims.iter().enumerate() {
            if i == dim {
                continue;
            }
            dim_range = dim_range.repeat_dim(i, item);
        }

View on GitHub (pinned to d16f7ba2ed)

Solutions

  1. Annotate the result type as Tensor<D+1, Int>, e.g. `Tensor::<3, _>` for a 2-D shape input.
  2. Let the compiler infer D2 instead of pinning it to a wrong constant.
  3. Fix the shape argument if the intended grid dimension differs from the annotated output rank.
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at crates/burn-tensor/src/tensor/api/cartesian_grid.rs:30 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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