pymc-devs / pymc-devs/pytensor
Scans are never constant-folded
Nobody has claimed this yet.
- 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:
And Alloc has this logic in it:
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 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