99 Commits

Author SHA1 Message Date
20749c622b metrics: stale work is the batch in flight at cancellation, not the whole search
All checks were successful
ci / fmt (pull_request) Successful in 21s
bench / build (pull_request) Successful in 1m1s
ci / clippy (pull_request) Successful in 1m55s
ci / doc (pull_request) Successful in 1m55s
bench / measure (pull_request) Successful in 2m56s
ci / test (pull_request) Successful in 6m35s
miner_stale_hashes_total was recorded in the QUIC loop for every result whose
job id no longer matched, which is every cancelled search: 74% of all hashes
on benjy flagged as stale on the first hour of data. That is the loop's
notion of a stale *result*, not wasted work; the hashes were done while the
job was current.

The wasted work is the batch that completes after the job was superseded.
Record that in the engine at the cancellation check, per device and kernel,
and drop the loop-level accounting. Expect one batch per job switch.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CBgs2nSi4H2mdh8kD8vMX5
2026-09-03 14:23:37 +03:00
3ba996dcdf metrics: attribute hashrate to build, device, kernel and job outcomes
All checks were successful
ci / fmt (pull_request) Successful in 20s
bench / build (pull_request) Successful in 1m2s
ci / clippy (pull_request) Successful in 1m37s
ci / doc (pull_request) Successful in 1m58s
bench / measure (pull_request) Successful in 2m55s
ci / test (pull_request) Successful in 6m50s
quantus/miner#9. Additive metrics in a lair-owned module of the metrics
crate; origin's metrics are untouched so the fleet dashboard keeps working
across origin merges.

Identity:
- miner_build_info{version, commit}: the join key for everything below.
- miner_config_info{engine, gpu_batch_size, gpu_devices, cpu_workers,
  gpu_throttle_ms}: two deploys of one commit with different flags are
  different experiments.

Per device (handles resolved once at engine init, no label lookups in the
batch path):
- miner_device_hashes_total{device, kernel}, miner_device_solutions_total,
  miner_device_lost_total.
- miner_gpu_batch_seconds{device, kernel, phase=gpu|host}: submit-to-mapped
  on the device versus everything else in the batch. This is the bubble
  #4, #5 and #6 attack, measured directly.

Jobs and results:
- miner_jobs_received_total, miner_stale_hashes_total{engine},
  miner_job_pickup_seconds{engine} (issued to picked up; the cancel latency
  of a busy worker), miner_results_submitted_total,
  miner_results_send_failed_total, miner_seal_latency_seconds (found to
  sent), miner_job_idle_seconds_total (sent to next job, node-attributable).

Connection: miner_connects_total, miner_connect_failures_total,
miner_disconnects_total, miner_connected, miner_disconnected_seconds_total.

