pymc-devs / pymc-devs/pytensor

PyTorch backend warns on every read-only constant: torch.as_tensor on non-writable array

Open Beginner friendly
#2,365 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug torch
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.