pymc-devs / pymc-devs/pytensor
XTensorType.dims and .shape are silently mutable, leaving ndim out of sync
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 644
- Forks
- 208
- Avg merge
- 2d 14h
- Merged PRs (30d)
- 16
Description
Reproduction
from pytensor.xtensor import xtensor
a = xtensor("a", dtype="float64", dims=("obs", "feature"))
b = xtensor("b", dtype="float64", dims=("feature",))
a.type.dims = ("g1", "g2", "obs", "feature")
a.type.shape = (None, None, None, None)
print(f"ndim={a.type.ndim}, len(dims)={len(a.type.dims)}") # ndim=2, len=4
c = a @ b # triggers shape rewrites; see traceback below
The @ operation triggers shape inference (shape.py:233) which iterates range(inp.type.ndim) to index into type.shape. Since ndim=2 but shape has 4 elements, indices 2 and 3 crash:
shape.py:233: tuple(input_shape_of(inp, j) for j in range(inp.type.ndim))
shape.py:275: if isinstance(var.type, HasShape) and var.type.shape[idx] is not None
IndexError: tuple index out of range
Expected behavior
dims and shape should be read-only properties. Mutating either should raise AttributeError.
Actual behavior
Both are plain instance attributes. ndim is computed once at __init__ and never updated.
Environment
pytensor 3.2.4 (PyPI) and 3.2.4 main branch — both affected
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at the XTensorType definition and inspect shape.py at lines 233 and 275, where ndim and shape become inconsistent during shape inference. Reproduce the example, then verify that assigning to dims or shape raises AttributeError and that the matmul case no longer fails with an index error.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 72/100