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.
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.
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 summarizes the deltas , never the two
samples separately.
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 . 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, and the coverage error of the percentile interval is of order .
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
is a step function on the data points (on midpoints of adjacent order statistics when is even). The interval endpoints therefore land on, or between, observed deltas, and with few blocks they move in coarse steps.
The derivation of both 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 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;
() still gives an infinite speedup.
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. 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. For the three regions
partition . For the first two overlap at , and because
Faster is tested first an exact tie is reported as Faster; use a positive
threshold. Uncertainty is reported next to the decision through the interval,
not folded into it.
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. 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, and
nothing in the runner or the event stream applies it. 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 is about four times more aggressive than the Tukey fence on normal data. It is also degenerate when more than half of the values coincide: the MAD is then and only values equal to the median survive.
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, 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 .33 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. They reduce the coverage error to order but need a jackknife acceleration estimate or a variance estimate for every resample; for the median both are unstable with the small that benchmarks have. Not implemented.
- Hierarchical bootstrap. Resampling datasets, then repetitions, matches
HierarchicalDatasetsAndRepeatsbetter, but the comparison functions take flat arrays. 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.
- 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.
filter_outliersis never applied automatically, andOutlierPolicyin aRunProtocolis a recorded intent, not an action.- Non-finite values are rejected only by the bootstrap functions.
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. ↩
-
N. J. Higham, Accuracy and Stability of Numerical Algorithms, 2nd ed., SIAM, 2002, §4.2 and §1.9. ↩