From df2b2b669389cb0095ffaaa42de6dc94c68a543b Mon Sep 17 00:00:00 2001 From: Anton Date: Sat, 28 Nov 2026 01:33:58 +0100 Subject: [PATCH] perf(agg): cov and scov by a wide key seed their pivots ahead of the scattered sums MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Defect Since #1850, `cov` and `scov` grouped by a wide random key were 18% slower at one worker when both sides are null-free F64 (#1889). On the 179,200-group date × U8 key, at 10,000,000 rows, they took 89.6 ms against 75.5 ms before #1850. The cost is in the v2 engine's per-row path, not in the arithmetic. On a wide key every row's state misses the cache. The per-row test "is this state new?" (seed its pivot from this pair) is a branch on that missed count. When it is mispredicted, once per group, it waits out the miss and drops the loads in flight behind it. Throwaway builds on that shape: | row path | ms | |---|---:| | the pivot subtraction only, no seed and no due test | 70.3 | | plus the seed branch | 82.5 | | plus the count bookkeeping and a due test that fires only at 64 | 86.4 | | the full design, a due test and a repivot at every power of two | 89.6 | ## Fix Null-free F64 × F64 pairs (`cov_update2_ff` in `src/ops/agg_stream.c`) now run in chunks of 256 rows, in two passes: - **The seed pass:** for each row, a state not yet touched takes the row's pair as its pivot. This is a bit select on the count, not a branch, so it takes the cache misses with little work per row. A group with several rows in a chunk is seeded by its last one there. That is still a pair of the group, which is all the pivot needs to be until its first move to the running mean at count 2, so the accuracy argument of #1850 is unchanged. - **The accumulation:** the same sums and due test as before, now on lines that are in the cache, where a mispredicted branch costs a few cycles instead of a memory latency. - **Which batches** (`cov_states_spill`): the chunked path is taken only when a batch's rows scatter over states that spill out of the cache. The decision is deterministic, from the batch's own group ids: - of its first 64 rows, at least three quarters must jump more than 4 KiB of states from the row before; - the largest id seen, times the state stride, must pass 1 MiB. A sorted, clustered or cyclic key walks neighbouring states that the cache and its prefetch serve, and there the extra pass only costs: the first review measured +43% on a clustered key and up to +20% on cyclic ones with a table-size gate alone. A key of few groups keeps its states in the cache. Both take the row-by-row path as before. Masked (`where:`) and nullable inputs keep it too. Every other pair keeps today's path. - **I64 × I64:** the same two-pass form measured slower (89–101 ms against today's 86). I spent a bounded pass on it; its instruction count is already below dev's, the cost is the same missed-load dependency, and none of the variants I tried beat the row-by-row path. - **F64 × I32:** within 3% of the commit before #1850 already. ## What changes against dev - **Answers:** within the tolerance of #1850, the same accuracy contract. A group whose first chunk holds several of its rows takes a different pair as its first pivot, so the last bits can differ from today's. The seeded search against the double-double reference has 0 failures: 400 cases from each of seeds 0x1847, 0x5eed and 0xc0ffee, 56,919,200 cells each, in the release-flags build; in the suite, 24 cases and 3,415,152 cells. - **Cost:** see below. ## Cost Wall time in ms, gcc release, 10,000,000 rows. Interleaved runs of each build, each the minimum of 25 calls; the tables compare the lowest minima. One worker is pinned to an idle performance core (`taskset -c 0`); all-core runs use all 28. The load average was about 4 to 8. The builds: - *before*: 1ce035735, the commit before #1850; - *today*: dev with #1850; - *this*: this commit. The `wsum` rows are controls: their code is unchanged. The wide key is #1889's 179,200-group date × U8 key, with `x = 1e8 + i%37` (F64) and `y = i%41` as F64 or I32; I64 × I64 is `1e16 + i%37` against `1e16 + i%41`. Three interleaved rounds: | query | 1 worker before | today | this | vs before | vs today | all cores before | today | this | vs before | vs today | |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| | wide F64xF64 cov | 76.24 | 89.98 | 84.22 | +10.5% | -6.4% | 19.64 | 19.43 | 19.70 | +0.3% | +1.4% | | wide F64xF64 scov | 76.18 | 89.63 | 84.01 | +10.3% | -6.3% | 19.44 | 19.17 | 19.72 | +1.4% | +2.9% | | wide F64xI32 cov | 75.78 | 77.29 | 77.31 | +2.0% | +0.0% | 17.34 | 17.44 | 17.18 | -0.9% | -1.5% | | wide F64xI32 scov | 75.68 | 77.35 | 77.33 | +2.2% | -0.0% | 17.55 | 17.40 | 17.56 | +0.1% | +1.0% | | wide I64xI64 cov | 76.32 | 85.46 | 84.85 | +11.2% | -0.7% | 19.43 | 19.44 | 19.52 | +0.4% | +0.4% | | wide I64xI64 scov | 76.60 | 85.49 | 84.88 | +10.8% | -0.7% | 19.31 | 19.13 | 19.66 | +1.8% | +2.8% | | wide F64xF64 wsum ctl | 76.10 | 76.31 | 76.39 | +0.4% | +0.1% | 19.61 | 19.73 | 19.74 | +0.7% | +0.0% | Other key shapes, at one worker, two interleaved rounds: - *clustered* `div i 56`; - *nearly sorted*, the same plus a small row offset; - *cyclic* `i % G`; - masks on the wide key; - *tiny*: `div i 2`, and `(i·7919) % 5,000,000`. | query | before | today | this | vs before | vs today | |---|---:|---:|---:|---:|---:| | random wide cov | 76.21 | 89.42 | 84.17 | +10.4% | -5.9% | | random wide wsum ctl | 76.20 | 76.35 | 76.62 | +0.5% | +0.4% | | clustered cov | 28.72 | 30.61 | 30.29 | +5.5% | -1.1% | | clustered wsum ctl | 28.74 | 28.70 | 28.67 | -0.3% | -0.1% | | nearly sorted cov | 26.64 | 29.56 | 27.93 | +4.9% | -5.5% | | cyclic 21845 cov | 23.83 | 20.12 | 20.10 | -15.6% | -0.1% | | cyclic 60000 cov | 25.05 | 25.01 | 25.01 | -0.2% | -0.0% | | cyclic 60000 wsum ctl | 24.97 | 25.08 | 25.09 | +0.5% | +0.0% | | cyclic 179200 cov | 26.76 | 28.70 | 28.73 | +7.4% | +0.1% | | mask 10pct wide cov | 28.36 | 29.67 | 30.05 | +5.9% | +1.3% | | mask 50pct wide cov | 58.52 | 63.54 | 62.36 | +6.6% | -1.9% | | mask 90pct wide cov | 86.68 | 96.67 | 95.22 | +9.9% | -1.5% | | mask 50pct wide wsum ctl | 58.64 | 58.55 | 58.25 | -0.7% | -0.5% | | tiny groups cov | 926.92 | 953.21 | 952.14 | +2.7% | -0.1% | | tiny random groups cov | 959.40 | 993.00 | 995.41 | +3.8% | +0.2% | | tiny random groups wsum ctl | 966.73 | 971.41 | 973.99 | +0.8% | +0.3% | | by3 cov | 22.15 | 18.32 | 18.78 | -15.2% | +2.5% | | cyclic 179200 where y>20 cov | 51.82 | 52.49 | 52.48 | +1.3% | -0.0% | | cyclic 179200 where y>20 wsum ctl | 51.68 | 51.27 | 51.45 | -0.5% | +0.3% | | cyclic 179200 first x null cov | 29.71 | 35.47 | 36.55 | +23.0% | +3.0% | | random wide where y>20 cov | 59.12 | 64.59 | 63.21 | +6.9% | -2.1% | Against dev today: - **Wide random F64 × F64:** 6% faster at one worker: +10% to +11% against the commit before #1850, down from +18%. - **Every other shape:** within ±2% at one worker, except two: - **The nullable shape** (cyclic 179,200, first x null) reads **+3%**. It never takes the new path; a build with the path compiled in but never called shows the same +3–4%. So it is the code layout of the added function, and moving the definitions, an out-of-line row loop and forbidding the clone did not remove it. - **`by3 cov`** read **+2.5%** in this table; an earlier pair read it level. - **All cores:** within 3% of both builds. Two `scov` rows read +2.8–2.9% in three rounds; earlier rounds read them level. What remains against the commit before #1850, at one worker, is in #1889, which stays open: - wide random F64 × F64, about +11%; - wide I64 × I64, +11–12%; - nullable cyclic, +19%; - masked wide keys, +7% to +12%. These come from the per-group pivot of #1850's design on paths this commit leaves alone. ## Tests - **`test/rfl/agg/comoment_large_magnitude.rfl`:** a 30,000-group F64 × F64 key with four rows per group, several groups to a chunk, and an outlier every 28th row, checked against each group's direct `cov`. It passes on dev too: this change keeps answers within the tolerance and only changes time. A timing change has no test that fails on dev. - **`agg_contract/comoment_random_search`** and **`agg_contract/comoment_large_magnitude`** cover the path, with null-free F64 × F64 pairs by high-cardinality keys at 1 and 4 workers. Runs: - gcc release and debug builds are clean; clang 23 `-fsyntax-only -Werror` on `src/ops/agg_stream.c`, with and without `DEBUG`, is clean. - `make -j4 test CC=gcc TEST_ARGS="-j 4"`: 5938 of 5942 passed, 4 skipped, 0 failed. - The co-moment tests pass in the release-flags build, with the 400-case search on three seeds as above. Part of #1889 --- src/ops/agg_stream.c | 70 +++++++++++++++++++++++ test/rfl/agg/comoment_large_magnitude.rfl | 13 +++++ 2 files changed, 83 insertions(+) diff --git a/src/ops/agg_stream.c b/src/ops/agg_stream.c index 23cf38b52..99c741190 100644 --- a/src/ops/agg_stream.c +++ b/src/ops/agg_stream.c @@ -805,11 +805,81 @@ static inline int64_t cov_read_i64(const ray_valid_t* v, int64_t i) { } \ } while (0) +/* Null-free F64 x F64 pairs (#1889), in chunks of COV_CHUNK rows: a seed + * pass first, then the accumulation. On a wide key every row's state + * misses the cache, and a branch on the missed count (is the state new? is + * the count due?) waits out the miss and drops the loads in flight behind + * it. The seed pass takes the misses with little work per row: a state + * not yet touched takes the row's pair as its pivot, by a bit select and + * not a branch. The accumulation then finds its lines in the cache, where + * the due test is a cheap branch. A group with several rows in a chunk is + * seeded by its last one there: still a pair of the group, which is all the + * pivot needs to be until its first move to the running mean. */ +#define COV_CHUNK 256 +static inline double cov_select(int64_t keep, double kept, double fresh) { + int64_t a, b, m = -(int64_t)(keep != 0); + memcpy(&a, &kept, 8); memcpy(&b, &fresh, 8); + a = (a & m) | (b & ~m); + double r; memcpy(&r, &a, 8); + return r; +} +/* Whether a batch's rows scatter over states that spill out of the core's + * cache, so the chunked path pays (#1889). Deterministic, from the batch's + * own group ids: of its first 64 rows, at least three quarters must jump + * more than 4 KiB of states from the row before (a sorted, clustered or + * cyclic key walks neighbouring states, which the cache and its prefetch + * serve, and there the extra pass only costs), and the largest id seen, + * times the state stride, must pass 1 MiB (a key of few groups keeps its + * states in the cache). */ +static inline bool cov_states_spill(size_t stride, const uint32_t* gids, int64_t n) { + int64_t m = n < 64 ? n : 64, jumps = 0; + uint32_t mg = m > 0 ? gids[0] : 0; + for (int64_t i = 1; i < m; i++) { + uint32_t a = gids[i - 1], b = gids[i]; + uint64_t d = a > b ? a - b : b - a; + jumps += d * stride > 4096; + mg = b > mg ? b : mg; + } + return m >= 16 && jumps * 4 >= 3 * (m - 1) && (uint64_t)mg * stride > ((uint64_t)1 << 20); +} +static __attribute__((noinline)) void cov_update2_ff(void* base, size_t stride, const uint32_t* gids, + const double* xd, const double* yd, int64_t n) { + if (!cov_states_spill(stride, gids, n)) { + for (int64_t i = 0; i < n; i++) { + cov_state* st = (cov_state*)((char*)base + (size_t)gids[i]*stride); + COV_STATE_ROW(st, xd[i], yd[i], false, false); + } + return; + } + for (int64_t lo = 0; lo < n; lo += COV_CHUNK) { + int64_t hi = n - lo > COV_CHUNK ? lo + COV_CHUNK : n; + for (int64_t i = lo; i < hi; i++) { + cov_state* st = (cov_state*)((char*)base + (size_t)gids[i]*stride); + int64_t n0 = st->n; + st->pivx = cov_select(n0, st->pivx, xd[i]); + st->pivy = cov_select(n0, st->pivy, yd[i]); + } + for (int64_t i = lo; i < hi; i++) { + cov_state* st = (cov_state*)((char*)base + (size_t)gids[i]*stride); + double dx = xd[i] - st->pivx, dy = yd[i] - st->pivy; + ray_comom_add(dx, dy, &st->sx, &st->sy, &st->sxy); + int64_t c = ++st->n; + if (RAY_UNLIKELY(ray_comom_due(c))) + ray_comom_repivot_cold(0u, (double)c, &st->pivx, &st->pivy, + &st->sx, &st->sy, &st->sxy); + } + } +} + static void cov_update2(void* base, size_t stride, const uint32_t* gids, const void* vx, const void* vy, const ray_valid_t* valx, const ray_valid_t* valy, int64_t n, acc_arena_t* a) { (void)a; (void)vx; (void)vy; + if (!valx->has_nulls && !valy->has_nulls && valx->type == RAY_F64 && valy->type == RAY_F64) { + cov_update2_ff(base, stride, gids, valx->base, valy->base, n); + return; + } #define COV_ROW(i, xv, yv, XI, YI) do { \ cov_state* st = (cov_state*)((char*)base + (size_t)gids[i]*stride); \ COV_STATE_ROW(st, xv, yv, XI, YI); \ diff --git a/test/rfl/agg/comoment_large_magnitude.rfl b/test/rfl/agg/comoment_large_magnitude.rfl index 5662b0812..60a3f36e8 100644 --- a/test/rfl/agg/comoment_large_magnitude.rfl +++ b/test/rfl/agg/comoment_large_magnitude.rfl @@ -153,3 +153,16 @@ (set Y5 (as 'F64 (map (fn [i] (if (in i [0 63]) 0.0 1e8)) I4))) (cov X5 Y5) (select {c: (cov x y) s: (scov x y) from: (table [g x y] (list (% I4 3) X5 Y5)) by: g}) + +;; #1889: null-free F64 pairs by a wide key take a seed pass per chunk of +;; rows; a group with several rows in a chunk, with an outlier among them, +;; keeps the accuracy of the row-by-row path. Each 4-row group holds +;; 1e8 + [0 1 2 3], one of them an outlier of 1e10 every 7th group +(set n9 120000) +(set i9 (til n9)) +(set X9 (+ 1e8 (as 'F64 (% i9 4)))) +(set X9 (+ X9 (* 1e10 (as 'F64 (== 0 (% i9 28)))))) +(set T9 (table [g x y] (list (div i9 4) X9 (- 7.0 (* 2.0 X9))))) +(set R9 (at (select {c: (cov x y) from: T9 by: g}) 'c)) +(set W9 (map (fn [k] (cov (take (drop X9 (* 4 k)) 4) (- 7.0 (* 2.0 (take (drop X9 (* 4 k)) 4))))) (til 30000))) +(< (max (abs (- R9 W9))) (* 1e-9 (max (abs W9)))) -- true