Skip to content

Speed up GPU mining ~2x via Poseidon2 kernel optimizations - #80

Closed
n13 wants to merge 1 commit into
mainfrom
gpu-hash-optimizations
Closed

n13 wants to merge 1 commit into
mainfrom
gpu-hash-optimizations

Conversation

@n13

@n13 n13 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Overview

~2x GPU mining speedup, measured on Apple M5 Pro (Metal) with criterion. All speedup comes from doing less work per hash in the WGSL kernel: 5 Poseidon2 permutations → 3, plus cheaper Goldilocks field arithmetic that now matches the CPU reference's lazy (non-canonical) reduction scheme bit-for-bit.

Benchmarks

Bench (criterion) Baseline This PR Change
gpu_throughput (10M nonces) 1784 ms 899 ms -49.6% time (5.60 → 11.12 MH/s)
large_range_1m/gpu 1127 ms 90.2 ms -92.0%
medium_range_100k/gpu 119 ms 10.2 ms -91.4%
small_range_10k/gpu 14.1 ms 1.31 ms -90.7%
gpu_find_solution 26.9 ms 3.68 ms -85.7%

Hashrate: 5.59 → 11.0 MH/s on Apple M5 Pro. Smaller ranges improve more because fixed overheads dominate them less after the kernel speedup.

What changed (crates/engine-gpu)

  • src/mining.wgsl
    • Field arithmetic rewritten to mirror qp-poseidon-core's lazy reduction exactly: branchless epsilon-fold add/sub, canonicalization only of the 4 squeezed output elements, no 0/1 special-case branches in gf_mul.
    • Second sponge squeeze is now conditional: the top 256 bits of the 512-bit hash come entirely from the first squeeze, so the 5th permutation runs only for winners and the ~2^-256 exact-tie case (tie path preserved; full hash still computed and written on a claim).
    • Kernel resumes from a precomputed header sponge state (new 96-byte header_state buffer), skipping the header-only first permutation.
    • Round constants loaded without re-reduction (all 130 verified < P), branchless reduce fold, target/header reads hoisted out of the nonce loop.
  • src/lib.rs — new precompute_header_state() (canonical qp-poseidon-core permutation, once per job), header buffer resized to 96 bytes.
  • src/end_to_end_tests.rs / src/main.rs — fixed the end-to-end GPU test: it created a stale 6th binding and panicked before ever comparing hashes. It now passes and CPU-verifies.
  • tests/gpu_golden.rs (new) — golden-vector GPU test suite runnable via cargo test (skips gracefully without a GPU): full-stack golden hashes from canonical qpow-math, seal accept/reject semantics against target, randomized CPU↔GPU cross-check, and direct shader-level golden tests of both the reference hash path and the new precomputed-state fast path.
  • examples/gpu_hashrate.rs (new) — bench/verify harness: loads WGSL at runtime, CPU-verifies seals, prints MH/s.
  • examples/gen_golden.rs (new) — regenerates the golden vectors if the hash construction ever changes.

Validation

  • cargo test --workspace --locked — all green, including the 5 new golden GPU tests.
  • GPU component suite (cargo run -p engine-gpu: gf_mul, sbox, MDS layers, rounds, permutation, hash vs CPU reference) — all pass, incl. end-to-end mining test.
  • cargo clippy --workspace --all-targets, cargo fmt --all -- --check, taplo fmt --check — clean.
  • Criterion GPU benches above (run individually; the bench harness panics when multiple GpuEngines are created in one process due to a pre-existing TLS resource-cache quirk, unrelated to this change).

Risks and mitigations

  • Hash correctness: byte-identical output enforced at three levels — component op tests vs CPU reference, golden vectors through the full engine stack, and a randomized CPU↔GPU cross-check. The lazy-reduction scheme is congruent mod P with canonicalization at the squeeze points, exactly as the CPU reference does internally.
  • Seal semantics: accept/reject against target covered by a dedicated test (valid seal found, invalid seal rejected); the exact-tie fallback computes the second squeeze, so no valid nonce can be missed.
  • Interface change is internal only: header_state buffer layout is engine-internal; MinerEngine API and CLI are unchanged.
  • Measured-and-rejected approaches (documented in commit message): 2-chain ILP (-18%) and vec2-packed field ops (-3%) were implemented, benched, and reverted.

