pymc-devs / pymc-devs/pytensor

Prune axis invariant offsets in (log)softmax

Open
#2,344 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Description
import numpy as np, pytensor, pytensor.tensor as pt

N, G, K, M = 2000, 8, 10, 64
rng = np.random.default_rng(0)
x = pt.tensor("x", shape=(N, G, K))
c = pt.tensor("c", shape=(N, G, M))
offset = pt.exp(c).sum(-1, keepdims=True)  # (N, G, 1): constant along the softmax axis

# log_softmax(x + offset) == log_softmax(x): offset cancels, so computing it is dead work
slow = pytensor.function([x, c], pt.special.log_softmax(x + offset, -1))
fast = pytensor.function([x], pt.special.log_softmax(x, -1))

xv, cv = rng.normal(size=(N, G, K)), rng.normal(size=(N, G, M))
assert np.allclose(slow(xv, cv), fast(xv))

%timeit slow(xv, cv)   # 11.6 ms
%timeit fast(xv)       # 4.2 ms  -> 2.8x

Note our softmax and log_softmax already do the max subtraction stabilization, so a user doing the stabilization manually (which has the form of invariant addition/subtraction) can also be removed safely.

Similar logsumexp(x + c) -> logsumexp(x) + c

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 by reproducing the issue's Python example and confirming the invariant offset is removed without changing results. Then locate PyTensor's optimization handling for softmax, log_softmax, and logsumexp, and add coverage for axis-invariant additions or subtractions. Done means the optimized graph avoids the dead computation while preserving the shown numerical equivalences.

Written by the indexing model from the issue text.

Assessment

Tech stack
numpy, python
Domain
performance
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.