Repository navigation
fix(agg): pearson_corr sums about the running mean - #1896
singaraiona wants to merge 1 commit into
Conversation
singaraiona
left a comment
There was a problem hiding this comment.
Review of 81af465: NEEDS CHANGES
[P1] Mixed and nullable paths add costs beyond the stated exceptions, and regress cov/scov (src/ops/agg.c:518–532; legacy keyless accumulators in src/ops/group.c). Four interleaved dev/PR pairs at 10M rows, minima of 25, reproduce these additional costs:
| Query | dev ms | PR ms | change |
|---|---|---|---|
| direct F64×I32 pearson_corr | 18.262 | 22.790 | +24.8% |
| keyless F64×I32 pearson_corr | 138.536 | 155.840 | +12.5% |
| parted keyless F64×I32 pearson_corr | 142.472 | 159.112 | +11.7% |
| direct F64×I32 cov | 18.994 | 20.977 | +10.4% |
| direct F64×I32 scov | 19.012 | 21.032 | +10.6% |
| direct F64×I32 wsum | 18.265 | 20.773 | +13.7% |
A separate four-triplet dev/PR/old-direct run, pinned to another performance core, confirms the direct regressions and adds nullable cases (only the first x is null):
| Direct query | dev ms | PR ms | head with former direct function ms |
|---|---|---|---|
| F64×I32 pearson_corr | 18.255 | 22.939 | 17.968 |
| F64×I32 cov | 19.017 | 21.045 | 19.015 |
| F64×I32 scov | 19.011 | 21.039 | 19.013 |
| F64×I32 wsum | 18.264 | 20.856 | 17.974 |
| nullable F64×F64 pearson_corr | 30.034 | 36.085 | 30.112 |
| nullable F64×I32 pearson_corr | 30.326 | 36.015 | 30.358 |
| nullable F64×F64 cov | 32.794 | 34.327 | 32.820 |
| nullable F64×I32 cov | 32.382 | 34.191 | 32.388 |
The diagnostic restores only the former agg_pair_vec, with helper-signature adaptations, retaining this head's count-eight schedule. It also restores the old, inaccurate raw Pearson calculation; it is evidence about the timing effect. Covariance and wsum recover dev timing in the same head build. The nullable direct wsum controls stay near dev, and the separate sum controls finish within 1.1%. The additional mixed/nullable costs and the covariance regressions need addressing; they are separate from the known wide-key and by-1k all-core tradeoffs.
[P2] Small magnitudes violate the new accuracy guarantee (src/ops/ops.h:458–462,659–664, and docs/docs/language/math.md:726). Squaring the unscaled differences loses subnormal precision or underflows to zero. Both debug and release, at one/four workers:
(pearson_corr [0.0 1e-200] [0.0 1e-200])
; 0Nf; exact correlation is 1
(pearson_corr [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])
; about 0.982047549733139; binary128 reference about 0.981980506061966The latter error is about 6.7e-5, well outside 1e-9; the answer itself is representable. Independent comparisons reproduce this across direct, keyless, grouped v2, forced legacy DA/hash, index-slice and parted queries. These finite inputs are below 1e150, with nonconstant sides and enough pairs. Dev also mishandles tiny inputs; this is a gap in the new unconditional accuracy promise and its breaking-change trailer. Preserve scale before the products and add tiny-scale coverage.
[P2] The replacement allocation-failure comparison accepts unexpected nulls (test/test_aware.c:7329–7330). The exact new comparator returns true with identical keys and Q.c = [0Nf 0Nf], R0.c = [0.3 0.7], in debug and release. In isolation, (all (< (abs (- [0Nf 0Nf] [0.3 0.7])) 1e-12)) is true. An allocation fallback returning null correlations would now pass this test. Check null-mask equality/expected non-null values before applying the agreed 1e-12 tolerance.
Full timing coverage: gcc 11.4 release on i7-14700; dev 283f08fe5 versus this exact head. Four interleaved pairs per shape, minimum of 25 calls per binary per pair, comparing the lowest minima. One worker was pinned to CPU 6; the diagnostic above used CPU 12. All-core runs used 28 workers, with my other probes finished. Input: x = 1e8 + i%37, y = i%41 as F64/I32, 10M rows; wide key DATE(20000 + (div i 256)%700) × U8(i%256). Index slices select three of eight grouped symbols. Parted queries use four equal partitions.
Pearson timings (known wide-key/by-1k costs are reported for the owner, not counted again as findings):
| Shape / pair | 1 worker dev → PR ms | change | 28 workers dev → PR ms | change |
|---|---|---|---|---|
| direct / F64×F64 | 19.067 → 5.108 | -73.2% | 19.106 → 5.099 | -73.3% |
| direct / F64×I32 | 18.262 → 22.790 | +24.8% | 18.276 → 22.984 | +25.8% |
| keyless / F64×F64 | 129.878 → 136.583 | +5.2% | 107.480 → 114.030 | +6.1% |
| keyless / F64×I32 | 138.536 → 155.840 | +12.5% | 108.933 → 115.196 | +5.7% |
| by 1k / F64×F64 | 22.893 → 19.970 | -12.8% | 4.723 → 5.382 | +14.0% |
| by 1k / F64×I32 | 22.467 → 23.415 | +4.2% | 4.282 → 4.720 | +10.2% |
| wide date×U8 / F64×F64 | 75.400 → 95.969 | +27.3% | 19.331 → 19.849 | +2.7% |
| wide date×U8 / F64×I32 | 75.069 → 97.273 | +29.6% | 17.681 → 18.071 | +2.2% |
| index slices / F64×F64 | 16.758 → 14.538 | -13.2% | 5.042 → 5.053 | +0.2% |
| index slices / F64×I32 | 13.954 → 14.407 | +3.2% | 3.509 → 3.535 | +0.7% |
| parted by 1k / F64×F64 | 32.899 → 29.897 | -9.1% | 14.926 → 15.363 | +2.9% |
| parted by 1k / F64×I32 | 30.917 → 31.784 | +2.8% | 12.791 → 13.307 | +4.0% |
| parted keyless / F64×F64 | 135.903 → 143.349 | +5.5% | 115.746 → 120.555 | +4.2% |
| parted keyless / F64×I32 | 142.472 → 159.112 | +11.7% | 113.042 → 120.317 | +6.4% |
Cov/scov changes against dev, in percent (each cell is cov / scov):
| Shape / pair | 1 worker | 28 workers |
|---|---|---|
| direct / F64×F64 | -71.6% / -71.5% | -71.3% / -71.4% |
| direct / F64×I32 | +10.4% / +10.6% | +10.6% / +10.6% |
| keyless / F64×F64 | -1.6% / -1.6% | +5.0% / +2.6% |
| keyless / F64×I32 | +1.3% / +1.6% | +2.3% / +3.7% |
| by 1k / F64×F64 | +0.5% / +0.8% | +3.1% / -0.8% |
| by 1k / F64×I32 | +0.6% / +0.1% | +0.9% / +2.1% |
| wide / F64×F64 | -2.6% / -2.2% | +0.3% / -0.2% |
| wide / F64×I32 | -0.7% / -1.0% | +0.2% / +0.9% |
| index slices / F64×F64 | -0.2% / +1.4% | -4.1% / -6.9% |
| index slices / F64×I32 | +1.8% / -0.3% | -5.6% / +1.7% |
| parted by 1k / F64×F64 | -0.3% / +0.1% | -1.0% / +0.5% |
| parted by 1k / F64×I32 | +0.0% / -0.1% | +0.1% / -0.9% |
| parted keyless / F64×F64 | -0.6% / -0.5% | +2.5% / +2.9% |
| parted keyless / F64×I32 | +2.1% / +1.3% | +0.6% / +3.2% |
A separate four-pair all-core repeat confirms additional covariance costs:
| F64×F64 query | cov dev → PR ms | scov dev → PR ms | cov / scov / wsum changes |
|---|---|---|---|
| keyless | 105.220 → 109.112 | 104.832 → 109.097 | +3.7% / +4.1% / +0.4% |
| parted keyless | 112.538 → 115.153 | 111.091 → 115.552 | +2.3% / +4.0% / +0.3% |
| by 1k | 5.085 → 5.091 | 5.022 → 5.030 | +0.1% / +0.2% / -1.3% |
The by-1k covariance increase in the first matrix did not persist. In this repeat, Pearson was +0.9% on the wide F64×F64 key and +13.2% by 1k, consistent with the known tradeoffs. The confirmed keyless/parted covariance increases are part of the first finding.
Accuracy and checks: independent strict binary128 references on the actual input values, using centered sums and a high-precision root, checked over 240M result cells across the debug/release runs. The main ordering matrices used 70,001–200,003 rows. Cases covered outliers first/last, positions 1–8, at and around power-of-two counts, first-seven-pairs-far-from-the-rest, alternating signs, sorted/reversed values, large offsets, exact I64 inputs past 2^53, F32 and mixed pairs, nulls, and constants. Routes included direct; keyless; dense and sparse grouping; forced legacy DA/hash; computed operands; masks; index slices including multiple 32,768-row tasks per group; and unequal partition splits of 7/65,529/remainder, at one and four workers. Apart from the tiny-scale finding above, no comparison failed: worst observed covariance/scov error was about 9.88e-13 of group spread, and Pearson error about 4.51e-12, below 1e-9. Worker/route differences consequently fit that tolerance. This is empirical coverage, not a proof of the approximate 3·n·u covariance / 6·n·u Pearson bounds.
Constant groups returned exactly zero covariance and null correlation. Empty, one-pair, all-null and ordinary nullable-group outputs matched dev in the separate differential probe, at one/four workers in debug/release. The count-eight schedule did not break the first-seven-pair/outlier cases in these probes. I also reran all five earlier 10M-row datasets (misleading-prefix clustered/cyclic, reverse prefix, constants, and four hot groups), with each aggregate queried separately, in both builds at one/four workers; all passed.
make -j4 test CC=gcc TEST_ARGS="-j 4": 5943/5947 passed, 4 skipped, 0 failed. Debug probes ran with ASan/UBSan; make docs-check passed. The single commit has a conventional subject and its final paragraph contains BREAKING CHANGE: followed by Fixes #1870; the repository's release-note parser recognizes the breaking-change text correctly. Its accuracy promise needs to account for the finding above.
Not covered: other compilers, CPUs/operating systems, TSan, exhaustive values/orders/splits, or a formal error proof. No guarantee is claimed for values at/above 1e150. Temporary build trees and generated data were deleted; the working tree was unchanged.
**Cost above what was shown to the owner:** on a wide random key (179,200 groups of about 56 rows), `pearson_corr` at one worker is **+26.5%** for F64 × F64 and **+18.7%** for F64 × I32 against dev. The owner was shown +6% to +19% for grouped routes. - About +16% is the 64-byte state: a throwaway row path with no seeding and no due test measured 88 ms against dev's 76. The rest is the per-group seed and the repivots. - At all cores the same shapes are +0.4% to +2.0%. - The other `pearson_corr` costs: - by1k at all cores, +13% to +15%; - keyless and parted keyless, +5% to +8% at either worker count. - Every other `pearson_corr` shape is faster than dev or within +4.4%. The direct call is 73% to 78% faster. - `cov` and `scov` are within about ±3% of dev on every shape, beside `wsum` controls that move up to +2.5%. They are faster on some: the direct call, mixed F64 × I32 keyless, and index slices. The full table is below. ### Since the previous head (review 1) - **Tiny magnitudes (finding 2):** the squares and products of the differences underflow for spreads below about 1e-150. That is a lower limit symmetric to the upper one at 1e150, now stated in the docs, here and in the trailer: neither range carries a guarantee. It is not the schedule; the review's own first-seven-pairs and rows-1-to-8 cases passed. On the review's cases: | expression | exact | dev | this head | |---|---|---|---| | `(pearson_corr [0.0 1e-200] [0.0 1e-200])` | 1 | `0Nf` | `0Nf` | | `(pearson_corr [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])` | 0.981980506 | `0Nf` | 0.982048 (6.7e-5 off) | | `(cov [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])` | 1e-320 | 9.99989e-321 | 9.99989e-321 | Dev is right on none of them. The rfl test runs them without asserting a value. - **The cost of mixed and nullable pairs and of `cov` (finding 1):** - The direct call's pivoted path is now its own function, with typed loops for mixed and nullable pairs. `wsum`'s raw loop is back to its own code. - A narrow integer side beside a float side takes the float arithmetic, except in the v2 engine's `cov` / `scov`. - The index slices have a typed F64 × I32 segment. - **`aware/plan_alloc_fail` (finding 3):** the comparison now also requires the nulls in the same places, so a fallback answering null where the reference has a number fails it. ## Defect `pearson_corr` computed its answer from the raw sums, `(n·Σxy − Σx·Σy) / sqrt((n·Σx² − (Σx)²)(n·Σy² − (Σy)²))`. Once the values are large next to their spread, those terms cancel to rounding noise (#1870): | expression | exact | dev, 1 worker | dev, 4 workers | |---|---|---|---| | `(pearson_corr Y Z)`, `Y` = `1e8 + (% (til 200000) 4)`, `Z` = `7 − 2Y` | `-1.0` | `0Nf` | `0Nf` | | `select … by: k` (3 groups) | `[-1.0 -1.0 -1.0]` | `[17.13 18.14 17.0]` | `[0Nf 0Nf 0Nf]` | | `(pearson_corr (take 3e38e n) (take 3e38e n))`, a constant side | `0Nf` | `1` | `1` | | `(pearson_corr 1e16+[0 1 2 3] [0 1 2 3])` | `1.0` | `2.6656e-08` | `2.6656e-08` | | the same pairs × 30,000, keyless `select` | `[1.0]` | `[1.34]` | `[1.34]` | The answer could fall outside [-1, 1], and under `by:` it changed with the worker count. ## Fix `pearson_corr` now takes the design `cov` and `scov` took in #1850, reusing its helpers in `src/ops/ops.h`; the helpers take the squares as optional pointers, NULL for `cov` and `scov`. - **State:** the pivot `(pivx, pivy)` and the sums Σdx, Σdy, Σdx·dy, Σdx² and Σdy², where `dx = x − pivx`, `dy = y − pivy`. In the v2 engine that is a 64-byte `comom_state`; bits 61 and 62 of its count hold the per-side integer mode. - **Pivot:** it starts at the first pair of each part a route sums. At every power of two from 8 it moves to the running mean, and the five sums are re-expressed about it exactly (`ray_comom_shift`: `Σdx²' = Σdx² − 2e·Σdx + n·e²`, with a float pivot's move taken apart as hi + lo). After the move at the largest power of two up to n, the pivot lies within a standard deviation of the final mean, whatever the order of the rows. - **Integers, per side** (`ray_comom_im`): when both sides are integers or temporals, each side's pivot slot holds an int64 exactly and its differences are taken in integers, so `1e16 + [0 1 2 3]` against `[0 1 2 3]` is exactly 1. Beside a float side: - a 64-bit integer side (I64, TIMESTAMP, TIMESPAN) keeps the integer arithmetic; - a narrower integer side (I32, I16, U8, BOOL, DATE, TIME) takes the float arithmetic, since its values and differences are exact as doubles. This applies on every route but one: the v2 engine keeps every integer side in integer mode for `cov` and `scov` (`ray_comom_im_all`), because their wide keys measured faster on its integer loops. Each route only merges its own states, so the two rules never meet. - **Merge:** the smaller part's five sums are re-expressed exactly about the larger part's pivot, then added. - **A cheaper move for float pairs:** this was the second idea I tried for the wide key's cost, and it needed no new code. The float pivot move already skips TwoSum only where the exactness condition (Sterbenz: the two pivots within a factor of two) is tested, one reciprocal serves both sides, and integer sides keep their exact int64 / int128 path. - **The schedule now starts at 8** (`RAY_COMOM_DUE0`), for `cov` and `scov` too, instead of 2. A move re-expresses five sums for `pearson_corr`, so on a key of a few dozen rows per group the moves were a large part of the work; this saves three moves per group. - The bound: below 8 pairs the pivot is the first pair, at some distance d from the mean of those m < 8 pairs. One pair that far makes their variance at least d²/m, so (d/σ)² ≤ m < 8, and the correction adds about 8u, below the 3·n·u term from n = 3 on. The first move at 8 re-expresses those sums exactly. - The documented bound is unchanged. The argument is in a comment where the schedule is defined (`ray_comom_due` in `src/ops/ops.h`). - The seeded search has new orders for this: the first 7 pairs far from the rest, and outliers at rows 1 to 8. It still has 0 failures. - **Final** (`ray_comom_pearson`): `(Σdxdy − c(sx, sy)) / (sqrt(Σdx² − c(sx, sx)) · sqrt(Σdy² − c(sy, sy)))`, each correction `c` by `ray_comom_corr`, and the root of each side taken apart, so no intermediate passes DBL_MAX where the sums do not. A side with no spread (a constant column, or fewer than two pairs) is the null, as on dev. Rounding can carry a perfect correlation a few ulps past ±1, so the answer is clamped to [-1, 1]. - **Routes:** every route `cov` takes: - the eager builtin; - the v2 engine; - the legacy dense arrays (the squares in `sumsq_f64` and `sumsq_y`); - the legacy hash rows (`GHT_AF2_COMOM_SQ`); - the index-slice tasks; - parted tables, through those. - **The direct call** (`agg_pair_comom`, out of `agg_pair_vec`, so `wsum`'s and `wavg`'s raw loop keeps its code): - Null-free pairs of one type, and F64 with I32 either way round, run in segments between the due counts, with the pivot and the five sums in locals and no per-row check. Each segment is a plain reduction the compiler vectorizes, for `cov` and `pearson_corr` alike. - F64 with I64 either way round, and pairs with nulls, run row by row on typed reads with the pivot and the sums in locals. - The throwaway measured on #1870 tested the due count on every row and kept the pivot in memory across the repivot call; a single group does not feel the state's size. ## What changes against dev - **The issue's cases:** each gives the exact answer at any worker count, as in the table above. The rows read `-1.0`, `[-1.0 -1.0 -1.0]`, `0Nf`, `1.0` and `[1.0]`. - **Accuracy:** for inputs whose magnitudes are all below 1e150 and whose spreads are above about 1e-150, the error is that of rounding sums of n pairs, as for `cov` (#1850): at most about 6·n·u of the correlation's range (u = 2^-53), which combines the covariance sum's 3·n·u with the two variance sums'. That is within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows, on every route. Worker counts and splits can differ within that bound. A constant column of any type gives the null, as on dev. - **Ordinary inputs, differential against dev:** - Setup: 60,000 rows, two partitions; six input pairs (F64, nullable F64, F32, I64, F64×I32, nullable×plain); nine forms; 1 and 4 workers; 192,060 cells per aggregate. - `pearson_corr`: 51% bit-identical, the rest within 2.28e-10 relative, nulls in the same places. - At the worst cell, `(pearson_corr xn y)`, the exact value (rational arithmetic) is 0.000328839737881783. This head is off by 3.5e-13 relative, dev by 2.3e-10. - 1 against 4 workers: identical. - **Too few pairs keep dev's answers.** **Limit:** values from 1e150. A difference, a product or a square can overflow, so the answer may be `0Nf` or inaccurate, as the raw formula's was. ## Cost Wall time in ms, gcc release, 10,000,000 rows, `x = 1e8 + i%37` (F64), `y = i%41` as F64 or I32. Three interleaved runs of each build, each the minimum of 15 calls; the table compares 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 2.8–11.9. The shapes: - *direct*: the builtin on the two vectors; - *keyless*: a `select` with no `by:`; - *by1k*: `% i 1000`; - *wide*: the 179,200-group (DATE, U8) key, `DATE(20000 + (i div 256) % 700) × U8(i % 256)`; - *index-slice*: a grouped symbol of eight values, three kept; - *parted*: four partitions. The `wsum` rows are controls: their code is unchanged except the direct call's, whose raw loop is now alone in `agg_pair_vec`. | query | 1 worker dev | this | change | all cores dev | this | change | |---|---:|---:|---:|---:|---:|---:| | direct F64xF64 pearson_corr | 19.12 | 5.10 | -73.3% | 19.13 | 5.04 | -73.7% | | direct F64xF64 cov | 17.29 | 4.97 | -71.2% | 17.34 | 4.86 | -71.9% | | direct F64xF64 scov | 17.30 | 4.90 | -71.7% | 17.27 | 4.83 | -72.0% | | direct F64xF64 wsum | 19.10 | 17.32 | -9.3% | 19.10 | 17.33 | -9.3% | | direct F64xI32 pearson_corr | 18.37 | 4.12 | -77.6% | 18.28 | 4.07 | -77.7% | | direct F64xI32 cov | 19.07 | 3.97 | -79.2% | 19.00 | 3.91 | -79.4% | | direct F64xI32 scov | 19.11 | 3.96 | -79.3% | 19.01 | 3.91 | -79.4% | | direct F64xI32 wsum | 18.31 | 17.38 | -5.1% | 18.30 | 17.27 | -5.6% | | keyless F64xF64 pearson_corr | 130.18 | 140.15 | +7.7% | 109.12 | 115.77 | +6.1% | | keyless F64xF64 cov | 133.25 | 135.46 | +1.7% | 105.88 | 108.79 | +2.8% | | keyless F64xF64 scov | 133.75 | 134.74 | +0.7% | 106.80 | 108.76 | +1.8% | | keyless F64xF64 wsum | 129.97 | 130.72 | +0.6% | 108.48 | 108.54 | +0.1% | | keyless F64xI32 pearson_corr | 138.33 | 147.51 | +6.6% | 107.57 | 114.84 | +6.8% | | keyless F64xI32 cov | 149.88 | 142.36 | -5.0% | 107.24 | 108.47 | +1.1% | | keyless F64xI32 scov | 149.48 | 142.46 | -4.7% | 107.38 | 108.06 | +0.6% | | keyless F64xI32 wsum | 137.91 | 140.40 | +1.8% | 107.55 | 107.52 | -0.0% | | by1k F64xF64 pearson_corr | 22.70 | 20.04 | -11.7% | 4.77 | 5.40 | +13.3% | | by1k F64xF64 cov | 18.86 | 18.94 | +0.4% | 4.98 | 5.12 | +2.8% | | by1k F64xF64 scov | 18.87 | 18.91 | +0.2% | 4.92 | 5.03 | +2.3% | | by1k F64xF64 wsum | 22.63 | 22.59 | -0.2% | 4.60 | 4.71 | +2.5% | | by1k F64xI32 pearson_corr | 22.47 | 20.43 | -9.1% | 4.17 | 4.80 | +15.1% | | by1k F64xI32 cov | 22.11 | 22.00 | -0.5% | 4.39 | 4.48 | +2.0% | | by1k F64xI32 scov | 22.11 | 22.02 | -0.4% | 4.41 | 4.53 | +2.6% | | by1k F64xI32 wsum | 22.45 | 22.26 | -0.8% | 4.14 | 4.22 | +1.9% | | wide F64xF64 pearson_corr | 76.40 | 96.63 | +26.5% | 19.36 | 19.76 | +2.0% | | wide F64xF64 cov | 89.71 | 87.47 | -2.5% | 19.17 | 19.50 | +1.7% | | wide F64xF64 scov | 89.92 | 87.67 | -2.5% | 19.77 | 19.52 | -1.3% | | wide F64xF64 wsum | 76.24 | 76.19 | -0.1% | 19.62 | 19.63 | +0.1% | | wide F64xI32 pearson_corr | 75.93 | 90.15 | +18.7% | 17.61 | 17.68 | +0.4% | | wide F64xI32 cov | 77.21 | 76.84 | -0.5% | 17.66 | 17.48 | -1.0% | | wide F64xI32 scov | 77.55 | 77.09 | -0.6% | 17.42 | 17.39 | -0.1% | | wide F64xI32 wsum | 75.95 | 76.04 | +0.1% | 17.66 | 17.48 | -1.0% | | index-slice F64xF64 pearson_corr | 16.92 | 14.87 | -12.1% | 4.88 | 5.06 | +3.9% | | index-slice F64xF64 cov | 14.31 | 14.28 | -0.3% | 4.89 | 4.99 | +2.1% | | index-slice F64xF64 scov | 14.24 | 14.18 | -0.4% | 5.08 | 5.01 | -1.3% | | index-slice F64xF64 wsum | 16.73 | 16.83 | +0.6% | 5.04 | 4.95 | -1.9% | | index-slice F64xI32 pearson_corr | 14.08 | 11.72 | -16.7% | 3.55 | 3.60 | +1.3% | | index-slice F64xI32 cov | 14.22 | 11.19 | -21.3% | 3.48 | 3.49 | +0.4% | | index-slice F64xI32 scov | 14.16 | 11.18 | -21.0% | 3.60 | 3.31 | -8.0% | | index-slice F64xI32 wsum | 14.05 | 13.97 | -0.6% | 3.49 | 3.47 | -0.7% | | parted by1k F64xF64 pearson_corr | 32.87 | 30.11 | -8.4% | 14.78 | 15.39 | +4.1% | | parted by1k F64xF64 cov | 29.05 | 28.98 | -0.3% | 15.05 | 15.15 | +0.7% | | parted by1k F64xF64 scov | 28.97 | 28.99 | +0.1% | 15.02 | 15.12 | +0.6% | | parted by1k F64xF64 wsum | 32.85 | 32.55 | -0.9% | 14.79 | 14.81 | +0.1% | | parted by1k F64xI32 pearson_corr | 30.98 | 28.86 | -6.9% | 12.79 | 13.35 | +4.4% | | parted by1k F64xI32 cov | 30.44 | 30.45 | +0.0% | 12.95 | 12.93 | -0.1% | | parted by1k F64xI32 scov | 30.56 | 30.37 | -0.6% | 12.98 | 12.99 | +0.1% | | parted by1k F64xI32 wsum | 30.91 | 30.68 | -0.7% | 12.75 | 12.82 | +0.5% | | parted keyless F64xF64 pearson_corr | 137.04 | 146.39 | +6.8% | 114.26 | 120.49 | +5.5% | | parted keyless F64xF64 cov | 142.68 | 141.98 | -0.5% | 113.77 | 115.84 | +1.8% | | parted keyless F64xF64 scov | 142.49 | 142.35 | -0.1% | 112.50 | 114.83 | +2.1% | | parted keyless F64xF64 wsum | 137.53 | 138.20 | +0.5% | 116.27 | 114.74 | -1.3% | | parted keyless F64xI32 pearson_corr | 143.79 | 154.15 | +7.2% | 114.69 | 120.12 | +4.7% | | parted keyless F64xI32 cov | 155.98 | 149.21 | -4.3% | 112.72 | 114.19 | +1.3% | | parted keyless F64xI32 scov | 155.89 | 148.75 | -4.6% | 113.11 | 113.44 | +0.3% | | parted keyless F64xI32 wsum | 143.17 | 145.65 | +1.7% | 113.83 | 113.12 | -0.6% | ## Tests - **`test/rfl/agg/pearson_large_magnitude.rfl`** (new): the issue's repros on the direct call, keyless, `by:` low and high cardinality, `where:`, an index slice and a parted table; constant columns (F32 at 3e38, I64 at INT64_MAX); integers past 2^53 with an integer and a float partner; outliers at rows 0 and 63; too few pairs; an I32 side beside an F64 side; and the review's tiny-spread cases, run without asserting a value. It fails on dev at its first line (`0Nf`, where the answer is −1). - **`agg_contract/comoment_large_magnitude`** and **`agg_contract/comoment_random_search`** now check `pearson_corr` beside `cov` and `scov` against the double-double reference: within 1e-9, and the null exactly where a side has no spread. The search's direct-call leg runs `pearson_corr` too. - It has two new row orders for the schedule: the first 7 pairs far from the rest, and outliers at rows 1 to 8. - Locally, 400 cases from each of seeds 0x1847, 0x5eed and 0xc0ffee, 85,379,200 cells each, 256,137,600 in all, gave **0 failures** in the release-flags build. In the suite: 24 cases, 5,122,752 cells. - **`aware/plan_alloc_fail`:** its `pearson_corr` comparison against the fallback route's answer was byte for byte. It is now the same keys, the nulls in the same places, and the values within 1e-12. Each route sums about its own running mean, so the last bits can differ. - **`scanrange/v2_route_shapes`:** `pearson_corr` by the (date, u8) key, with its 64-byte state, pins the tablestack strategy; `cov` pins the partitioned-dense one. Runs: - gcc release and debug builds are clean; clang 23 `-fsyntax-only -Werror` on the changed C files, with and without `DEBUG`, is clean. - `make -j4 test CC=gcc TEST_ARGS="-j 4"`: 5943 of 5947 passed, 4 skipped, 0 failed, `aware/plan_alloc_fail` included. - The co-moment tests pass in the release-flags build, with the 400-case search on three seeds as above. - `make docs-check` and `mkdocs build --strict` pass. - The new rfl test fails on dev at its first line (`0Nf`, where the answer is −1) and passes here. ## Docs `language/math.md`'s "Covariance and correlation accuracy" section now covers `pearson_corr`: its squares, its tolerance, and the null for a constant column. The `pearson_corr` entry points to it. BREAKING CHANGE: pearson_corr answers change. For inputs whose magnitudes are all below 1e150 and whose spreads are above about 1e-150, its error is that of rounding sums of n pairs: at most about 6·n·u (u = 2^-53), within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows and on every route. Answers at different worker counts can differ within that bound. A constant column of any type gives the null. Against dev, ordinary inputs move only in their last bits (2.28e-10 relative at most in the sweep). Large values close together, integers past 2^53 and groups with outliers get the right answer where they got rounding noise that depended on the worker count, or the null. From 1e150, and for spreads below about 1e-150, the answer may be 0Nf or inaccurate: neither range carries a guarantee. Fixes #1870
81af465 to
bc306ea
Compare
|
Review addressed in bc306ea (one commit; the description matches its message, and its first lines and the cost table are rewritten).
|
singaraiona
left a comment
There was a problem hiding this comment.
Review of bc306ea: NEEDS CHANGES
P2 — The generic direct mixed-type path still regresses cov/scov and Pearson. The specializations at src/ops/agg.c:548–559 fix F64×I32, but F32×I32 and F64×I16 fall through to ROWS2(XGEN, YGEN, SKIPN). At 10M rows, one worker pinned to CPU 6, four interleaved dev/head pairs with minima of 25 executions:
| Direct pair | Operation | Dev ms | Head ms | Change |
|---|---|---|---|---|
| F32×I32 | pearson_corr | 17.641 | 26.780 | +51.8% |
| F32×I32 | cov | 19.074 | 23.141 | +21.3% |
| F32×I32 | scov | 19.095 | 23.136 | +21.2% |
| F32×I32 | wsum control | 17.655 | 17.176 | −2.7% |
| F64×I16 | pearson_corr | 18.666 | 27.602 | +47.9% |
| F64×I16 | cov | 19.355 | 24.513 | +26.6% |
| F64×I16 | scov | 19.375 | 24.517 | +26.5% |
| F64×I16 | wsum control | 18.662 | 17.249 | −7.6% |
Inputs are null-free: i = (til 10000000), xf = (as 'F32 (% i 37)), yi = (as 'I32 (% i 41)), x = (+ 1e8 (as 'F64 (% i 37))), ys = (as 'I16 (% i 41)); time (cov xf yi) / (cov x ys) and the other operations. These are well outside the stated +3% covariance allowance and the stated +4.4% limit for other Pearson shapes, with controls moving in the opposite direction. A second isolated four-pair run confirmed Pearson +51.6% / +48.2%, cov +21.2% / +25.6%, and scov +21.2% / +26.4%, with wsum −2.7% / −7.5%. Please extend the fix to the generic mixed-type path without imposing these covariance costs.
P2 — Random wide-key F64×I32 Pearson costs more at all cores than the stated +0.4–2%. With the 10M-row random date × U8 key below and 28 workers, the complete four-pair matrix measured +4.0% (wsum +1.6%); an independent four-pair rerun measured +3.5% (wsum +1.0%). A final four-pair run timing only this Pearson query and its matching control gave 16.9427 → 17.8825 ms, +5.55%, while wsum was 17.3476 → 17.3577 ms, +0.06%. Each run used minima of 25 and alternated binaries. The final focused run separates this excess from the control movement. This is additional to the already-disclosed costs; please account for it in the change and owner decision, or bring it within the stated range.
P2 — Preserve a tiny-scale answer that dev computes correctly. In ray_comom_pearson, lines 682–685, dividing the subnormal square by the count loses information before the final ratio:
(set x (* [0.0 0.0 1.0] (pow 2.0 -537)))
(pearson_corr x [0.0 1.0 0.0])The exact correlation is −0.5. Dev 283f08fe5 returns −0.5 exactly; this head returns −0.40824829046386302, an absolute error of 0.09175170953613698. I reproduced that in gcc release and debug builds, with 1 and 4 workers, direct, keyless, grouped native and forced legacy routes, grouped-symbol index slices, and an unequal two-part query. Here x² = 2^-1074; the new correction rounds x²/3 to zero, whereas dev's equivalent count-scaled expression retains the necessary subnormal information. Please preserve this dev-correct result, for example through appropriate scaling of the final calculation, and add a regression assertion.
This finding uses the review's explicit exception for a tiny case where dev is correct and the new head is wrong; it does not ask to restore a general guarantee below the accepted spread limit. I also reran the original examples: dev returns null on both original tiny Pearson cases, and dev/head return the same rounded tiny covariance.
Accuracy and the other fixes checked. An independent strict binary128 reference, using the actual stored inputs, passed the per-group 3*n*u covariance and 6*n*u Pearson bounds in both gcc release and debug builds at 1 and 4 workers. The matrix used 131,080 rows, up to 32,770 groups, and unequal 7 / 65,529 / 65,544-row partitions. It covered ten integer/float/mixed type pairs, outliers at the first nine positions, last and power-of-two boundaries, first seven pairs far from the rest, alternating signs, sorted/reversed order, large offsets, near-limit small spreads, constants and pairwise nulls. Routes covered direct, keyless, low/high/sparse cardinality, forced legacy DA/hash, computed arguments, where:, grouped-symbol index slices and unequal partition splits. The matrix plus sorted-order checks made 700,735,280 result-cell comparisons; a separate 20,000-case small-group search per build (seed 0x5eed, 2–32 rows) added 118,638, with no failures inside the contract. A further 10M-row / 179,200-random-group binary128 comparison covered F64×F64 and F64×I32, first-seven and power-of-two outliers, native and forced legacy routes, 1/4 workers, release/debug: 34,406,400 more comparisons, zero failures; the largest Pearson error was 3.13e-15. Ordinary empty, one-pair, all-null and constant cases matched dev, with null correlation and exact zero covariance as applicable.
The new allocation-failure comparator rejects the previous unexpected-null counterexample. The gcc suite passed 5943/5947, four skipped, zero failures, using make -j4 and TEST_ARGS="-j 4"; make docs-check passed. The commit is one commit over its base, and the repository's release-note parser recognizes its final BREAKING CHANGE trailer including both accuracy limits, followed by Fixes #1870.
Timing matrix against dev 283f08fe5480ef82a980580c37c6cb2a846b25b5. GCC release builds on an i7-14700; 10M rows; 1 worker pinned to CPU 6 or 28 workers; four alternating dev/head process pairs, each query timed 25 times, reporting the lowest minimum. Every shape had a matching wsum control. Positive percentages mean slower. These are the first complete four-pair measurements; focused repeats of the small all-core discrepancies are discussed below.
| Pearson shape | 1 worker F64×F64 | 1 worker F64×I32 | 28 workers F64×F64 | 28 workers F64×I32 |
|---|---|---|---|---|
| Direct | -73.3% | -77.3% | -73.3% | -77.3% |
| Keyless | +7.8% | +6.3% | +5.1% | +5.4% |
| By 1k | -13.5% | -9.1% | +15.2% | +13.1% |
| Wide cyclic | +26.5% | +18.5% | +1.5% | +3.0% |
| Wide random | +9.2% | +10.0% | +4.8% | +4.0% |
| Index slices | -13.1% | -16.5% | +1.3% | -3.7% |
| Parted by 1k | -9.2% | -7.0% | +3.8% | +4.4% |
| Parted keyless | +6.3% | +7.9% | +5.5% | +5.2% |
Both wide keys have 179,200 groups (date × U8). Cyclic uses r = (% i 179200); random uses r = (rand 10000000 179200); date is 20000 + div(r,256) and U8 is r % 256. The cyclic case reproduces the reported single-worker costs; the randomized case has lower single-worker costs on this host. Index slices select three of eight grouped-symbol values; the parted fixture has four 2.5M-row partitions. The reported wide-key and by-1k costs already under owner consideration are not findings here.
Focused all-core repeats: the initial F64 index-slice scov reading of +4.85% became −0.73% (wsum +1.15%); its cov was +2.99%, so I do not report that initial spike as a finding. Random wide-key F64×F64 Pearson became +1.95% on rerun; cyclic wide-key Pearson repeated at +1.33% / +3.96% for F64×F64 / F64×I32. By-1k repeated at +14.43% / +15.87%, alongside controls +0.33% / +1.81%. The mixed random-key excess that survived focused checks is the finding above. Apart from the generic direct mixed-type finding, the tested covariance shapes were within the +3% allowance after these checks.
Not covered: other compilers or architectures, every possible type pairing/order/partition split, a formal proof of the error bound, or a general accuracy guarantee outside the accepted magnitude/spread limits. I did not rerun the pre-#1850 baseline or build the complete MkDocs site; this follow-up compares against current dev and runs docs-check.
Temporary build trees and generated data were deleted; the working tree was left unchanged.
Cost above what was shown to the owner: on a wide random key (179,200 groups of about 56 rows),
pearson_corrat one worker is +26.5% for F64 × F64 and +18.7% for F64 × I32 against dev. The owner was shown +6% to +19% for grouped routes.pearson_corrcosts:pearson_corrshape is faster than dev or within +4.4%. The direct call is 73% to 78% faster.covandscovare within about ±3% of dev on every shape, besidewsumcontrols that move up to +2.5%. They are faster on some: the direct call, mixed F64 × I32 keyless, and index slices.The full table is below.
Since the previous head (review 1)
Tiny magnitudes (finding 2): the squares and products of the differences underflow for spreads below about 1e-150. That is a lower limit symmetric to the upper one at 1e150, now stated in the docs, here and in the trailer: neither range carries a guarantee. It is not the schedule; the review's own first-seven-pairs and rows-1-to-8 cases passed. On the review's cases:
(pearson_corr [0.0 1e-200] [0.0 1e-200])0Nf0Nf(pearson_corr [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])0Nf(cov [0.0 1e-160 2e-160] [0.0 1e-160 3e-160])Dev is right on none of them. The rfl test runs them without asserting a value.
The cost of mixed and nullable pairs and of
cov(finding 1):wsum's raw loop is back to its own code.cov/scov.aware/plan_alloc_fail(finding 3): the comparison now also requires the nulls in the same places, so a fallback answering null where the reference has a number fails it.Defect
pearson_corrcomputed its answer from the raw sums,(n·Σxy − Σx·Σy) / sqrt((n·Σx² − (Σx)²)(n·Σy² − (Σy)²)). Once the values are large next to their spread, those terms cancel to rounding noise (#1870):(pearson_corr Y Z),Y=1e8 + (% (til 200000) 4),Z=7 − 2Y-1.00Nf0Nfselect … by: k(3 groups)[-1.0 -1.0 -1.0][17.13 18.14 17.0][0Nf 0Nf 0Nf](pearson_corr (take 3e38e n) (take 3e38e n)), a constant side0Nf11(pearson_corr 1e16+[0 1 2 3] [0 1 2 3])1.02.6656e-082.6656e-08select[1.0][1.34][1.34]The answer could fall outside [-1, 1], and under
by:it changed with the worker count.Fix
pearson_corrnow takes the designcovandscovtook in #1850, reusing its helpers insrc/ops/ops.h; the helpers take the squares as optional pointers, NULL forcovandscov.State: the pivot
(pivx, pivy)and the sums Σdx, Σdy, Σdx·dy, Σdx² and Σdy², wheredx = x − pivx,dy = y − pivy. In the v2 engine that is a 64-bytecomom_state; bits 61 and 62 of its count hold the per-side integer mode.Pivot: it starts at the first pair of each part a route sums. At every power of two from 8 it moves to the running mean, and the five sums are re-expressed about it exactly (
ray_comom_shift:Σdx²' = Σdx² − 2e·Σdx + n·e², with a float pivot's move taken apart as hi + lo). After the move at the largest power of two up to n, the pivot lies within a standard deviation of the final mean, whatever the order of the rows.Integers, per side (
ray_comom_im): when both sides are integers or temporals, each side's pivot slot holds an int64 exactly and its differences are taken in integers, so1e16 + [0 1 2 3]against[0 1 2 3]is exactly 1. Beside a float side:This applies on every route but one: the v2 engine keeps every integer side in integer mode for
covandscov(ray_comom_im_all), because their wide keys measured faster on its integer loops. Each route only merges its own states, so the two rules never meet.Merge: the smaller part's five sums are re-expressed exactly about the larger part's pivot, then added.
A cheaper move for float pairs: this was the second idea I tried for the wide key's cost, and it needed no new code. The float pivot move already skips TwoSum only where the exactness condition (Sterbenz: the two pivots within a factor of two) is tested, one reciprocal serves both sides, and integer sides keep their exact int64 / int128 path.
The schedule now starts at 8 (
RAY_COMOM_DUE0), forcovandscovtoo, instead of 2. A move re-expresses five sums forpearson_corr, so on a key of a few dozen rows per group the moves were a large part of the work; this saves three moves per group.ray_comom_dueinsrc/ops/ops.h).Final (
ray_comom_pearson):(Σdxdy − c(sx, sy)) / (sqrt(Σdx² − c(sx, sx)) · sqrt(Σdy² − c(sy, sy))), each correctioncbyray_comom_corr, and the root of each side taken apart, so no intermediate passes DBL_MAX where the sums do not. A side with no spread (a constant column, or fewer than two pairs) is the null, as on dev. Rounding can carry a perfect correlation a few ulps past ±1, so the answer is clamped to [-1, 1].Routes: every route
covtakes:sumsq_f64andsumsq_y);GHT_AF2_COMOM_SQ);The direct call (
agg_pair_comom, out ofagg_pair_vec, sowsum's andwavg's raw loop keeps its code):covandpearson_corralike.What changes against dev
-1.0,[-1.0 -1.0 -1.0],0Nf,1.0and[1.0].cov(fix(agg): cov and scov sum about the running mean #1850): at most about 6·n·u of the correlation's range (u = 2^-53), which combines the covariance sum's 3·n·u with the two variance sums'. That is within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows, on every route. Worker counts and splits can differ within that bound. A constant column of any type gives the null, as on dev.pearson_corr: 51% bit-identical, the rest within 2.28e-10 relative, nulls in the same places.(pearson_corr xn y), the exact value (rational arithmetic) is 0.000328839737881783. This head is off by 3.5e-13 relative, dev by 2.3e-10.Limit: values from 1e150. A difference, a product or a square can overflow, so the answer may be
0Nfor inaccurate, as the raw formula's was.Cost
Wall time in ms, gcc release, 10,000,000 rows,
x = 1e8 + i%37(F64),y = i%41as F64 or I32. Three interleaved runs of each build, each the minimum of 15 calls; the table compares 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 2.8–11.9.The shapes:
selectwith noby:;% i 1000;DATE(20000 + (i div 256) % 700) × U8(i % 256);The
wsumrows are controls: their code is unchanged except the direct call's, whose raw loop is now alone inagg_pair_vec.Tests
test/rfl/agg/pearson_large_magnitude.rfl(new): the issue's repros on the direct call, keyless,by:low and high cardinality,where:, an index slice and a parted table; constant columns (F32 at 3e38, I64 at INT64_MAX); integers past 2^53 with an integer and a float partner; outliers at rows 0 and 63; too few pairs; an I32 side beside an F64 side; and the review's tiny-spread cases, run without asserting a value. It fails on dev at its first line (0Nf, where the answer is −1).agg_contract/comoment_large_magnitudeandagg_contract/comoment_random_searchnow checkpearson_corrbesidecovandscovagainst the double-double reference: within 1e-9, and the null exactly where a side has no spread. The search's direct-call leg runspearson_corrtoo.aware/plan_alloc_fail: itspearson_corrcomparison against the fallback route's answer was byte for byte. It is now the same keys, the nulls in the same places, and the values within 1e-12. Each route sums about its own running mean, so the last bits can differ.scanrange/v2_route_shapes:pearson_corrby the (date, u8) key, with its 64-byte state, pins the tablestack strategy;covpins the partitioned-dense one.Runs:
-fsyntax-only -Werroron the changed C files, with and withoutDEBUG, is clean.make -j4 test CC=gcc TEST_ARGS="-j 4": 5943 of 5947 passed, 4 skipped, 0 failed,aware/plan_alloc_failincluded.make docs-checkandmkdocs build --strictpass.0Nf, where the answer is −1) and passes here.Docs
language/math.md's "Covariance and correlation accuracy" section now coverspearson_corr: its squares, its tolerance, and the null for a constant column. Thepearson_correntry points to it.BREAKING CHANGE: pearson_corr answers change. For inputs whose magnitudes are all below 1e150 and whose spreads are above about 1e-150, its error is that of rounding sums of n pairs: at most about 6·n·u (u = 2^-53), within 1e-9 for groups of up to 1.5 million pairs, for any order of the rows and on every route. Answers at different worker counts can differ within that bound. A constant column of any type gives the null. Against dev, ordinary inputs move only in their last bits (2.28e-10 relative at most in the sweep). Large values close together, integers past 2^53 and groups with outliers get the right answer where they got rounding noise that depended on the worker count, or the null. From 1e150, and for spreads below about 1e-150, the answer may be 0Nf or inaccurate: neither range carries a guarantee.
Fixes #1870