rohitg00/ai-engineering-from-scratch · error · ValueError

Inconsistent shapes at index

Error message

Inconsistent shapes at index {i}: {s} vs {sub_shape}

What it means

Raised in Tensor._flatten_nested when sibling sublists at one nesting level report different shapes, i.e. the input is ragged rather than a regular rectangular nested sequence. A tensor requires uniform extents on every axis; the index of the first mismatching element and the two conflicting shapes are reported.

Solutions

  1. Pad or trim the ragged rows so every sublist at the same depth has equal length
  2. Fix the data producer that emitted unequal-length rows (common when mapping over variable-length inputs)
  3. Validate regularity before constructing the Tensor and raise a clearer domain error
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:37 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/9c71f69931ec6b28. Report an issue: GitHub.

Appendix: source

Thrown at phases/01-math-foundations/12-tensor-operations/code/tensors.py:37

            if total != len(self._data):
                raise ValueError(
                    f"Cannot reshape {len(self._data)} elements into shape {shape}"
                )
            self._shape = tuple(shape)

        self._strides = self._compute_strides(self._shape)

    def _flatten_nested(self, data):
        if not isinstance(data, (list, tuple)):
            return [data], ()
        if len(data) == 0:
            return [], (0,)

        sub_results = [self._flatten_nested(item) for item in data]
        sub_shape = sub_results[0][1]
        for i, (_, s) in enumerate(sub_results):
            if s != sub_shape:
                raise ValueError(
                    f"Inconsistent shapes at index {i}: {s} vs {sub_shape}"
                )

        flat = []
        for sub_data, _ in sub_results:
            flat.extend(sub_data)

        return flat, (len(data),) + sub_shape

    @staticmethod
    def _compute_strides(shape):
        if len(shape) == 0:
            return ()
        strides = [1] * len(shape)
        for i in range(len(shape) - 2, -1, -1):
            strides[i] = strides[i + 1] * shape[i + 1]
        return tuple(strides)

View on GitHub (pinned to 39ea8a1c6d)