pymc-devs / pymc-devs/pytensor

Avoid explicit broadcasting of indices in Advanced[Inc]Subtensor

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

Nobody has claimed this yet.

graph rewriting indexing memory opt vectorization
Dominant language
Python
Stars
644
Forks
208
Avg merge
2d 14h
Merged PRs (30d)
16

Description

Description

Advanced indexing broacast indices implicitly, so in the following case there's no reason to allocate several ones:

import pytensor
import pytensor.tensor as pt

x = pt.matrix("x")
out = x[pt.arange(x.shape[0]), pt.ones(x.shape[0], dtype=int)]
fn = pytensor.function([x], out)
fn.dprint()
# AdvancedSubtensor [id A] 3
#  ├─ x [id B]
#  ├─ ARange{dtype='int64'} [id C] 2
#  │  ├─ 0 [id D]
#  │  ├─ Shape_i{0} [id E] 0
#  │  │  └─ x [id B]
#  │  └─ 1 [id F]
#  └─ Alloc [id G] 1
#     ├─ 1 [id H]
#     └─ Shape_i{0} [id E] 0
#        └─ ···

We already do this optimization for the y value in IncSubtensor with local_useless_inc_subtensor_alloc:

https://github.com/pymc-devs/pytensor/blob/11218cf44b0c11e5847d20964327059d57322fc5/pytensor/tensor/rewriting/subtensor.py#L1275-L1279

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 in pytensor/tensor/rewriting/subtensor.py around local_useless_inc_subtensor_alloc, then run the reproducer in the issue and inspect its dprint output. Reuse the existing optimization's context to determine how AdvancedSubtensor and AdvancedIncSubtensor handle implicitly broadcast indices; done means redundant index allocations no longer appear in the graph.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, performance
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 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.