Skip to content

Add ReduceGroundCartesianProduct - #731

Open
eb8680 wants to merge 2 commits into
staging-weightedfrom
eb-ground-cartesian-product
Open

Add ReduceGroundCartesianProduct#731
eb8680 wants to merge 2 commits into
staging-weightedfrom
eb-ground-cartesian-product

Conversation

@eb8680

@eb8680 eb8680 commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Adds ReduceGroundCartesianProduct, the fallback rule for a reduction over a
cartesian-product row stream whose body admits no per-plate factorization.

The rewrite

reduce(M, body, {X: CartesianProduct.reduce(Union.reduce([as_dict((idx, w))], D), P)} ∪ S)
═══════════════════════════════════════════════════════════════════════════
reduce(M, body[X[a] := w_a], {w_a: D[idx := a]} ∪ S)

where a ranges over the plate assignments the body actually subscripts.

_GroundRow is a Mapping that stands in for the row variable. Unrolling the
body's plate folds hands it concrete keys, and it answers each with a variable
minted on first sight (the same variable for a repeated key, which is what ties
the factors of a chain together). A key that is still symbolic never reaches it:
the subscript stays a term until the fold supplying the index is expanded.
_GroundRow.residual returns whatever plate values no key consumed, which stay
in the expression as a smaller cartesian product; sealed + fvsof reject a
half-ground result, in which case the rule declines.

When this applies vs. ReduceDistributeCartesianProduct

Where the body folds over the plates uniformly, ReduceDistributeCartesianProduct
inverts the reduction instead — cheaper, and it leaves the plate fold intact.
Grounding is for bodies where inversion does not apply, e.g. a chain
X[t], X[t+1] couples adjacent plate indices. Grounding costs one variable per
assignment (|P| variables over D) instead of enumerating the |D|^|P| rows,
after which what is left is an ordinary variable-elimination problem that
Factor solves. ReduceGroundCartesianProduct() is registered in
NormalizeIntp immediately before ReduceDistributeCartesianProduct().

ReduceDistributeCartesianProduct itself is untouched here.

ReducePartial.unrolled

ReducePartial gains an optional unrolled set of stream variables and skips
any stream not in it. Grounding installs ReducePartial(plate_vars) so that
expanding the body expands only the plate folds it is grounding over, and not,
say, the value domains.

Test

tests/test_ops_monoid.py::test_ground_cartesian_product_chain reduces a chain
Sum_ixs Prod_t phi[t][ixs[t]][ixs[t+1]] and checks the result against the
forward algorithm computed in plain Python.

It is written longhand with explicit defop variables. In #724 it is written
as

Sum(
    Product(phi()[t][ixs[t]][ixs[t + 1]] for t in range(T - 1))
    for ixs in CartesianProduct(range(K) for _ in range(T))
)

using the generator-comprehension syntax that lands in a later PR; the body
below is exactly what desugar_comprehension produces for it.

T is 10 rather than the 20 used in #724: normalization is superlinear in the
chain length until the separate evaluate performance fix lands, and this
branch is deliberately not stacked on it. At T = 10 the test takes ~6s; at
T = 20 it takes over an hour. K = 3 as in #724.

The test does discriminate: unregistering the rule makes normalization a no-op
and the added structural assertion fails immediately. (Without that assertion
the test would still pass at T = 10, just 11x slower, because evaluation
falls back to enumerating all K ** T rows — which is why the assertion is
there.)

Prerequisite: #729

This PR is stacked on #729 (eb-jax-scalar-plus), which fixes _jax_args in
effectful/handlers/jax/monoid.py. That fix is a genuine prerequisite here, not
a cosmetic one: jax.typing.ArrayLike includes bool/int/float/complex,
so the jax handlers claimed pure-Python scalar arithmetic. Without it the new
test does not merely produce a different type — it raises TypeError: Cannot unify type <class 'int'> with <class 'jax.Array'>
, because
tests/test_ops_monoid.py imports effectful.handlers.jax.monoid
unconditionally.

This branch's own diff is just effectful/ops/monoid.py and
tests/test_ops_monoid.py.

The ReduceDisequalityMask or -> is None fix that also lives in #724 was
checked and is not needed here: the full suite passes without it.

Testing

  • tests/test_ops_monoid.py + tests/test_handlers_jax_monoid.py: 531 passed.
  • Full tests/ sweep excluding tests/test_handlers_llm_*.py: 18318 passed,
    2 skipped, 2078 xfailed — versus 18317/2/2078 on pristine staging-weighted,
    the difference being the new test. No regressions.
  • ruff check, ruff format --diff clean. mypy clean apart from the one
    pre-existing effectful/handlers/jax/monoid.py error already on
    staging-weighted.

Split out of #724 for review. Stacked on #729. Independent of the sibling
ReduceDistributeCartesianProduct refactor (#730), also split out of #724.

🤖 Generated with Claude Code

@eb8680
eb8680 force-pushed the eb-ground-cartesian-product branch from c5efdf2 to 93a5895 Compare July 28, 2026 16:07
@eb8680
eb8680 changed the base branch from staging-weighted to eb-jax-scalar-plus July 28, 2026 16:07
@eb8680 eb8680 added the blocked label Jul 28, 2026
Base automatically changed from eb-jax-scalar-plus to staging-weighted July 28, 2026 16:19
@jfeser jfeser removed the blocked label Jul 28, 2026
@eb8680
eb8680 requested a review from jfeser July 28, 2026 22:23
@eb8680
eb8680 marked this pull request as ready for review July 29, 2026 00:08
@eb8680

eb8680 commented Jul 29, 2026

Copy link
Copy Markdown
Contributor Author

The slop in the PR description is from disaggregating #724. The code in this PR was largely written and checked by me.

@jfeser jfeser left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pushed some new tests that currently fail. We should either fix those cases or forward. The diagonal stream consumption issue also affects ReduceDistributeCartesianProduct (there it causes a performance problem, not a correctness one).

@jfeser
jfeser force-pushed the staging-weighted branch from 0553c4a to fe1e760 Compare July 30, 2026 17:05
eb8680 and others added 2 commits July 30, 2026 14:58
Replaces a cartesian-product stream with one stream per plate assignment
the body actually subscripts. Where the body folds over the plates
uniformly, ReduceDistributeCartesianProduct inverts the reduction instead,
which is cheaper and leaves the plate fold intact. This rule is the
fallback for bodies that admit no per-plate factorization: a chain
`X[t], X[t+1]` couples adjacent plate indices, so inversion does not apply.
Grounding costs one variable per assignment instead of enumerating the
|D|^|P| rows, after which the result is an ordinary variable-elimination
problem that `Factor` solves.

`ReducePartial` gains an `unrolled` filter so grounding can expand only the
plate folds it is grounding over.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@jfeser
jfeser force-pushed the eb-ground-cartesian-product branch from 7acbe8c to 7be9b05 Compare July 30, 2026 18:58
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.

2 participants