Skip to content

Add a re-vectorization pass for expressions built by loops - #178

Draft
dance858 wants to merge 1 commit into
mainfrom
vectorization-pass
Draft

dance858 wants to merge 1 commit into
mainfrom
vectorization-pass

Conversation

@dance858

@dance858 dance858 commented Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

What it does

A loop in the user's code leaves many small isomorphic expressions: the terms of a chain of adds, the args of an hstack, or a list of constraints. new_problem takes a new argument, vectorize; when it is set, it runs a pass that replaces k of them by one expression computing their concatenation ("zip"). It uses one law: an elementwise atom commutes with concatenation,

zip_j f(a_j, b_j) = f(zip_j a_j, zip_j b_j)

which pushes the concatenation down to the leaves. There, entries of one array become a single gather (or the array itself), constants become one constant, and k copies of a scalar become a broadcast. A chain of adds becomes sum(zip(terms)):

cos(x[0]) + ... + cos(x[n-1])  ->  sum(cos(x))

Full sums (nested loops) and multiplications by constants have laws of their own. Anything else is concatenated with an hstack.

Where the code is

  • include/vectorize.h: the API and the design in one comment.
  • src/vectorize/laws.c: the laws, i.e. how k nodes of one kind become one. This is the file to extend for a new kind of atom.
  • src/vectorize/zip.c: vec_zip, the part that is the same for every kind of node (reuse a zip built before, try the laws, fall back to an hstack).
  • src/vectorize/pass.c: the pass over the graph, i.e. which nodes to merge (numbering, add chains, grouping, roots).
  • src/vectorize/vectorize_internal.h: the pass state and the two functions the halves share.

What an atom provides

An elementwise atom sets new_same_atom in its constructor (build a new node of the same atom over other children), and same_attrs if it has attributes; only power does. Atoms built on new_elementwise inherit new_same_atom. Other atoms need nothing; the pass recognises index, sum, hstack, broadcast, parameter and the constant multiplications through expr_is_* predicates.

The option

new_problem(objective, constraints, n_constraints, verbose, vectorize): with vectorize false the problem keeps the roots exactly as given, as before this PR. This changes the signature, so the Python bindings need the extra argument when they move to this version. The engine's existing tests pass true.

Ownership

vectorize_exprs / vectorize_expr: the caller must hold a reference to each root it passes in, and keeps it. Each root returned carries a new reference that belongs to the caller. new_problem follows this; its callers keep the ownership they had.

Behaviour worth knowing

  • Groups of fewer than 8 isomorphic expressions are left alone (VECTORIZE_MIN_GROUP), so hand-vectorized problems are not rewritten.
  • A subexpression shared inside a loop body stays shared, and one that does not depend on the loop index is computed once and repeated.
  • The pass follows the DAG, not its expansion into a tree, and its recursion depth is capped.
  • The order of summation inside a chain changes, so values agree to rounding only.
  • The pass time is reported in prob->stats.time_vectorize; it is 0 when vectorize is false.

Benchmarks

macOS arm64, release build, medians; differences under 10% are within noise on the machine used.

Problems already written in vectorized form (7 problems, 45 sizes, up to 675,000 variables): the pass leaves them unchanged and takes 1-12 µs, at most 1.2% of setup time.

The same problems written with Python loops. "Eval" is the time of one gradient + Jacobian + Hessian: of the loop-written problem without the pass, of the same problem with the pass, and of the hand-vectorized version.

problem nodes built nodes after pass pass time eval, no pass eval, with pass eval, hand-written speedup from the pass
control-of-car, N = 10,000 739,998 113 56 ms 630 ms 1.17 ms 1.13 ms 540×
battery-calibration, K = 20,000 919,993 61 72 ms 761 ms 1.36 ms 1.11 ms 560×
optimal-pricing, n = 20,000 260,009 19 23 ms 1,192 ms 0.58 ms 0.53 ms 2,000×

The pass pays for itself within the first evaluation. The hand-written versions have 106, 54 and 16 nodes. Without the pass, optimal-pricing at n = 40,000 did not finish (the process was killed); with it, an evaluation takes 1.15 ms.

On 12 loop-written C cases (sums, dot products, least squares, Rosenbrock, nested loops, constraint lists) at n = 100,000 the output has the node count of the hand-written expression, or within 3 nodes of it, and evaluates at 0.93-1.06× its time; the pass takes 20-140 ms for 300,000-1,400,000 input nodes. The harness for these cases is not part of this PR.

Tests

30 tests in tests/vectorize/test_vectorize.h, one per pattern plus one for the option, each comparing values, Jacobian and Hessian against the unvectorized expression or against finite differences. Locally, a fuzzer over random loop-built DAGs found no value mismatch in 30,000 cases and no leak in 400.

Known limits

  • The loop-written battery problem is still 1.22× slower than hand-written, mostly in the Jacobian; the cause is not found.
  • Atoms with restricted domains (log, entr, tan, atanh) have no new_same_atom: k of them in a group are concatenated with an hstack, not merged into one.
  • The engine's own recursion (forward, Jacobian, Hessian, free of right-deep trees) is still as deep as the expression, with or without the pass.

🤖 Generated with Claude Code

@dance858
dance858 force-pushed the vectorization-pass branch 12 times, most recently from 4ffdf16 to 4a69ab7 Compare December 2, 2026 23:01
A loop in the user's code leaves many small isomorphic expressions: the
terms of a chain of adds, the args of an hstack, or a list of
constraints. new_problem takes a new argument, vectorize; when it is
set, it runs a pass that replaces k of them by one expression computing
their concatenation, using that an elementwise atom commutes with
concatenation. For example

    cos(x[0]) + ... + cos(x[n-1])  ->  sum(cos(x))

An elementwise atom takes part by setting 'new_same_atom' in its constructor (and
'same_attrs' if it has attributes); other atoms need nothing. Groups of
fewer than 8 expressions are left alone, so hand-vectorized problems are
not rewritten.

Callers of vectorize_exprs / vectorize_expr must hold a reference to
each root they pass in; each root returned carries a reference for the
caller.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
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.

1 participant