Repository navigation
GPU mining 4.1x faster on Apple Silicon: native-u64 Poseidon2, midstate precompute, lazy second squeeze - #81
Conversation
…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]>
Does the u64 fast path cover common NVIDIA cards?Yes — effectively every card miners actually use takes the
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]>
Native CUDA / Metal exploration — measured resultsPrototyped the full mining kernel in hand-written native Metal (metal-rs,
Decomposition of the "native" gap: ~9% is naga's injected runtime bounds checks + forced loop bounding, ~1.5% is 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 ( Remaining native headroom after this: ~6-7% for a Metal engine (mostly |
…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
left a comment
There was a problem hiding this comment.
i don't think we need so many examples but its fine. huge performance boost!
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.
main)mining_u64.wgsl)* at 2M batch; 11.43 MH/s at the default 1M batch, 11.8 MH/s at 8M.
Criterion cross-check:
large_range_1m/gpu355.8 ms → 86.3 ms (−75.7%, p=0.00).The optimizations
SHADER_INT64(all Apple Silicon, NVIDIA, modern AMD), the engine now loadsmining_u64.wgsl: field elements are singleu64s with plonky2-style lazy reduction (values live in[0, 2^64), canonicalized only at squeeze). The old 32-bit-limbmining.wgsl(which emulated 32×32→64 multiplies out of 16-bit pieces) remains the fallback for GPUs without int64.header ‖ nonce_bein 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_midstateruns 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).hash < targeton 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
cargo run -p engine-gpu) now runs all 17 suites against both shader variants (34 suites green).mining_u64.wgslcarries a thin compat layer (GoldilocksField,gf_add,gf_mul,poseidon2_permute, …) so the existing test kernels exercise the u64 core directly.gpu_cpu_parityexample: 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.get_nonce_hashexactly../clippy.sh(CI lint) clean; workspace tests pass.Benchmark accuracy
GpuEngineinstances (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.miner-cli benchmarknow 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_INT64is 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 existinggpu_tiersworkgroup 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
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.