pymc-devs / pymc-devs/pytensor

Replace 0 sized nodes by zeros

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

Nobody has claimed this yet.

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

Description

Description

If we have any empty operations, we can truncate the whole graph above it:

import pytensor
import pytensor.tensor as pt

x = pt.vector("x", shape=(10,))
out = pt.add.outer(x, x)[9:-1]

fn = pytensor.function([x], out)
fn.dprint(print_shape=True)
# Subtensor{start:stop} [id A] shape=(0, 10) 3
#  ├─ Add [id B] shape=(10, 10) 2
#  │  ├─ ExpandDims{axis=1} [id C] shape=(10, 1) 1
#  │  │  └─ x [id D] shape=(10,)
#  │  └─ ExpandDims{axis=0} [id E] shape=(1, 10) 0
#  │     └─ x [id D] shape=(10,)
#  ├─ 9 [id F] shape=()
#  └─ -1 [id G] shape=()

PyTensor knows that the shape=(0, 10). We can replace the graph by just zeros. Worse thing it could do would be to hide shape errors, so we can add the shape_unsafe tag.

We need to be careful with Operations that cannot figure out the output shape without computing itself (such as while Scan). We can ask the ShapeFeature for the shape of the variable, and if the variable is still in the shape graph we know we can't really avoid computing the graph. Otherwise just replace it by zeros.

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 ShapeFeature and the shape graph behavior described in the issue, then reproduce the empty-output example using pytensor.function and inspect how while Scan is handled. Done means zero-sized outputs are replaced with zeros when their shapes are known without evaluating the graph, while shape_unsafe preserves cases where shape errors could otherwise be hidden.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.