diff --git a/knowledge-base/045-libsais-parallel-induced-sorting.md b/knowledge-base/045-libsais-parallel-induced-sorting.md new file mode 100644 index 0000000..a842b4a --- /dev/null +++ b/knowledge-base/045-libsais-parallel-induced-sorting.md @@ -0,0 +1,113 @@ +# Speeding up parallel induced-sorting suffix array construction (libsais) with identical output + +## Problem + +Make libsais (SA-IS with induced sorting, the fastest open-source 32-bit suffix array builder) faster on +100 MB texts (english, dna, source code, a repetitive DNA collection) in two modes: serial (`libsais`, +one core) and 8 threads (`libsais_omp`, one thread per physical core of a 16-core Xeon Silver 4216, +6-channel DDR4). Metric: geometric mean of the time ratios of both modes against the unmodified code. +Hard gates: the suffix array is identical (it is unique, so any correct algorithm qualifies), peak RSS at +most +1%, no input assumptions. 53 experiments after the baseline, 23 kept (several as multi-component changes). + +## What Worked + +**Score 0.802 measured directly (8 threads 0.687 of the original, serial 0.936).** The library is heavily +tuned for memory-level parallelism; almost all gains came from removing serial steps that 8 threads +wait on, not from making any loop faster. + +1. **Find the serial steps with wall-clock phase timers, not a CPU profiler.** `perf` was unavailable; + a SIGPROF sampler showed 36% of 8-thread CPU time spinning in libgomp, but only per-call wall timers + (serial vs 8 threads side by side) showed *which* phases do not scale. Instrument statements inside + conditionals and ternaries too: a phase costing 7% of one text's run (non-unique LMS-name resolution) + stayed invisible for 25 experiments because the timer script skipped them. +2. **Split a serial "master" bucket step by symbol ownership (+5.4% score, the largest single gain).** + Block-parallel induced sorting gathers a block in parallel, then one thread walks every entry to + update bucket pointers, then places in parallel. Bucket pointers stay inside their bucket, so they + are monotone in the symbol: the buckets that can still induce *into the current block* form one + symbol interval found by binary search. A short serial resolve handles only those (and the entries + they create); all other entries are induced in parallel, each thread owning a contiguous symbol + range (split by target positions). Then let the owners write `SA[target]` directly instead of + writing back into the shared block cache, where ~8 owners per cache line caused line ping-pong + (+1.8%). +3. **Pipeline when the serial step cannot be split.** In the dense partial-sorting scans (every slot + is an entry, in-block inductions frequent) the owner scheme lost; overlapping the workers' gather of + block b+1 with the master's sort of block b won 4% at 8 threads. Only the next-block slots that the + current block's place writes are stale; patch them during the place with the gather's own formula. +4. **Dynamic scheduling of the first phase (2.6% at 8 threads, 3x the phase gain).** With the + `schedutil` governor idle cores start at 800 MHz: the master finished its static segment of the + first pass in 14 ms, the workers in 50 ms. Chunks taken dynamically (summed back per segment so all + downstream per-thread state is unchanged) also sped up later phases. +5. **Hunt every serial loop between parallel phases.** Each was small, together they were ~8%: + memsets of SA ranges (~535 MB per run), memmoves of per-thread lists by the master, O(k) prefix sums + at recursion levels with a 3M-symbol alphabet, 2-thread counting with 50 MB private bucket copies + (replaced by writing per-position bucket codes into free space and letting each thread count its + own code range), static splits of irregular work (non-unique name groups). +6. **Transparent huge pages in serial runs (2.7%).** With THP in `madvise` mode the caller's buffers + are on 4 KB pages. `madvise(MADV_COLLAPSE)` on the 2 MB-aligned interior of the text (copy, 0.03 s) + and of the output array after `MADV_DONTNEED` of all but one page per 2 MB (zero fill instead of + copy, 0.08 s instead of 0.12 s) pays for itself several times. A fully emptied range cannot be + collapsed, and after `MADV_DONTNEED` faults stay on 4 KB pages because the page tables remain. +7. **Bundle consistent sub-threshold gains.** With a 0.5% keep threshold many real 1% 8-thread gains + failed alone; as separate commits measured together (multi-component) and attributed by phase + timers they were kept. + +8. **Replace a random scatter by partitioning (serial -1.7%, 8 threads -2.5%).** A scatter of one value per + entry over 200 MB costs a full miss each (8-10 ns serial). Write (slot, value) pairs into cache-sized + regions with streaming stores (software write combining), then scatter each region inside the cache + and emit it directly: 4 GB of line traffic become about 0.9 GB. Order outputs so that unread pairs are + not overwritten, and sample the input first: regular texts already stream and lose from it. +9. **Look for dependency chains where the profile says "memory".** A right-to-left loop over the bits of + a mask (bsr, xor, sub, shl by cl, xor: 8-9 cycles per entry) looked like a memory limit for 47 + experiments. Reversing the word once and clearing the lowest bit gave 2% at 8 threads. Compiling one + suspect function for other instructions (BMI2) is a cheap probe; always add a placebo clone. + +## What Didn't Work + +- Owner-parallel versions of steps whose serial loop is already ~2-3 ns per entry (dense partial + scans, LMS radix sort): every owner must read every cache line of the block, which costs more. +- Precomputing the symbols the serial step needs (removing dependent random reads from it): out-of-order + execution already hides them. +- Huge pages for the 8-thread mode: collapse is serialized on the mm lock (8 threads slower than 1) + and a background collapse in idle worker slots made the run 4-6% slower (TLB shootdowns on all cores). +- Keeping idle workers spinning instead of sleeping, prefetch-distance changes, `prefetcht1`, + branch-free scans, 4k instead of 6k bucket layout, larger or smaller blocks, store prefetching. +- The 8-bit induction scans at 8 threads run at the machine's random-read ceiling (685M reads/s on + 4 KB pages, measured with a microbenchmark); nothing short of fewer accesses helps there. + +- Extra or fewer prefetches: one text prefetch per entry instead of two (+6%, the rare line crossings are + full misses), prefetch of write targets (0 to +2%, the fill buffers are the limit), non-temporal hints (+14%). +- Text-only huge pages at 8 threads, work stealing of block parts, branch-free classification, huge page for + a 512 KB buffer. + +## Experiment Data + +| | serial | 8 threads | +|---|---|---| +| english | 4.45 -> 4.15 s | 1.80 -> 1.20 s | +| dna | 3.56 -> 3.36 s | 1.31 -> 0.91 s | + +Score measured directly against the original: 0.834 after 34 experiments, 0.802 after 54 (counting the +baseline as the first). The products of the kept step scores (0.831 and 0.789) overstate the gain: step runs +of 8-thread changes also showed small serial gains, probably from code placement. Report the direct run. +The last kept change (lower parallel limits, 0.993) bundles two parts that failed alone and is borderline. + +## Adversarial Texts + +Added parallel code must bound its barriers and scans by the machine, not by the input: a parallel move +of a periodic text's bucket by one slot needed millions of barriers (20-90x slower), per-chunk scans to +the end of a run repeated on all-equal text, and huge pages slowed Thue-Morse texts by 1.36x. Keep +periodic, all-equal, Fibonacci and Thue-Morse texts in the routine checks. + +## Measurement Pitfall + +A harness that builds `--control-rev` by `git archive | tar -x` stamps the sources with the commit +time; if the control build directory holds objects compiled later, `make` keeps them and the control +silently stays the previous revision. One result counted an earlier gain twice. Delete the control +build directory before every run, and when a change speeds up a code path it does not touch, compare +the control and candidate binaries byte by byte. + +## Environment + +C99, GCC 14 with OpenMP (libgomp), `-O3`, SSE2 only; Xeon Silver 4216 (16 cores, 22 MB L3), 92 GB +DDR4, Linux 6.8, THP in madvise mode, `schedutil` governor. Gains 2-6 assume many parallel phases +separated by short serial steps; gain 6 is Linux-specific. diff --git a/knowledge-base/INDEX.md b/knowledge-base/INDEX.md index 272abe2..2ac3b62 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 | Speeding up parallel induced-sorting suffix array construction (libsais) | Suffix array construction, OpenMP | Symbol-owner split of serial bucket steps, pipelined gather of the next block, dynamic scheduling of the first phase, removing serial steps between parallel phases, huge pages for serial runs, partitioned scatter, shorter mask dependency chains, adversarial-text checks | [045-libsais-parallel-induced-sorting.md](045-libsais-parallel-induced-sorting.md) |