stats design
Design goal
Benchmark timings are skewed, heavy-tailed and correlated with the moment they
were taken. stats gives decisions that survive these properties: robust
location estimates, comparisons on paired measurements, an explicit practical
threshold, and an interval whose randomness is pinned by a seed. Every function
is a pure transformation of arrays, so a decision can be recomputed from the
raw observations kept in the event stream.
Constraints
- Timings are skewed and heavy-tailed, with a hard lower bound and rare large outliers.
- A benchmark has few blocks, often fewer than ten pairs per comparison.
- Every result must be recomputable from the raw observations and identical on every target.
- The functions take flat arrays; pairing and phase selection happen before
they are called (in
report.document_from_jsonlfor a JSONL record).
Mathematical background
Order statistics and the sample quantile
Let be a sample and its order statistics. The package uses one quantile definition everywhere, the linear interpolation of Hyndman and Fan’s type 7:11 R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages”, The American Statistician 50(4), 1996. Type 7 is the default of R and NumPy.
Three properties follow directly from the formula and are used below.
- Range. is a convex combination of two adjacent order statistics, so , with and .
- Monotonicity. is the piecewise linear interpolation of the non-decreasing sequence at the nodes , so implies .
- Affine equivariance. For with , sorting commutes with the map and convex combinations commute with affine maps, so . Rescaling timings from µs to ns rescales every quantile, median, IQR and MAD by the same factor.
When is an integer the second term vanishes, so is
never read past the end of the sample (at , ). For an empty
sample the implementation returns instead of a quantile; summarize makes
that visible through count == 0.
For the formula gives the usual median: for , and for .
Location and spread
summarize reports two families of estimators side by side:
| Classical | Robust |
|---|---|
| , |
The breakdown point of an estimator is the largest fraction of the sample that can be moved arbitrarily far without moving the estimate arbitrarily far. It is for and (one value suffices), for the quartiles and the IQR, and for the median and the MAD. A single descheduled run moves the mean of a benchmark; it cannot move the median unless half of the runs are affected.
divides by : it is the standard deviation of the sample viewed as a population, a descriptive quantity. As an estimator of it is biased, because
so . Multiply by when you need the unbiased variance.
The MAD is reported unscaled. For normally distributed data with standard deviation , with , so estimates and .
Paired measurements
The runner measures every implementation once per block, in a rotated order (see the runner design). Model a baseline timing and a candidate timing from block as
where is the block effect shared by both (machine state, frequency, cache contents) with variance , and , are independent noise with variances , . The paired delta cancels the block effect:
whereas a difference taken across blocks has variance
. When drift between
blocks dominates the noise inside a block, pairing removes most of the
variance. compare_paired therefore takes the location of the deltas,
, and never the difference
of two separate locations; the
baseline median enters only as the scale of the relative delta.
The percentile bootstrap
Let be the empirical distribution of the deltas and . A bootstrap resample draws values from with replacement; its median is . Write for the bootstrap distribution. The percentile interval at confidence is
It is exact under the following condition. Suppose an increasing map exists such that has a distribution symmetric about , and the same describes under resampling. Then and
using . For a continuous the coverage is . The interval never needs to know , which is why it is transformation-respecting.22 B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap, Chapman & Hall, 1993, §13.3 and §14.
In general the condition holds only approximately. For smooth statistics (means and smooth functions of means) Edgeworth expansions give the size of the error: each one-sided percentile bound misses its nominal tail probability by , and in the two-sided equal-tailed interval these leading terms cancel, leaving a coverage error of .33 P. Hall, The Bootstrap and Edgeworth Expansion, Springer, 1992, §3.5. BCa and the bootstrap- reduce the one-sided error to . The median is not a smooth statistic: its bootstrap distribution is discrete (derived next), the expansions do not apply, and for the small of a benchmark the error is dominated by that discreteness.
For the median the bootstrap distribution can be written down exactly. Take distinct values. holds exactly when at least of the draws are at most , and each draw is with probability , so
For odd , is a step function that jumps only at the data points. For even the resampled median is the midpoint of the -th and -th resampled order statistics, which can be any two data points, so the jumps sit at the midpoints with , not only at midpoints of adjacent values. Either way the interval endpoints land on, or between, observed deltas, and with few blocks they move in coarse steps.
Actual coverage for small . Let the deltas be independent draws from a continuous distribution with median , and odd. With many resamples the endpoints are order statistics, and , where is the smallest with and the smallest with ; by the formula above, and depend on and only. The number of deltas at or below the median is , and , , so
for every continuous distribution. For a nominal 95 % interval:
| actual coverage | ||
|---|---|---|
| 5 | 93.75 % | |
| 7 | 87.5 % | |
| 9 | 96.1 % | |
| 11 | 93.5 % | |
| 21 | 92.2 % | |
| 51 | 95.1 % |
The coverage oscillates around the nominal level and can fall well below it with a handful of blocks; it settles near 95 % only from about fifty pairs on. Treat the interval of a short run as a description of the spread of the resampled medians, not as a guarantee.
The derivation of these results in full, with the discreteness bound, is in the attachment:
Design decisions
Medians as the default centre
Problem. Timing distributions have a hard lower bound (the work itself) and a
long right tail (interrupts, page faults, frequency changes). Options. Mean,
trimmed mean, median. Choice. The median for every decision, with the mean
kept in SummaryStats as a diagnostic. Why. Its breakdown point is , it
is affine equivariant, and the distance between mean and median signals a tail
that deserves a look in the report.
Paired deltas instead of two independent samples
Problem. Machine state drifts between blocks. Options. Compare
; compare the paired deltas.
Choice. compare_paired computes and summarizes
. Why. The variance derivation above: the block effect
cancels in and stays in an unpaired difference. The cost is a contract:
index of both arrays must come from the same dataset, repetition and block.
paired_deltas truncates to the shorter array and compare_paired marks
unequal lengths Invalid, so a broken alignment is visible instead of being
silently repaired.
The relative delta and the speedup
Problem. Gates are stated in percent, people read speedups. Choice. With and ,
Both are functions of the same two medians, so away from the guards below they never disagree: is decreasing in on , and for a threshold
A threshold of declares the candidate Faster exactly when
. When the candidate is a constant shift of the baseline,
, then and is the
ratio of the medians; in general is a robust estimate of the typical
candidate time built from the paired data. The guards
and keep degenerate input finite. They break the
identity in one case: with and the
code reports but . A baseline whose median time is
cannot be compared in relative terms; check SummaryStats.median first.
(, for example a candidate that always reports )
still gives an infinite speedup.
When the arrays have different lengths, comes from the
pairs but from the whole baseline;
the decision is then Invalid, and and are not meaningful.
A practical threshold instead of a significance test
Problem. With enough repetitions any difference becomes statistically significant, including a 0.1 % change nobody would act on. Options. A -test or Wilcoxon test; an equivalence test (TOST); a practical threshold on the point estimate. Choice. For the decision is the three-way rule
checked after Invalid (unequal lengths) and Unknown (no pairs). Why. The
threshold states the question the user is asking (“is it at least 2 % faster?”)
in the unit of the decision, the rule is reproducible from two medians, and it
does not reward running more repetitions. Uncertainty is reported next to the
decision through the interval, not folded into it.
The rule is meaningful only for a threshold and a
relative delta ; compare_paired returns Invalid
otherwise. For valid inputs the code evaluates
The sign conditions make the first two regions disjoint for every :
and
, so together with the rest
of the line they partition . For the sign conditions are
implied by the threshold tests and the rule is exactly the one above. For
they matter: an exact tie lies in neither of the first two
regions and is Equivalent, while every other is Faster or Slower.
Without them, would make a tie Faster.44 Fixed in issue #1. experiment.comparator_label uses the same rule and returns "Unknown" where compare_paired returns Equivalent or Invalid.
A threshold that is NaN, infinite or negative has no meaning as “the smallest
change you care about”, and every comparison with NaN is false, so such a
threshold would silently classify everything as Equivalent (or, for ,
small slowdowns as Faster). Returning Invalid makes the mistake visible.
runner.validate_protocol rejects the same thresholds before a run.
Seeded percentile bootstrap of the median delta
Problem. A reader of a report needs to see how stable the median delta is,
and the number must be the same when the report is regenerated. Choice.
bootstrap_interval draws resamples with an explicit seed and returns the
type-7 quantiles and of the resampled
medians. Why. The percentile method needs no variance formula for the median
(which would need a density estimate), it is transformation-respecting, and it
is cheap: .
The random stream is generated by a 64-bit xorshift step followed by a multiplication:
These are the constants of Marsaglia–Vigna xorshift64*, but the multiplied
value is fed back as the next state, so the classical period result for
xorshift64* does not carry over. What does carry over: each xorshift step is
an invertible linear map over (a unipotent triangular
matrix), and multiplication by an odd constant is invertible modulo , so
one step is a permutation of the 64-bit words that fixes . That is why seed
0 is replaced by the constant 88172645463393265; as a consequence the seeds
0 and 88172645463393265 give the same stream. Because the step is a
permutation that fixes , a non-zero state never becomes . The generator
uses only
wrapping 64-bit integer arithmetic, so the stream is identical on every target.
A state is mapped to an index by . Writing with , the residues are hit times and the others times, so for a uniformly distributed state
For a million deltas the bias is below , far below the Monte Carlo error of the interval.
Choosing . An endpoint estimated from resampled medians has a standard error of order in probability units, with . For a 95 % interval and this is about percentage points of the 2.5 % tail mass. Use for 95 % intervals and keep the seed and with the experiment configuration.
Outlier views instead of outlier deletion
Problem. Reports want plots without one 50 ms page-fault spike; decisions
must not depend on which points someone chose to hide. Choice.
filter_outliers returns a filtered copy under an explicit OutlierPolicy.
The runner and the event stream never apply it; the run records its policy in
the protocol, and the report applies that policy to the paired deltas of a
comparison, never to the stored observations (see below). Why. The raw data
stay auditable, and the policy is a named value that can be recorded. The two
non-trivial policies have known false-flag rates on clean normal data:
Because the MAD is unscaled, the MAD trim removes about six times as many
points as the Tukey fence from clean normal data ( against
). It is also degenerate when more than half of the values coincide:
the MAD is then and only values equal to the median survive. Both filters
compute their fences from the values that are not NaN and never keep a
NaN.
How the report uses compare_paired_with_bootstrap
report.document_from_jsonl is the one caller inside mare_mark, and it fixes
everything this package leaves to the caller. For each case, scale and
candidate it pairs the confirmatory, valid, kept observations of the candidate
and the baseline by block_id, so index of both arrays is one block (the
contract of compare_paired); it applies the recorded OutlierPolicy with
filter_outliers to the paired deltas and keeps the pairs whose delta
survives, which is exact because the fences depend on the deltas only; it
requires at least three pairs; and it calls compare_paired_with_bootstrap
with the recorded practical_delta_pct, resamples,
and a seed derived per row from the recorded run seed. The decision is
therefore the threshold rule above on , and the
interval is the percentile bootstrap of , which the
report also divides by to show it in percent. With
the Monte Carlo error of each endpoint is about
percentage points of tail mass.
The report design derives the pairing, the
exactness of the outlier step and the minimum of three blocks.
NaN propagates
Problem. The default Double order puts a NaN at an unspecified position
of a sort, so order statistics computed after sorting a sample with a NaN
are inconsistent (a minimum above the maximum) and depend on the position of
the NaN in the input. Options. Reject NaN with an error; drop it
silently; propagate it. Choice. summarize returns NaN for every
statistic except count when the input contains a NaN, and
compare_paired turns the resulting NaN relative delta into Invalid.
Why. Both functions are total and have no error channel; propagation keeps
the result honest without changing their signatures, and count still shows
how many values were passed. Dropping values would change and the pairing
silently. The bootstrap functions, which already return Result, keep
rejecting non-finite values with NonFiniteSample.
Errors as values
Invalid bootstrap input returns Err(BootstrapError). An empty or non-finite
sample would otherwise yield a plausible-looking interval of zeros or NaN.
summarize and compare_paired stay total: they return neutral values
(count == 0, NaN statistics, Unknown, Invalid) that a caller can
test.
Correctness and invariants
- Inputs are not modified.
summarizesorts a copy;filter_outliersreturns a new array; the bootstrap sorts each resample, never the input. - Range. By the range property of ,
median,q1andq3lie in . Every resampled median lies in because it is a quantile of values drawn from ; the interval endpoints are quantiles of those medians, hencelowhigh. - Order. For , , and monotonicity
of gives
lowhigh. - Determinism. The bootstrap is a function of (values, seed, , ). Sorting finite doubles is deterministic, and the generator uses wrapping integer arithmetic, so the same inputs give bit-identical bounds on every target.
- Floating-point error. The mean is a left-to-right sum. With and , the standard bound becomes a relative error of at most for positive timings. The variance uses the two-pass formula , which avoids the cancellation of the one-pass .55 N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, §4.2 and §1.9.
- Complexity.
summarizeis ;compare_pairedis ;bootstrap_intervalis ;filter_outliersis .
Alternatives rejected
- BCa and studentized bootstrap. For smooth statistics they reduce the one-sided coverage error from to , but they need a jackknife acceleration estimate or a variance estimate for every resample; for the median both are unstable with the small that benchmarks have, and neither removes the discreteness derived above. Not implemented.
- Hierarchical bootstrap. Resampling datasets, then repetitions, matches
HierarchicalDatasetsAndRepeatsbetter, but the comparison functions take flat arrays, and the report pools the blocks of all datasets of a scale into one flat sample. Callers can still resample per dataset themselves. - Hodges–Lehmann estimator. The median of pairwise Walsh averages is more efficient under symmetry, but costs and is harder to explain in a report.
- Hypothesis tests (, Welch, Mann–Whitney). Rejected for the decision as explained above; their -values answer a different question.
- Scaled MAD. Multiplying by 1.4826 assumes normality; the unscaled value is reported and the factor is documented instead.
Boundaries
- The decision uses the point estimate and the threshold only; the interval is reported, not used to decide. There is no equivalence test.
- Comparisons take flat arrays. Pairing, phase separation (exploratory or
confirmatory) and environment compatibility are the caller’s job; for JSONL
records
report.document_from_jsonldoes the pairing and the phase separation, not the environment check. - The bootstrap interval is in the unit of the deltas; the decision is in percent. Divide by to compare them.
- The bootstrap assumes exchangeable deltas. Rotation order makes neighbouring blocks dependent; the interval does not model that.
- This package never applies
filter_outliersby itself. TheOutlierPolicyof aRunProtocolis applied by the report, to paired deltas only. - Non-finite values are rejected with an error only by the bootstrap
functions;
summarizeandcompare_pairedpropagateNaNas derived above. - The bootstrap interval has no coverage guarantee for small (see the coverage table). An interval with guaranteed coverage for the median is the order-statistic interval with and chosen from ; it is not provided.
Footnotes
-
R. J. Hyndman and Y. Fan, “Sample quantiles in statistical packages”, The American Statistician 50(4), 1996. Type 7 is the default of R and NumPy. ↩
-
B. Efron and R. J. Tibshirani, An Introduction to the Bootstrap, Chapman & Hall, 1993, §13.3 and §14. ↩
-
P. Hall, The Bootstrap and Edgeworth Expansion, Springer, 1992, §3.5. BCa and the bootstrap- reduce the one-sided error to . ↩
-
Fixed in issue #1.
experiment.comparator_labeluses the same rule and returns"Unknown"wherecompare_pairedreturnsEquivalentorInvalid. ↩ -
N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, §4.2 and §1.9. ↩