diff --git a/knowledge-base/045-mphf-space-under-query-and-build-limits.md b/knowledge-base/045-mphf-space-under-query-and-build-limits.md new file mode 100644 index 0000000..39a720a --- /dev/null +++ b/knowledge-base/045-mphf-space-under-query-and-build-limits.md @@ -0,0 +1,147 @@ +# Shrinking a bucket-placement minimal perfect hash function under strict query and construction limits + +## Problem + +Reduce the space (bits per key, geometric mean over 7 key sets: random 64-bit +integers 10^6..10^9 and random strings 10^6..10^8) of PHastR, a PHast-style +minimal perfect hash function (8-bit seed per bucket, expected bucket size 4.25, +four layouts, slices of 1024 slots, bumped buckets go to smaller levels whose +outputs are remapped to the free slots of the first level through an +Elias-Fano sequence). Hard constraints: no construction slowdown (+0.5% geomean +with 1 thread), no query slowdown (loop/batch/pass/latency, 1.5-3% geomean), +no space growth on any instance. Baseline: 1.946 bits/key. + +## What Worked + +- **Measure the space breakdown first.** 97% of the space was the first-level + seeds (8 bits / 4.25 keys = 1.882 bits/key); remap and following levels + together were only 0.06 bits/key. This bounds every non-seed idea at a few + tenths of a percent and tells you where to look. +- **Look for edge effects with a histogram of free slots.** Outputs of bumped + keys are exactly the free slots of the first level, so their histogram is + free to compute. Slots within one slice length of the ends of the output + range were free 9x more often than in the bulk (low demand: fewer slices + reach them). On small following levels (a few thousand keys with 1024-slot + slices) this is a third of all slots: capping the slice length of following + levels at an eighth of their output range saved 0.1% on 10^6 keys at zero + query cost (kept). +- **Map the Pareto front with a cheap space tool before committing.** One + binary that builds the function with given parameters and prints bits/key, + bump share and build time made it possible to scan seed width (6-9 bits), + slice length, layouts, bucket size, cost-function origin, window size and + priority weights in minutes. Result: the defaults sat on the constrained + front; 9-bit seeds would save 3.7% but cost 45% construction. +- **Fix edge effects where the query path is cold.** At the first level a + wrap-around costs fast-path instructions, but on the following levels (only + reached by ~0.5% of keys) the slice start can be drawn from a range longer by + one slice length L, shifted down by L/2 and clamped to [0, m - L]: on average + the end slots are then reachable from as many slices as the bulk. Level-2 + bumped keys dropped 55-60%; -0.16% bits on 10^6 keys, -0.06% geomean, with + no measurable query or construction cost. Clamping (unlike wrapping) + keeps slice starts monotone in the hash, so a windowed sweep works unchanged. + It passed all benchmark rules but was reverted by the project owner: it + needed a stored flag (changing how serialized data is read) and changed the + outcome of a failure-mode test. Check early whether the project accepts + format changes and test edits; a library's tests can pin its types and + failure behaviour as hard as any benchmark limit. +- **Screen the query cost of a format change separately from the change.** + Adding only the decode (or a never-taken wrap) to the query path and running + the benchmark on a subset answers "can this ever pass?" in two minutes. + +## What Didn't Work + +- **Larger bucket size** (4.3, 4.35, 4.4): seeds shrink, but each extra bumped + key costs ~80-100 ns in the query (branch misprediction + second hash + + second-level seed + Elias-Fano select), so batch/pass limits fail. +- **PDEP-free select** in the Elias-Fano remap: PDEP is microcoded on AMD Zen 1/2 + (~250 cycles) and was 62% of the slow path; a broadword select saved ~20 ns + per bumped key, not enough. It also moved the binary layout (see below). +- **Packed 9-bit seeds** (generic bit-field vector, 7 seeds per aligned u64, + 9 bytes per 8 seeds): loop queries +40..100% in cache. The first-level query + is a pure latency chain hash -> seed load -> position; any instruction between + seed load and position (even one compare-and-subtract for wrap-around slices: + +19% loop) is paid in full. Only byte seeds pass. +- **Fewer bumps at a larger bucket size** via construction effort: retuned + priority weights (-0.8% bumps), a 512-bucket window (0%; the window saturates + at one slice span of buckets, ~240; smaller windows are much worse), power-law + costs instead of log-distance (worse), one-step eviction of a smaller + obstructing bucket (-6.5% bumps for +25% construction). Re-placing bumped + buckets after the sweep can never succeed (occupancy only grows). +- **Last-level tuning** (range slack, bucket size, threshold): +-0.0001 bits/key. +- **Removing "overhead" instructions from the hot query.** In cache, query time + grows ~4-5% per added instruction (IPC ~2, latency-chain bound), but the + reverse does not hold blindly: replacing a store-to-load field extraction by + an equivalent variable shift made in-cache batch queries 7% slower. The + store/load kept the seed-dependent part off the critical chain and let + independent queries overlap; read source comments about memory-level + parallelism before "simplifying". +- **Squeezing the remap.** An Elias-Fano sequence of the free slots uses ~9.5 + bits per entry against ~9.0 bits of entropy for an arbitrary hole set; + subtracting the index from each value never changes the low-bit width when + u/n ~ 190, and the select inventory is 1.5% of the remap. Narrower seeds on + the following levels also lose: every bumped key costs ~11.5 bits, so with + 16-64 seeds the extra bumps outweigh the seed bits saved. +- **Steering seeds toward low-demand edge slots** (cost bonus): only moves which + edge slots stay empty; the holes are demand-limited. +- **Priority for large buckets**: bumped keys are spread over bucket sizes + (sizes 5-8 give 64%, >= 11 only 9%); stronger large-bucket priority raised + bumped keys by 4-10%. Single-key buckets are bumped only at the window tail, + by design (cheapest bump). +- **Remapping the seed alphabet.** The chosen first-level seeds had empirical + entropy 8.00 bits (uniform: the offset is a random hash field plus a seed + multiple, so the best seed does not depend on its value), the output range + had no slack, and seed -> (layout, rotation) is a bijection onto the full + candidate set: no reordering can change feasibility. +- **Dropping remap entries of empty following-level slots.** Gross -0.02 to + -0.09%, but marking the 1-4% empty slots for a rank costs as many bits as + the entries removed: net zero or negative. +- **Accounting checks.** The measured size counted lengths of boxed slices (no + capacity slack); fixed overhead was 0.0017 bits/key at 10^6 and the rest of + the small-instance excess was algorithmic (holes, second-level bumps). +- **CPU-specific slow-path speedups.** A broadword select beats PDEP only on + CPUs with microcoded PDEP (Zen 1/2); on Intel and Zen 3+ it is ~8-10 cycles + slower per call. Spending that "budget" on space would be tuning for one + machine. + +## Pitfall: code layout + +A change that added a 2 KB lookup table to .rodata shifted all of .text by +0x870 bytes; an unchanged, byte-identical string batch-query loop then ran +16% slower (12.8 vs 14.9 ns), reproducibly across 5 binaries, keyed only on its +address. When a per-instance regression is far too large for the change, compare +function addresses (`nm -S`) between binaries before blaming the algorithm; do +not "fix" it with alignment hacks aimed at the benchmark loop. + +## Experiment Data + +| exp | change | bits/key (geomean) | verdict | +|---|---|---|---| +| 001 | baseline | 1.94639 | - | +| 002 | bucket size 4.3 | -0.62% | discard (batch +3.1%) | +| 003 | broadword select + bucket size 4.35 | -1.13% | discard (batch/pass, layout) | +| 004 | one-step eviction | -0.2% | discard (build +25%) | +| 005 | slices <= m/8 on small following levels | -0.03% (-0.1% on 10^6) | keep | +| 006 | wrap-around slices (query screen) | (-0.47% on 10^6 possible) | discard (loop +19%) | +| 007 | last-level parameters | +-0.005% | discard | +| 008 | 9-bit packed seeds | -2..-3.8% | discard (loop +40..100%) | +| 009 | drop duplicate remap entries | <= -0.07% | not pursued | +| 010 | fewer bumps at bucket size 4.4 | needs -40% bumps, best -0.8% | discard | +| 011 | codegen analysis of fast path | - | ~4-5% per instruction | +| 012 | leaner get (shift instead of store/load) | 0 (budget) | discard (batch +7%) | +| 013 | remap hole - index | -0.002% | discard (analysis) | +| 014 | 4-6 bit seeds on following levels | worse | discard (analysis) | +| 015 | edge-slot cost bonus | ~0 | discard | +| 016 | sparser select inventory / other remap | <= -0.02% | discard | +| 017 | local select for remap lookup | - | discard (CPU-specific) | +| 018 | bump histogram, large-bucket priority | +4..10% bumps | discard | +| 019 | clamped slice starts on following levels | -0.06% (-0.16% on 10^6) | kept, then reverted (format flag, test edit) | +| 020 | last level: clamping, tighter range | <= -0.01% | discard | +| 021 | level-2 bucket size; seed alphabet | 0 (entropy 8.00 bits) | discard | +| 022 | drop entries of empty following slots | net ~0 | discard | +| 024 | size accounting; wider level-2 seeds | -0.01% / worse | discard | + +Final: -0.03% bits/key geomean (only exp 005), all time metrics within noise. + +## Environment + +Rust, AMD EPYC 7702 (Zen 2), 1-64 threads, keys 10^6-10^9. diff --git a/knowledge-base/INDEX.md b/knowledge-base/INDEX.md index 272abe2..165d860 100644 --- a/knowledge-base/INDEX.md +++ b/knowledge-base/INDEX.md @@ -45,3 +45,4 @@ Optimization techniques, experiment results, and lessons learned from AAE sessio | 039 | Choosing the solve direction in pseudoflow max flow | Maximum flow / min cut, pseudoflow & push-relabel | Reverse s-t from a cheap excess-vs-deficit estimate; cheap flow recovery; instrument before importing textbook relabel tricks | [039-pseudoflow-solve-direction.md](039-pseudoflow-solve-direction.md) | | 040 | Speeding up a distributed (MPI) multilevel graph partitioner with bit-identical output | Distributed graph partitioning (ParHIP), MPI label propagation | Per-phase timers with one change per phase per run and a per-component keep rule with phase noise bands, buffered output, lazy side-effect-free conditions in LP, open addressing only where order is unobserved, stamp arrays instead of reset scans, LP prefetch, devirtualizing both implementations, a type-local node pool for the order-defining hash map, reproducing the libstdc++ unordered_map iteration order with arrays (guarded and tested), dense arrays for the local part of a sparse key range | [040-parhip-bit-identical-speedup.md](040-parhip-bit-identical-speedup.md) | | 044 | Replacing hand-written secp256k1 BigInteger arithmetic with a curve library (Java Schnorr signing) | Java, BIP-340 Schnorr signatures, JSON event serialization | Library curve with Jacobian coordinates and a precomputed comb for G (~100x sign), `sumOfTwoMultiplies` in verify (-42%), streaming `JsonGenerator` instead of a tree, single-pass hash-set filter predicate; CPU-time and min-of-rounds measurement on a loaded machine | [044-java-secp256k1-library-arithmetic.md](044-java-secp256k1-library-arithmetic.md) | +| 045 | Shrinking a bucket-placement MPHF under strict query and construction limits | Minimal perfect hashing (PHast/PHastR), space | Space breakdown first, free-slot histogram for edge effects, cheap Pareto-mapping tool, separate query-cost screens of formats, code-layout pitfall | [045-mphf-space-under-query-and-build-limits.md](045-mphf-space-under-query-and-build-limits.md) |