Skip to content

Simplify basic reads and sums of basic writes - #2745

Open
velochy wants to merge 10 commits into
pymc-devs:mainfrom
velochy:block-write-rewrites
Open

velochy wants to merge 10 commits into
pymc-devs:mainfrom
velochy:block-write-rewrites

Conversation

@velochy

@velochy velochy commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes #2691.

The gradient of a slice is a full-size array of zeros with the small gradient block written into it. When that array is then only read through other slices or sums, almost all the work is filling and reading zeros. Two rewrites skip it:

local_basic_read_of_write_constant_indices   (canonicalize + specialize, shape_unsafe)
  x[1:3].set(v)[2]     -> v[1]                    full coverage of a set (#2691)
  x[1:3].set(v)[5:]    -> x[5:]                   no coverage

local_unbuilt_basic_write                    (specialize, shape_unsafe)
  w = x[:, 1:3].inc(v), every client one of:
  w[:, 2]              -> x[:, 2] + v[:, 1]
  w[:, 2:6]            -> x[:, 2:6][:, :1].inc(v[:, 1:])
  w.sum(axis=0)        -> x.sum(axis=0)[1:3].inc(v.sum(axis=0))

The first is the basic-index counterpart of local_advanced_read_of_write_constant_indices, with the same three outcomes and the same registration. Coverage is decided per axis, for constant scalars and unit-step slices (or the very same index on both sides); negative entries need a static length.

Fusion: the result reads v through basic indices only, which lift into whatever produces v, and the covered inc case is an add of two views. No advanced index is introduced.

Pessimisation: the first rewrite only makes views. The second computes something new for each client (an add, a patched copy of the read region, a sum of v), so it replaces all clients of the write together or none: the write is never built next to its replacements. It skips a write that covers all of x, which local_useless_inc_subtensor turns into an add. The sum of a set is only rewritten for a constant or Alloc base, whose sum folds; otherwise it would also sum what the set overwrites. What remains: one wide operation can become several narrow ones.

Not done here: steps other than 1, an advanced write read by a scalar (x[[1, 2]].set(v)[2], mentioned in #2691), sums of advanced writes, other reductions.

Known limitation: under JAX, with unknown static shapes, the read of a gradient's zeros becomes zeros(w.shape[0], k), which JAX's Alloc rejects ("shapes must be concrete"). pt.zeros((w.shape[0], w.shape[1]))[:, 5:8] fails the same way on main. No test in tests/link/jax hits it.

Evidence

  • Before: pt.zeros(4)[1:3].set(v)[2] compiles to Alloc, SetSubtensor{start:stop}, Subtensor{i}
    After: Subtensor{i} (v[1])

logp + dlogp, Numba, median eval per call, paired runs against main. voting is a large private hierarchical model whose gradients are zero-padded column blocks (1303 x 313 buffers); the other two are in pymc-devs/pymc-model-catalogue#27:

model main this PR
voting 28.5 ms 21.9 ms (compile 1,359 s -> 1,339 s)
survey_split_ballot_scoped_multinomial 6.1 ms -25%
survey_split_ballot_multinomial 5.6 ms -1.5% (rewrite does not fire)

An earlier revision, which rewrote reads one at a time, was 2.2x slower on survey_split_ballot_multinomial; that is why all clients are replaced together. The earlier revision was also measured on a second large model (34.9 -> 21.2 ms) and on 199 pymc-examples models (eval geomean 1.000); neither has been re-run on this one.

Merge Danger

Door: two-way

Blast Radius: default-mode graphs

Both rewrites are shape_unsafe: a write whose value has the wrong runtime shape may no longer raise once the write is rewritten away.

🤖 Generated with Claude Code

@velochy

velochy commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Sorry @aaronanish-t for potentially sniping you, but my models ran into a slightly modified version of original #2691 (inc and sum rewrites) and I figured it makes sense to cover the original proposal as well in a slightly more general rewrite PR

@velochy
velochy requested a review from ricardoV94 December 1, 2026 16:10
Comment thread pytensor/tensor/rewriting/subtensor.py Resolved
Comment thread pytensor/tensor/rewriting/subtensor.py Resolved
@velochy
velochy force-pushed the block-write-rewrites branch from 785c441 to 387577f Compare December 2, 2026 06:05
@velochy

velochy commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

The Benchmarks job failed on test_inplace_rewrite_benchmark, which pins the number of inplace nodes of a random graph (141). The new read rewrite fires 25 times on that graph, so the count is now 148; I updated the pin. The compiled function went from 337 to 343 nodes and its runtime is unchanged within noise (~39 µs both ways, 4-element vectors).

velochy and others added 2 commits December 3, 2026 07:21
x[1:3].set(v)[2] -> v[1], and the no-coverage and partial cases, per axis.
The basic-index counterpart of local_advanced_read_of_write_constant_indices.

Closes pymc-devs#2691

Co-Authored-By: Claude Fable 5.2 <[email protected]>
x[:, 1:3].inc(v).sum(axis=0) -> x.sum(axis=0)[1:3].inc(v.sum(axis=0))

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@velochy
velochy force-pushed the block-write-rewrites branch from 387577f to 9781045 Compare December 3, 2026 05:21
@ricardoV94

ricardoV94 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

I pushed some simplifications/comments on the first rewrite that I'm on board with (just extending what we already were trying to do for advanced cases).

I'm not sure how to think about multiple clients. In the read of write rewrite you gate on other clients, except if they have ops that may or may not be simplified by other rewrites (we never know unless you reimplemented the rewrite checks in this rewrite - obviously not a solution). I don't have good answers here, but note the adavced version did not gate on other clients.

Then on the sum rewrite, you do not check for other clients (otherwise you'd have deadlocked anyway in your motivating example I suppose). But it's not a principled way of going about this. I DO NOT HAVE the magical solution either.

Anyway a couple of concerns on the new sum rewrite (which doesn't have an advanced counterpart, should it?):

  • The early cast in .inc() changes the result for some mixed dtypes. The original adds in the promoted dtype and casts on store. local_read_of_write_same_indices already preserves that order. PR #2350. And/or in a more recent PR we gated on np.can_cast or somethig.
  • For .set(), the rewrite sums the part of x whose totals it immediately overwrites. Means it's a memory/compute tradeoff, not optimistic in terms of raw flop count... Need to think about it a bit more.
  • [Bot dumb concern raising of my point above] Should this check the write’s clients too? If another client keeps the full write alive, either form can add separate reductions on top of work the graph still has to do.

@ricardoV94
ricardoV94 force-pushed the block-write-rewrites branch from bbd8fa0 to 7f69921 Compare December 3, 2026 14:24
ricardoV94 and others added 2 commits December 3, 2026 15:50
@velochy

velochy commented Dec 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for the simplifications, they read better.

Multiple clients. I agree it isn't principled, but each gate is there because removing it measurably hurt (Numba, logp + dlogp, paired runs against main):

  • Write feeds only reads and sums. Without it on covered inc reads (the PR as it was at 387577f), survey_split_ballot_multinomial from Add two split-ballot survey models to the benchmark core pymc-model-catalogue#27 is 2.2-2.3x slower in eval. One likelihood reads a column range of a matrix that the others row-gather, so the read is recomputed as a 22-term sum beside the full matrix. With the gate it is unchanged from main.
  • Write doesn't cover all of x. As your comment says, local_useless_inc_subtensor turns that into an add; without the gate this rewrite gets there first. A variant of the same model where every likelihood reads a column slice (not in the catalogue PR) is 2x slower with only the clients gate, and unchanged with both.
  • Why not a plain single-client rule. I tried it. On the large voting model in the PR description it removes the gain (main 30.0 ms, single-client 29.1 ms, current rule 23.2 ms): there several block readers share one zero-padded gradient buffer. That model is private, so I can't give you a public counterexample for this one: on survey_split_ballot_scoped_multinomial from the same catalogue PR the two rules are equal (eval -20% and -22%, one run). That multi-reader case is the one that motivated the PR, so the current rule is the one I'd ask for: a single-client rule would leave the Missing basic read of write simplification #2691 fix and the single-reader gain, but not the large-model one.

You're right that a Subtensor or Sum client may not simplify, and then one narrow read is duplicated. That cost is bounded by the read's size. The advanced version is ungated and I haven't measured whether it can regress the same way.

Sum rewrite.

  • Early cast: confirmed for an inc of float values into an integer array, where the original truncates x + v and the rewrite truncated v. Now skipped, with a test (192accb). Float-only mixes differ at rounding level, as any reordered sum does.
  • Set sums what it overwrites: yes. The waste is the overwritten fraction of one sum, against not copying x and not storing v. It is a small net loss in adds when the write would have run in place.
  • Check clients: if something keeps the write alive, the extra work is one sum over v, which is smaller than the buffer. I have no case where it hurts, so I left it ungated; happy to gate it like the read if you prefer the symmetry.
  • Advanced counterpart: possible, but I'd leave it to a follow-up.

@ricardoV94

ricardoV94 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

and then one narrow read is duplicated

This is very loaded. "Narrow" in one example you're looking at.

And it's not the read that's the concern it's the duplicated write(s)

Set sums what it overwrites: yes. The waste is the overwritten fraction of one sum, against not copying x and not storing v. It is a small net loss in adds when the write would have run in place

Again "small" qualifiers don't make a good argument. I can build a counterexample where you nearly double the cost of whatever gigantic array this applies in

Although sum isn't necessarily very expensive vs copy

@ricardoV94

Copy link
Copy Markdown
Member

I didn't argue for single client rule btw, I said the logic was unprincipled and made one rewrite the "reference" coordinator/aware of the others.

Those others have to then be unconditional for the "coordination to work".

@ricardoV94

ricardoV94 commented Dec 3, 2026 •

Copy link
Copy Markdown
Member

Write feeds only reads and sums.

The issue with that is you protected against a regression but you have no guarantees the cases you let pass through aren't still gonna regress in other cases.

A read that computes something and a Sum are only rewritten when every
client of the write can be, so the write is never built next to its
replacements. Reads that cost nothing stay in
local_basic_read_of_write_constant_indices.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@velochy

velochy commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

You're right on all four, and "narrow" and "small" were my qualifiers, not bounds. I've pushed a restructure (9a0f883) that removes the coordination:

  • local_basic_read_of_write_constant_indices now only does the reads that cost nothing: a miss, or a fully covered read of a set (Missing basic read of write simplification #2691). No gate.
  • local_unbuilt_basic_write replaces the sum rewrite and the gated half of the read rewrite. It sits on the write node and replaces all of its clients together, only if every one is a basic read or whole-axis sum it can convert itself; otherwise it does nothing.

So there is one rewrite, no knowledge of other rewrites, and the write has no clients afterwards: it is never built next to its replacements. That covers the duplicated-write concern.

Numbers (Numba, logp + dlogp, one paired run each against main):

model previous head this
voting (private) 28.5 -> 21.6 ms 28.5 -> 21.9 ms
survey_split_ballot_scoped_multinomial -24% -25%
survey_split_ballot_multinomial -3% -2%
variant where every likelihood reads a slice +6% +1%

What it does not fix:

  • The sum of a set still sums the part of x it overwrites, so your near-doubling counterexample stands. Restricting the sum case to an inc, or to a zero base (the gradient case), would remove it; I haven't done that and would take your preference.
  • No guarantee that the cases it lets through never regress. Even with the write gone, one wide operation can become several narrow ones, and that was the 2x case before the "write covers all of x" check. That check is still a heuristic.

I updated the PR description to match.

@ricardoV94

Copy link
Copy Markdown
Member

For the sum of set how crazy to sum only the part that's not shadowed and then combine with two sets?

sum(x) would also sum what the set overwrites.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@velochy

velochy commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

For the sum of set how crazy to sum only the part that's not shadowed and then combine with two sets?

Not crazy for a write sliced on one kept axis: it is a join of up to three sums, join(x[:, :1].sum(0), v.sum(0), x[:, 3:].sum(0)). I didn't do it, for two reasons: writes sliced on several kept axes don't split into a few boxes, and the output stops being a small write, which is what lets the read-of-write rewrites and local_add_of_sparse_write keep going on it.

What I pushed instead (fbd432b): the sum of a set is only rewritten when the base is a constant or an Alloc, so sum(x) folds and nothing is summed twice. A set into any other base is left alone, so your near-doubling case is simply not rewritten. An inc is unaffected, since there sum(x) is needed in full anyway.

It costs nothing on the benchmarks (one paired run each against main): voting 33.8 -> 25.0 ms (24.1 ms before this commit, same run, within noise: minima 22.3 and 22.8), survey_split_ballot_scoped_multinomial -22%, survey_split_ballot_multinomial +3% with an unchanged rewrite count.

Happy to add the join for the one-axis case if you'd rather have that than skip it.

@ricardoV94

Copy link
Copy Markdown
Member

No I'm happy with that direction

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Missing basic read of write simplification

2 participants