Follow-ups

  • The multi-GpuEngine-per-process TLS panic in the bench harness exists on main; worth fixing separately (e.g. clearing worker resources between engines).
  • Upstream (qpow-math/qp-poseidon-core) was left untouched; the GPU kernel now carries its own optimized-but-identical Poseidon2, verified against the canonical implementation.

Hashrate on Apple M5 Pro (Metal): 5.59 -> 11.0 MH/s (criterion
gpu_throughput: 1784 ms -> 899 ms per 10M nonces, -49.6% time).

Shader work per hash is cut from 5 Poseidon2 permutations to 3, and the
remaining arithmetic is made cheaper:

- Goldilocks field arithmetic rewritten to match the CPU reference's
  lazy (non-canonical) reduction: branchless epsilon-fold add/sub, no
  canonical reduction after every add; canonicalize only the 4 squeezed
  elements at output. Removed never-taken 0/1 special cases in gf_mul.
- Skip the second sponge squeeze: the top 256 bits of the 512-bit hash
  come entirely from the first squeeze, so the target comparison is
  decided without the 5th permutation except for winners and the ~2^-256
  exact tie (tie path preserved, full hash still written on claim).
- Header-only first permutation precomputed once per job on the CPU
  (precompute_header_state, canonical qp-poseidon-core), passed via a
  96-byte header_state buffer; kernel resumes from that state.
- Round constants loaded without re-reduction (all verified < P),
  branchless reduce fold, hoisted target/header loads out of nonce loop.

Also fixes the stale end-to-end GPU test (extra 6th binding made it
panic before comparing hashes) and adds a cargo-test-runnable golden
vector suite (tests/gpu_golden.rs): full-stack golden hashes, seal
accept/reject semantics, randomized CPU-vs-GPU cross-check, and direct
shader-level golden tests of both hash paths. Vectors generated by
examples/gen_golden.rs from canonical qpow-math.

Measured-and-rejected experiments: two interleaved nonce chains per
thread (-18%, register pressure) and vec2-packed field ops (-3%, Metal
scalarizes vectors); both reverted.

Validation: cargo test --workspace, GPU component suite
(cargo run -p engine-gpu), golden GPU tests, clippy --all-targets,
cargo fmt, taplo fmt all clean.

Key paths:
- crates/engine-gpu/src/mining.wgsl (kernel + field arithmetic)
- crates/engine-gpu/src/lib.rs (precompute_header_state, header buffer)
- crates/engine-gpu/tests/gpu_golden.rs (golden vector suite)
- crates/engine-gpu/examples/gpu_hashrate.rs (bench/verify harness)
@n13
n13 marked this pull request as draft August 11, 2026 15:37
@n13

n13 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

its great however, there's another PR coming that looks promising

n13 added a commit that referenced this pull request Aug 11, 2026
Evaluated all ideas from #80 against the native-u64 kernel. Its three
main wins (lazy field arithmetic, precomputed sponge state, conditional
second squeeze) were already present in stronger form; two micro-opts
carried over and measured positive at large batches (+1.3% at 16M,
noise-level at the 1M default):

- Hoist midstate/target/start-nonce storage reads out of the nonce loop.
- Produce byte-swapped hash words on demand during the target compare,
  so the reject path skips building the swapped hash entirely.

Forcing nonces_per_thread=2 was also tested and regressed; one thread
per nonce stays.

Co-Authored-By: Claude Fable 5 <[email protected]>
@n13

n13 commented Aug 11, 2026

Copy link
Copy Markdown
Contributor Author

#81 does all that but better - closing

@n13 n13 closed this Aug 11, 2026
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