Skip to content

GPU mining 4.1x faster on Apple Silicon: native-u64 Poseidon2, midstate precompute, lazy second squeeze - #81

Merged
n13 merged 5 commits into
mainfrom
gpu-poseidon2-optimization
Aug 12, 2026
Merged

n13 merged 5 commits into
mainfrom
gpu-poseidon2-optimization

Conversation

@n13

@n13 n13 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

An optimize-measure-verify loop on the GPU engine (Apple M4, Metal via wgpu). Three stacked optimizations take the M4 from 2.81 MH/s to 11.4 MH/s at the default 1M batch (4.1x), with every step gated on bit-exact parity against the CPU reference.

Step MH/s (M4) Gain vs prev Cumulative
Baseline (main) 2.81 — —
1. Native-u64 shader (mining_u64.wgsl) 4.21 +50% +50%
2. Midstate precompute (5 → 3 permutations/hash) 7.42 +76% +164%
3. Lazy second squeeze (3 → 2 permutations for rejects) 11.68* +56% +316%

* at 2M batch; 11.43 MH/s at the default 1M batch, 11.8 MH/s at 8M.

Criterion cross-check: large_range_1m/gpu 355.8 ms → 86.3 ms (−75.7%, p=0.00).

The optimizations

  1. Native-u64 Goldilocks arithmetic. When the adapter reports SHADER_INT64 (all Apple Silicon, NVIDIA, modern AMD), the engine now loads mining_u64.wgsl: field elements are single u64s with plonky2-style lazy reduction (values live in [0, 2^64), canonicalized only at squeeze). The old 32-bit-limb mining.wgsl (which emulated 32×32→64 multiplies out of 16-bit pieces) remains the fallback for GPUs without int64.
  2. Midstate precompute. The PoW hash absorbs header ‖ nonce_be in three rate-8 chunks; chunk 1 (header) and chunk 2 (high 32 bytes of the nonce) are constant for an entire batch. pow_core::mining_midstate runs those two permutations once on the CPU per batch and the kernels resume the sponge from the uploaded state. Batches are clamped so nonce increments never carry into the high 256 bits (boundary crossing is covered by a parity test).
  3. Lazy second squeeze. The first squeeze produces the most significant 256 bits of the 512-bit hash, which settle hash < target on their own unless they exactly equal the target's high half. The common reject path now skips the final permutation; only candidates/ties pay for the second squeeze. Applied to both shader variants.

Correctness

  • The component test binary (cargo run -p engine-gpu) now runs all 17 suites against both shader variants (34 suites green). mining_u64.wgsl carries a thin compat layer (GoldilocksField, gf_add, gf_mul, poseidon2_permute, …) so the existing test kernels exercise the u64 core directly.
  • New gpu_cpu_parity example: 25 random jobs with random 512-bit range starts (plus a deterministic 2^256-boundary-crossing job); every GPU-found nonce is re-hashed on the CPU and must match byte-exactly. 25/25 pass.
  • New pow-core unit test proves midstate resumption reproduces get_nonce_hash exactly.
  • Fixed the stale end-to-end harness (6-binding layout from an older shader revision).
  • ./clippy.sh (CI lint) clean; workspace tests pass.

Benchmark accuracy

  • Fixed a real bench crash: thread-local GPU worker resources were reused across different GpuEngine instances (each with its own device), panicking inside wgpu. Resources are now tagged with an engine id and recreated on mismatch, so all criterion GPU benches run reliably.
  • Hash counts remain exact for exhausted ranges (every nonce is hashed); benches use impossible difficulty, so reported rates are true hashes/second.
  • miner-cli benchmark now honors --gpu-batch-size/--cpu-batch-size: the harness previously fed each worker a fixed 1M-nonce range, silently capping GPU dispatches at 1M nonces regardless of the flag, and re-searched that same range on every iteration. Worker ranges now advance through the nonce space and are sized from the flags — floored at the old 10k/1M widths so tiny batches keep engine-internal cancellation batching instead of measuring per-call harness overhead. Zero batch sizes are rejected at parse time (serve and benchmark) and the effective batch sizes are echoed in the benchmark banner.

Portability (M5 and other chips)

Nothing here is tuned per-chip: SHADER_INT64 is detected at runtime (all M-series support it), and midstate/lazy-squeeze are algorithmic wins for every vendor. The only per-chip knobs are the existing gpu_tiers workgroup hints — M5-family entries added (mirroring M4) so they don't fall to the fallback tier. Measured batch-size sensitivity is mild (~5% from 250k→8M), so the 1M default stays.

SIMD-on-GPU (vectorware) assessment

