Skip to content

perf(halo2_proofs): compile polynomial ASTs into a register program (−21–41% Orchard proof time) - #1

Open
PastaPastaPasta wants to merge 1 commit into
dashifiedfrom
perf/compiled-evaluator
Open

PastaPastaPasta wants to merge 1 commit into
dashifiedfrom
perf/compiled-evaluator

Conversation

@PastaPastaPasta

@PastaPastaPasta PastaPastaPasta commented Oct 5, 2026 •

Copy link
Copy Markdown
Member

Why

Dash Platform shielded transactions are Orchard bundles proved with this crate (via dashpay/orchard). On a phone the proof dominates send latency, so it's worth making faster.

Profiling a 2-action Orchard proof on an M4 Pro put the quotient-polynomial evaluation (poly::Evaluator::evaluate, called from plonk/vanishing/prover.rs for h(X)) at ~27–31% of proving time (≈143 ms of ≈530 ms; ≈425 ms of ≈1.37 s for 6 actions). The evaluator walks an Ast recursively for every chunk of rows, and does three kinds of wasted work:

  • every leaf occurrence copies a rotated chunk into a fresh Vec;
  • every node allocates a temporary vector;
  • shared subtrees and repeated column/rotation queries are recomputed each time they appear.

For Orchard, the h(X) expression has ~3,000 distinct nodes after de-duplication but is visited far more times than that.

This is the first PR to the new dashpay/halo2 fork. The dashified base branch is the exact crates.io source that Platform ships today: halo2_proofs 0.3.2, halo2_gadgets 0.5.0 and halo2_poseidon 0.1.0. Every src/ file is byte-identical to the published crates.

What

Evaluator::evaluate now compiles the Ast once per call and then executes the compiled program (halo2_proofs/src/poly/evaluator/compiled.rs):

  1. Hash-consed DAG. Structurally identical nodes become one node, including repeated column/rotation queries and commutative a+b / b+a. A pointer memo means Arc-shared subtrees are lowered once.

  2. Exact simplifications that depend only on expression shape and public constants (gate constants and transcript challenges):

    • scale by 0 / 1 / −1;
    • adding zero and constant folding;
    • a product with a constant polynomial becomes a scale;
    • the leading zero step of a DistributePowers Horner chain is dropped;
    • x + (−y) becomes x − y.

    Field arithmetic is exact, so these rewrites cannot change any output.

  3. Register program. One instruction per remaining node, with scratch registers reused after a value's last read. Constants live in a side table, so instructions are ~36 bytes and Orchard's ~2,600-instruction program stays cache-resident.

  4. Row-blocked execution. Each instruction runs on 4 independent rows, giving instruction-level parallelism and amortizing dispatch. Leaves are read in place at row + rotation_offset instead of being copied. Chunks run in parallel as before.

Orchard's h(X) program for a 2-action proof: 3,001 DAG nodes → 2,592 instructions (1,050 mul, 429 Horner, 459 add, 420 sub, 234 scale), using 105 registers (≈13 KiB of scratch per worker).

The recursive evaluator, and the chunk helpers only it uses, are kept #[cfg(test)] as a reference. While writing the tests I fixed Coeff::linear_term, which indexed past the end of a chunk of length one; that code is now test-only.

No public API change. The verifier is untouched.

Correctness evidence

  • Byte-identical proofs. With a seeded (test-only) RNG, Orchard proofs for 1/2/6 outputs (2/2/6 actions), 2–3 seeds each, have identical SHA-256 to proofs from unmodified crates.io halo2_proofs 0.3.2. Every timed proof below was also verified.
  • New unit tests (poly::evaluator::tests):
    • compiled_matches_reference_{coeff,lagrange,extended}: 40 random expressions per domain over six (j, k) domains, including shared Arc subtrees, repeated queries, rotations up to ±3, empty and nested Horner chains, and special scalars 0/1/−1. Each is compared against a direct per-row evaluation built from the old term definitions, and against the old recursive evaluator in the Lagrange bases, for every chunk size from 1 to the polynomial length (partial 4-row blocks, wrap-around).
    • compiler_deduplicates_and_simplifies: instruction counts for dedup and each simplification.
    • coeff_linear_term_short_chunks: regression test for the length-one-chunk bug.
  • cargo test --release -p halo2_proofs (37 + 1 + 8), the same with --no-default-features --features batch (no multicore), and cargo test --release -p halo2_gadgets (38) all pass on the pinned 1.60 toolchain. cargo clippy --all-targets -- -D warnings and cargo fmt --check are clean.
  • Two independent review passes (a correctness review including mutation testing of the new code, and a simplification pass) found no correctness issues; their suggestions are applied.

