pymc-devs / pymc-devs/pytensor

Scans are never constant-folded

Open
#1,688 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

graph rewriting performance scan
Dominant language
Python
Stars
644
Forks
208
Avg merge
2d 14h
Merged PRs (30d)
16

Description

Description
import pytensor
import pytensor.tensor as pt

x0 = pt.zeros(())
xs, _ = pytensor.scan(lambda x: x+1, outputs_info=[x0], n_steps=4)
fn = pytensor.function([], xs)
fn.dprint()  # Scan still in the graph

This happens because Alloc never constant-folds if used by a SetSubtensor, as most times we want to write in place (and we can't write in-place of constants). But when the whole chain could ultimately be constant-folded (as here), this is wasteful.

The logic for whether to constant-fold based on the graph or not should be the responsibility of the constant-fold rewrite, not the Op. Right now it's implemented here.

AllocEmpty never constant_folds:

https://github.com/pymc-devs/pytensor/blob/17c675a2d908661f9d1f84ae56f4cb6f5c4fa7c8/pytensor/tensor/basic.py#L4397-L4398

And Alloc has this logic in it:

https://github.com/pymc-devs/pytensor/blob/17c675a2d908661f9d1f84ae56f4cb6f5c4fa7c8/pytensor/tensor/basic.py#L1780-L1818

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 with the Alloc and AllocEmpty implementations in pytensor/tensor/basic.py at the linked sections, then reproduce the provided pytensor.scan example and inspect its fn.dprint() output. Trace the constant-fold rewrite and move the graph-dependent decision out of the Ops; done means the example no longer retains Scan while existing in-place behavior remains correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Refactor
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.