Evaluated the technique from https://www.vectorware.com/blog/simd-on-gpu/ (map a 32-lane warp to a portable-SIMD vector with cross-lane shuffles/reductions). It does not fit this workload: their toolchain is Rust→CUDA (not WGSL/Metal), and cooperative hashing would waste lanes here — Poseidon2 width is 12 (vs 32-lane simdgroups), and the 22 internal rounds apply the S-box to a single element, which would leave 1/32 lanes active during the dominant cost. Mining is embarrassingly parallel, so per-thread independent hashing already saturates the ALUs (confirmed: workgroup size and occupancy changes move nothing). The insight the technique points at — use the hardware's native integer width — is exactly what the u64 shader delivers.

Not pursued

  • Host-side double-buffering: measured dispatch overhead is ~2 ms per batch (~1% at sane batch sizes) — not worth the complexity.
  • Upstream CPU Poseidon2 (qp-poseidon-core) optimization — out of scope here; the GPU-side Poseidon2 lives in this repo as suggested and is verified against the canonical implementation.

Relation to #80

#80 independently lands the same three core ideas in weaker form: 32-bit lazy field arithmetic (vs native u64 here), a header-only precomputed sponge state skipping 1 permutation (vs header + high-nonce midstate skipping 2 here), and the same conditional second squeeze. Its M5 Pro reaches 11.0 MH/s where this branch reaches 11.4 MH/s on a base M4 — roughly 1.5–2x more work per ALU.

All remaining #80 ideas were evaluated on top of this branch; two micro-optimizations measured positive and were adopted (second commit): hoisting midstate/target/start-nonce reads out of the nonce loop, and producing byte-swapped hash words on demand so the reject path never builds the swapped hash (+1.3% at 16M batches, noise at the 1M default). Constants-without-re-reduction is inherent to the u64 core (constants are plain u64 literals). Forcing nonces_per_thread=2 was tested and regressed. #80's cargo-test golden-vector suite is a complementary testing idea not duplicated here; note both PRs touch the same files and will conflict.

n13 and others added 2 commits August 11, 2026 23:40
…tate, lazy squeeze)

Three stacked optimizations, each verified bit-exact against the CPU
reference (qp-poseidon-core) by the dual-shader component suite and a
new GPU/CPU parity example:

- mining_u64.wgsl: native 64-bit Goldilocks arithmetic with plonky2-style
  lazy reduction, used automatically when the adapter supports
  SHADER_INT64 (all Apple Silicon, NVIDIA, modern AMD). mining.wgsl
  remains the 32-bit fallback. (+50%)
- Midstate precompute: the first two of five sponge permutations absorb
  the header and high nonce half, both constant per batch; they are now
  computed once on the CPU (pow_core::mining_midstate) and resumed on
  the GPU. Batches are clamped so nonces never carry past 2^256. (+77%)
- Lazy second squeeze: the first squeeze yields the most significant 256
  bits of the hash, which decide hash-vs-target unless exactly equal to
  the target's high half, so the common reject path skips the final
  permutation. (+56%)

Apple M4 throughput: 2.81 -> 11.4 MH/s at the default 1M batch
(criterion large_range_1m/gpu: 355.8ms -> 86.3ms, -75.7%).

Also:
- Fix criterion GPU bench crash: thread-local worker resources are now
  tagged with an engine id so multiple GpuEngines per process never mix
  devices.
- Fix stale end-to-end test harness (6-binding layout) and run the full
  component suite against both shader variants.
- New examples: hashrate, gpu_cpu_parity (25 jobs incl. 2^256-boundary
  crossing), gpu_features.
- Add Apple M5 family GPU tiers.

Co-Authored-By: Claude Fable 5 <[email protected]>
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

Does the u64 fast path cover common NVIDIA cards?

Yes — effectively every card miners actually use takes the mining_u64.wgsl path:

  • NVIDIA: Vulkan's shaderInt64 (what wgpu's SHADER_INT64 maps to on the backend this engine ranks first) has been exposed by NVIDIA drivers for over a decade — GTX 900 series and every 10/16/20/30/40/50-series card report it.
  • AMD: GCN and RDNA (RX 400 onward) expose it on both Windows and Mesa/RADV.
  • Intel Arc: yes; older Intel iGPUs mostly yes, though slowly.
  • Genuinely missing: mobile-class GPUs (Qualcomm Adreno, older Mali) — exactly what the 32-bit mining.wgsl fallback remains for.