Benchmarks

Orchard proof creation, dashified-0.14.1 circuit with the 36-byte Dash memo. One of these Orchard proofs is what a wallet builds on Send.

Setup:

  • Host: Mac Studio, Apple M4 Max (12P + 4E).
  • Release build with fat LTO, codegen-units = 1, panic = "abort", matching Platform's release-ios profile.
  • Baseline = exactly what Platform's Cargo.lock pins today: crates.io halo2_proofs 0.3.2 + pasta_curves 0.5.1, orchard dashified-0.14.1. The patched build uses the same pasta.
  • Interleaved ABBA: 4 rounds × 3 proofs = 12 proofs per cell. Every proof is verified.
  • Seeded proofs from both binaries are byte-identical.
  • The host was shared with other workloads, so the max column includes some outliers; medians are robust. CPU time is process user+sys during the proof.
Actions Threads Before median (range) After median (range) Δ wall CPU before → after
2 2 1512 ms (1468–3869) 965 ms (950–995) −36.2% 2.78 → 1.69 s
2 6 659 ms (650–3521) 488 ms (484–1634) −26.0% 2.78 → 1.76 s
2 16 568 ms (502–2936) 424 ms (410–445) −25.4% 3.53 → 2.51 s
6 2 3985 ms (3924–9620) 2347 ms (2326–7947) −41.1% 7.30 → 4.09 s
6 6 1779 ms (1712–3374) 1248 ms (1185–7945) −29.9% 7.51 → 4.34 s
6 16 1461 ms (1286–9333) 1152 ms (984–3791) −21.1% 9.89 → 5.99 s

An earlier run against crates.io halo2_proofs 0.3.5 / pasta 0.5.2 (the newest semver-compatible releases) gave the same picture: −20% to −42%.

The gain is largest at low thread counts, which is the phone case: an iPhone has 6 cores, 2 of them performance cores.

Evaluator stage alone (2 actions, M4 Pro, 14 threads, loaded host): ~143–215 ms → ~52–63 ms. Instruction encoding was chosen by measurement: compact 4-lane beat the first version (inline constants) and an 8-lane variant.

Harness

A small standalone crate builds an Orchard bundle with N outputs (padded to ≥2 actions), proves it with Bundle::create_proof, and verifies it.

  • --mode prove: OS RNG, timed.
  • --mode seeded: ChaCha20 seeded RNG; prints the SHA-256 of each proof.

Baseline is orchard at tag dashified-0.14.1 with crates.io halo2_proofs 0.3.2 / pasta_curves 0.5.1, pinned in the lockfile. The patched build is the same orchard with [patch.crates-io] pointing halo2_proofs / halo2_gadgets / halo2_poseidon at this branch. The harness will be added to dashpay/orchard together with the PR that switches it to this fork.

Follow-ups (separate PRs)

  • Parallel per-circuit witness synthesis (each Orchard action is synthesized serially today).
  • MSM and IPA opening speedups.
  • dashpay/orchard: depend on this fork, and embed canonical params and fixed-base tables to speed up the cold key build.

🤖 Generated with Claude Code

The prover evaluates the quotient polynomial h(X) (and the compressed lookup
expressions) by recursively walking an Ast for every chunk of rows. Every leaf
occurrence copies a rotated chunk into a fresh Vec, every node allocates, and
shared subtrees and repeated column/rotation queries are recomputed each time
they appear. For the Orchard Action circuit this was ~27-31% of proving time.

