pymc-devs / pymc-devs/pytensor
PyTorch backend warns on every read-only constant: torch.as_tensor on non-writable array
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 644
- Forks
- 208
- Avg merge
- 2d 14h
- Merged PRs (30d)
- 16
Description
Rewrites can produce constants whose data is read-only, and pytorch_typify_tensor hands them straight to torch.as_tensor, which shares memory and warns that writes are undefined behavior. Anything running filterwarnings = error fails on it.
import numpy as np
import pytensor
import pytensor.tensor as pt
x = pt.vector("x")
fn = pytensor.function([x], pt.grad((x**2).sum(), x), mode="PYTORCH")
fn(np.ones(3)) # UserWarning: The given NumPy array is not writable
The read-only array comes from TensorConstant.unique_value, so the forward pass is fine and only a rewrite in the gradient trips it.
Potential fix (requires testing):
def pytorch_typify_tensor(data, dtype=None, **kwargs):
if isinstance(data, np.ndarray) and not data.flags.writeable:
data = data.copy()
return torch.as_tensor(data, dtype=dtype)
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 pytorch_typify_tensor and trace how TensorConstant.unique_value reaches torch.as_tensor during the PyTorch gradient example. Reproduce the warning with filterwarnings = error, then add coverage for a read-only NumPy array and verify the gradient runs without the warning.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- numpy, python, pytorch
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 72/100