Origin-owned code touched, each block marked lair: engine-gpu gains a
metrics dependency, a DeviceMetrics handle on GpuContext and timing points
in run_single_batch; miner-service gains found_at on WorkerResult,
created_at on MiningJob and the recording calls; miner-cli sets build info
at startup. Deploy validate now asserts miner_build_info carries the
deployed commit.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CBgs2nSi4H2mdh8kD8vMX5
2026-09-03 14:09:43 +03:00
Nikolaus Heger
09323d33e4 Different kernels for Apple Metal vs Nvidia and everything else (#92)
* Select Apple Metal 4.0.1 kernel; keep 4.0.0 u64 elsewhere

NVIDIA was ~37% slower on the 4.0.1 Metal-tuned kernel. Split
Poseidon2 kernels and pick by backend:

- Metal + SHADER_INT64: v4.0.1 u64
- other SHADER_INT64: v4.0.0 u64
- no SHADER_INT64: 32-bit fallback (same as 4.0.0)

CI uploads the Linux release binary as an artifact so we can
bench NVIDIA without building on the GPU box.

* Drop version numbers from GPU kernel labels

Log native-u64 vs native-u64 Apple Metal without tying
the strings to release tags.
2026-09-01 23:21:43 +08:00
Nikolaus Heger
ea5e5e742e Speed up the u64 mining kernel ~1.8x on Apple Metal (#87)
Apple M5 Pro, CLI benchmark: 24.0 -> 43.2 MH/s. Kernel output is
unchanged and bit-exact against the CPU reference.

Field arithmetic:
- Deferred-carry additions (Acc): the external layer and the internal
  row sum accumulate unreduced with a carry counter and fold once per
  output instead of two epsilon corrections per add.
- gf64_mul_add folds the row sum into the 128-bit product before a
  single plain reduction.
- mul_wide / gf64_sqr assemble the 128-bit product from 32-bit-valued
  partial sums with no carry compares.

Kernel structure (code size dominates on Apple's compiler; every
unrolled variant measured slower):
- One loop drives all 30 rounds so each layer is emitted once, with
  round constants added by the linear layer preceding each S-box
  (RC_EXT table, RC_INTERNAL padded with a trailing zero).
- One S-box site with a runtime lane count (12 external, 1 internal).
- mining_main runs pad / first squeeze / second squeeze through a
  single inlined permute64 call in a phase loop.

Measured and rejected: uniform buffers and unhoisted loads, workgroup
sizes 64/128/512, 8-add MDS, one-compare reduce, fully unrolled
layers, two nonces per thread.
2026-08-31 22:50:27 +08:00
Nikolaus Heger
2b966e780a Revert "Fuzz GPU/CPU parity at scale and CPU-verify every seal before submission"
This reverts commit b0cfc3005e.
2026-08-12 15:41:38 +08:00
Nikolaus Heger
b0cfc3005e Fuzz GPU/CPU parity at scale and CPU-verify every seal before submission
Investigating reported seal submission failures. Root cause analysis:
the miner's job-id staleness chain (worker check, quic-loop filter,
node-side job_id compare) cannot mislabel a candidate — internal and
node job ids are updated atomically together. The remaining benign race
is node-side: a block-template rebuild (new pre_hash, same parent) does
not bump the node's job counter, so an in-flight seal mined on the old
template passes the job-id check and fails seal verification, logging
"Failed to submit seal". Fixing that belongs in the chain repo (bump the
job counter on template rebuild).

Miner-side hardening in this commit:

- gpu_cpu_parity is now a two-phase fuzzer. Phase 1 dumps FULL 512-bit
  hashes for randomized (header, nonce) pairs via the real
  midstate-resume datapath and verifies each against the canonical CPU
  implementation, multi-threaded (defaults to 1M hashes, ~5s; 10M runs
  in ~15s). Phase 2 fuzzes whole mining jobs with five profiles: random,
  carry-edge starts (saturated low limbs), 2^256-boundary crossings,
  impossible difficulty with exact hash-count assertion, and CPU-known
  solutions to catch false negatives. Seeded and reproducible; also
  asserts the submitted work bytes match the nonce.
  Verified clean: 10M bulk hashes + ~1,500 seals across 6 seeds.

- miner-service re-verifies every candidate on the CPU (one hash) before
  sending JobResult; an engine-produced invalid seal is never submitted
  and is logged loudly instead.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 14:24:05 +08:00
illuzen
22d87d4772 fix benches 2026-08-12 11:16:26 +08:00
Nikolaus Heger
8aa81ec853 Disable naga runtime shader checks for the trusted mining shaders (+8-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 <noreply@anthropic.com>
2026-08-12 00:55:15 +08:00
Nikolaus Heger
58615ed3fa Adopt PR #80 micro-optimizations that measure positive on the u64 kernel
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 <noreply@anthropic.com>
2026-08-12 00:01:39 +08:00
Nikolaus Heger
d55b970ab6 Optimize GPU Poseidon2 mining 4.1x on Apple Silicon (u64 shader, midstate, 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 <noreply@anthropic.com>
2026-08-11 23:40:12 +08:00
illuzen
a47db3d1a2 Fix windows again (#72)
* handle lost device correctly

* Update lib.rs

* allow-integrated flag otherwise exclude

* DeviceLost is a status

* Integrated GPU skipped when discrete init fails

* nits
2026-06-30 16:30:11 +08:00
Nikolaus Heger
d99be29a64 Select GPU adapters by backend to fix multi-backend OOM (#67)
On Windows wgpu enumerates each physical GPU once per backend (Vulkan +
DX12) plus a CPU-emulated fallback ("Microsoft Basic Render Driver").
Building a mining context for every entry causes VRAM contention and
OOMs the process during benchmark/serve startup (#61).

Instead of deduplicating by (vendor, device) PCI IDs - which would
collapse rigs with multiple identical cards into a single context - drop
CPU-emulated adapters and keep all adapters from the highest-ranked
backend present (Vulkan/Metal, then DX12). Within a single backend each
physical GPU appears exactly once, so identical cards are preserved by
construction and no physical-ID matching is needed.

Selected adapters are ordered discrete-first so `--gpu-devices 1` picks
the discrete card on hybrid laptops. Skipped adapters are logged at info
level; if nothing usable remains, init fails with an explicit error.

Selection logic is a pure index-based function unit-tested against the
exact enumeration reported in #61, identical multi-GPU rigs, DX12-only
machines, and software-only environments.

Co-authored-by: illuzen <illuzen@users.noreply.github.com>
2026-06-30 13:13:45 +08:00
illuzen
7296c003bb Improve Windows gpu support (#70)
* support AMD GPUs on windows

* add support for more GPUs

* remove shader dump from logs

* handle gpu initialization failure better

* fmt

* re-order matching to avoid mobile / desktop false positives

* harden gpu matching

* add tests to engine-gpu module

* handle dead device and failed mapping correctly

* handle timeout properly with tokio

* nits

* fix benchmarks

* fmt
2026-06-30 12:55:35 +08:00
illuzen
157aa6fb5c Address v12 issues (#65)
* don't accept zero difficulty jobs

* bound job queue

* synchronous emit_payload

* cleaner gpu_batch_size type

* remove build script

* distance_threshold -> difficulty

* enable pq-cert checking with miner

* clearer logs

* Revert "enable pq-cert checking with miner"

This reverts commit 7a7f5394352b60d8c946f547f77a057504b29c44.

* update versions of relevant deps, including rand
2026-06-12 10:48:01 +08:00
illuzen
5ce62b3e12 add gpu-throttle arg (#64)
* add gpu-throttle arg

* smarter sleep logic

* document cli args
2026-05-22 23:31:54 +08:00
illuzen
d7bf27854f GPU fixes (#58)
* improve logging

* don't let the queue spill, just drain it

* move cancellation out of the shader, since it doesn't work

* simplify batch size mechanism, improve logs

* fmt

* address review items
2026-04-22 13:42:01 +08:00
illuzen
417a3efd86 Single hash, new poseidon (#50)
* single hash, new poseidon

* fix build

* new poseidon api

* fmt

* fix race condition with stale jobs being reported

* fmt

* fix deps

* format toml

remove stale comments

---------

Co-authored-by: Nikolaus Heger <nheger@gmail.com>
2026-04-02 14:06:54 +08:00
illuzen
443f0f9f89 QUIC miner (#49)
* implement quic

* simpler names

* simplify worker logic

* simplify gpu configuration logic

* miner initiates and picks random start nonce

* remove mining service

* clean up logs and remove unused engines

* clean up metrics

* metrics fix

* shared worker pool, cpu driven cancellation

just 10x the gpu thru-put, no more batch-size on gpu

* fmt

* non-local git

* taplo derp

* fix the benches

* handle stale results correctly in gpu

* more accurate gpu hashrate

* fmt

* remove unused

* handle duplicate solutions, cli controls gpu cancel frequency

* put plonky2 back

* demote noisy log
2026-02-02 16:38:21 +08:00
Nikolaus Heger
ad46f200c0 fmt 2026-01-05 17:47:47 +08:00
Nikolaus Heger
d14ebdf65c fix tests 2026-01-05 17:47:38 +08:00
Nikolaus Heger
af5564796b dynamic batch size for GPU 2026-01-05 17:15:10 +08:00
Nikolaus Heger
ffc5b8f83c GPU batch size automatically adjusts to target duration 2026-01-05 15:53:14 +08:00
Nikolaus Heger
3b5f759fbd refactored and unified gpu devices number logic
use all GPUs by default, handle the parameter, disallow more GPU devices than available
2025-12-27 11:40:03 +08:00
Nikolaus Heger
a548f74f7d fmt 2025-12-26 12:47:42 +08:00
Nikolaus Heger
97ec1350de Fix for #39
Fix GPU worker crash, enable GPU default, and improve benchmark output
2025-12-26 12:46:57 +08:00
Nikolaus Heger
ac87758996 Fix GPU contention, benchmarking 2025-12-26 10:53:00 +08:00
Nikolaus Heger
6ae4658209 add benchmark command
so we can easily compare CPU and GPU without having to run cargo bench.
2025-12-19 15:22:24 +08:00
Nikolaus Heger
f7209be81b fixed some logs 2025-12-19 14:42:02 +08:00
illuzen
b4999ab448 unused 2025-12-13 17:45:05 +08:00
illuzen
1eaea91909 clippy 2025-12-13 17:42:43 +08:00
illuzen
52318aeaad support multiple gpus 2025-12-13 17:38:24 +08:00
illuzen
22fecf183e clippy 2025-12-13 17:07:24 +08:00
illuzen
0978d3bebd fmt 2025-12-13 16:21:28 +08:00
illuzen
8e073c110a almost par with cpu now 2025-12-11 15:55:50 +08:00
illuzen
c13b0027f3 optimized mds 2025-12-11 14:55:14 +08:00
illuzen
3cb91c4798 simplify 2025-12-11 14:42:13 +08:00
illuzen
43e857dfba simplify 2025-12-11 04:01:31 +08:00
illuzen
83e0c9edce a bit faster 2025-12-11 00:39:23 +08:00
illuzen
1509e2283b clean up documentation 2025-12-09 23:07:57 +08:00
illuzen
d423b5c1b1 faster 2025-12-09 22:40:41 +08:00
illuzen
6c7835f348 faster 2025-12-09 22:36:56 +08:00
illuzen
46202989df faster 2025-12-09 22:31:10 +08:00
illuzen
09b63783e0 more benching 2025-12-09 20:49:48 +08:00
illuzen
e8e0d6acf4 dynamic thread allocation and work coarsening 2025-12-09 20:31:17 +08:00
illuzen
14022a367f a bit faster 2025-12-09 17:59:42 +08:00
illuzen
587303b480 slight simplification 2025-12-09 17:33:20 +08:00
illuzen
9c88ac7aff a bit simpler 2025-12-09 17:14:25 +08:00
illuzen
ffe58596d4 further simplification 2025-12-09 16:58:52 +08:00
illuzen
0ab3049703 simplified gpu code 2025-12-09 15:53:19 +08:00
illuzen
30c3b3f1a7 fix benches 2025-12-08 15:46:15 +08:00