Evaluator::evaluate now lowers the Ast once into a hash-consed DAG, applies
exact identities that depend only on the expression shape and public constants
(scale by 0/1/-1, adding zero, constant folding, multiplying by a constant
polynomial as a scale, the leading zero step of a Horner chain, x + -y as
x - y), allocates scratch registers with reuse after a value's last read, and
executes the program four independent rows per instruction, reading leaves in
place. Instructions refer to constants by index so the instruction stream
stays small enough to remain in L1 across row blocks. Field arithmetic is
exact, so the output is identical; Orchard proofs created with the same RNG
are byte-for-byte unchanged.

The recursive evaluator and the chunk helpers only it uses are kept as a
test-only reference. New tests compare the compiled evaluator with it and with
a direct per-row evaluation on random expressions (shared subtrees, rotations,
Horner chains, special scalars) in all three bases, for every chunk size on
small domains. The reference's Coeff::linear_term indexed past the end of a
chunk of length one; that is fixed so it can serve as a reference.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: ff3d7c27-0a95-4c07-ae75-ce6c7848a4c8
📥 Commits

Reviewing files that changed from the base of the PR and between a842ff9 and 0ee5601.

📒 Files selected for processing (5)
  • halo2_proofs/CHANGELOG.md
  • halo2_proofs/src/poly.rs
  • halo2_proofs/src/poly/domain.rs
  • halo2_proofs/src/poly/evaluator.rs
  • halo2_proofs/src/poly/evaluator/compiled.rs

Included review availability: This review used your included allowance. Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The polynomial evaluator now compiles expression ASTs into a deduplicated register program and evaluates it in four-row lanes. Basis-specific rotation and X behavior inform compilation and execution. Tests compare results across bases, domains, and chunk sizes. The changelog states that proofs are unchanged.

Changes

Compiled polynomial evaluation

Layer / File(s) Summary
Expression model and basis behavior
halo2_proofs/src/poly/evaluator/compiled.rs, halo2_proofs/src/poly/evaluator.rs, halo2_proofs/src/poly/domain.rs
The compiler interns expression nodes and applies constant folding and algebraic simplifications. Basis operations define rotation scaling and the degree-1 polynomial’s values for coefficient, Lagrange, and extended Lagrange bases.
Register program compilation and evaluator routing
halo2_proofs/src/poly/evaluator/compiled.rs, halo2_proofs/src/poly/evaluator.rs
The compiler lowers AST nodes into instructions and reuses registers based on operand last uses. Evaluator::evaluate now compiles the AST and evaluates the resulting program.
Chunk execution and validation
halo2_proofs/src/poly/evaluator/compiled.rs, halo2_proofs/src/poly/evaluator.rs, halo2_proofs/src/poly.rs, halo2_proofs/src/poly/domain.rs, halo2_proofs/CHANGELOG.md
Program evaluation processes four rows per instruction and writes valid rows to the output. Tests compare compiled results across bases, domains, and chunk sizes, and check compiler simplifications and short coefficient chunks. The changelog records the evaluator change.

Priority: ⬆️ High

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Eval as Evaluator::evaluate
  participant Program
  participant Polynomials
  participant BasisOps
  participant Output
  Eval->>Program: compile AST into instructions
  Eval->>Program: evaluate polynomials on the domain
  Program->>Polynomials: load polynomial values for each row
  Program->>BasisOps: obtain basis-specific X values
  Program->>Output: write valid lane results
Loading

Merge Risk: ⚪ Minimal · up to 0ee56

The change rewrites polynomial evaluation as a compiled register program. Proof output is reported unchanged and covered by comparison tests. No concrete merge-blocking issue was found.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0ee56

No new privilege boundary or verification bypass was identified. Residual risk concerns correctness of the replacement proof-generation logic; downstream proof compatibility was not demonstrated by executing tests in this review.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A semantic discrepancy would primarily affect proof-generation workloads using this evaluator, including quotient-polynomial construction and lookup compression. It could produce rejected proofs or reduce proving availability, but does not by itself bypass the independent verifier. Deployed service, tenant and environment exposure is not established by the inspected source.