One nuance: no consumer GPU (NVIDIA or Apple) has 64-bit integer ALUs. "Supports u64" means the driver's compiler lowers 64-bit ops into 32-bit instruction pairs itself, using add-with-carry and native 32×32→64 widening multiplies. That is precisely what WGSL at 32 bits cannot express (no carry flag, no widening multiply), which is why the old shader was stuck building 64-bit math out of 16-bit pieces. The u64 shader's win is letting the driver do that lowering optimally — NVIDIA's compiler is very good at it, so the relative u64 gain there should be at least the +50% measured on the M4.

Worth noting where the gains actually come from: u64 is the second-biggest win. Measured on the M4: native u64 = 1.50×; midstate precompute + lazy second squeeze together = 2.77× (5 Poseidon2 permutations per hash down to 2). Those two are pure algorithm and were applied to both shader variants, so a typical NVIDIA card gets the full ~4× stack, and even an int64-less Adreno gets ~2.7× of it.

…-9%)

Exploring a fully native Metal port of the mining kernel showed it runs
~16% faster than the wgpu path at equal batch size. Decomposing that gap:
~9% is naga's injected runtime bounds checks and forced loop bounding,
~1.5% is mulhi()-based multiplication (inexpressible in WGSL), <1% is
the constant address space; the rest is binding/codegen residue.

The dominant term is recoverable inside wgpu on every backend:
the engine now builds its pipelines with create_shader_module_trusted +
ShaderRuntimeChecks::unchecked(). This is sound for our shaders: sources
are compiled into the binary, every buffer access is a constant-bounded
loop index into fixed-size bindings the engine allocates itself, all
loops have static bounds, and both variants remain covered by the
dual-shader component suite and the CPU parity example.

Apple M4: 11.39 -> 12.34 MH/s at the default 1M batch (+8.3%), 11.74 ->
12.73 MH/s at 8M (+8.4%). Cumulative vs main: 4.4x.

New examples/trusted_hashrate.rs measures checked vs trusted on the same
shader and CPU-verifies results.

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

n13 commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Native CUDA / Metal exploration — measured results

Prototyped the full mining kernel in hand-written native Metal (metal-rs, ulong + mulhi, constant address space) and benchmarked it against the wgpu engine on the same M4 at the same 8M batch, with results CPU-verified against pow-core:

Path MH/s @8m vs wgpu engine
wgpu, default runtime checks 11.66 —
wgpu, create_shader_module_trusted (checks off) 12.72 +9.1%
Native Metal, same math as WGSL 13.35 +14.5%
Native Metal, mulhi() multiply 13.55 +16.2%

Decomposition of the "native" gap: ~9% is naga's injected runtime bounds checks + forced loop bounding, ~1.5% is mulhi (inexpressible in WGSL), <1% is the constant address space, and the remainder is binding/codegen residue.

The dominant term doesn't require going native: wgpu can skip those checks for shaders we compile into our own binary. The latest commit does exactly that (create_shader_module_trusted + ShaderRuntimeChecks::unchecked()), which applies on every backend — including NVIDIA over Vulkan — and lifts the M4 to 12.34 MH/s at the default 1M batch (4.4× baseline cumulative). Soundness: static shader sources, constant-bounded loop indices into fixed-size engine-allocated bindings, all loops statically bounded, still gated by the dual-shader suite + parity example.

Remaining native headroom after this: ~6-7% for a Metal engine (mostly mulhi + dispatch overhead) at the cost of a second backend (~500 LOC + metal-rs dep) — probably not worth it. CUDA for NVIDIA: the repo previously shipped an engine-gpu-cuda (removed in #28; it implemented the old Montgomery-modexp PoW, so only its nvcc/PTX build scaffolding and cuda-builder.cf image are reusable). Expected gain over the now-trusted wgpu/Vulkan path is the same class as Metal's residue — order 5-15% from __umul64hi/PTX carry intrinsics, CUDA-stream pipelining, and per-arch launch tuning — but it needs NVIDIA hardware to validate and carries a real maintenance/distribution cost (nvcc or NVRTC at runtime). Suggest treating it as a follow-up validated on a real rig rather than folding it into this PR.

illuzen and others added 2 commits August 12, 2026 11:16
…ranges

The benchmark fed each worker a fixed range (10k CPU / 1M GPU nonces),
capping GPU dispatches at 1M regardless of --gpu-batch-size, and
re-searched the same range on every iteration. Worker ranges now step
through the nonce space and are sized from the batch flags, floored at
the old widths so tiny flags keep engine-internal cancellation batching
instead of turning per-call harness overhead into the measured quantity.
Batch-size flags are validated non-zero at parse time (serve and
benchmark) and echoed in the benchmark banner.

@illuzen illuzen 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 don't think we need so many examples but its fine. huge performance boost!

@n13
n13 merged commit 9b16df1 into main Aug 12, 2026
4 checks passed
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