Building `pt.diag` is 50x slower than building an Elemwise

Open
#2,631 3 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
48/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
python
Domain
performance

Research direction

Start by tracing pt.diag(x) through SymbolicOp.__call__ and the AllocDiag construction described in the issue; compare that path with reusing the existing op. Run the included timing snippet to reproduce the slowdown. Done means repeated calls avoid the reported construction cost while preserving correct behavior; the issue leaves open whether to memoize AllocDiag or make OpFromGraph construction cheaper.

Written by the indexing model from the issue text.

Description

OpFromGraph performance

pt.diag(x) takes about 1.2 ms to build on 3.3.8. pt.exp(x) takes 0.024 ms. Most of the time goes to SymbolicOp.__call__ making a brand new AllocDiag on every call. Each new one reruns build_inner_graph and the whole OpFromGraph constructor, even when the props and input types match one that already exists.

Reusing an existing AllocDiag takes 0.008 ms, so memoizing the specialized op seems like an obvious thing to try. Maybe that's a hack and the real fix is making OpFromGraph construction cheaper in general? Not sure.

import timeit

import pytensor.tensor as pt

x = pt.vector("x")
diag_op = pt.diag(x).owner.op

# seconds per 1000 calls == ms per call
print(timeit.timeit(lambda: pt.diag(x), number=1000))   # 1.20
print(timeit.timeit(lambda: diag_op(x), number=1000))   # 0.008
print(timeit.timeit(lambda: pt.exp(x), number=1000))    # 0.024
print(pt.diag(x).owner.op is pt.diag(x).owner.op)       # False
Dominant language
Python
Stars
655
Forks
266
Avg merge
3d 23h
Merged PRs (30d)
43

Getting set up

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.

More from pymc-devs/pytensor

All issues in pymc-devs/pytensor

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.