Trust Boundaries and Controls

  • observed — Proof verification retains its separate verifier-query and multi-opening verification path; the PR does not route verifier authority through the compiled evaluator. Polynomial inputs remain registered within the evaluator context rather than arriving as externally supplied register instructions.

Resilience and Maintainability Implications

  • inferred — Mutable execution state is confined to a newly allocated result and task-local registers. Parallel tasks receive disjoint output slices and read immutable inputs; repeated evaluation allocates fresh state. Partial execution does not mutate a persistent store or shared configuration. Backend panic propagation remains unverified, but no evaluator-owned recovery state was identified that could strand a weakened security configuration.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 61.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 62 functions across 4 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: compiling polynomial ASTs into a register program. The performance claim adds relevant context.
Full details: Docstring Coverage

Explanation

Docstring coverage is 61.29% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 62 functions across 4 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@PastaPastaPasta

Copy link
Copy Markdown
Member Author

CI status: GitHub Actions has not run on this PR.

dashpay/halo2 is a fork of zcash/halo2, and GitHub has registered none of its workflows (GET /actions/workflows returns 0 workflows and there are 0 runs, even though the Actions permission says enabled: true). On forks, GitHub keeps workflows off until a repo admin enables them in the Actions tab ("I understand my workflows, go ahead and enable them"). This affects the base branch dashified too, so this PR did not cause it. I did not change any CI config.

Once workflows are enabled, some inherited upstream jobs will not apply to this fork. bench.yml, book.yml and the push half of ci.yml/zizmor.yml trigger on main, which does not exist here. Codecov upload needs a secret.

CI checks run locally instead (head 0ee5601b, toolchain 1.60.0 from rust-toolchain.toml, CI feature flags --no-default-features --features "batch dev-graph gadget-traces test-dependencies"):

Check Result
cargo fmt --all -- --check pass
cargo clippy <flags> nightly --all-targets -- -D warnings pass
cargo test --release --workspace <flags> pass
cargo test --release --workspace <flags> nightly pass
cargo test --release -p halo2_proofs (default features) pass
cargo doc --all --all-features --document-private-items pass (1 warning in halo2_poseidon, which this PR does not touch)
cargo build --target wasm32-unknown-unknown (nightly flags) pass

Across the test runs: 231 tests passed, 0 failed. CodeRabbit had no actionable comments.


🤖 Posted autonomously by Claude on behalf of pasta.

@PastaPastaPasta PastaPastaPasta changed the title perf(halo2_proofs): compile polynomial ASTs into a register program (−20–42% Orchard proof time) perf(halo2_proofs): compile polynomial ASTs into a register program (−21–41% Orchard proof time) Oct 5, 2026
PastaPastaPasta added a commit to dashpay/orchard that referenced this pull request Nov 7, 2026
Switch halo2_proofs, halo2_gadgets and halo2_poseidon from crates.io to
https://github.com/dashpay/halo2, which starts from the exact crates.io
halo2_proofs 0.3.2 / halo2_gadgets 0.5.0 / halo2_poseidon 0.1.0 sources and adds
prover performance work: a compiled polynomial evaluator (dashpay/halo2#1),
Booth MSM and GLV IPA generator collapse (dashpay/halo2#2), and concurrent
per-circuit proving (dashpay/halo2#3). Together they cut Orchard proving time by
50-61% with byte-identical proofs. The pin points at the integration commit
that merges all three; it should move to the dashified merge commit once those
PRs land. pasta_curves resolves to 0.5.2 (needed by the GLV collapse).

Orchard is the only halo2 user in Platform's dependency graph, so this swaps
one copy for another rather than duplicating it.

Add examples/prover_bench.rs, the harness used to measure that work: cold key
build, warm proof timing for N-action bundles with the Dash memo (every proof is
verified), and a seeded mode that prints proof digests to check two prover builds
for byte-identical output.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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